@runtypelabs/persona 4.28.2 → 4.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) 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.d.cts +1 -1
  6. package/dist/approval-ui.d.ts +1 -1
  7. package/dist/artifacts-ui.d.cts +2 -2
  8. package/dist/artifacts-ui.d.ts +2 -2
  9. package/dist/chunk-BkW8s3fj.js +2 -0
  10. package/dist/chunk-CIVsNcrk.js +1 -0
  11. package/dist/chunk-CKdlNyzM.js +9 -0
  12. package/dist/{chunk-DrYAfpvk.js → chunk-DjOvgFsn.js} +1 -1
  13. package/dist/chunk-lA5CJCgK.js +1 -0
  14. package/dist/client-history.js +1 -1
  15. package/dist/codegen.cjs +1 -1
  16. package/dist/codegen.js +1 -1
  17. package/dist/{composer-input-C39npJaz.d.cts → composer-input-D3sB8_P_.d.cts} +1 -1
  18. package/dist/{composer-input-C39npJaz.d.ts → composer-input-D3sB8_P_.d.ts} +1 -1
  19. package/dist/{context-mention-manager-DLCB1l9E.d.cts → context-mention-manager-D2qxE5op.d.cts} +1 -1
  20. package/dist/{context-mention-manager-DLCB1l9E.d.ts → context-mention-manager-D2qxE5op.d.ts} +1 -1
  21. package/dist/context-mentions-inline.d.cts +2 -2
  22. package/dist/context-mentions-inline.d.ts +2 -2
  23. package/dist/context-mentions.d.cts +3 -3
  24. package/dist/context-mentions.d.ts +3 -3
  25. package/dist/{defaults-DiAgWHXy.d.cts → defaults-Dsw66XqE.d.cts} +1 -1
  26. package/dist/{defaults-DiAgWHXy.d.ts → defaults-Dsw66XqE.d.ts} +1 -1
  27. package/dist/event-stream-view.d.cts +1 -1
  28. package/dist/event-stream-view.d.ts +1 -1
  29. package/dist/{fallback-speech-engine-C5_PUZjH.d.cts → fallback-speech-engine-DJpJcWAk.d.cts} +1 -1
  30. package/dist/{fallback-speech-engine-C5_PUZjH.d.ts → fallback-speech-engine-DJpJcWAk.d.ts} +1 -1
  31. package/dist/forms-ui.d.cts +2 -2
  32. package/dist/forms-ui.d.ts +2 -2
  33. package/dist/history-view.d.cts +1 -1
  34. package/dist/history-view.d.ts +1 -1
  35. package/dist/index.cjs +45 -44
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.d.cts +7 -7
  38. package/dist/index.d.ts +7 -7
  39. package/dist/index.global.js +1 -1
  40. package/dist/index.global.js.map +1 -1
  41. package/dist/index.js +34 -33
  42. package/dist/index.js.map +1 -1
  43. package/dist/{markdown-parsers-loader-BBdyIEU7.d.cts → markdown-parsers-loader-CCY7T4Up.d.cts} +1 -1
  44. package/dist/{markdown-parsers-loader-BBdyIEU7.d.ts → markdown-parsers-loader-CCY7T4Up.d.ts} +1 -1
  45. package/dist/{preview-Chjb0bmI.d.cts → preview-DKKpfTo7.d.cts} +2 -2
  46. package/dist/{preview-Chjb0bmI.d.ts → preview-DKKpfTo7.d.ts} +2 -2
  47. package/dist/{session-a_qIp4xp.d.ts → session-DleMr9dZ.d.cts} +13 -7
  48. package/dist/{session-a_qIp4xp.d.cts → session-DleMr9dZ.d.ts} +13 -7
  49. package/dist/session-reconnect.d.cts +2 -2
  50. package/dist/session-reconnect.d.ts +2 -2
  51. package/dist/smart-dom-reader.d.cts +1 -1
  52. package/dist/smart-dom-reader.d.ts +1 -1
  53. package/dist/theme-editor-preview.cjs +41 -40
  54. package/dist/theme-editor-preview.d.cts +1 -1
  55. package/dist/theme-editor-preview.d.ts +1 -1
  56. package/dist/theme-editor-preview.js +20 -20
  57. package/dist/theme-editor.d.cts +2 -2
  58. package/dist/theme-editor.d.ts +2 -2
  59. package/dist/theme-reference.d.cts +2 -2
  60. package/dist/theme-reference.d.ts +2 -2
  61. package/dist/{types-BdO1jNRm.d.cts → types-oAZ1VReS.d.cts} +166 -21
  62. package/dist/{types-BdO1jNRm.d.ts → types-oAZ1VReS.d.ts} +166 -21
  63. package/dist/voice-client-tools.cjs +1 -0
  64. package/dist/voice-client-tools.d.cts +13 -0
  65. package/dist/voice-client-tools.d.ts +13 -0
  66. package/dist/voice-client-tools.js +1 -0
  67. package/dist/voice-runtime.cjs +3 -3
  68. package/dist/voice-runtime.d.cts +7 -3
  69. package/dist/voice-runtime.d.ts +7 -3
  70. package/dist/voice-runtime.js +4 -4
  71. package/dist/voice-worklet-player.d.cts +2 -2
  72. package/dist/voice-worklet-player.d.ts +2 -2
  73. package/dist/{webmcp-runtime-entry-B6bpVWSa.d.ts → webmcp-runtime-entry-Deg0NfmB.d.cts} +26 -5
  74. package/dist/{webmcp-runtime-entry-B6bpVWSa.d.cts → webmcp-runtime-entry-Deg0NfmB.d.ts} +26 -5
  75. package/dist/webmcp-runtime.cjs +2 -1
  76. package/dist/webmcp-runtime.d.cts +1 -1
  77. package/dist/webmcp-runtime.d.ts +1 -1
  78. package/dist/webmcp-runtime.js +2 -1
  79. package/package.json +6 -1
  80. package/src/client.ts +37 -0
  81. package/src/client.voice-tools.test.ts +65 -0
  82. package/src/generated/runtype-openapi-contract.ts +38 -0
  83. package/src/index-core.ts +11 -0
  84. package/src/index-global.ts +6 -0
  85. package/src/session.test.ts +26 -0
  86. package/src/session.ts +8 -1
  87. package/src/session.voice.test.ts +43 -0
  88. package/src/types.ts +141 -20
  89. package/src/voice/runtype-voice-provider.ts +85 -3
  90. package/src/voice/session-voice-wiring.ts +26 -1
  91. package/src/voice/voice-client-tools-session.ts +116 -0
  92. package/src/voice/voice-delegation.ts +9 -0
  93. package/src/voice/voice.test.ts +360 -0
  94. package/src/voice-client-tools-bundle.test.ts +37 -0
  95. package/src/voice-client-tools-loader.ts +24 -0
  96. package/src/voice-client-tools.ts +9 -0
  97. package/src/webmcp-bridge.test.ts +152 -1
  98. package/src/webmcp-bridge.ts +5 -6
  99. package/src/webmcp-polyfill.integration.test.ts +5 -1
  100. package/src/webmcp-runtime-entry.ts +151 -26
  101. package/dist/chunk-CztSjKHK.js +0 -9
  102. package/dist/chunk-HUOUif-P.js +0 -1
  103. package/dist/chunk-UlcxdHef.js +0 -1
@@ -5,5 +5,5 @@ var AgentWidget=function(e){var t=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),
5
5
  * This source code is licensed under the ISC license.
6
6
  * See the LICENSE file in the root directory of this source tree.
7
7
  */
8
- e.Activity=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]],e.ArrowDown=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]],e.ArrowLeft=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]],e.ArrowRight=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]],e.ArrowUp=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]],e.ArrowUpRight=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]],e.AtSign=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]],e.Bot=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]],e.Check=[["path",{d:"M20 6 9 17l-5-5"}]],e.ChevronDown=[["path",{d:"m6 9 6 6 6-6"}]],e.ChevronLeft=[["path",{d:"m15 18-6-6 6-6"}]],e.ChevronRight=[["path",{d:"m9 18 6-6-6-6"}]],e.ChevronUp=[["path",{d:"m18 15-6-6-6 6"}]],e.Circle=[["circle",{cx:"12",cy:"12",r:"10"}]],e.Clipboard=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]],e.ClipboardCopy=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]],e.Clock=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]],e.CodeXml=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]],e.Copy=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]],e.Download=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]],e.Ellipsis=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]],e.EllipsisVertical=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]],e.ExternalLink=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]],e.Eye=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]],e.File=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]],e.FileCode=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]],e.FileSpreadsheet=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]],e.FileText=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]],e.History=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]],e.ImagePlus=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]],e.Loader=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]],e.LoaderCircle=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]],e.Maximize=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]],e.Menu=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]],e.MessageSquare=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]],e.Mic=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]],e.Minimize=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]],e.Minus=[["path",{d:"M5 12h14"}]],e.PanelLeft=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M9 3v18"}]],e.Paperclip=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]],e.Pencil=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]],e.Plus=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]],e.Quote=[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}]],e.RefreshCw=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]],e.Search=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]],e.Send=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]],e.ShieldAlert=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]],e.ShieldCheck=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]],e.ShieldX=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]],e.Square=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]],e.Star=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]],e.ThumbsDown=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]],e.ThumbsUp=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]],e.Trash=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]],e.Trash2=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]],e.Upload=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]],e.Volume2=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]],e.X=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]]})();let n=(e,t=24,r="currentColor",n=2)=>{if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],r=e[1];if(!r)return;let n=document.createElementNS("http://www.w3.org/2000/svg",t);Object.entries(r).forEach(([e,t])=>{"stroke"!==e&&n.setAttribute(e,String(t))}),o.appendChild(n)}),o},o=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function a(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];r[e]=o(t)&&o(n)?a(t,n):n}return r}let s=Symbol("persona.defaultsProvenance"),i=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function l(e,t=""){return Object.entries(e).flatMap(([e,r])=>{let n=t?`${t}.${e}`:e;return i(r)?l(r,n):[n]})}function d(e,t){for(let r of t.split(".")){if(!i(e)||!Object.prototype.hasOwnProperty.call(e,r))return"absent";if(void 0===(e=e[r]))return"clear"}return"explicit"}function c(e,t){return e?.[s]??t.filter(t=>"explicit"===d(e,t))}function p(e,t){return Object.defineProperty(e,s,{value:t,enumerable:!0,configurable:!0}),e}function u(e,t,r){return p(e,c(t,l(r)))}let h=Symbol("persona.panelAliasProvenance"),m=(e,t)=>null!=e&&Object.prototype.hasOwnProperty.call(e,t),g=(e,t)=>m(e,t)&&void 0!==e[t],f=e=>{let t=e?.[h];return t?{...t}:(e=>({launcherWidth:g(e?.launcher,"width"),legacyLauncherWidth:g(e,"launcherWidth"),sidebarWidth:g(e?.launcher,"sidebarWidth"),dockWidth:g(e?.launcher?.dock,"width")}))(e)},y=(e,t)=>(Object.defineProperty(e,h,{value:t,enumerable:!0,configurable:!0}),e),b=(e,t)=>y(e,f(t)),v="min(440px, calc(100vw - 24px))",w={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},x={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},C={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:{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:v,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",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)"},copy:{inputPlaceholder:"How can I help...",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:w,reasoningDisplay:x,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},S={},k={launcher:{variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},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"}}}};function A(e){return!0===e?.future?.v5Defaults?"v5":"v4"}function M(e){let t="v5"===A(e)?k:S;return a(C,t)}let I=M();function T(e,t){if(e||t)return e?t?a(e,t):e:t}function E(e){let t=M(e);return e?u(b({...t,...e,theme:T(t.theme,e.theme),darkTheme:T(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 r=t.features?.artifacts,n=e.features?.artifacts,o=t.features?.scrollToBottom,a=e.features?.scrollToBottom,s=t.features?.scrollBehavior,i=e.features?.scrollBehavior,l=t.features?.streamAnimation,d=e.features?.streamAnimation,c=t.features?.askUserQuestion,p=e.features?.askUserQuestion,u=t.features?.history,h=e.features?.history,m=void 0===r&&void 0===n?void 0:{...r,...n,layout:{...r?.layout,...n?.layout}},g=void 0===o&&void 0===a?void 0:{...o,...a},f=void 0===s&&void 0===i?void 0:{...s,...i},y=void 0===l&&void 0===d?void 0:{...l,...d},b=void 0===c&&void 0===p?void 0:{...c,...p,styles:{...c?.styles,...p?.styles}},v=void 0===u&&void 0===h?void 0:{...u,...h,copy:{...u?.copy,...h?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...void 0===g?{}:{scrollToBottom:g},...void 0===f?{}:{scrollBehavior:f},...void 0===m?{}:{artifacts:m},...void 0===y?{}:{streamAnimation:y},...void 0===b?{}:{askUserQuestion:b},...void 0===v?{}:{history:v}}})(),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,k):u(b(t),void 0,k)}let L=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},P=(e,t={},...r)=>{let n=document.createElement(e);if(t.className&&(n.className=t.className),void 0!==t.text&&(n.textContent=t.text),t.attrs)for(let[e,r]of Object.entries(t.attrs))n.setAttribute(e,r);if(t.style){let e=n.style,r=t.style;for(let t of Object.keys(r)){let n=r[t];null!=n&&(e[t]=n)}}let o=r.filter(e=>null!=e);return o.length>0&&n.append(...o),n},B=(...e)=>e.filter(Boolean).join(" "),N=e=>{let{fallbackImport:t,resetOnSetLoader:r=!1}=e,n=null,o=null,a=null;return{setLoader:e=>{n=e,r&&(o=null,a=null)},load:()=>o?Promise.resolve(o):a||(a=(n??t)().then(e=>(o=e,e)).catch(e=>{throw a=null,e}),a),provide:e=>{o=e},getSync:()=>o}},{setLoader:R,load:H}=N({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),$=R,W=H,D={activity:r.Activity,"arrow-down":r.ArrowDown,"arrow-up":r.ArrowUp,"arrow-up-right":r.ArrowUpRight,bot:r.Bot,"chevron-down":r.ChevronDown,"chevron-up":r.ChevronUp,"chevron-right":r.ChevronRight,"chevron-left":r.ChevronLeft,check:r.Check,clipboard:r.Clipboard,"clipboard-copy":r.ClipboardCopy,"code-xml":r.CodeXml,copy:r.Copy,file:r.File,"file-code":r.FileCode,"file-spreadsheet":r.FileSpreadsheet,"file-text":r.FileText,"image-plus":r.ImagePlus,loader:r.Loader,"loader-circle":r.LoaderCircle,mic:r.Mic,paperclip:r.Paperclip,quote:r.Quote,"refresh-cw":r.RefreshCw,search:r.Search,send:r.Send,"shield-alert":r.ShieldAlert,"shield-check":r.ShieldCheck,"shield-x":r.ShieldX,square:r.Square,"thumbs-down":r.ThumbsDown,"thumbs-up":r.ThumbsUp,upload:r.Upload,"volume-2":r.Volume2,x:r.X,"at-sign":r.AtSign,"arrow-left":r.ArrowLeft,"arrow-right":r.ArrowRight,"external-link":r.ExternalLink,ellipsis:r.Ellipsis,"ellipsis-vertical":r.EllipsisVertical,menu:r.Menu,"panel-left":r.PanelLeft,plus:r.Plus,minus:r.Minus,pencil:r.Pencil,trash:r.Trash,"trash-2":r.Trash2,download:r.Download,maximize:r.Maximize,minimize:r.Minimize,"message-square":r.MessageSquare,star:r.Star,eye:r.Eye,history:r.History},F="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("."),O=new Map(Object.entries(D)),z=new Set,q=!1,j=new Set,_=e=>{let t=[...j];e&&j.clear();for(let e of t)try{e()}catch{}},U=e=>q?()=>{}:(j.add(e),()=>{j.delete(e)}),V=()=>{let e=0;for(let t of[...z]){let r=O.get(t.name);if(!r)continue;z.delete(t),e++;let o=n(r,t.size,t.color,t.strokeWidth);if(o)for(t.el.removeAttribute("data-persona-icon-pending");o.firstChild;)t.el.appendChild(o.firstChild)}return e},G=!1,K=(e,t=24,r="currentColor",o=2)=>{let a=O.get(e);if(a)return n(a,t,r,o);if(F.includes(e)){G&&=!1;let n=((e,t,r)=>{let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",t),n.setAttribute("stroke-width",String(r)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("data-persona-icon-pending","true"),n})(t,r,o);if(z.size>=500){let e=z.values().next().value;e&&z.delete(e)}return z.add({el:n,name:e,size:t,color:r,strokeWidth:o}),W().then(e=>{if(!q){for(let[t,r]of Object.entries(e.EXTRA_LUCIDE_ICONS))O.has(t)||O.set(t,r);q=!0,V(),_(!0)}}).catch(e=>{G=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)}),n}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},J=["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"],Q=(e,t)=>{let r=L("div",["persona-message-bubble",e,...J].join(" "));return r.id=`bubble-${t}`,r.setAttribute("data-message-id",t),r},X=e=>{let t=L("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},Y=(e,t,o)=>{e.innerHTML="";let a=n(t?r.ChevronUp:r.ChevronDown,16,o,2);a?e.appendChild(a):e.textContent=t?"Hide":"Show"},Z=(e,t,r)=>{if(!r.expandable)return e.append(t),null;let n=L("div","persona-flex persona-items-center");Y(n,r.expanded,r.iconColor);let o=L("div",r.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return o.append(n),e.append(t,o),n},ee=e=>{let t=L("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 r=e.renderPreview?.();((e,t)=>null!=t&&("string"==typeof t?(e.textContent=t,!0):(e.appendChild(t),!0)))(t,r)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},te=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&Y(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"},re=(e,t,r)=>{let n=r.stateSet.has(e),o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),s=t.querySelector(`[data-persona-collapsed-preview="${r.previewKind}"]`);if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");i&&Y(i,n,r.iconColor),a.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")};function ne(e,t){let r="tool"===t?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[r]:{..."tool"===t?w:x,...!0===e?.future?.v5Defaults?k.features?.[r]:{},...e?.features?.[r]}}}}function oe(e,t){let r="tool"===t?"toolCallDisplay":"reasoningDisplay";return e?.features?.[r]?.variant??(e?.future?.v5Defaults?"row":"card")}function ae(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 se(e,t,o,a){if("row"!==oe(o,a))return e;e.className=`persona-message-bubble persona-${a}-bubble persona-activity-row`,e.dataset.activityKind=a,"tool"===a&&void 0===o.toolCall?.shadow&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let s=e.querySelector(":scope > button");if(!s)return e;s.className="persona-activity-header";let i="tool"===a?t.toolCall:t.reasoning,l="complete"!==i?.status,d=t.approval?.status??t.toolCall?.approvalStatus,c="denied"===d?"denied":"pending"===d?"awaiting-approval":!1===t.toolCall?.success?"error":l?"pending"===i?.status?"pending":"running":"done";e.dataset.activityState=c;let p=L("span","persona-activity-icon");p.dataset.activityIcon=c;let u="reasoning"===a?o.features?.reasoningDisplay?.iconName:void 0,h=u?K(u,16,"currentColor",2):"pending"===c?n(r.Circle,16,"currentColor",2):"awaiting-approval"===c?n(r.Clock,16,"currentColor",2):K({pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"}[c],16,"currentColor",2);h&&p.appendChild(h),s.querySelector(".persona-reasoning-header-icon")?.remove();let m="tool"===a?"toolCallDisplay":"reasoningDisplay",g=o.features?.[m]?.iconVisibility??(o.future?.v5Defaults?"active":"always");if(("always"===g||"active"===g&&"done"!==c)&&s.prepend(p),"tool"===a&&i){let e=L("span","persona-activity-duration");l&&i.startedAt&&e.setAttribute("data-tool-elapsed",String(i.startedAt));let r=("tool"===a?t.toolCall?.duration:void 0)??i.durationMs??(void 0!==i.completedAt&&void 0!==i.startedAt?i.completedAt-i.startedAt:void 0);e.textContent=void 0===r?"":ae(r),s.appendChild(e)}s.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),s.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let f=e.querySelector(":scope > .persona-border-t");return f?.classList.add("persona-activity-body"),f&&(f.id=`activity-details-${t.id}`,s.setAttribute("aria-controls",f.id)),e}function ie(e,t,r,n){let o=L("div","");o.id=`bubble-${e.id}`,o.dataset.messageId=e.id;let a=L("button","");a.type="button",a.dataset.expandHeader="true",a.dataset.bubbleType="tool",a.setAttribute("aria-expanded",String(r));let s=L("div","");"string"==typeof n?s.textContent=n:s.appendChild(n),Z(a,s,{expandable:!0,expanded:r,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let i=L("div","persona-border-t");return i.id=`activity-details-${e.id}`,i.style.display=r?"":"none",a.setAttribute("aria-controls",i.id),o.append(a,i),se(o,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),o.dataset.personaToolGroup="true","shimmer"===t.features?.toolCallDisplay?.loadingAnimation&&(o.dataset.activityGroupShimmer="true"),{bubble:o,body:i}}let le=(e,t,r)=>{let n="transient"===t.mode,o=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=((e,t)=>!1!==e.visible&&("transient"!==e.mode||"connecting"===t||"paused"===t||"resuming"===t||"error"===t))(t,r)||n&&o&&!1!==t.visible?"":"none",e.classList.toggle("persona-mt-2",!n),e.classList.toggle("persona-mb-2",n)},de=(e,t,r)=>{t.parentElement&&e.parentElement===t.parentElement&&("transient"===r.mode?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))};function ce(e){return"runtype"===e?.type||"custom"===e?.type}let{setLoader:pe,load:ue,provide:he,getSync:me}=N({fallbackImport:()=>import("./markdown-parsers-entry")}),ge=new Set,fe=pe,ye=()=>{let e=me();return e?Promise.resolve(e):ue().then(e=>((()=>{let e=[...ge];ge.clear();for(let t of e)try{t()}catch{}})(),e))},be=e=>me()?()=>{}:(ge.add(e),()=>{ge.delete(e)}),ve=me,we=e=>{let t=null;return r=>{let n=ve();if(!n)return ke(r);if(!t){let{Marked:r}=n,o=e?.markedOptions;t=new r({gfm:o?.gfm??!0,breaks:o?.breaks??!0,pedantic:o?.pedantic,silent:o?.silent});let a=(e=>{if(!e)return;let t={},r=e;if(r.heading){let e=r.heading;t.heading=(t,r,n)=>e({type:"heading",raw:n,depth:r,text:t,tokens:[]})}if(r.code){let e=r.code;t.code=(t,r,n)=>e({type:"code",raw:"",text:t,lang:r,escaped:n})}if(r.blockquote){let e=r.blockquote;t.blockquote=t=>e({type:"blockquote",raw:"",text:t,tokens:[]})}if(r.table){let e=r.table;t.table=(t,r)=>e({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:t,bodyHtml:r})}if(r.link){let e=r.link;t.link=(t,r,n)=>e({type:"link",raw:"",href:t,title:r??null,text:n,tokens:[]})}if(r.image){let e=r.image;t.image=(t,r,n)=>e({type:"image",raw:"",href:t,title:r??null,text:n})}if(r.list){let e=r.list;t.list=(t,r,n)=>e({type:"list",raw:"",ordered:r,start:n,loose:!1,items:[],itemsHtml:t})}if(r.listitem){let e=r.listitem;t.listitem=(t,r,n)=>e({type:"list_item",raw:"",task:r,checked:n,loose:!1,text:t,tokens:[]})}if(r.paragraph){let e=r.paragraph;t.paragraph=t=>e({type:"paragraph",raw:"",text:t,tokens:[]})}if(r.codespan){let e=r.codespan;t.codespan=t=>e({type:"codespan",raw:"",text:t})}if(r.strong){let e=r.strong;t.strong=t=>e({type:"strong",raw:"",text:t,tokens:[]})}if(r.em){let e=r.em;t.em=t=>e({type:"em",raw:"",text:t,tokens:[]})}if(r.del){let e=r.del;t.del=t=>e({type:"del",raw:"",text:t,tokens:[]})}if(r.html){let e=r.html;t.html=t=>e({type:"html",raw:t,text:t})}if(r.text){let e=r.text;t.text=t=>e({type:"text",raw:t,text:t})}if(r.checkbox){let e=r.checkbox;t.checkbox=t=>e({checked:t})}return r.hr&&(t.hr=r.hr),r.br&&(t.br=r.br),t})(e?.renderer);a&&t.use({renderer:a})}return t.parse(r)}},xe=e=>e?we({markedOptions:e.options,renderer:e.renderer}):we(),Ce=we(),Se=e=>Ce(e),ke=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Ae=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Me=e=>`%%FORM_PLACEHOLDER_${e}%%`,Ie=(e,t)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,r)=>{try{let e=JSON.parse(r.trim());if(e&&"object"==typeof e&&"form"===e.component&&e.type){let r=Me(t.length);return t.push({token:r,type:String(e.type)}),r}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,r)=>{let n=Me(t.length);return t.push({token:n,type:r}),n}),r},Te={ALLOWED_TAGS:"h1.h2.h3.h4.h5.h6.p.br.hr.div.span.ul.ol.li.dl.dt.dd.strong.em.b.i.u.s.del.ins.mark.small.sub.sup.abbr.kbd.var.samp.code.a.img.blockquote.pre.details.summary.table.thead.tbody.tfoot.tr.th.td.caption.colgroup.col.input.label.select.option.textarea.button".split("."),ALLOWED_ATTR:"href.src.alt.title.target.rel.loading.width.height.colspan.rowspan.scope.class.id.type.name.value.placeholder.disabled.checked.for.aria-label.aria-hidden.aria-expanded.role.tabindex.data-tv-form.data-message-id.data-persona-component-directive.data-preserve-animation.data-persona-instance".split(".")},Ee=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Le=()=>{let e=null;return t=>{let r=ve();if(!r)return ke(t);if(!e){let{DOMPurify:t}=r;e=t(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(e,t)=>{if("src"===t.attrName||"href"===t.attrName){let e=t.attrValue;e.toLowerCase().startsWith("data:")&&!Ee.test(e)&&(t.attrValue="",t.keepAttr=!1)}})}return e.sanitize(t,Te)}},Pe=e=>!1===e?null:"function"==typeof e?e:Le(),Be=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Ne=e=>e.includes("|"),Re=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())},He=e=>`| ${e.join(" | ")} |`,$e=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,We=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),De="var(--persona-md-table-scroll-fade, 24px)",Fe=new WeakSet;function Oe(e){let t=e.scrollWidth-e.clientWidth;if(t<=1)return void e.removeAttribute("data-persona-scroll-x");e.setAttribute("data-persona-scroll-x","");let r="rtl"===getComputedStyle(e).direction?t+e.scrollLeft:e.scrollLeft,n=t-r;e.style.setProperty("--persona-fade-l",r<=1?"0px":De),e.style.setProperty("--persona-fade-r",n<=1?"0px":De)}function ze(e){Fe.has(e)||(Fe.add(e),e.addEventListener("scroll",e=>{let t=e.target;t?.classList?.contains("persona-table-scroll")&&Oe(t)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Oe)}let{setLoader:qe,load:je,provide:_e,getSync:Ue}=N({fallbackImport:()=>import("./client-stream")}),Ve=qe,Ge=je,Ke=Ue,Je="webmcp:",Qe=new Map,Xe=e=>{Qe.clear();for(let t of e){let e=t.title?.trim();e&&Qe.set(t.name,e)}},Ye=e=>Qe.get(tt(e)),Ze=null;function et(e,t){let r=3735928559^t,n=1103547991^t;for(let t=0;t<e.length;t++){let o=e.charCodeAt(t);r=Math.imul(r^o,2654435761),n=Math.imul(n^o,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)}let tt=e=>e.startsWith("webmcp:")?e.slice(7):e,rt=e=>e.startsWith(Je),nt=()=>Ze?Ze():import("@mcp-b/webmcp-polyfill"),{setLoader:ot,load:at}=N({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),st=ot,it=at;function lt(e){return e.startsWith("agent_")?{kind:"agentId",agentId:e}:e.startsWith("flow_")?{kind:"flowId",flowId:e}:null}function dt(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function ct(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}var pt=t(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow}),ut=t(e=>{var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var n in e)"default"!==n&&!Object.prototype.hasOwnProperty.call(r,n)&&t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let n=pt();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return n.Allow}}),r(pt(),e);var o=class extends Error{};e.PartialJSON=o;var a=class extends Error{};function s(e,t=n.Allow.ALL){if("string"!=typeof e)throw TypeError("expecting str, got "+typeof e);if(!e.trim())throw Error(`${e} is empty`);return i(e.trim(),t)}e.MalformedJSON=a,e.parseJSON=s;let i=(e,t)=>{let r=e.length,s=0,i=e=>{throw new o(`${e} at position ${s}`)},l=e=>{throw new a(`${e} at position ${s}`)},d=()=>(m(),s>=r&&i("Unexpected end of input"),'"'===e[s]?c():"{"===e[s]?p():"["===e[s]?u():"null"===e.substring(s,s+4)||n.Allow.NULL&t&&r-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||n.Allow.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||n.Allow.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||n.Allow.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||n.Allow._INFINITY&t&&1<r-s&&r-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):"NaN"===e.substring(s,s+3)||n.Allow.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):h()),c=()=>{let o=s,a=!1;for(s++;s<r&&('"'!==e[s]||a&&"\\"===e[s-1]);)a="\\"===e[s]&&!a,s++;if('"'==e.charAt(s))try{return JSON.parse(e.substring(o,++s-Number(a)))}catch(e){l(String(e))}else if(n.Allow.STR&t)try{return JSON.parse(e.substring(o,s-Number(a))+'"')}catch{return JSON.parse(e.substring(o,e.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},p=()=>{s++,m();let o={};try{for(;"}"!==e[s];){if(m(),s>=r&&n.Allow.OBJ&t)return o;let a=c();m(),s++;try{o[a]=d()}catch(e){if(n.Allow.OBJ&t)return o;throw e}m(),","===e[s]&&s++}}catch{if(n.Allow.OBJ&t)return o;i("Expected '}' at end of object")}return s++,o},u=()=>{s++;let r=[];try{for(;"]"!==e[s];)r.push(d()),m(),","===e[s]&&s++}catch{if(n.Allow.ARR&t)return r;i("Expected ']' at end of array")}return s++,r},h=()=>{if(0===s){"-"===e&&l("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(n.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}l(String(r))}}let o=s;for("-"===e[s]&&s++;e[s]&&-1===",]}".indexOf(e[s]);)s++;s==r&&!(n.Allow.NUM&t)&&i("Unterminated number literal");try{return JSON.parse(e.substring(o,s))}catch{"-"===e.substring(o,s)&&i("Not sure what '-' is");try{return JSON.parse(e.substring(o,e.lastIndexOf("e")))}catch(e){l(String(e))}}},m=()=>{for(;s<r&&" \n\r\t".includes(e[s]);)s++};return d()};e.parse=s})();let ht="ask_user_question",mt="data-persona-ask-sheet-for",gt="Type your own answer here",ft="Send",yt="data-ask-question-count",bt="data-ask-answers",vt="data-ask-grouped",wt=!1,xt=e=>e.replace(/["\\]/g,"\\$&"),Ct=e=>"tool"===e.variant&&!!e.toolCall&&"ask_user_question"===e.toolCall.name,St=e=>e?.features?.askUserQuestion??{},kt=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r="complete"===t.status;if(t.args&&"object"==typeof t.args)return{payload:t.args,complete:r};let n=t.chunks;if(!n||0===n.length)return{payload:null,complete:r};try{let e=n.join(""),t=(0,ut.parse)(e,ut.STR|ut.OBJ|ut.ARR);if(t&&"object"==typeof t)return{payload:t,complete:r}}catch{}return{payload:null,complete:r}},At=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!wt&&(wt=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},Mt=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},It=(e,t,r)=>{if("rows"!==e)return null;let n=L("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let e=L("span","persona-ask-row-check");n.appendChild(e)}else{let e=L("span","persona-ask-row-badge");e.textContent=String(r+1),n.appendChild(e)}return n},Tt=e=>{let t=L("span","rows"===e?"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},Et=(e,t)=>{let r=L("div","rows"===t?"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");r.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=e.freeTextPlaceholder??gt,n.setAttribute("data-ask-free-text-input","true"),r.appendChild(n),"rows"!==t){let t=L("button","persona-ask-free-text-submit persona-pointer-events-auto");t.type="button",t.textContent=e.submitLabel??ft,t.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(t)}return r},Lt=e=>{let t=e.getAttribute(bt);if(!t)return{};try{let e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch{return{}}},Pt=e=>{let t=Number(e.getAttribute("data-ask-current-index")??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Bt=e=>{let t=Number(e.getAttribute("data-ask-question-count")??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Nt=e=>"true"===e.getAttribute(vt),Rt=(e,t,r)=>{let n=St(r),o=(e=>"pills"===e.getAttribute("data-ask-layout")?"pills":"rows")(e),{payload:a,complete:s}=kt(t),i=Nt(e),l=Pt(e),d=Bt(e),c=i?((e,t)=>At(e)[t]??null)(a,l):(e=>At(e)[0]??null)(a),p=!!c?.multiSelect,u=e.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${l+1}/${d}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let m=e.querySelector('[data-ask-question="true"]');if(m){let e="string"==typeof c?.question?c.question:"";m.textContent=e,m.classList.toggle("persona-ask-question-skeleton",!e&&!s)}let g=e.querySelector('[data-ask-pill-list="true"]');if(g){let e=((e,t,r,n)=>{let o=L("div","rows"===n?"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");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,s=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&"string"==typeof e.label&&e.label.length>0);if(0===s.length&&!r){for(let e=0;e<3;e++)o.appendChild(Tt(n));return o}if(s.forEach((e,t)=>{o.appendChild(((e,t,r,n)=>{let o=L("button","rows"===r?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",n?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),"rows"===r){let a=L("span","persona-ask-row-content"),s=L("span","persona-ask-row-label");if(s.textContent=e.label,a.appendChild(s),e.description){let t=L("span","persona-ask-row-description");t.textContent=e.description,a.appendChild(t)}o.appendChild(a);let i=It(r,n,t);i&&o.appendChild(i)}else o.textContent=e.label,e.description&&(o.title=e.description);return o})(e,t,n,a))}),!1!==e?.allowFreeText){let e="rows"===n?"Other":"Other…";if("rows"===n){let r=L("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");r.setAttribute("data-ask-user-action","focus-free-text"),r.setAttribute("data-option-index",String(s.length)),r.setAttribute("data-ask-other-row","true");let i=L("span","persona-ask-row-content"),l=document.createElement("input");l.type="text",l.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",l.placeholder=t.freeTextPlaceholder??gt,l.setAttribute("data-ask-free-text-input","true"),l.setAttribute("aria-label",t.freeTextLabel??e),i.appendChild(l),r.appendChild(i);let d=It(n,a,s.length);d&&r.appendChild(d),o.appendChild(r)}else{let r=L("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");r.type="button",r.setAttribute("data-ask-user-action","open-free-text"),r.textContent=t.freeTextLabel??e,o.appendChild(r)}}return o})(c,n,s,o);g.replaceWith(e)}if("rows"!==o){let t=e.querySelector('[data-ask-free-text-row="true"]');t&&t.replaceWith(Et(n,o))}let f=e.querySelector('[data-ask-multi-actions="true"]');i||!p||f?(!p||i)&&f&&f.remove():e.appendChild((e=>{let t=L("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=L("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=e.submitLabel??ft,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t})(n)),e.setAttribute("data-multi-select",p?"true":"false");let y=e.querySelector('[data-ask-nav-row="true"]');if(i){let t=((e,t,r)=>{let n=L("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=L("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=r.backLabel??"Back",o.setAttribute("data-ask-user-action","back"),o.disabled=0===e,n.appendChild(o);let a=L("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=L("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=r.skipLabel??"Skip",s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=L("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let l=e===t-1;return i.textContent=l?r.submitAllLabel??"Submit all":r.nextLabel??"Next",i.setAttribute("data-ask-user-action",l?"submit-all":"next"),i.disabled=!0,a.appendChild(i),n.appendChild(a),n})(l,d,n);y?y.replaceWith(t):e.appendChild(t)}else y&&y.remove();(e=>{let t=Lt(e)[Pt(e)],r=new Set;"string"==typeof t?r.add(t):Array.isArray(t)&&t.forEach(e=>r.add(e));let n=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');n.forEach(e=>{let t=e.getAttribute("data-option-label")??"",n=r.has(t);e.setAttribute("aria-pressed",n?"true":"false"),e.classList.toggle("persona-ask-pill-selected",n)});let o=new Set(Array.from(n).map(e=>e.getAttribute("data-option-label")??"")),a=e.querySelector('[data-ask-free-text-input="true"]');a&&("string"==typeof t&&t.length>0&&!o.has(t)?(a.value=t,a.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):a.value="")})(e),(e=>{if(!Nt(e))return;let t=Lt(e)[Pt(e)],r="string"==typeof t&&t.length>0||Array.isArray(t)&&t.length>0,n=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');n&&(n.disabled=!r);let o=e.querySelector('[data-ask-user-action="submit-multi"]');o&&(o.disabled=0===Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).length)})(e)},Ht=(e,t,r)=>{if(!r||!Ct(e)||!1===St(t).enabled)return;let n=e.toolCall.id;r.querySelectorAll(`[${mt}]`).forEach(e=>{e.getAttribute(mt)!==n&&e.remove()});let o=r.querySelector(`[${mt}="${xt(n)}"]`);if(o)return void((e,t,r)=>{let{payload:n}=kt(t),o=Math.max(1,At(n).length);o>Bt(e)&&(e.setAttribute(yt,String(o)),o>1&&!Nt(e)&&e.setAttribute(vt,"true")),Rt(e,t,r)})(o,e,t);let{payload:a}=kt(e),s=((e,t,r)=>{let n=St(t),o=(e=>"pills"===e.layout?"pills":"rows")(n),a=e.toolCall.id,s=At(r),i=Math.max(1,s.length),l=i>1,d=((e,t)=>{let r=e.agentMetadata?.askUserQuestionAnswers;if(!r||"object"!=typeof r)return{};let n={};return t.forEach((e,t)=>{let o="string"==typeof e?.question?e.question:"";if(o&&Object.prototype.hasOwnProperty.call(r,o)){let e=r[o];("string"==typeof e||Array.isArray(e))&&(n[t]=e)}}),n})(e,s),c=l?((e,t)=>{let r=e.agentMetadata?.askUserQuestionIndex;return"number"==typeof r&&Number.isFinite(r)?Math.max(0,Math.min(t-1,Math.floor(r))):0})(e,i):0,p=L("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(mt,a),p.setAttribute("data-tool-call-id",a),p.setAttribute("data-message-id",e.id),p.setAttribute(yt,String(i)),p.setAttribute("data-ask-current-index",String(c)),p.setAttribute(vt,l?"true":"false"),p.setAttribute("data-ask-layout",o),((e,t)=>{e.setAttribute(bt,JSON.stringify(t))})(p,d),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),void 0!==n.slideInMs&&p.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),Mt(p,n);let u=L("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=L("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",u.appendChild(h);let m=L("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",u.appendChild(m),p.appendChild(u);let g=L("div","rows"===o?"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 g.setAttribute("data-ask-pill-list","true"),g.setAttribute("role","group"),p.appendChild(g),"rows"!==o&&p.appendChild(Et(n,o)),Rt(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p})(e,t,a);r.appendChild(s)},$t=(e,t)=>{if(!e)return;let r=t?`[${mt}="${xt(t)}"]`:`[${mt}]`;e.querySelectorAll(r).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)})},Wt="suggest_replies",Dt={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},Ft={name:Wt,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:Dt,origin:"sdk",annotations:{readOnlyHint:!0}},Ot=e=>"tool"===e.variant&&"suggest_replies"===e.toolCall?.name,zt=e=>{let t=e;if("string"==typeof t)try{t=JSON.parse(t)}catch{return[]}let r=t?.suggestions;if(!Array.isArray(r))return[];let n=r.flatMap(e=>{if("string"==typeof e){let t=e.trim();return t?[t]:[]}if(!e||"object"!=typeof e)return[];let t=e;if("string"!=typeof t.label||!t.label.trim())return[];let r={label:t.label.trim()};return"string"==typeof t.prompt&&t.prompt.trim()&&(r.prompt=t.prompt.trim()),"string"==typeof t.description&&t.description.trim()&&(r.description=t.description.trim()),[r]});return n.length>4?(console.warn(`[persona] suggest_replies: ${n.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),n.slice(0,4)):n},qt=e=>{for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role)return null;if(!Ot(r))continue;let n=zt(r.toolCall?.args);return n.length>0?n:null}return null},jt=new Set,_t=e=>{let t=e?.suggestions?.followUps,r=e?.features?.suggestReplies,n=e=>{let n=t?.[e],o=r?.[e];void 0!==n&&void 0!==o&&n!==o&&((e,t,r)=>{let n=`${e}:${t}:${r}`;jt.has(n)||(jt.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))})(e,o,n)};e&&(n("enabled"),n("expose"));let o=t?.enabled??r?.enabled??!0;return{enabled:o,expose:!!o&&(t?.expose??r?.expose??!1)}},Ut={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},Vt={name:ht,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:Ut,origin:"sdk",annotations:{readOnlyHint:!0}},Gt=e=>{let t=[],r=e?.features?.askUserQuestion;return!0===r?.expose&&!1!==r.enabled&&t.push(Vt),_t(e).expose&&t.push(Ft),t},Kt=e=>"object"==typeof e&&!!e&&!Array.isArray(e),Jt=e=>{if("tool"!==e.variant)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||void 0===t.result)return null;let r=(e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""))(t.toolName);return r?{call:{toolCallId:t.toolCallId,toolName:r,args:Kt(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:r,result:t.result}}:null},Qt=(e,t)=>{let r,n=[],o=[],a=[],s="",i=()=>{0!==o.length&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:a}),o=[],a=[])};for(let l of e){let e=Jt(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(void 0===t||t!==r)&&i(),0===o.length&&(s=l.createdAt,r=t),o.some(t=>t.toolCallId===e.call.toolCallId)||(o.push(e.call),a.push(e.result));continue}let d=t(l);d&&(i(),n.push(d))}return i(),n},Xt=e=>e.replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Yt=e=>{if(null===e)return"null";if(void 0===e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Zt=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},er=e=>{let t="number"==typeof e.duration?e.duration:"number"==typeof e.durationMs?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Zt(t)},tr=e=>{let t=void 0===e.durationMs?Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())):e.durationMs;return Zt(t)},rr=(e,t,r)=>{if(!t)return r;let n=e.name?.trim()||"tool",o=er(e);return t.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},nr=(e,t)=>{let r,n=e.replace(/\{toolName\}/g,t),o=[],a=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0;for(;null!==(r=a.exec(n));)r.index>s&&or(o,n.slice(s,r.index),[]),void 0===r[1]?void 0===r[2]?void 0!==r[3]&&or(o,r[3],["dim"]):or(o,r[2],["italic"]):or(o,r[1],["bold"]),s=r.index+r[0].length;return s<n.length&&or(o,n.slice(s),[]),o},or=(e,t,r)=>{let n=t.split("{duration}");for(let t=0;t<n.length;t++)n[t]&&e.push({text:n[t],styles:r}),t<n.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},ar=()=>({processChunk:()=>null,getExtractedText:()=>null,__isPlainTextParser:!0}),sr=()=>{let e=(()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return null===e?null:{text:e,raw:r};let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let o=(e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/);if(t&&t[1])try{return t[1].replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return t[1]}let r=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/);if(r&&r[1])try{return r[1].replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return r[1]}return null})(r);return null!==o&&(e=o),t=r.length,null===e?null:{text:e,raw:r}},close:async()=>{}}})();return{processChunk:async t=>{let r=t.trim();return r.startsWith("{")||r.startsWith("[")?e.processChunk(t):null},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},ir=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=t)return null!==e||""===e?{text:e||"",raw:r}:null;try{let t=(0,ut.parse)(r,ut.STR|ut.OBJ);t&&"object"==typeof t&&(t.component&&"string"==typeof t.component?e="string"==typeof t.text?Xt(t.text):"":"init"===t.type&&t.form?e="":"string"==typeof t.text&&(e=Xt(t.text)))}catch{}return t=r.length,null===e?null:{text:e,raw:r}},close:()=>{}}},lr=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}},dr="4.28.2",{setLoader:cr,load:pr,provide:ur}=N({fallbackImport:()=>import("./client-history")}),hr=cr,mr=pr;function gr(e){return"string"!=typeof e&&e.some(e=>"image"===e.type)}function fr(e){return{type:"text",text:e}}let yr=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],br=[...yr,"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"];function vr(e){return function(e){return yr.includes(e)||e.startsWith("image/")}(e.type)}function wr(e,t=br,r=10485760){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function xr(e){let t=e.content;if("string"!=typeof t||""===t)return;let r=e.contentParts??e.llmContent??e.rawContent??t;return"string"!=typeof r||r!==t?t:void 0}function Cr(e,t){let r=new Map;for(let t of e)r.set(t.id,t);for(let e of t)r.set(e.id,e);return[...r.values()].sort((e,t)=>{let r=new Date(e.createdAt).getTime(),n=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(n)&&r!==n)return r-n;let o=e.sequence??0,a=t.sequence??0;return o===a?e.id.localeCompare(t.id):o-a})}let Sr={idle:"Online",connecting:"Connecting…",connected:"Streaming…",error:"Offline",paused:"Connection lost…",resuming:"Reconnecting…"};var kr=class extends Error{constructor(e,t,r){super(t),this.name="HistoryClientError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};let Ar=e=>"reason"in e?e.reason:void 0,Mr=(e,t)=>e instanceof kr&&e.code===t,Ir=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),Tr=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),Er=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});var Lr=class{#e;#t;#r;#n;#o;#a;#s;#i;#l;#d;#c;#p;#u;#h;#m;#g;#f;#y;#b;#v;#w;constructor(e={},t={}){if(this.config=e,this.historyInternals=t,this.#d=null,this.clientSession=null,this.#c=null,this.#p=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#u=null,this.#h=!1,this.#m=!1,this.#g=!1,this.#f=null,this.#y=new Set,this.#b=new Set,this.webMcpBridge=null,this.#v=null,this.#x=null,this.#C=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":dr,...e.headers},this.debug=!!e.debug,this.#r=e.streamParser??function(e){switch(e){case"json":return ir;case"regex-json":return sr;case"xml":return lr;default:return ar}}(e.parserType),this.#n=e.contextProviders??[],this.#o=e.requestMiddleware,this.#a=e.customFetch,this.#s=e.parseSSEEvent,this.#i=e.getHeaders,!0===e.webmcp?.enabled&&(this.#v=this.#S(e.webmcp))}#S(e){return it().then(t=>{let r=new t.WebMcpBridge(e,{recordToolDisplayTitles:Xe,getToolDisplayTitle:Ye,loadPolyfill:nt});return void 0!==this.#w&&r.setConfirmHandler(this.#w),this.webMcpBridge=r,r}).catch(e=>(this.#v=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",e),null))}#k(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):!0===this.config.webmcp?.enabled?(this.#v||=this.#S(this.config.webmcp),this.#v):Promise.resolve(null)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#l=e}setWebMcpConfirmHandler(e){this.#w=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return!0===this.webMcpBridge?.isOperational()}executeWebMcpToolCall(e,t,r){return!0===this.config.webmcp?.enabled?this.#k().then(n=>n?n.executeToolCall(e,t,r):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]}):null}getSSEEventCallback(){return this.#l}isClientTokenMode(){return!!this.config.clientToken}#A(){let{agentId:e,flowId:t,target:r,targetProviders:n}=this.config;if(!r)return{agentId:e,flowId:t};let o=function(e,t){let r=e.trim();if(!r)throw Error("[Persona] `target` is empty.");let n=r.indexOf(":");if(n>0){let e=r.slice(0,n),o=r.slice(n+1);if("runtype"===e){let e=lt(o);if(e)return e;throw Error(`[Persona] target "runtype:${o}" 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(o).payload}}let o=lt(r);if(o)return o;let a=t?.default;if(a)return{kind:"payload",payload:a(r).payload};throw Error(`[Persona] target "${r}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${r}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}(r,n);return"agentId"===o.kind?{agentId:o.agentId}:"flowId"===o.kind?{flowId:o.flowId}:{targetPayload:o.payload}}isAgentMode(){return!(!this.config.agent&&!this.#A().agentId)}#M(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||"https://api.runtype.com"}#I(e){return`${this.#M()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),r=!1;for(;;){let n=t.conversationId,o=await this.readVisitorToken();if(!0!==t.durableRecovery?.enabled||!n||!o)throw new kr("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.#M()}/v1/client/conversations/${encodeURIComponent(n)}/executions/${encodeURIComponent(e.executionId)}/events`,s=new URLSearchParams({sessionId:t.sessionId,after:e.after}),i=await fetch(`${a}?${s}`,{method:"GET",headers:{"X-Persona-Version":dr,"X-Visitor-Token":o},signal:e.signal});if(401!==i.status||r){if(!i.ok)throw await(await mr()).historyErrorFor(this.#T(),i,!0);return i}{r=!0;let e=await mr();t=await e.recoverFromUnauthorized(this.#T(),await e.readErrorCode(this.#T(),i),null,!0)}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#c||e&&new Date<e.expiresAt||this.#p===e?null:(this.#p=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#c)return this.#c;let e=this.#c=this.#E().then(t=>this.#c===e?(this.clientSession=t,this.#p=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#c===e&&(this.#c=null)});return e}#L(){return!0===this.config.features?.history?.enabled&&this.isClientTokenMode()&&!this.#h}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#P(){if(!this.#h){this.#B({state:"unavailable",reason:"history_disabled"}),this.#h=!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.#b])e(!1)}}getHistoryIdentityStatus(){return this.#f??this.#N()}subscribeHistoryIdentityStatus(e){return this.#y.add(e),()=>{this.#y.delete(e)}}subscribeHistoryAvailability(e){return this.#b.add(e),this.#h&&e(!1),()=>{this.#b.delete(e)}}#N(){return this.isClientTokenMode()?!0!==this.config.features?.history?.enabled||this.#h?{state:"unavailable",reason:"history_disabled"}:this.#R():{state:"unavailable",reason:"ineligible_mode"}}#R(){let e=this.#f;return"browser_only"===e?.state?e:this.#H()}#H(){return"browser"===this.config.features?.history?.scope?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}#B(e){let t=this.getHistoryIdentityStatus(),r=t.state===e.state&&Ar(t)===Ar(e);if(this.#f=e,!r){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#y])t(e)}}async#$(e){let t=this.#L()&&!e.omitVisitorFields,r=!e.omitVisitorFields,n=null;(t||r)&&(await this.historyInternals.historyBootstrapReady,n=await this.readVisitorToken());let o=this.#A(),a=o.agentId??o.flowId,s=t||e.durableResume?e.conversationId:void 0,i={token:this.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...r&&{durableRecovery:!0},...(t||r)&&n?{visitorToken:n}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...s?{conversationId:s}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let l=await fetch(this.#I("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":dr},body:JSON.stringify(i),signal:e.signal});if(!l.ok){let r=await l.json().catch(()=>({error:"Session initialization failed"}));if(t&&403===l.status&&"visitor_history_disabled"===r.error){if(this.#P(),s)throw new kr("history_disabled","Visitor history is disabled for this surface");return this.#$({...e,omitVisitorFields:!0})}throw 403===l.status&&"durable_recovery_disabled"===r.error?new kr("history_disabled","Durable recovery is disabled for this surface"):(t||e.durableResume)&&401===l.status&&"visitor_required"===r.error?new kr("visitor_required","Visitor credential no longer resolves"):s&&404===l.status?new kr("not_found","Conversation not found"):401===l.status?Error(`Invalid client token: ${r.hint||r.error}`):403===l.status?Error(`Origin not allowed: ${r.hint||r.error}`):Error(r.error||"Failed to initialize session")}let d=await l.json();return d.visitor?.token&&await(this.historyInternals.visitorStore?.set(d.visitor.token)),{sessionId:d.sessionId,expiresAt:new Date(d.expiresAt),flow:d.flow,...d.conversationId?{conversationId:d.conversationId}:{},...d.targetId?{targetId:d.targetId}:{},...d.conversationRevision?{conversationRevision:d.conversationRevision}:{},...d.durableRecovery?{durableRecovery:d.durableRecovery}:{},...d.visitor?{visitor:d.visitor}:{},config:{welcomeMessage:d.config.welcomeMessage,placeholder:d.config.placeholder,theme:d.config.theme}}}async#E(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,t=!0===this.historyInternals.shouldResumeDurableConversation?.();if(!this.#L()&&!t)return this.#W(e,!1);let r=await this.readVisitorToken();if(e&&r)try{let r=await this.#$({conversationId:e,durableResume:t});return t&&!0!==r.durableRecovery?.enabled&&this.historyInternals.setStoredResumableHandle?.(null),this.#D(r,e,!1)}catch(r){if(!Mr(r,"not_found")&&!Mr(r,"visitor_required")&&!Mr(r,"history_disabled"))throw r;return t&&this.historyInternals.setStoredResumableHandle?.(null),this.#W(e,!0)}return this.#W(e,!1)}async#W(e,t){let r=this.historyInternals.visitorStore;return r&&!await this.readVisitorToken()?r.withFirstInitLock(()=>this.#F(e,t)):this.#F(e,t)}async#F(e,t){let r=this.config.getStoredSessionId?.()||null,n=await this.#$({storedSessionId:r}),o=await this.#O(n);return this.#D(o,e,t)}async#z(e){let t=this.config.getStoredSessionId?.()||null,r=this.config.getStoredConversationId?.()||null,n=await this.#$({storedSessionId:t,identityProof:e}),o=this.#D(n,r,!1);return this.clientSession=o,this.#c=null,this.#p=!1,this.resetClientToolsFingerprint(),o}async#O(e){if(!e.visitor?.token||this.#g||!this.#L()&&!0!==e.durableRecovery?.enabled)return e;this.#g=!0;try{return await this.#$({storedSessionId:e.sessionId})}catch{return e}finally{this.#g=!1}}#D(e,t,r){let n=e.conversationId;return n&&t&&(r||n!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:n}),this.config.setStoredSessionId?.(e.sessionId),n&&(this.config.setStoredConversationId?.(n),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#q(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#p=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error("prepareConversationSession() only available in client token mode");if(!this.#L())throw new kr("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let r=t?.proof??null;if(!await this.readVisitorToken()&&!r)throw new kr("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let n=await this.#$({conversationId:e,identityProof:r});return this.#q(n)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.#$({});return this.#q(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#L()&&this.#B(this.#H())}clearClientSession(){this.clientSession=null,this.#c=null,this.#p=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#u=null}#j(){return`${this.#M()}/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("csat"===e.type&&(void 0===e.rating||e.rating<1||e.rating>5))throw Error("CSAT rating must be between 1 and 5");if("nps"===e.type&&(void 0===e.rating||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}},r=await fetch(this.#j(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":dr},body:JSON.stringify(t)});if(!r.ok){let e=await r.json().catch(()=>({error:"Feedback submission failed"}));throw 401===r.status?(this.clientSession=null,this.#p=!1,this.config.onSessionExpired?.(),Error("Session expired. Please refresh to continue.")):Error(e.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let r=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async#_(e){e?.throwIfAborted();let t=this.config.identityProvider;if(void 0===t)return;let r,n,o=this.config.getIdentityProof;if(!t.trim()||!o)throw Error("Chat identity requires identityProvider and getIdentityProof.");try{let t=Promise.resolve().then(()=>o());r=e?await Promise.race([t,new Promise((t,r)=>{n=()=>r(e.reason),e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})]):await t}catch{throw e?.throwIfAborted(),Error("The identity proof provider failed.")}finally{n&&e?.removeEventListener("abort",n)}if("string"!=typeof r||!r.trim())throw Error("A fresh identity proof is required to send this message.");return{provider:t,token:r}}#x;#U(){let e=this;return this.#x??={get config(){return e.config},headers:this.#t,getHeaders:this.#i,debug:this.debug,clientApiBase:()=>e.#M(),getClientApiUrl:t=>e.#I(t),getWebMcpBridge:()=>e.#k(),sendWithClientToolsDiff:(t,r,n,o)=>e.#V(t,r,n,o),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#C;#T(){let e=this;return this.#C??={HistoryClientError:kr,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#M(),setHistoryIdentityStatus:t=>e.#B(t),browserOnlyStatus:()=>e.#R(),derivedBrowserOnly:()=>e.#H(),reinitWithProof:t=>e.#z(t),isHistoryCapable:()=>e.#L(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await mr()).listConversations(this.#T(),e)}async getConversation(e,t){return(await mr()).getConversation(this.#T(),e,t)}async finalizeDisplayProjections(e,t){return(await mr()).finalizeDisplayProjections(this.#T(),e,t)}async deleteConversation(e,t){return(await mr()).deleteConversation(this.#T(),e,t)}async deleteAllConversations(e){return(await mr()).deleteAllConversations(this.#T(),e)}async resetVisitor(){return(await mr()).resetVisitor(this.#T())}async dispatch(e,t){return e.signal?.throwIfAborted(),Ge().catch(()=>{}),this.isClientTokenMode()?this.#G(e,t):this.isAgentMode()?this.#K(e,t):this.#J(e,t)}async#G(e,t){let r=`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`;this.#d=r;let n=()=>this.#d===r,o=e=>{n()&&t(e)};t({type:"status",status:"connecting"});try{let t=()=>{if(e.signal?.throwIfAborted(),!n())throw new DOMException("Turn superseded","AbortError")},a=this.clientSession??await this.initSession();t();let s=async()=>{t();let r=a,n=!0===r.durableRecovery?.enabled;if(n&&(!r.conversationId||!await this.readVisitorToken()))throw Error("Renewing this conversation requires its visitor credential.");t();let o=await this.#$({...n||this.#L()?{conversationId:r.conversationId,durableResume:n}:{storedSessionId:r.sessionId},signal:e.signal});if(t(),r.conversationId&&o.conversationId!==r.conversationId||n&&!0!==o.durableRecovery?.enabled)throw Error("Session renewal did not preserve this conversation.");a=this.#D(o,r.conversationId??null,!1),this.clientSession=a,this.#p=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(a)};Date.now()>=a.expiresAt.getTime()-6e4&&await s();let i=await this.#Q(e.messages),l=i.metadata?Object.fromEntries(Object.entries(i.metadata).filter(([e])=>"sessionId"!==e&&"session_id"!==e)):void 0,d=this.#L(),c={sessionId:a.sessionId,messages:e.messages.filter(Ir).map(e=>{let t=d?xr(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...void 0!==t&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...l&&Object.keys(l).length>0&&{metadata:l},...i.inputs&&Object.keys(i.inputs).length>0&&{inputs:i.inputs},...i.context&&{context:i.context},turnId:r,...e.interrupt&&{submitMode:"interrupt"},...e.voiceSpoken&&{voice:{spoken:!0}}},p=async()=>{t();let r=!0===a.durableRecovery?.enabled?await this.readVisitorToken():null;return t(),this.#V(a.sessionId,i.clientTools,async n=>{t();let o=await this.#_(e.signal);t();let s={...c,sessionId:a.sessionId,...n,...o&&{identityProof:o}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...s,...o&&{identityProof:{provider:o.provider,token:"[REDACTED]"}}}),fetch(this.#I("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":dr,...r?{"X-Visitor-Token":r}:{}},body:JSON.stringify(s),signal:e.signal})})},u=await p();if(t(),401===u.response.status){let e=await u.response.clone().json().catch(()=>null);t(),"Session not found or expired"===e?.error&&(await s(),u=await p(),t())}let{response:h,commit:m}=u;if(!h.ok){let e=await h.json().catch(()=>({error:"Chat request failed"}));if(401===h.status&&"invalid_identity_proof"===e.error){let e=new kr("invalid_identity_proof","The identity proof was rejected");throw o({type:"error",error:e}),e}if(401===h.status){this.clearClientSession(),this.config.onSessionExpired?.();let e=Error("Session expired. Please refresh to continue.");throw o({type:"error",error:e}),e}if(429===h.status){let t=Error(e.hint||"Message limit reached for this session.");throw o({type:"error",error:t}),t}if(410===h.status&&"conversation_deleted"===e.error){let e=new kr("conversation_deleted","This conversation was deleted");throw o({type:"error",error:e}),e}let t=Error(e.error||"Failed to send message");throw o({type:"error",error:t}),t}if(!h.body){let e=Error("No response body received");throw o({type:"error",error:e}),e}m(),o({type:"status",status:"connected"});try{await this.#X(h.body,o,e.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof kr)&&!t.message.includes("Session expired")&&!t.message.includes("Message limit")&&o({type:"error",error:t}),t}}async#J(e,t){t({type:"status",status:"connecting"});let r=await this.#Q(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let n,o={...this.#t};if(this.#i)try{let e=await this.#i();o={...o,...e}}catch(e){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",e)}if(this.#a)try{n=await this.#a(this.#e,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(e){let r=e instanceof Error?e:Error(String(e));throw t({type:"error",error:r}),r}else n=await fetch(this.#e,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!n.ok||!n.body){let e=Error(`Chat backend request failed: ${n.status} ${n.statusText}`);throw t({type:"error",error:e}),e}t({type:"status",status:"connected"});try{await this.#X(n.body,t)}finally{t({type:"status",status:"idle"})}}async#K(e,t){t({type:"status",status:"connecting"});let r=await this.#Y(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let n,o={...this.#t};if(this.#i)try{let e=await this.#i();o={...o,...e}}catch(e){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",e)}if(this.#a)try{n=await this.#a(this.#e,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(e){let r=e instanceof Error?e:Error(String(e));throw t({type:"error",error:r}),r}else n=await fetch(this.#e,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!n.ok||!n.body){let e=Error(`Agent execution request failed: ${n.status} ${n.statusText}`);throw t({type:"error",error:e}),e}t({type:"status",status:"connected"});try{await this.#X(n.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,n){t({type:"status",status:"connected"});try{await this.#X(e,t,r,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){return(await Ge()).resolveApproval(this.#U(),e,t)}async#V(e,t,r,n){let o,a=!!(t&&t.length>0),s=a?function(e){if(0===e.length)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}:${function(e){return`${et(e,0).toString(36)}.${et(e,2654435761).toString(36)}`}(t.join(""))}`}(t):void 0,i=this.clientToolsFingerprintSessionId===e,l=a&&i&&this.lastSentClientToolsFingerprint===s,d=!a&&!0===n?.emptyMeansReplace&&this.#u===e,c=!1;for(let e=0;o=await r({...a&&(c||!l)&&t?{clientTools:t}:{},...d?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),409===o.status&&0===e&&a&&"client_tools_resend_required"===(await o.clone().json().catch(()=>null))?.error;e++)c=!0,this.lastSentClientToolsFingerprint=null;return{response:o,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=e,a?this.#u=e:d&&(this.#u=null)}}}async resumeFlow(e,t,r){return(await Ge()).resumeFlow(this.#U(),e,t,r)}#Z(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role)return r.mentionContext&&Object.keys(r.mentionContext).length>0?{mentions:r.mentionContext}:null}return null}async#ee(e){let t={};this.#n.length&&await Promise.all(this.#n.map(async r=>{try{let n=await r({messages:e,config:this.config});n&&"object"==typeof n&&Object.assign(t,n)}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",e)}}));let r=this.#Z(e);return r&&Object.assign(t,r),Object.keys(t).length?t:null}#te(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}#re(e,t){let r=t?.selectedModelId;return r&&"model"in e&&this.config.composer?.models?.some(e=>e.id===r)?{...e,model:r}:e}async#Y(e,t){let r=this.#A().agentId;if(!this.config.agent&&!r)throw Error("Agent configuration required for agent mode");let n=Qt(Tr(e),e=>!Ir(e)||"user"!==e.role&&"assistant"!==e.role&&"system"!==e.role||e.variant&&"assistant"!==e.variant?null:Er(e)),o=this.#te(t),a={agent:this.#re(this.config.agent??{agentId:r},o),messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};o&&(a.composerOptions=o);let s=[...Gt(this.config),...await((await this.#k())?.snapshotForDispatch())??[]];s.length>0&&(a.clientTools=s);let i=await this.#ee(e);return i&&(a.context=i),a}async#Q(e,t){let r=Qt(Tr(e),e=>Ir(e)?Er(e):null),n=this.#A(),o={messages:r,...n.agentId?{agent:{agentId:n.agentId}}:n.flowId?{flowId:n.flowId}:{}};if(n.targetPayload)for(let[e,t]of Object.entries(n.targetPayload))"messages"!==e&&(o[e]=t);let a=[...Gt(this.config),...await((await this.#k())?.snapshotForDispatch())??[]];a.length>0&&(o.clientTools=a);let s=await this.#ee(e);s&&(o.context=s);let i=this.#te(t);if(i&&(o.composerOptions=i),this.#o)try{let e=await this.#o({payload:{...o},config:this.config});if(e&&"object"==typeof e){let t=e;return void 0!==o.clientTools&&!("clientTools"in t)&&(t.clientTools=o.clientTools),t}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",e)}return o}async#X(e,t,r,n){let{streamResponse:o}=Ke()??await Ge();return o({config:()=>this.config,createStreamParser:this.#r,parseSSEEvent:this.#s,onSSEEvent:(e,t)=>this.#l?.(e,t)},e,t,r,n)}},Pr=class extends Error{constructor(e,t,r){super(t),this.name="HistoryProviderError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};let{setLoader:Br,load:Nr,provide:Rr,getSync:Hr}=N({fallbackImport:()=>import("./ui-extras-entry")}),$r=Br,Wr=Nr,Dr=Hr,{setLoader:Fr,load:Or,provide:zr,getSync:qr}=N({fallbackImport:()=>import("./session-actions")}),jr=Fr,_r=Or,Ur=qr;function Vr(e){return"card"===e?"collapsed":e}function Gr(e){return e.split(";",1)[0].trim().toLowerCase()}function Kr(e,t){let r=e?.display,n="string"==typeof r?{default:r}:r??{};if(t.file&&n.files){if("string"==typeof n.files)return{mode:Vr(n.files),matchedBy:{type:"files"}};let e=t.file.mimeType?Gr(t.file.mimeType):void 0,r=e?function(e,t){if(!e)return;let r=Object.entries(e);for(let[e,n]of r)if(Gr(e)===t)return{mode:Vr(n),selector:Gr(e)};let n=`${t.split("/",1)[0]}/*`;for(let[e,t]of r)if(Gr(e)===n)return{mode:Vr(t),selector:n}}(n.files.byMediaType,e):void 0;if(e&&r)return{mode:r.mode,matchedBy:{type:"mediaType",mediaType:e,selector:r.selector}};if(n.files.default)return{mode:Vr(n.files.default),matchedBy:{type:"files"}}}let o=n.byKind?.[t.artifactType];if(o)return{mode:Vr(o),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=n.byType?.[t.artifactType];if(a)return{mode:Vr(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:Vr(s),matchedBy:{type:"preferredMode"}}:n.default?{mode:Vr(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Jr(e,t){return Kr(e,t).mode}function Qr(e,t){return JSON.stringify({component:"inline"===e?"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}:{},..."inline"===e&&t.component?{component:t.component}:{},..."inline"===e&&t.componentProps?{componentProps:t.componentProps}:{},...void 0===t.markdown?{}:{markdown:t.markdown}}})}function Xr(e,t=140){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-1)}…`}function Yr(e,t){let r=e.findIndex(e=>e.id===t);if(r<=0)return null;for(let t=r-1;t>=0;--t)if("user"===e[t].role)return e[t].id;return null}function Zr(e){return!("user"!==e.role||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||void 0!==e.rawContent||void 0!==e.llmContent&&e.llmContent!==e.content||e.quote)&&"string"==typeof e.content&&e.content.length>0}function en(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 r=e.find(e=>e.name===t);if(r)return r}return e.find(e=>e.lang.startsWith("en"))??e[0]}var tn=class e{constructor(e={}){this.options=e,this.id="browser",this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,r){if(!e.isSupported())return void r.onError?.(Error("Web Speech API is unavailable"));let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(t.text),a=n.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(o.voice=e)}else a.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(a):en(a));void 0!==t.rate&&(o.rate=t.rate),void 0!==t.pitch&&(o.pitch=t.pitch),o.onend=()=>r.onEnd?.(),o.onerror=e=>{let t=e.error;"canceled"===t||"interrupted"===t?r.onEnd?.():r.onError?.(Error(t||"Speech synthesis failed"))},setTimeout(()=>{n.speak(o),r.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},rn=class{#e=null;#t=null;#r="idle";#n=new Set;#o=0;#a;constructor(e){this.#a=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#t===e?this.#r:"idle"}activeMessageId(){return this.#t}onChange(e){return this.#n.add(e),()=>this.#n.delete(e)}toggle(e,t){if(this.#t===e){if("playing"===this.#r)return void(this.#e?.supportsPause?(this.#e.pause(),this.#s(e,"paused")):this.stop());if("paused"===this.#r)return this.#e?.resume(),void this.#s(e,"playing");if("loading"===this.#r)return void this.stop()}this.play(e,t)}async play(e,t){let r=++this.#o;this.#e?.stop(),this.#s(e,"loading");try{if(!this.#e){let e=await this.#a();if(r!==this.#o)return;if(!e)return void this.#s(null,"idle");this.#e=e}this.#e.speak(t,{onStart:()=>{r===this.#o&&this.#s(e,"playing")},onEnd:()=>{r===this.#o&&this.#s(null,"idle")},onError:()=>{r===this.#o&&this.#s(null,"idle")}})}catch{r===this.#o&&this.#s(null,"idle")}}stop(){this.#o++,this.#e?.stop(),this.#s(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#n.clear()}#s(e,t){this.#t="idle"===t?null:e,this.#r=t;for(let e of this.#n)e(this.#t,this.#r)}},nn=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)}};let{setLoader:on,load:an,getSync:sn}=N({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),ln=on,dn=an,cn=sn;function pn(e){if(!e)return"";let t=function(e){let t=e.trim(),r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(r&&(t=r[1].trim()),!t.startsWith("{"))return null;try{let e=JSON.parse(t);if(e&&"object"==typeof e&&"string"==typeof e.text)return e.text}catch{}return null}(e);return function(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,"\n"),t=t.replace(/\n{2,}/g,"\n"),t.trim()}(null===t?e:t)}let un=null,hn=()=>un?un():import("./voice/runtype-tts-entry"),{setLoader:mn,load:gn}=N({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),fn=mn,yn=gn,bn="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(".");var vn=class extends Error{constructor(e,t){super(t),this.name="SessionHistoryError",this.code=e}};function wn(e,t){let r=e instanceof Error?e:Error(String(e));if("string"==typeof t)return t;if("function"==typeof t)return t(r);let n="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 r.message?`${n}\n\n_Details: ${r.message}_`:n}let xn=e=>rt(e)||"suggest_replies"===e;var Cn=class e{#e;#t;#r;#n;#o;#a;#s;#i;#l;#d;#c;#p;#u;#h;#m;#g;#f;#y;#b;#v;#w;#S;#k;#A;#M;#I;#L;#P;#N;#R;#H;#B;#$;#E;#W;#F;constructor(e={},t,r={}){this.config=e,this.callbacks=t,this.historyInternals=r,this.status="idle",this.streaming=!1,this.#e=new Map,this.abortController=null,this.#r=Date.now(),this.clientSession=null,this.agentExecution=null,this.#n=null,this.#o=null,this.#a=!1,this.#s=null,this.#i=null,this.#l=null,this.artifacts=new Map,this.#d=null,this.webMcpInflightKeys=new Set,this.webMcpResolvedKeys=new Set,this.webMcpResolveControllers=new Set,this.#c=0,this.webMcpApprovalResolvers=new Map,this.#p=0,this.approvalTokens=new Map,this.webMcpAwaitBatches=new Map,this.#u=null,this.#h=null,this.#m=0,this.#g=0,this.#f=!1,this.#y="disconnected",this.#b=null,this.#v=null,this.#w=null,this.#S=0,this.#k=!1,this.#A=null,this.#M=!1,this.#I=null,this.#L=new Map,this.#P=null,this.#N=new Map,this.#R=null,this.#H=null,this.#B=!1,this.#$=null,this.#E=null,this.#W=!1,this.#F=null,this.#D=null,this.#q=null,this.#j=new nn,this.#_=Promise.resolve(),this.#x=null,this.#U=null,this.ttsSpokenMessageIds=new Set,this.readAloud=new rn(()=>this.#C()),this.#ne=null,this.#oe=0,this.handleEvent=e=>{let t=this.#U,r=!1;if(t&&("error"===e.type||"status"===e.type&&"error"===e.status?t.failed=!0:"message"===e.type&&"assistant"===e.message.role&&(t.dropped||this.ttsSpokenMessageIds.add(e.message.id),t.ids.includes(e.message.id)||t.ids.push(e.message.id),r=!0)),"message"===e.type){this.upsertMessage(e.message),r&&t.onUpdate?.(),"approval"===e.message.variant&&e.message.approval&&"pending"!==e.message.approval.status&&this.#e.set(e.message.id,this.#t),"assistant"===e.message.role&&!e.message.variant&&e.message.streaming&&(this.#o=e.message.id),("approval"===e.message.variant||!0===e.message.agentMetadata?.awaitingLocalTool)&&_r().catch(()=>{});let n=e.message.toolCall,o=!!n?.name&&(rt(n.name)||"suggest_replies"===n.name&&_t(this.config).enabled);!0===e.message.agentMetadata?.awaitingLocalTool&&o&&this.#ae(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?void 0!==e.message.agentMetadata.iteration&&(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("cursor"===e.type)this.#se(e.id);else if("status"===e.type){if("idle"===e.status&&!e.terminal&&this.#ie())return void this.#le();if(this.#de(e.status),"connecting"===e.status)this.#ce(!0);else if("idle"===e.status||"error"===e.status){this.#pe()||this.#ue(),0===this.webMcpResolveControllers.size&&(this.#ce(!1),this.abortController=null,this.#he(),this.#me());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;"running"===this.agentExecution?.status&&("error"===e.status?this.agentExecution.status="error":t||(this.agentExecution.status="complete")),this.#ge()}}else"error"===e.type?(this.#de("error"),this.#ue(),0===this.webMcpResolveControllers.size&&(this.#ce(!1),this.abortController=null),"running"===this.agentExecution?.status&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):("artifact_start"===e.type||"artifact_delta"===e.type||"artifact_update"===e.type||"artifact_complete"===e.type)&&this.#fe(e)},this.historyInternals=this.#Z(r),this.messages=[...e.initialMessages??[]].map(e=>({...e,sequence:e.sequence??this.#ye()})),this.messages=this.#be(this.messages),this.client=new Lr(e,this.historyInternals),this.#ve(),this.#we();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:"complete"});null!=e.initialSelectedArtifactId&&(this.#d=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#xe(),this.callbacks.onStatusChanged(this.status),this.#O(),this.#z()}#z(){this.config.voiceRecognition?.provider&&dn().catch(()=>{})}#O(){let e=this.config.textToSpeech;if("runtype"!==e?.provider||e.createEngine)return;let t=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&r&&this.config.clientToken&&hn().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return"running"===this.agentExecution?.status}isVoiceSupported(){return function(e){try{if("custom"===e?.type&&e.custom){let t=e.custom,r="function"==typeof t?t():t;return!!r&&"function"==typeof r.startListening}return!("runtype"!==e?.type||!e.runtype)||typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window)}catch{return!1}}(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#f}getVoiceStatus(){return this.#y}getVoiceNotice(){return this.#u?.takeNotice?.()??null}getVoiceDisclosure(){return this.#u?.getDisclosure?.()??null}getVoiceLevel(){return this.#u?.onLevel?this.#g:null}getVoiceInterruptionMode(){return this.#u?.getInterruptionMode?this.#u.getInterruptionMode():"none"}stopVoicePlayback(){this.#u?.stopPlayback&&(this.#j.cancel(),this.#x?.cancel(),this.#u.stopPlayback())}isBargeInActive(){return this.#u?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#u?.deactivateBargeIn&&await this.#u.deactivateBargeIn()}#D;#q;#j;#_;#x;#U;#C(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=tn.isSupported()?new tn({pickVoice:e?.pickVoice}):null;if("runtype"===e?.provider){let r=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,o=this.config.clientToken,a=!1!==e.browserFallback;if(r&&n&&o)return hn().then(({RuntypeSpeechEngine:s,FallbackSpeechEngine:i})=>{let l=new s({host:r,agentId:n,clientToken:o,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new i(l,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):l});if(a&&t)return o&&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 r=this.#_,n=++this.#m;this.#h=dn().then(async e=>{await r,n===this.#m&&this.#T(e,e.createVoiceProvider(t))}).catch(e=>{console.error("Failed to setup voice:",e)}).finally(()=>{n===this.#m&&(this.#h=null)})}catch(e){console.error("Failed to setup voice:",e)}}#T(e,t){this.#u=t;let r=this;e.wireSessionVoice({session:this,provider:()=>r.#u,generation:()=>r.#m,get keyed(){return r.#x},set keyed(e){r.#x=e},get pendingUser(){return r.#D},set pendingUser(e){r.#D=e},get pendingAssistant(){return r.#q},set pendingAssistant(e){r.#q=e},turns:()=>r.#j,busy:()=>r.#G(),setStreaming:e=>r.#ce(e),setDelegation:e=>{r.#U=e},setLevel:e=>{r.#g=e},setStatus:e=>{r.#y=e,r.#f="listening"===e},settlePending:e=>r.#K(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#u&&this.#h&&await this.#h,this.#u)if(this.#f)await this.#u.stopListening();else{this.stopSpeaking();try{await this.#u.startListening()}catch(e){console.error("Failed to start voice:",e)}}else console.error("Voice not configured")}prewarmVoice(){if(!ce(this.config.voiceRecognition?.provider))return void this.warmClientSession();let e=this.#m,t=()=>{let t=this.#u;t?.prewarm&&e===this.#m&&(this.#f||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#u&&this.#h?this.#h.then(t,()=>{}):t()}#G(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#a||"resuming"===this.status}cleanupVoice(){let e=null!==this.#u;if(this.#m++,this.#h=null,this.#u){let e=this.#u;this.#u=null,this.#_=this.#J(e)}this.#f=!1,this.#y="disconnected",this.#K(!0),this.#x?.settle(),this.#x=null,this.#j=new nn,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#J(e){try{await e.disconnect()}catch(e){console.error("Failed to disconnect voice:",e)}}#K(e){let t=e?this.#D:null,r=this.#q;(t||r)&&(r&&this.#j.cancel(),e&&(this.#D=null),this.#q=null,r&&this.ttsSpokenMessageIds.add(r),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==r?[e]:e.id!==r||e.content.trim()?[{...e,streaming:!1,voiceProcessing:!1}]:[]),this.callbacks.onMessagesChanged([...this.messages]),r&&this.#ce(!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.#H=this.historyInternals.getStoredConversationRevision?.()??null,this.#B=!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.#V(e,t)}#V(e,t=!this.messages.length){if(this.#k||!e.config.welcomeMessage||!t)return;let r=this.messages[0],n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:r?.createdAt??(new Date).toISOString(),sequence:r?(r.sequence??0)-1:this.#ye()};this.#Ce(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return!!e&&new Date<e.expiresAt}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.#Z(e),this.client.setHistoryInternals(this.historyInternals),this.#ve()}destroy(){this.cleanupVoice(),this.#$?.(),this.#$=null,this.#E=null}#Z(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#Se(e),t?.(e)}}}get#ee(){return this.historyInternals.historyProvider??null}#te(){let e=this.#ee;if(!e)throw new vn("history_unavailable","No conversation history provider is installed");return e}#re(e){let t=this.#te(),r=e??this.config.features?.history?.scope,n=this.config.getIdentityProof?"verified-user":"browser",o=r??(t.capabilities.scopes.includes(n)?n:t.capabilities.scopes[0]??n);if(!t.capabilities.scopes.includes(o))throw new Pr("unsupported_scope","This history scope is not supported.");return{scope:o}}getHistoryState(){return{activeConversationId:this.#b,conversationRevision:this.#v,nextMessageCursor:this.#w,recovery:this.#A,sendBlocked:this.#M}}getActiveConversationId(){return this.#b}#Y(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#Q(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#I;e&&await e.catch(()=>{});let t=this.#P;t&&await t.catch(()=>{})}#X(){if(this.streaming||"paused"===this.status||"resuming"===this.status)throw new vn("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.#te().list({...e?.cursor?{cursor:e.cursor}:{},...void 0===e?.limit?{}:{limit:e.limit},...void 0===e?.targetId?{}:{targetId:e.targetId},context:this.#re(e?.scope)})}async openConversation(e,t){let r=this.#te();this.#X();let n=this.#re(t?.scope);await this.awaitHistorySettled();let o=++this.#S,a=await r.getPage(e,{context:n});if(o!==this.#S)throw new vn("superseded","A later selection won");let s=await r.prepareOpen(e,{context:n});if(o!==this.#S)throw s.discard(),new vn("superseded","A later selection won");this.#k=!0;try{await this.#ke(s)}finally{this.#k=!1}this.#b=s.conversationId||e,this.#v=s.conversationRevision||a.conversationRevision||null,this.#w=a.nextCursor,this.#A=null,this.#M=!1,this.#Ae();for(let e of a.messages)this.#N.set(e.id,e.content);return this.#Me(),this.hydrateMessages(a.messages),this.#Y(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,t,r){let n=this.#te(),o=this.#re(r?.scope),a=t??this.#w;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let s=`${e} ${a}`,i=this.#L.get(s);if(i)return i;let l=this.#Ie(n,e,a,o).finally(()=>{this.#L.delete(s)});return this.#L.set(s,l),l}async#Ie(e,t,r,n){let o=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:r,...o?{beforeCreatedAt:o}:{},context:n});if(this.#b&&this.#b!==t)return{messages:[],nextMessageCursor:a.nextCursor};let s=Cr(this.messages,a.messages);this.messages=this.#be(s.map(e=>this.#Te(e))),this.#w=a.nextCursor;for(let e of a.messages)this.#N.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#Y(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let t=this.#te(),r=this.#re(e?.scope);await this.awaitHistorySettled();let n=++this.#S,o=await t.prepareStartNew({context:r});if(n!==this.#S)throw o.discard(),new vn("superseded","A later action won");await this.#Ee(o)}async#Ee(e){this.#Le(),await this.#ke(e),this.#b=e.conversationId||null,this.#v=e.conversationRevision||null,this.#w=null,this.#A=null,this.#M=!1,this.#Me(),this.#Y()}async deleteConversation(e,t){let r=this.#te(),n=this.#re(t?.scope);await this.awaitHistorySettled(),await r.delete(e,{context:n}),e===this.#b&&await this.#Pe(n)}async updateConversation(e,t,r){let n=this.#te();if(!n.update)throw new vn("history_unavailable","This history provider cannot update conversations");let o=this.#re(r?.scope);return await this.awaitHistorySettled(),n.update(e,t,{context:o})}canUpdateConversations(){return"function"==typeof this.#ee?.update}async clearConversationHistory(e){let t=this.#te(),r=this.#re(e?.scope);await this.awaitHistorySettled();let n=await t.deleteAll({...void 0===e?.targetId?{}:{targetId:e.targetId},context:r});return await this.#Pe(r),n}async resetHistoryDevice(){let e=this.#te();if(!e.resetDevice)throw new vn("history_unavailable","This history provider cannot reset the device");this.#S+=1,this.#P=null;try{return await e.resetDevice()}finally{this.#Le(),this.#b=null,this.#v=null,this.#w=null,this.#A=null,this.#M=!1,this.#Y()}}async#Pe(e){this.#S+=1,this.#P=null,this.#Le(),this.#b=null,this.#v=null,this.#w=null,this.#M=!0,this.#A=null,this.#Y(),await this.#Be(e)}async#Be(e){let t=this.#ee;if(t)try{let r=await t.prepareStartNew({context:e});await this.#Ee(r)}catch{this.#M=!0,this.#A="new_conversation_required",this.#Y(),this.#Q("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}else this.#M=!1,this.#Y()}async#Ne(){if("new_conversation_required"===this.#A&&this.#ee&&(this.#A=null,await this.#Be(this.#re()),"new_conversation_required"===this.#A))throw new vn("new_conversation_required","A new conversation is required before sending")}async#ke(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.#b=e.conversationId,this.#v=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#k||this.#V(e)}#Me(){this.#b?this.config.setStoredConversationId?.(this.#b):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#v),this.historyInternals.setStoredMessageCursor?.(this.#w)}#Ae(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Re(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#N.clear(),this.#He(null)}#Le(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#$e(),this.#We(),this.#oe++,this.messages=[],this.#Ae(),this.#L.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#ce(!1),this.#de("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Se(e){this.#S+=1,this.#P=null,this.#M=!0,this.#Le(),this.#b=e.conversationId,this.#v=null,this.#w=null,this.#A=null,this.#Y(),this.#Q("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#I=Promise.resolve().then(()=>{this.#M=!1,this.#I=null,this.#Y()})}#ve(){let e=this.historyInternals.visitorStore??null;e!==this.#E&&(this.#$?.(),this.#$=null,this.#E=e,e&&(this.#$=e.subscribe(e=>this.#De(e))))}#De(e){if("external"!==e.source||null===e.previousToken)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#S+=1,this.#P=null,this.#W=!0,this.#F=null;let t=this.messages.length>0;t||null!==this.#b||null!==(this.config.getStoredConversationId?.()??null)?this.#Le():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#L.clear(),this.#He(null)),this.#b=null,this.#v=null,this.#w=null,this.#A=null,this.#Y(),t&&this.#Q("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#Fe(){return this.#W?(this.#F||=this.#Oe().finally(()=>{this.#F=null}),this.#F):Promise.resolve()}async#Oe(){if(this.isClientTokenMode())try{this.bindActivatedSession(await this.client.initSession()),this.#W=!1}catch{}else this.#W=!1}reconcileBootConversation(e){let t=this.#ee,r=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#b;if(!t||!r)return Promise.resolve();let n=this.#re(e?.scope);this.#M=!0,this.#Y();let o=this.#ze(t,r,n).finally(()=>{this.#M=null!==this.#A,this.#I===o&&(this.#I=null),this.#Y()});return this.#I=o,o}async#ze(e,t,r){this.#b=t;let n=this.clientSession?.conversationRevision??this.#v??null,o=this.#B?this.#H:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#B=!1,this.#w=this.historyInternals.getStoredMessageCursor?.()??this.#w,await this.replayPendingProjections(),n&&o&&n===o)return void(this.#v=n);let a,s=await e.getPage(t,{context:r}),i=new Set(s.messages.map(e=>e.id)),l=this.messages.some(e=>i.has(e.id)),d=s.messages[0]?.createdAt;if(l){let e=this.#n?this.#o:null;a=Cr(this.messages.filter(t=>!(!i.has(t.id)&&t.id!==e)||void 0!==d&&t.createdAt<d),s.messages).map(e=>this.#Te(e))}else a=s.messages.map(e=>this.#Te(e));this.#w=s.nextCursor,this.#v=s.conversationRevision||n||null,this.#N.clear();for(let e of s.messages)this.#N.set(e.id,e.content);this.#Me(),this.messages=this.#be(a),this.callbacks.onMessagesChanged([...this.messages])}#qe(){return!0===this.config.features?.history?.enabled&&this.isClientTokenMode()}#He(e){this.#R=e,this.historyInternals.setPendingDisplayProjections?.(e)}#je(){return this.historyInternals.getPendingDisplayProjections?.()??this.#R}#_e(e){if(this.#qe())for(let t of e){let e=xr(t);void 0!==e&&this.#N.set(t.id,e)}}#me(){if(!this.#qe())return;let e=this.#b;if(!e)return;let t=[];for(let e of this.messages){if("assistant"!==e.role||e.streaming)continue;let r=xr(e);void 0!==r&&this.#N.get(e.id)!==r&&t.push({id:e.id,displayContent:r})}0!==t.length&&(this.#He({conversationId:e,messageIds:t.map(e=>e.id)}),this.#Ue(e,t))}#Ue(e,t){let r=(this.#P??Promise.resolve()).catch(()=>{}).then(()=>this.#Ve(e,t,!1)).finally(()=>{this.#P===r&&(this.#P=null)});this.#P=r}async#Ve(e,t,r){if(this.#b!==e)return;let n=t.filter(e=>this.#N.get(e.id)!==e.displayContent);if(0===n.length)this.#Ge(e,t);else try{let{conversationRevision:r}=await this.client.finalizeDisplayProjections(e,n);for(let e of n)this.#N.set(e.id,e.displayContent);this.#b===e&&r&&(this.#v=r),this.#Ge(e,t)}catch(o){if(!r&&this.#Ke(o))return void await this.#Ve(e,n,!0);if(o instanceof kr&&("not_found"===o.code||"conversation_deleted"===o.code))return void this.#Ge(e,t);this.#Q("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#Ke(e){return e instanceof kr?"request_failed"===e.code:e instanceof Error}#Ge(e,t){let r=this.#je();if(!r||r.conversationId!==e)return;let n=new Set(t.map(e=>e.id)),o=r.messageIds.filter(e=>!n.has(e));this.#He(o.length?{conversationId:e,messageIds:o}:null)}async replayPendingProjections(){if(!this.#qe())return;let e=this.#je();if(!e)return;if(this.#b&&e.conversationId!==this.#b)return void this.#He(null);let t=[];for(let r of e.messageIds){let e=this.messages.find(e=>e.id===r);e&&"string"==typeof e.content&&t.push({id:r,displayContent:e.content})}0===t.length?this.#He(null):(this.#Ue(e.conversationId,t),await(this.#P?.catch(()=>{})))}#he(){this.#b&&(this.#v=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Je(){await this.awaitHistorySettled(),await this.#Fe(),"new_conversation_required"===this.#A&&await this.#Ne()}static#Qe(e){return e instanceof kr&&"conversation_deleted"===e.code}async#Xe(t,r,n,o,a){this.#_e(t);try{return void await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:n,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken},this.handleEvent)}catch(t){if(!e.#Qe(t))throw t;let s=await this.#Ye(o);if(!s)throw t;this.#_e([s]),await this.client.dispatch({messages:[s],signal:r.signal,assistantMessageId:n,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken},this.handleEvent)}}async#Ye(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let r={...t};this.#S+=1,this.#P=null,this.#Le(),this.#b=null,this.#v=null,this.#w=null,this.#k=!0;try{let e=this.#ee;if(e){let t=await e.prepareStartNew({context:this.#re()});await this.#Ee(t)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#M=!0,this.#A="new_conversation_required",this.#Y(),this.#Q("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#k=!1}return this.#Ce(r),this.#ce(!0),this.#Q("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(e=>e.id===r.id)??r}updateConfig(e){let t=this.config.features?.artifacts?.display,r={...this.config,...e},n=function(e,t){let r=e.voiceRecognition,n=t.voiceRecognition;return!0===r?.enabled!=(!0===n?.enabled)||r?.provider?.type!==n?.provider?.type||r?.provider?.custom!==n?.provider?.custom||r?.provider?.runtype?.createPlaybackEngine!==n?.provider?.runtype?.createPlaybackEngine||JSON.stringify(r?.provider?.runtype)!==JSON.stringify(n?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}(this.config,r),o=function(e,t){return bn.some(r=>e[r]!==t[r])}(this.config,r);this.config=r,n&&(this.cleanupVoice(),!0===r.voiceRecognition?.enabled&&ce(r.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(r.features?.artifacts?.display);if(!o)return this.client.updateConfig(r),void(a&&this.#Ze());this.#We(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.client=new Lr(this.config,this.historyInternals),a&&this.#Ze(),this.#we(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:n,contentParts:o,id:a,createdAt:s,sequence:i,streaming:l=!1,voiceProcessing:d,voiceCaption:c,rawContent:p}=e,u={id:a??("user"===t?dt():"assistant"===t?ct():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:r,createdAt:s??(new Date).toISOString(),sequence:i??this.#ye(),streaming:l,...void 0!==n&&{llmContent:n},...void 0!==o&&{contentParts:o},...void 0!==d&&{voiceProcessing:d},...c&&{voiceCaption:c},...void 0!==p&&{rawContent:p}};return this.upsertMessage(u),u}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 r of e){let{role:e,content:n,llmContent:o,contentParts:a,id:s,createdAt:i,sequence:l,streaming:d=!1,voiceProcessing:c,rawContent:p}=r,u={id:s??("user"===e?dt():"assistant"===e?ct():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:n,createdAt:i??(new Date).toISOString(),sequence:l??this.#ye(),streaming:d,...void 0!==o&&{llmContent:o},...void 0!==a&&{contentParts:a},...void 0!==c&&{voiceProcessing:c},...void 0!==p&&{rawContent:p}};t.push(u)}return this.messages=this.#be([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:n="",llmContent:o,id:a,createdAt:s,sequence:i}=e,l={text:n,component:t,props:r};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(l),...void 0!==o&&{llmContent:o},...void 0!==a&&{id:a},...void 0!==s&&{createdAt:s},...void 0!==i&&{sequence:i}})}async#et(e,t,r){let n;try{n=await r()}catch{return}let o=n.blocks.join("\n\n"),a=[o,t].filter(Boolean).join("\n\n"),s=Array.isArray(e.contentParts)&&e.contentParts.length>0,i=n.contentParts.length>0;if(s){let t=[];o&&t.push(fr(o)),t.push(...n.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(i){let t=[];a&&t.push(fr(a)),t.push(...n.contentParts),e.contentParts=t}else o&&(e.llmContent=a);Object.keys(n.context).length>0&&(e.mentionContext=n.context)}async sendMessage(e,t){let r=e.trim(),n=!!t?.replayFields&&(void 0!==t.replayFields.llmContent||void 0!==t.replayFields.rawContent||(t.replayFields.contextMentions?.length??0)>0);if(!(r||t?.contentParts&&0!==t.contentParts.length||t?.mentions&&0!==t.mentions.refs.length||n))return;this.#U&&!t?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#I||this.#P||this.#M||this.#W)&&await this.#Je(),this.stopSpeaking(),this.abortController?.abort(),this.#We(),this.#oe++,this.#$e();let o=t?.voiceTurn?.userMessageId,a=o?this.messages.find(e=>e.id===o&&"user"===e.role):void 0,s=a?.id??dt(),i=ct();this.#o=null;let l=t?.contentParts&&gr(t.contentParts)?"[Image]":"",d={id:s,role:"user",content:r||l,createdAt:(new Date).toISOString(),sequence:this.#ye(),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()!==r&&(a.llmContent=r),this.callbacks.onMessagesChanged([...this.messages])):this.#Ce(d),this.#ce(!0);let c=new AbortController;if(this.abortController=c,t?.mentions){let e=this.messages.find(e=>e.id===s)??d;if(await this.#et(e,r,t.mentions.finalize),c.signal.aborted||this.abortController!==c)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===s)??d,r=function(e){let t=function(e){let t=e?.text?.trim()??"";return t?function(e,t){let r="`".repeat(Math.max(3,function(e){let t=0;for(let r of e.split("\n")){let e=/^ {0,3}(`+)/.exec(r);e&&e[1].length>t&&(t=e[1].length)}return t}(t)+1));return`${r}${e}\n${t}\n${r}`}((e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text")(e),t):""}(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[fr(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join("\n\n")}:{}}({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});r.contentParts&&(e.contentParts=r.contentParts),void 0!==r.llmContent&&(e.llmContent=r.llmContent),(r.contentParts||void 0!==r.llmContent)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let p=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:(new Date).toISOString()}]:[...this.messages];try{await this.#Xe(p,c,i,s,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn})}catch(e){if("resuming"===this.status||this.#a)return;this.#U&&(this.#U.failed=!0);let t=e instanceof Error&&("AbortError"===e.name||e.message.includes("aborted")||e.message.includes("abort"));if(!t){let t=wn(e,this.config.errorMessage);if(t){let e={id:i,role:"assistant",createdAt:(new Date).toISOString(),content:t,sequence:this.#ye()};this.#Ce(e)}}this.#de("idle"),this.#ce(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}resubmitFrom(e,t){let r=function(e,t){let r=e.findIndex(e=>e.id===t);if(-1===r||"user"!==e[r].role)return null;let n=r+1;for(;n<e.length&&"user"!==e[n].role;)n+=1;return{start:r,end:n}}(this.messages,e);if(!r)return!1;let n=this.messages[r.start],o=t.replacement,a=o?o.text:n.content,s=o?o.contentParts:n.contentParts;if(!(a?.trim()||(s?.length??0)>0||!o&&(n.llmContent?.trim()?.length??0)>0))return!1;let i=o?void 0:{...void 0!==n.llmContent&&{llmContent:n.llmContent},...void 0!==n.rawContent&&{rawContent:n.rawContent},...n.mentionContext&&{mentionContext:n.mentionContext},...n.contextMentions&&{contextMentions:n.contextMentions},...n.quote&&{quote:n.quote}},l=o?this.#tt(o.options):n.composerOptions,d=o?o.contentSegments:n.contentSegments,c=o?o.options?.quote:void 0,p=o?o.viaVoice:n.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,r.start),this.sendMessage(a??"",{...s?.length?{contentParts:[...s]}:{},...d?.length?{contentSegments:[...d]}:{},...l?{composerOptions:l}:{},...c?{quote:c}:{},...i&&Object.keys(i).length>0?{replayFields:i}:{},viaVoice:!0===p}),!0}#tt(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.#I||this.#P||this.#M||this.#W)&&await this.#Je(),this.abortController?.abort(),this.#$e();let e=ct();this.#o=null,this.#ce(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(t){if("resuming"===this.status||this.#a)return;let r=t instanceof Error&&("AbortError"===t.name||t.message.includes("aborted")||t.message.includes("abort"));if(!r){let r=wn(t,this.config.errorMessage);if(r){let t={id:e,role:"assistant",createdAt:(new Date).toISOString(),content:r,sequence:this.#ye()};this.#Ce(t)}}this.#de("idle"),this.#ce(!1),this.abortController=null,r||(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.#o=t.assistantMessageId);let r=t?.preserveAssistantId?t.assistantMessageId:void 0,n=!1;for(let e of this.messages)e.streaming&&e.id!==r&&(e.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.#ce(!0);let o={};try{await this.client.processStream(e,e=>{let t=this.#t;this.#t=o;try{this.handleEvent(e)}finally{this.#t=t}},t?.assistantMessageId,t?.seedContent),this.#rt(o)}catch(e){if("resuming"===this.status||this.#a)return void this.#nt(o);this.#rt(o),this.#de("error"),0===this.webMcpResolveControllers.size&&(this.#ce(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#we(){let e=this.config.webmcp;!0===e?.enabled&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(!0===this.config.webmcp?.autoApprove?.(e))return Promise.resolve(!0)}catch{}let t={id:"webmcp-"+ ++this.#p,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(e=>{this.webMcpApprovalResolvers.set(r,e)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let n=this.messages.find(t=>t.id===e);n?.approval&&this.upsertMessage({...n,approval:{...n.approval,status:t,resolvedAt:Date.now()}}),r("approved"===t)}#ne;#oe;#ot(e){let t=this.#ne??={s:this,setStreaming:e=>this.#ce(e),appendMessage:e=>this.#Ce(e),nextSequence:()=>this.#ye(),settleApprovalPausedToolCall:e=>this.#at(e),resumeAfter:e=>this.#n?.executionId===e?this.#n.lastEventId:void 0},r=Ur();if(r)return e(r,t);let n=this.#oe;return _r().then(r=>n===this.#oe?e(r,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,r){return this.#ot((n,o)=>n.resolveApproval(o,e,t,r))}resolveAskUserQuestion(e,t){return this.#ot((r,n)=>r.resolveAskUserQuestion(n,e,t))}resolveWebMcpToolCall(e){return this.#ot((t,r)=>t.resolveWebMcpToolCall(r,e))}persistAskUserQuestionProgress(e,t){let r=this.messages.find(t=>t.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(t=>t.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#ae(e){let t=e.agentMetadata?.executionId,r=e.toolCall?.id;if(!t||!r){let t=this.#c;return void queueMicrotask(()=>{t===this.#c&&this.resolveWebMcpToolCall(e)})}let n=this.webMcpAwaitBatches.get(t);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,n)),!n.seen.has(r)&&(n.seen.add(r),n.snapshots.push(e))}#ge(){if(0===this.webMcpAwaitBatches.size)return;let e=this.#c;queueMicrotask(()=>{if(e===this.#c)for(let e of[...this.webMcpAwaitBatches.keys()])this.#st(e)})}#st(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;1===r.length?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.#ot((t,n)=>t.resolveWebMcpToolCallBatch(n,e,r))}#We(){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.#c++}cancel(){this.abortController?.abort(),this.abortController=null,this.#$e(),this.#We(),this.#oe++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#ce(!1),this.#de("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#$e(),this.#We(),this.#oe++,this.messages=[],this.agentExecution=null,this.#Re(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#ce(!1),this.#de("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#d}selectArtifact(e){this.#d=e,this.#xe()}clearArtifacts(){this.#Re()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,r="markdown"===e.artifactType?{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,r),this.#d=t,this.#xe(),!1!==e.transcript&&this.#it(r),r}#it(e){let t=`artifact-ref-${e.id}`,r=Qr(Jr(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}:{},...void 0===e.markdown?{}:{markdown:e.markdown}}),n=this.messages.find(e=>e.id===t);n?(n.rawContent=r,n.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:"",rawContent:r})}#Ze(){let e=!1;for(let t of this.artifacts.values()){let r=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!r)continue;let n=Qr(Jr(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}:{},...void 0===t.markdown?{}:{markdown:t.markdown}});r.rawContent!==n&&(r.rawContent=n,r.streaming="streaming"===t.status,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#Re(){(0!==this.artifacts.size||null!==this.#d)&&(this.artifacts.clear(),this.#d=null,this.#xe())}#xe(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#d})}#fe(e){switch(e.type){case"artifact_start":"markdown"===e.artifactType?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.#d=e.id;break;case"artifact_delta":{let t=this.artifacts.get(e.id);"markdown"===t?.artifactType&&(t.markdown=(t.markdown??"")+e.artDelta);break}case"artifact_update":{let t=this.artifacts.get(e.id);"component"===t?.artifactType&&(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.#xe()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#$e(),this.#We(),this.#oe++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#be(e.map(e=>({...e,streaming:!1,sequence:e.sequence??this.#ye()}))),this.#ce(!1),this.#de("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.#d=t,this.#xe()}#se(e){let t=this.agentExecution?.executionId;if(!t||!this.#o||"running"!==this.agentExecution?.status)return;let r=null===this.#n;this.#n={executionId:t,lastEventId:e,assistantMessageId:this.#o,status:"running"},this.#lt(r)}#ie(){return null!==this.#n&&"function"==typeof this.config.reconnectStream&&!0!==this.abortController?.signal.aborted&&0===this.webMcpResolveControllers.size&&0===this.webMcpAwaitBatches.size&&!this.#pe()}#pe(){return this.messages.some(e=>!0===e.agentMetadata?.awaitingLocalTool&&!0!==e.agentMetadata?.askUserQuestionAnswered||"approval"===e.variant&&"pending"===e.approval?.status)}#le(){this.#a||this.#n&&"function"==typeof this.config.reconnectStream&&(this.#a=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#n}),this.#ce(!0),this.#de("resuming"),this.#dt().then(e=>{this.#a&&this.#n&&e.begin()}))}#dt(){return this.#s?Promise.resolve(this.#s):(this.#i||(this.#i=yn().then(({createReconnectController:e})=>{let t=e(this.#ct());return this.#s=t,t}),this.#i.catch(()=>{this.#i=null})),this.#i)}#ct(){let e=this;return{get config(){return e.config},getResumable:()=>e.#n,clearResumable:()=>e.#ue(),getStatus:()=>e.status,setStatus:t=>e.#de(t),setStreaming:t=>e.#ce(t),setReconnecting:t=>{e.#a=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,n)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:n}),appendMessage:t=>e.#Ce(t),nextSequence:()=>e.#ye(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>wn(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#a?this.#s?.wake():this.#le()}resumeFromHandle(e){if("function"!=typeof this.config.reconnectStream||this.#a)return;let t=this.#pt();t||(t=ct(),this.#Ce({id:t,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,sequence:this.#ye()})),this.#o=t,this.agentExecution||={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0},this.#n={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.#le()}#pt(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if("assistant"===t.role&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if("user"===t.role)break}return null}#$e(){this.#a=!1,this.#s?.teardown(),this.#ue()}#ue(){this.#l&&=(clearTimeout(this.#l),null);let e=null!==this.#n;this.#n=null,e&&this.config.onExecutionState?.(null)}#lt(e){let t=this.config.onExecutionState;t&&(e?(this.#l&&=(clearTimeout(this.#l),null),t(this.#n)):this.#l||=setTimeout(()=>{this.#l=null,this.config.onExecutionState?.(this.#n)},500))}getResumableHandle(){return this.#n}#de(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#ce(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#rt(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||t.provider&&"browser"!==t.provider&&("runtype"!==t.provider||!t.browserFallback))return;let r=[...this.messages].reverse().find(e=>"assistant"===e.role&&e.content&&!e.voiceProcessing);if(!r||e&&!e.includes(r.id))return;if(this.ttsSpokenMessageIds.has(r.id))return void this.ttsSpokenMessageIds.delete(r.id);let n=pn(r.content);n.trim()&&this.readAloud.play(r.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return en(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||"assistant"!==t.role)return;let r=pn(t.content||"");if(!r.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:n?.voice,rate:n?.rate,pitch:n?.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()}#rt(e){for(let[t,r]of[...this.#e])r===e&&(this.#e.delete(t),this.#at(t))}#nt(e){for(let[t,r]of this.#e)r===e&&this.#e.set(t,void 0)}#at(e){let t=this.messages.find(t=>t.id===e)?.approval,r=t?.toolCallId,n=r&&this.messages.find(e=>e.toolCall?.id===r),o=n&&n.toolCall;if(!o||"complete"===o.status||"pending"===t.status)return;let a={...o,status:"complete",approvalStatus:t.status,completedAt:Date.now(),..."approved"===t.status?{superseded:!0}:{success:!1,error:"denied"===t.status?"Denied":"Approval timed out"}};this.upsertMessage({...n,streaming:!1,toolCall:a})}#Ce(e){let t=this.#Te(e);this.messages=this.#be([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#Te(e),r=this.messages.findIndex(e=>e.id===t.id);-1===r?this.#Ce(t):(this.messages=this.messages.map((e,n)=>{if(n!==r)return e;let o={...e,...t};!0===e.agentMetadata?.askUserQuestionAnswered&&t.agentMetadata&&(o.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),!0===e.agentMetadata?.suggestRepliesResolved&&t.agentMetadata&&(o.agentMetadata={...o.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&o.agentMetadata&&!o.agentMetadata.clientToolAnswer&&(o.agentMetadata={...o.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let r=e.approval,n=t.approval;o.approval={...r,...n,executionId:n.executionId||r.executionId,toolName:n.toolName||r.toolName,description:n.description||r.description,toolType:n.toolType??r.toolType,reason:n.reason??r.reason,parameters:n.parameters??r.parameters,toolCallId:n.toolCallId??r.toolCallId}}let s=t.toolCall?.name,i=t.agentMetadata?.executionId,l=t.toolCall?.id;if(s&&xn(s)&&i&&l&&!0===t.agentMetadata?.awaitingLocalTool){let t=`${i}:${l}`,r=this.webMcpInflightKeys.has(t),n=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,s=e.agentMetadata?.executionId===i&&e.toolCall?.id===l&&void 0!==a&&xn(a)&&"complete"===e.toolCall?.status;(r||n||s)&&(o.agentMetadata={...o.agentMetadata??{},awaitingLocalTool:!1},o.toolCall=e.toolCall,o.streaming=e.streaming)}return o}),this.messages=this.#be(this.messages),this.callbacks.onMessagesChanged([...this.messages]))}#Te(e){return void 0===e.sequence?{...e,sequence:this.#ye()}:{...e}}#ye(){return this.#r++}#be(e){return[...e].sort((e,t)=>{let r=new Date(e.createdAt).getTime(),n=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(n)&&r!==n)return r-n;let o=e.sequence??0,a=t.sequence??0;return o===a?e.id.localeCompare(t.id):o-a})}};let Sn={add:e=>async function(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result;vr(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},n.onerror=()=>r(Error("Failed to read file")),n.readAsDataURL(e)})}(e)},kn={allowedTypes:br,maxFileSize:10485760,maxFiles:4};function An(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Mn(e){return"application/pdf"===e||e.startsWith("text/")||e.includes("word")?r.FileText:e.includes("excel")||e.includes("spreadsheet")?r.FileSpreadsheet:"application/json"===e?r.FileCode:r.File}var In=class e{#e;#t;#r;constructor(e={}){this.attachments=[],this.#e=null,this.#t=new Map,this.#r=!1,this.config={allowedTypes:e.allowedTypes??kn.allowedTypes,maxFileSize:e.maxFileSize??kn.maxFileSize,maxFiles:e.maxFiles??kn.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#n(){return"function"==typeof this.config.adapter?.add}#o(){return this.#n()?this.config.adapter:Sn}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML="";for(let e of this.attachments)this.#d(e)}this.#u()}updateConfig(e){void 0!==e.allowedTypes&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:kn.allowedTypes),void 0!==e.maxFileSize&&(this.config.maxFileSize=e.maxFileSize),void 0!==e.maxFiles&&(this.config.maxFiles=e.maxFiles),void 0!==e.onFileRejected&&(this.config.onFileRejected=e.onFileRejected),void 0!==e.onAttachmentsChange&&(this.config.onAttachmentsChange=e.onAttachmentsChange),void 0!==e.adapter&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>"ready"===e.status)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>null!==e)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){e&&0!==e.length&&await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#r)return;let t=[];for(let r of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(r,"count");continue}let e=wr(r,this.config.allowedTypes,this.config.maxFileSize);if(!e.valid){let t=e.error?.includes("type")?"type":"size";this.config.onFileRejected?.(r,t);continue}let n={id:An(),file:r,previewUrl:vr(r)?URL.createObjectURL(r):null,contentPart:null,status:this.#n()?"uploading":"processing",progress:this.#n()?0:void 0};this.attachments.push(n),this.#d(n),t.push(n)}this.#u(),this.#l(),await Promise.all(t.map(e=>this.#a(e)))}async#a(e){let t=new AbortController;this.#t.set(e.id,t);let r=()=>this.#r||t.signal.aborted||this.#t.get(e.id)!==t||!this.attachments.includes(e);try{let n=await this.#o().add(e.file,{signal:t.signal,onProgress:t=>{r()||"uploading"!==e.status||(e.progress=(e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0)(t),this.#c(e),this.#l())}});if(r())return;e.contentPart=n,e.status="ready",e.progress=void 0,e.error=void 0}catch(t){if(r())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.#c(e),this.#l()}retryAttachment(e){let t=this.attachments.find(t=>t.id===e);!t||"error"!==t.status||this.#r||(t.status=this.#n()?"uploading":"processing",t.progress=this.#n()?0:void 0,t.error=void 0,this.#c(t),this.#l(),this.#a(t))}#s(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(-1===t)return;let r=this.attachments[t];this.#s(e),r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let n=this.#e?.querySelector(`[data-attachment-id="${e}"]`);n&&n.remove(),"ready"===r.status&&r.contentPart&&this.#i(r.contentPart),this.#u(),this.#l()}#i(e){let t=this.config.adapter?.remove;if(t)try{let r=t(e,{signal:(new AbortController).signal});r&&"function"==typeof r.catch&&r.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.#s(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=""),this.#u(),this.#l()}destroy(){if(!this.#r){this.#r=!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}}#l(){this.#r||this.config.onAttachmentsChange?.(this.getAttachments())}#d(e){if(!this.#e)return;let t=vr(e.file),o=L("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",t&&e.previewUrl){let t=L("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",o.appendChild(t)}else{let t=L("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=Mn(e.file.type),a=n(r,20,"var(--persona-muted, #6b7280)",1.5);a&&t.appendChild(a);let s=L("span");s.textContent=function(e,t){let r=function(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}(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]||r||"FILE"}(e.file.type,e.file.name),s.style.fontSize="8px",s.style.fontWeight="600",s.style.color="var(--persona-muted, #6b7280)",s.style.textTransform="uppercase",s.style.lineHeight="1",t.appendChild(s),o.appendChild(t)}let a=P("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=L("div","persona-attachment-progress");s.appendChild(L("div","persona-attachment-progress__bar"));let i=P("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=K("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):i.textContent="↻",i.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),a.append(s,i),o.appendChild(a);let d=L("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let c=n(r.X,10,"var(--persona-text-inverse, #ffffff)",2);c?d.appendChild(c):(d.textContent="×",d.style.color="var(--persona-text-inverse, #ffffff)",d.style.fontSize="14px",d.style.lineHeight="1"),d.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(d),this.#e.appendChild(o),this.#p(o,e)}#c(e){let t=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);t&&this.#p(t,e)}#p(e,t){e.dataset.status=t.status;let r="ready"!==t.status&&"error"!==t.status;e.setAttribute("aria-busy",r?"true":"false"),e.title="error"===t.status?`${t.file.name}: ${t.error??"Upload failed"}`:t.file.name;let n=e.querySelector(".persona-attachment-progress__bar");if(n){let e=t.progress;n.style.width="number"==typeof e?`${Math.round(100*e)}%`:""}}#u(){this.#e&&(this.#e.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:r,adapter:t?.adapter})}};let Tn=(e,t)=>e.length===t.length&&e.every((e,r)=>e===t[r]);function En(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,r=null,n=!1,o=!1,a=()=>(r||=(()=>{let t=e.preparing?"preparing":e.streaming?"streaming":"idle";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:"idle"!==t||e.sendDisabled||e.inputDisabled})})(),r),s=()=>{if(n=!1,o||0===t.size)return;let e=a();for(let r of[...t])try{r(e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",e)}},i=()=>{r=null,!o&&!n&&(n=!0,queueMicrotask(s))};return{getState:a,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,i())},setAttachments:t=>{((e,t)=>e.length===t.length&&e.every((e,r)=>{let n=t[r];return e.id===n.id&&e.name===n.name&&e.mimeType===n.mimeType&&e.size===n.size&&e.status===n.status&&e.progress===n.progress&&e.error===n.error}))(e.attachments,t)||(e.attachments=[...t],i())},setMentionRefs:t=>{Tn(e.mentionRefs,t)||(e.mentionRefs=[...t],i())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,i())},setActiveModeIds:t=>{Tn(e.activeModeIds,t)||(e.activeModeIds=[...t],i())},setQuote:t=>{let r=e.quote;(r?.text!==t?.text||r?.messageId!==t?.messageId||r?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,i())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,i())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,i())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,i())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,i())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,i())},flush:()=>{n&&s()},destroy:()=>{o=!0,n=!1,t.clear()}}}let Ln=(e,...t)=>{for(let r of t){let t=e.querySelector(r);if(t)return t}return null},Pn=(e,t)=>{let r=L("div",e);return r.setAttribute(t,""),r.setAttribute("data-persona-composer-synthesized",""),r.style.display="contents",r};function Bn(e,t={}){let r=Ln(e,"[data-persona-composer-form]"),n=Ln(e,"[data-persona-composer-input]");if(!r||!n){let e=`[Persona] composer surface is missing required element(s): ${[!r&&"form",!n&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(r||n))throw Error(e);return typeof console<"u"&&console.warn(e),null}let o={header:Ln(e,"[data-persona-composer-header]"),body:Ln(e,"[data-persona-composer-body]"),actionsStart:Ln(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Ln(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Ln(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Ln(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Ln(e,"[data-persona-composer-status]")},a=new Set,s=o.header;s||(a.add("header"),s=Pn("persona-widget-composer__header","data-persona-composer-header"),r.parentNode?r.parentNode.insertBefore(s,r):e.appendChild(s));let i=o.body??n.parentElement??r,l=(e,t,r,n,o)=>{if(t)return t;a.add(e);let s=Pn(r,n);return o.appendChild(s),s},d=l("actionsStart",o.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",r),c=l("actionsEnd",o.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",r),p=l("suggestions",o.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),u=l("status",o.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[];return{footer:e,form:r,input:n,header:s,body:i,actionsStart:d,actionsEnd:c,suggestions:p,status:u,attachmentInput:Ln(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0,attachmentPreviews:Ln(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Ln(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Ln(e,"[data-persona-composer-submit]")??void 0,micButton:Ln(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:o,addListener:(e,t,r,n)=>{e.addEventListener(t,r,n),h.push({target:e,type:t,handler:r,options:n})},removeListener:(e,t,r,n)=>{e.removeEventListener(t,r,n),h=h.filter(n=>!((e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler)(n,{target:e,type:t,handler:r}))},destroy:()=>{for(let e of h)e.target.removeEventListener(e.type,e.handler,e.options);h=[]}}}let Nn=200,Rn=300,Hn=0,$n=e=>Math.max(0,e);function Wn(e){void 0!==e.delayMs&&(Nn=$n(e.delayMs)),void 0!==e.skipDelayMs&&(Rn=$n(e.skipDelayMs))}let Dn=new WeakMap,Fn=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,On=(e,t,r)=>Math.min(Math.max(e,t),Math.max(t,r)),zn=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"];function qn(e){Dn.get(e.anchor)?.destroy();let t,{anchor:r,trigger:n=r,text:o,hint:a,enabled:s=!0,gap:i=8,viewportPadding:l=8}=e,d=()=>r.ownerDocument,c=()=>d().defaultView??window,p=null,u=null,h=null,m=null,g=!1,f=!1,y=!1,b=()=>("function"==typeof o?o():o).trim(),v=()=>("function"==typeof a?a():a??"").trim(),w=()=>$n(e.delayMs??Nn),x=()=>$n(e.skipDelayMs??Rn),C=()=>{void 0!==t&&(c().clearTimeout(t),t=void 0)},S=()=>{C();let e=null!==p;m?.(),m=null,p?.remove(),p=null,u=null,h=null,e&&(e=>{Hn=e>0?Date.now()+e:0})(x())},k=()=>{if(!p)return;let e=d(),t=c(),n=r.getBoundingClientRect(),o=p.getBoundingClientRect(),a=e.documentElement.clientWidth||t.innerWidth,s=e.documentElement.clientHeight||t.innerHeight,u=a-l-o.width,h=n.left+n.width/2-o.width/2,m=On(h,l,u),g=n.top-l,f=s-l-n.bottom,y=g>=o.height+i||g>=f?"top":"bottom",b="top"===y?n.top-i-o.height:n.bottom+i,v=s-l-o.height,w=On(b,l,v),x=n.left+n.width/2,C=Math.max(10,o.width-10),S=On(x-m,10,C);p.dataset.placement=y,p.style.left=`${m}px`,p.style.top=`${w}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${S}px`)},A=()=>{if(y||!s||p||!r.isConnected||(e=>"function"==typeof e.closest&&null!==e.closest("[data-persona-tooltip-suppressed]"))(r))return;let e=b(),t=(e=>{let t=e.getRootNode?.();return Fn(t)?t:e.ownerDocument.body})(r);if(!e||!t)return;let n=d(),o=c();p=n.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex="100001";let a=o.getComputedStyle?.(r);if(a){for(let e of zn){let t=a.getPropertyValue(e).trim();t&&p.style.setProperty(e,t)}a.fontFamily&&(p.style.fontFamily=a.fontFamily)}u=n.createElement("span"),u.className="persona-control-tooltip__label",u.textContent=e,p.appendChild(u);let i=v();i&&(h=n.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=i,p.appendChild(h));let l=n.createElement("span");l.className="persona-control-tooltip__arrow",p.appendChild(l),t.appendChild(p),k(),p.dataset.state="open";let g=()=>{r.isConnected?(u&&(u.textContent=b()),h&&(h.textContent=v()),k()):S()};o.addEventListener("scroll",g,!0),o.addEventListener("resize",g);let f=r.getRootNode(),w=Fn(f)?f:n.documentElement,x=typeof MutationObserver>"u"?null:new MutationObserver(()=>{r.isConnected||S()});x?.observe(w,{childList:!0,subtree:!0}),m=()=>{o.removeEventListener("scroll",g,!0),o.removeEventListener("resize",g),x?.disconnect()}},M=()=>{g||f?(e=>{y||p||(C(),e||w()<=0||Date.now()<Hn?A():t=c().setTimeout(()=>{t=void 0,A()},w()))})(f):S()},I=()=>{let e=c();e.matchMedia&&e.matchMedia("(hover: none)").matches||(g=!0,M())},T=()=>{g=!1,M()},E=()=>{try{f=r.matches(":focus-visible")}catch{f=!0}M()},L=()=>{f=!1,M()},P=()=>{g=!1,f=!1,S()},B=e=>{"Escape"===e.key&&P()};n.addEventListener("mouseenter",I),n.addEventListener("mouseleave",T),r.addEventListener("focus",E),r.addEventListener("blur",L),r.addEventListener("keydown",B),r.addEventListener("click",P);let N={get isOpen(){return null!==p},show:A,hide:S,reposition:k,destroy:()=>{y||(y=!0,S(),n.removeEventListener("mouseenter",I),n.removeEventListener("mouseleave",T),r.removeEventListener("focus",E),r.removeEventListener("blur",L),r.removeEventListener("keydown",B),r.removeEventListener("click",P),Dn.delete(r))}};return Dn.set(r,N),N}function jn(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let r=t.getComputedStyle(e).lineHeight;if(!r||!r.trim().endsWith("px"))return 20;let n=parseFloat(r);return Number.isFinite(n)&&n>0?n:20}function _n(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function Un(e,t){e.style.maxHeight=t*jn(e)+"px",e.style.overflowY="auto"}function Vn(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||"function"!=typeof t.matchMedia)return!1;try{return!0===t.matchMedia("(pointer: coarse)").matches}catch{return!1}}function Gn(e){return!0===e.insertNewlineOnTouchEnter&&!0===e.coarsePointer}function Kn(e,t){if("Enter"!==e.key||e.shiftKey||e.isComposing)return!1;let r=!0===e.metaKey||!0===e.ctrlKey,n=t.submitKey??"enter";return"none"!==n&&("mod-enter"===n?r:r||!Gn(t))}function Jn(e,t){e.setAttribute("enterkeyhint",function(e){return"enter"===(e.submitKey??"enter")?Gn(e)?"enter":"send":"enter"}(t))}function Qn(e,t){let r=t?.autocomplete;e.setAttribute("autocomplete","string"==typeof r&&r?r:"off");let n=(t,r)=>{void 0===r?e.removeAttribute(t):e.setAttribute(t,r)};n("autocapitalize","string"==typeof t?.autocapitalize?t.autocapitalize:void 0),n("spellcheck","boolean"==typeof t?.spellcheck?String(t.spellcheck):void 0),n("inputmode","string"==typeof t?.inputmode&&t.inputmode?t.inputmode:void 0),n("aria-label","string"==typeof t?.ariaLabel&&t.ariaLabel?t.ariaLabel:void 0)}function Xn(e){return!0===e?{disabled:!0}:e&&"object"==typeof e?{disabled:!0,reason:"string"==typeof e.reason&&e.reason?e.reason:void 0}:{disabled:!1}}let Yn="persona-composer-control",Zn="persona-composer-control--glyph",eo=(e,t,r)=>{let n=e.ownerDocument?.defaultView;if(!n)return;let o=n.getComputedStyle(e);for(let e of r){let r=o.getPropertyValue(e).trim();r?t.style.setProperty(e,r):t.style.removeProperty(e)}},to=(e,t)=>{let r=L("textarea");r.setAttribute("data-persona-composer-input",""),r.placeholder=e?.copy?.inputPlaceholder??"How can I help...",r.dir="auto",Jn(r,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Vn(r)}),Qn(r,e?.composer?.inputAttributes),r.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",r.rows=1,r.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',r.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=_n(e?.composer?.maxLines,t?.defaultMaxLines??3),o=20*n+"px";return r.style.maxHeight=o,r.style.overflowY="auto",r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.addEventListener("focus",()=>{r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.style.boxShadow="none"}),r.addEventListener("blur",()=>{r.style.border="none",r.style.outline="none"}),{textarea:r,attachAutoResize:()=>{r.addEventListener("input",()=>{r.style.height="auto";let e=Math.min(r.scrollHeight,(()=>{let e=r.style.maxHeight;if(e!==o){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=n*jn(r);return o=`${t}px`,r.style.maxHeight=o,t})());r.style.height=`${e}px`})}}},ro=(e,t,r="send")=>{let n=P("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":r,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),n.append(e,t),n},no=e=>{let t=e?.sendButton??{},r=t.useIcon??!1,n=t.iconText??"↑",o=t.iconName,a=t.stopIconName??"square",s=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",l=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,p=t.size,u=parseFloat(p??"")||40,h=t.backgroundColor,m=t.textColor,g=L("div","persona-send-button-wrapper"),f=P("button",{className:B("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?`persona-flex persona-items-center persona-justify-center ${Yn}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!h&&"persona-bg-persona-primary",!r&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:r?p:void 0,height:r?p:void 0,minWidth:r?p:void 0,minHeight:r?p:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?m||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":m||void 0,backgroundColor:r&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:r?"0":t.paddingX||void 0,paddingRight:r?"0":t.paddingX||void 0,paddingTop:r?"0":t.paddingY||void 0,paddingBottom:r?"0":t.paddingY||void 0}}),y=null,b=null,v=null;if(r){let e=parseFloat(t.iconSize??"")||Math.round(.5*u),r=t.iconStrokeWidth??2,s=m?.trim()||"currentColor";if(o&&(y=K(o,e,s,r)),b=K(a,e,s,r),!t.iconSize)for(let t of[y,b])t&&(t.style.width=`var(--persona-components-composer-sendIconSize, ${e}px)`,t.style.height=`var(--persona-components-composer-sendIconSize, ${e}px)`);y&&b?(v=ro(y,b),f.appendChild(v)):y?f.appendChild(y):(f.textContent=n,b=null)}else f.textContent=l;f.setAttribute("aria-label",s),g.appendChild(f),qn({anchor:f,trigger:g,text:()=>f.getAttribute("aria-label")??"",enabled:c});let w="send";return{button:f,wrapper:g,setMode:e=>{if(e===w)return;w=e;let t="stop"===e?i:s;f.setAttribute("aria-label",t),f.setAttribute("data-persona-send-mode",e),r?(f.querySelector("[data-persona-glyph-stack]")??v)?.setAttribute("data-mode",e):f.textContent="stop"===e?d:l},glyphStack:v}},oo=e=>{let t=e?.voiceRecognition??{};if(!0!==t.enabled)return null;let r=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),n="runtype"===t.provider?.type,o="custom"===t.provider?.type;if(!(r||n||o))return null;let a=t.iconName??"mic",s=t.iconSize,i=parseFloat(s??"")||24,l=t.backgroundColor??e?.sendButton?.backgroundColor,d=t.iconColor??e?.sendButton?.textColor,c=L("div","persona-send-button-wrapper"),p=P("button",{className:B("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Yn,!s&&"persona-composer-control--glyph"),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",color:d||"var(--persona-text, #111827)",backgroundColor:l||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}}),u=K(a,i,d||"currentColor",1.5);u?p.appendChild(u):p.textContent="🎤",c.appendChild(p);let h=t.tooltipText??"Start voice recognition";return qn({anchor:p,trigger:c,text:()=>p.getAttribute("aria-label")??h,enabled:t.showTooltip??!1}),{button:p,wrapper:c}},ao=e=>{let t=e?.attachments??{};if(!0!==t.enabled)return null;let r=L("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let n=L("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??br).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let o=t.buttonIconName??"paperclip",a=L("div","persona-send-button-wrapper"),s=P("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Yn} ${Zn}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),i=K(o,24,"currentColor",1.5);i?s.appendChild(i):s.textContent="📎",s.addEventListener("click",e=>{e.preventDefault(),n.click()}),a.appendChild(s);let l=t.buttonTooltipText??"Attach file";return qn({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??l}),{button:s,wrapper:a,input:n,previewsContainer:r}},so=e=>{let t=e?.statusIndicator??{},r="left"===t.align?"persona-text-left":"center"===t.align?"persona-text-center":"persona-text-right",n=L("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status",""),le(n,t,"idle");let o=t.idleText??"Online";if(t.idleLink){let e=L("a");e.href=t.idleLink,e.target="_blank",e.rel="noopener noreferrer",e.textContent=o,e.style.color="inherit",e.style.textDecoration="none",n.appendChild(e)}else n.textContent=o;return n},io=()=>P("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function lo(e){let{anchor:t,content:r,placement:n="bottom-start",offset:o=6,matchAnchorWidth:a=!1,horizontalOffset:s,verticalOffset:i,zIndex:l=2147483e3,onOpen:d,onDismiss:c}=e,p=e.container??function(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}(t),u=!1,h=null,m=()=>{if(!u)return;let e=t.getBoundingClientRect();r.style.position="fixed",a&&(r.style.minWidth=`${e.width}px`),s&&(r.style.maxWidth=`${e.width}px`);let l=r.getBoundingClientRect(),d=i?.()??null,c=null==d?e.top:e.top+d,p="top-start"===n||"top-end"===n?c-o-l.height:e.bottom+o,h="bottom-end"===n||"top-end"===n?e.right-l.width:e.left,m=s?.()??null;if(null!=m){let t=Math.max(e.left,e.right-l.width);h=Math.min(Math.max(e.left+m,e.left),t)}r.style.top=`${p}px`,r.style.left=`${h}px`},g=()=>{u&&(u=!1,h&&=(h(),null),r.remove())},f=()=>{if(u)return;u=!0,null!=l&&(r.style.zIndex=String(l)),p.appendChild(r),m();let e=(t.ownerDocument??document).defaultView??window,n=t.ownerDocument??document,o=()=>{t.isConnected?m():(g(),c?.("anchor-removed"))},a=e=>{let n="function"==typeof e.composedPath?e.composedPath():[];n.includes(r)||n.includes(t)||(g(),c?.("outside"))},s=e.setTimeout(()=>{n.addEventListener("pointerdown",a,!0)},0);e.addEventListener("scroll",o,!0),e.addEventListener("resize",o),h=()=>{e.clearTimeout(s),n.removeEventListener("pointerdown",a,!0),e.removeEventListener("scroll",o,!0),e.removeEventListener("resize",o)},d?.()};return{get isOpen(){return u},open:f,close:g,toggle:()=>u?g():f(),reposition:m,destroy:g}}let co=["--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"],po="data-persona-menu-focus",uo=new Set(["ArrowDown","ArrowUp","Home","End"]);function ho(e){return"menuitem"===e.getAttribute("role")?e:e.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')??e}let mo=1e3,go="data-persona-composer-action",fo="data-persona-composer-disable-when-streaming";function yo(e){let t=e.clientWidth;if(!t)return 0;let r=e.ownerDocument?.defaultView;if(!r?.getComputedStyle)return t;let n=r.getComputedStyle(e),o=(Number.parseFloat(n.paddingLeft)||0)+(Number.parseFloat(n.paddingRight)||0);return Math.max(0,t-o)}let bo=(e,t)=>{e&&typeof console<"u"&&console.warn(t)},vo=e=>"plugin"===e.source?`plugin "${e.pluginId}"`:"config"===e.source?"composer.actions":"a core built-in",wo=(e,t,r)=>void 0===e?r:"function"==typeof e?!0===e(t):!0===e;function xo(e,t){if(!e||"always"===e)return!0;let r=(e=>"streaming"===e.phase||e.text.trim().length>0||e.attachments.length>0)(t);return"when-text"===e?r:!r}let Co=e=>"custom"===e.kind,So=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e;function ko(e){let t=new Map,r=[],n=!1,o=()=>e.getButtonSize?.(),a=(e,t)=>{let r=e.button;if(!r)return;if(r.setAttribute("aria-label",t.label),void 0===t.pressed?r.removeAttribute("aria-pressed"):r.setAttribute("aria-pressed",t.pressed?"true":"false"),r.toggleAttribute(fo,!0===t.disableWhenStreaming),"menu"===e.mode)return e.tooltip?.destroy(),e.tooltip=void 0,void((e,t)=>{let r=e.button;if(!r)return;r.setAttribute("role","menuitem"),r.setAttribute("tabindex","-1"),r.className="persona-composer-overflow-menu__item";for(let e of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])r.style[e]="";r.style.lineHeight="1",t.tooltipText?r.setAttribute("title",t.tooltipText):r.removeAttribute("title"),r.replaceChildren();let n=L("span","persona-composer-overflow-menu__icon");if(t.iconName){let e=K(t.iconName,16,"currentColor",1.5);e&&n.appendChild(e)}let o=L("span","persona-composer-overflow-menu__label");o.textContent=t.shortLabel??t.label,r.append(n,o)})(e,t);r.removeAttribute("role"),r.removeAttribute("tabindex"),r.removeAttribute("title");let n=o(),a=!!t.shortLabel;if(r.className=B("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Yn,Zn,a&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),r.style.width=n&&!a?n:"",r.style.height=n??"",r.style.minWidth=n&&!a?n:"",r.style.minHeight=n??"",r.style.fontSize=a?"":"18px",r.style.lineHeight="1",r.style.color=t.iconColor??"",r.style.backgroundColor=t.backgroundColor??"",r.replaceChildren(),t.iconName){let e=K(t.iconName,24,"currentColor",1.5);e&&r.appendChild(e)}if(a){let e=L("span","persona-composer-action-button__label");e.textContent=t.shortLabel,r.appendChild(e)}else r.firstChild||(r.textContent=t.label);e.tooltip?.destroy(),e.tooltip=qn({anchor:r,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,r)=>{let n=t.action,o=P("button",{attrs:{type:"button"}}),s=o;if("bar"===r){let e=L("div","persona-send-button-wrapper");e.appendChild(o),s=e}s.setAttribute(go,t.id);let i={resolved:t,element:s,button:o,owned:!0,managed:!0,busy:!1,visible:!0,mode:r},l=t=>{if(t.preventDefault(),t.stopPropagation(),i.busy||o.disabled)return;let r,n=i.resolved.action;"menu"===i.mode&&u?.close(!0);try{r=n.onSelect(e.actionContext,t)}catch(t){return void e.reportError(t,{actionId:i.resolved.id})}r&&"function"==typeof r.then&&(i.busy=!0,o.setAttribute("aria-busy","true"),r.catch(t=>{e.reportError(t,{actionId:i.resolved.id})}).finally(()=>{i.busy=!1,o.removeAttribute("aria-busy")}))};return o.addEventListener("click",l),i.detach=()=>o.removeEventListener("click",l),a(i,n),i},i=t=>{let r,n=t.action;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(go,t.id),r.element.toggleAttribute(fo,!0===n.disableWhenStreaming),{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:!0===e.builtIn.managed,busy:!1,visible:!0,mode:"bar"}:null}let r=e.action;return r?Co(r)?i(e):s(e,t):null},d=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(r){e.reportError(r,{actionId:t.resolved.id})}t.element.remove()}},c=(e,t)=>{for(let r=0;r<t.length;r++){let n=t[r];if(!n.managed)continue;let o=null;for(let n=r+1;n<t.length;n++){let r=t[n];if(!r.managed&&r.element.parentElement===e){o=r.element;break}}o?(n.element.parentElement!==e||n.element.nextSibling!==o)&&e.insertBefore(n.element,o):e.lastChild!==n.element&&e.appendChild(n.element)}},p=(e,t)=>{if(e.button)return void(e.button.disabled=t);if(!e.owned)return;let r=e.element;r.toggleAttribute("data-disabled",t),r.setAttribute("aria-disabled",t?"true":"false");let n=r instanceof HTMLButtonElement||r instanceof HTMLSelectElement||r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement?r:r.querySelector("button, select, input, textarea");n&&(n.disabled=t)},u=null,h=null,m=null,g=0,f=()=>(u?u.setLabel(e.getOverflowLabel?.()??"More actions"):u=function(e){let t=e.label,r=!1,n=L("div","persona-send-button-wrapper"),o=P("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Yn} ${Zn}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});n.appendChild(o);let a=P("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),s=()=>{let t=e.getButtonSize?.()??"";o.style.width=t,o.style.height=t,o.style.minWidth=t,o.style.minHeight=t,o.style.lineHeight="1",o.replaceChildren();let r=K("plus",24,"currentColor",1.5);r?o.appendChild(r):o.textContent="+"},i=()=>{o.setAttribute("aria-label",t),o.setAttribute("title",t),a.setAttribute("aria-label",t)};i(),s();let l=[],d=-1,c=!1,p=()=>{let e=(()=>{let e=a.getRootNode().activeElement;return e instanceof HTMLElement?e:null})();for(let t of l){let r=!!e&&ho(t)===e;t.toggleAttribute(po,r&&c)}},u=()=>l.filter(e=>e.isConnected||a.contains(e)).map(ho).filter(e=>!(e=>!0===e.disabled||"true"===e.getAttribute("aria-disabled"))(e)),h=(e,t)=>{e.forEach((e,r)=>{e.setAttribute("tabindex",r===t?"0":"-1")})},m=e=>{let t=u();if(0===t.length)return;let r=(e%t.length+t.length)%t.length;d=r,h(t,r),t[r].focus(),p()},g=()=>n.ownerDocument??document,f=null,y=null,b=null,v=()=>{f&&=(g().removeEventListener("focusin",f,!0),null)},w=()=>{y&&=(a.removeEventListener("focusin",y),null),b&&=(a.removeEventListener("pointerdown",b,!0),null)},x=null,C=()=>!0===x?.isOpen,S=(e=!1)=>{if(C()){x?.close(),o.setAttribute("aria-expanded","false"),v(),w(),d=-1,c=!1;for(let e of l)e.removeAttribute(po);e&&o.focus()}},k=(e=0,t=!1)=>{if(r||C())return;c=t,eo(o,a,co),(x||=lo({anchor:o,content:a,placement:"top-start",offset:6,onDismiss:()=>{o.setAttribute("aria-expanded","false"),v()}}),x).open(),o.setAttribute("aria-expanded","true");let s=u();h(s,-1),m(e<0?s.length-1:e),f=e=>{let t="function"==typeof e.composedPath?e.composedPath():[];t.includes(a)||t.includes(n)||S()},g().addEventListener("focusin",f,!0),y=()=>p(),a.addEventListener("focusin",y),b=()=>{c=!1},a.addEventListener("pointerdown",b,!0)},A=e=>{e.preventDefault(),e.stopPropagation(),C()?S(!0):k(0)},M=e=>{"ArrowDown"===e.key||"Enter"===e.key||" "===e.key?(e.preventDefault(),c=!0,C()?m(0):k(0,!0)):"ArrowUp"===e.key&&(e.preventDefault(),c=!0,C()?m(-1):k(-1,!0))},I=e=>{switch(uo.has(e.key)&&(c=!0),e.key){case"ArrowDown":return e.preventDefault(),void m(d+1);case"ArrowUp":return e.preventDefault(),void m(d-1);case"Home":return e.preventDefault(),void m(0);case"End":return e.preventDefault(),void m(u().length-1);case"Escape":return e.preventDefault(),e.stopPropagation(),void S(!0);case"Tab":return void S(!0)}};return o.addEventListener("click",A),o.addEventListener("keydown",M),a.addEventListener("keydown",I),{trigger:n,triggerButton:o,panel:a,setItems:e=>{for(let t of l)e.includes(t)||t.removeAttribute(po);if(l=[...e],!C())return;let t=u();h(t,Math.min(d,t.length-1)),p()},isOpen:C,open:()=>k(0),close:S,setLabel:e=>{e!==t&&(t=e,i())},applyButtonSize:s,destroy:()=>{r=!0,v(),w(),o.removeEventListener("click",A),o.removeEventListener("keydown",M),a.removeEventListener("keydown",I),x?.destroy(),x=null,n.remove(),a.remove(),l=[]}}}({label:e.getOverflowLabel?.()??"More actions",getButtonSize:o}),u),y=(e,t,r)=>{if(!t)return"bar";if(e.resolved.builtIn){let r=(e=>"core:attachment"===e?"attachments":e.startsWith("core:mention")?"mentions":null)(e.resolved.id);return r&&t.includeBuiltIns?.includes(r)?"menu":"bar"}let n=e.resolved.presentation;return"overflow"===n||"auto"===n&&r?"menu":"bar"},b=e=>{let t=e.menuSlot;if(!t)return;if(!(e=>0===function(e){let t="",r=e=>{if(e.nodeType===Node.TEXT_NODE)return void(t+=e.nodeValue??"");if(e.nodeType!==Node.ELEMENT_NODE)return;let n=e;"function"==typeof n.matches&&n.matches('.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]')||e.childNodes.forEach(r)};return r(e),t.trim()}(e).length)(e.element))return e.menuLabel?.remove(),void(e.menuLabel=void 0);let r=(e=>{let t=So(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""})(e.element);r?(e.menuLabel||=L("span","persona-composer-overflow-menu__label"),e.menuLabel.textContent!==r&&(e.menuLabel.textContent=r),e.menuLabel.parentElement!==t&&t.appendChild(e.menuLabel)):(e.menuLabel?.remove(),e.menuLabel=void 0)},v=(e,r)=>{if(e.mode===r)return e;let n=e.resolved.action;if(n&&!Co(n)){d(e),t.delete(e.resolved.id);let n=s(e.resolved,r);return t.set(e.resolved.id,n),n}if("menu"===r){let t=P("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none","data-persona-tooltip-suppressed":""}});t.appendChild(e.element),function(e){Dn.get(e)?.hide()}(So(e.element)),e.menuSlot=t;let r=t=>{let r=So(e.element);if(r.disabled)return;let n=t.target===r||r.contains(t.target);u?.close(!0),n||r.click()};t.addEventListener("click",r,!0),e.detachMenuSlot=()=>t.removeEventListener("click",r,!0),e.managed=!0,b(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=r,e},w=()=>{if(n)return;let o=e.getBindings();if(!o)return;let a=e.getState(),s="streaming"===a.phase,i=(()=>{let t=e.getOverflow?.();return!0===t?.enabled?t:void 0})();i&&(e=>{h!==e&&(m?.disconnect(),h=e,g=yo(e),typeof ResizeObserver<"u"&&(m=new ResizeObserver(t=>{let r=t[t.length-1]?.contentRect?.width??yo(e);r!==g&&(g=r,w())}),m.observe(e)))})(o.footer);let l=!!i&&((e,t)=>{let r=function(e,t){if(void 0===e)return null;if("number"==typeof e)return Number.isFinite(e)?e:null;let r=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(r))return r;let n=L("div");n.style.position="absolute",n.style.visibility="hidden",n.style.pointerEvents="none",n.style.height="0",n.style.width=e,t.appendChild(n);let o=n.getBoundingClientRect().width;return n.remove(),Number.isFinite(o)&&o>0?o:Number.isFinite(r)?r:null}(e.collapseAutoActionsBelow,t);if(null===r)return!1;let n=g||yo(t);return n>0&&n<r})(i,o.footer),d={start:[],end:[]},x=[];for(let e of r){let r=t.get(e.id);if(!r)continue;let n=e.action,o=!n||wo(n.visible,a,!0)&&xo(n.visibility,a);if(r.visible!==o&&(r.visible=o,!o&&r.managed&&(r.menuSlot??r.element).remove()),o){if(r=v(r,y(r,i,l)),n){let e=wo(n.disabled,a,!1)||!0===n.disableWhenStreaming&&s;p(r,e),!Co(n)&&void 0!==n.pressed&&r.button?.setAttribute("aria-pressed",n.pressed?"true":"false")}"menu"===r.mode?(b(r),x.push(r)):d[e.placement].push(r)}}if(x.length>0){let e=f();((e,t)=>{let r=t.map(e=>e.menuSlot??e.element);for(r.forEach((t,r)=>{let n=e.children[r];n!==t&&(n?e.insertBefore(t,n):e.appendChild(t))});e.children.length>r.length;)e.lastElementChild?.remove()})(e.panel,x),e.setItems(x.map(e=>e.menuSlot??e.element)),e.applyButtonSize();let t=Number.isFinite(i?.order)?i?.order:900,r=d.start.findIndex(e=>e.resolved.order>t),n={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"};d.start.splice(r<0?d.start.length:r,0,n)}else u&&(u.close(),u.trigger.remove(),u.setItems([]));c(o.actionsStart,d.start),c(o.actionsEnd,d.end)};return{resolve:()=>{if(n)return;let o=function(e){let{debug:t}=e,r=[],n=new Map,o=0,a=e=>{let o=n.get(e.id);o?bo(t,`[Persona] composer action "${e.id}" is already contributed by ${vo(o)}; the ${vo(e)} copy is ignored.`):(n.set(e.id,e),r.push(e))};for(let t of e.builtIns)a({id:t.id,placement:t.placement,presentation:"bar",order:t.order,sequence:o++,source:"core",builtIn:t});let s=(e,r,n)=>{let s=n?((e,t)=>t.includes(":")?t:`${e}:${t}`)(n,e.id):e.id,i=e.order??500;"end"===e.placement&&i>=mo&&(bo(t,`[Persona] composer action "${s}" ordered at ${i} would render after send; clamped to 999.`),i=999),a({id:s,placement:e.placement,presentation:e.presentation??"bar",order:i,sequence:o++,source:r,pluginId:n,action:e})};for(let t of e.configActions??[])s(t,"config");for(let t of e.plugins){if(!t.contributeComposerActions)continue;let r;try{r=t.contributeComposerActions(e.contributionContext)}catch(e){typeof console<"u"&&console.error(`[Persona] plugin "${t.id}" contributeComposerActions failed:`,e);continue}for(let e of r??[])s(e,"plugin",t.id)}return r.sort((e,t)=>e.order===t.order?e.sequence-t.sequence:e.order-t.order)}(e.collect()),s=new Set(o.map(e=>e.id));for(let[e,r]of t)s.has(e)||(d(r),t.delete(e));for(let e of o){let r=t.get(e.id);if(!r){let r=l(e,"bar");r&&t.set(e.id,r);continue}let n=r.resolved.action,o=e.action;if(!!n!=!!o||n&&o&&Co(n)!==Co(o)||n&&o&&Co(n)&&Co(o)&&n.render!==o.render){d(r),t.delete(e.id);let n=l(e,r.mode);n&&t.set(e.id,n)}else r.resolved=e,e.builtIn?(r.managed=!0===e.builtIn.managed||"menu"===r.mode,e.builtIn.element&&"bar"===r.mode&&(r.element=e.builtIn.element)):o&&!Co(o)?a(r,o):o&&r.element.toggleAttribute(fo,!0===o.disableWhenStreaming)}r=o,w()},sync:w,getResolved:()=>r,getOverflowMenu:()=>u,destroy:()=>{if(!n){n=!0,m?.disconnect(),m=null,h=null;for(let e of t.values())d(e);t.clear(),u?.destroy(),u=null,r=[]}}}}let Ao=["--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"],Mo=()=>({wrapper:P("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),chevron:P("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}})});function Io(e){let t=e.label??"Model",r=e.presentation??"native",n=null,o=t=>{let r=e.getSelectedModelId();return t.find(e=>e.id===r)??t[0]};return{action:{id:"core:model",kind:"custom",placement:"end",order:700,presentation:"popover"===r?"bar":"auto",label:t,render:()=>"popover"===r?(()=>{let r=P("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=L("span","persona-composer-model-picker-label"),s=L("span","persona-composer-model-picker-suffix");r.append(a,s);let i=P("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),l=new Map,d="",c=null,p=()=>!0===c?.isOpen,u=(e=!1)=>{p()&&(c?.close(),r.setAttribute("aria-expanded","false"),e&&r.focus())},h=e=>{let t=[...l.values()];0!==t.length&&t[(e%t.length+t.length)%t.length].focus()},m=t=>{if(p())return;c||=lo({anchor:r,content:i,placement:"top-start",offset:6,onDismiss:()=>r.setAttribute("aria-expanded","false")}),eo(r,i,Ao),c.open(),r.setAttribute("aria-expanded","true");let n=[...l.keys()].indexOf(o(e.getModels())?.id??"");h(t??(n>=0?n:0))},g=t=>{u(!0),e.onSelect(t)},f=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute("data-persona-model-option");t&&g(t)},y=()=>{let n=e.getModels(),c=n.map(e=>`${e.id}:${e.label}:${e.icon??""}:${e.description??""}`).join("|");if(c!==d){d=c;for(let e of l.values())e.removeEventListener("click",f);l.clear(),i.replaceChildren(...n.map(e=>{let t=(e=>{let t=P("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 r=K(e.icon,16,"currentColor",1.5);if(r){let e=L("span","persona-composer-model-option-icon");e.appendChild(r),t.appendChild(e)}}let r=L("span","persona-composer-model-option-body"),n=L("span","persona-composer-model-option-label");if(n.textContent=e.label,r.appendChild(n),e.description){let t=L("span","persona-composer-model-option-description");t.textContent=e.description,r.appendChild(t)}t.appendChild(r);let o=L("span","persona-composer-model-option-check");o.setAttribute("aria-hidden","true");let a=K("check",16,"currentColor",2);return a&&o.appendChild(a),t.appendChild(o),t.addEventListener("click",f),t})(e);return l.set(e.id,t),t}))}let p=o(n);for(let[e,t]of l)t.setAttribute("aria-selected",String(e===p?.id));a.textContent=p?.label??"";let u=e.getSuffix?.()??"";s.textContent=u,r.setAttribute("aria-label",[t,[p?.label,u].filter(Boolean).join(" ")].filter(Boolean).join(": "))};y(),n=y;let b=e=>{e.preventDefault(),e.stopPropagation(),p()?u(!0):m()},v=e=>{"ArrowDown"===e.key?(e.preventDefault(),p()?h(0):m(0)):"ArrowUp"===e.key&&(e.preventDefault(),p()?h(-1):m(-1))},w=e=>{let t=[...l.values()],r=t.indexOf(e.target?.closest?.(".persona-composer-model-option"));switch(e.key){case"ArrowDown":return e.preventDefault(),void h(r+1);case"ArrowUp":return e.preventDefault(),void h(r-1);case"Home":return e.preventDefault(),void h(0);case"End":return e.preventDefault(),void h(t.length-1);case"Escape":return e.preventDefault(),e.stopPropagation(),void u(!0);case"Tab":return void u(!0)}};r.addEventListener("click",b),r.addEventListener("keydown",v),i.addEventListener("keydown",w);let{wrapper:x,chevron:C}=Mo();return x.append(r,C),{element:x,destroy:()=>{n===y&&(n=null),r.removeEventListener("click",b),r.removeEventListener("keydown",v),i.removeEventListener("keydown",w);for(let e of l.values())e.removeEventListener("click",f);l.clear(),c?.destroy(),c=null,i.remove()}}})():(()=>{let r=P("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),a="",s=()=>{let t=e.getModels(),n=t.map(e=>`${e.id}:${e.label}`).join("|");n!==a&&(a=n,r.replaceChildren(...t.map(e=>{let t=P("option",{attrs:{value:e.id}});return t.textContent=e.label,t}))),r.value=o(t)?.id??""};s(),n=s;let i=()=>{r.value&&e.onSelect(r.value)};r.addEventListener("change",i);let l=e=>e.stopPropagation();r.addEventListener("click",l);let{wrapper:d,chevron:c}=Mo();return d.append(r,c),{element:d,destroy:()=>{n===s&&(n=null),r.removeEventListener("change",i),r.removeEventListener("click",l)}}})()},repaint:()=>n?.()}}let To="[data-persona-composer-chip-row]";function Eo(e){e.style.display=e.childElementCount>0?"flex":"none"}function Lo(e){let t=e.querySelector(To);if(t)return t;let r=P("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});r.style.display="none";let n=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return n?.parentElement===e?e.insertBefore(r,n):e.appendChild(r),r}function Po(e){let t=e.row,r="",n=!1,o=new Set(e.initialIds??[]),a=t=>{let r=P("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=L("span","persona-mention-chip-icon"),n=K(t.iconName,12,"currentColor",1.5);n&&e.appendChild(n),r.appendChild(e)}let n=L("span","persona-mention-chip-label");n.textContent=t.shortLabel??t.label,r.appendChild(n);let o=P("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${t.label}`}}),a=K("x",12,"currentColor",2);return a?o.appendChild(a):o.textContent="×",o.addEventListener("click",r=>{r.preventDefault(),r.stopPropagation(),e.onRemove(t.id)}),r.appendChild(o),r},s=()=>Array.from(t.querySelectorAll(":scope > [data-persona-composer-mode]")),i=e=>{e.setAttribute("data-persona-chip-exit",""),e.setAttribute("aria-hidden","true"),e.style.pointerEvents="none";let r=()=>{e.remove(),Eo(t)},n=t.ownerDocument.defaultView,o="function"==typeof n?.getComputedStyle?n.getComputedStyle(e).animationName:"";o&&"none"!==o?(e.addEventListener("animationend",r,{once:!0}),e.addEventListener("animationcancel",r,{once:!0})):r()};return{element:t,render:(e,l)=>{if(n)return;let d=l.filter(t=>e.includes(t.id)),c=d.map(e=>`${e.id}:${e.shortLabel??e.label}`).join("|");if(c===r)return;r=c;let p=new Map;for(let e of s()){let t=e.getAttribute("data-persona-composer-mode");t&&d.some(e=>e.id===t)&&!e.hasAttribute("data-persona-chip-exit")?p.set(t,e):e.hasAttribute("data-persona-chip-exit")||i(e)}let u=t.firstChild;for(let e of d){let r=p.get(e.id);r||(r=a(e),o.has(e.id)||(r.setAttribute("data-persona-chip-enter",""),r.addEventListener("animationend",()=>r?.removeAttribute("data-persona-chip-enter"),{once:!0}))),o.delete(e.id),r!==u&&t.insertBefore(r,u),u=r.nextSibling}Eo(t)},destroy:()=>{n=!0,(()=>{for(let e of s())e.remove()})(),Eo(t)}}}let Bo=e=>`core:mode:${e}`,No=e=>Math.min(300+e,499),Ro=e=>`core:mode-group:${e}`;function Ho(e,t){return!!e&&"segmented"===t?.find(t=>t.id===e)?.presentation}function $o(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function Wo(e){let t=null;return{action:{id:Ro(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let r=P("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),n=new Map,o="",a=t=>{t.preventDefault(),t.stopPropagation();let r=t.currentTarget.getAttribute("data-persona-composer-mode");r&&(e.getActiveIds().includes(r)&&"single"===e.getGroup()?.selection||e.onSelect(r))},s=()=>{let t=e.getGroup();t?.label?(r.setAttribute("role","group"),r.setAttribute("aria-label",t.label)):(r.removeAttribute("role"),r.removeAttribute("aria-label"));let s=e.getModes(),i=s.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??""}`).join("|");if(i!==o){o=i;for(let e of n.values())e.removeEventListener("click",a);n.clear();let e=s.map(e=>{let t=(e=>{let t=P("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let r=K(e.iconName,16,"currentColor",1.5);r&&t.appendChild(r)}let r=L("span","persona-composer-segmented-label");return r.textContent=e.shortLabel??e.label,t.appendChild(r),t.addEventListener("click",a),t})(e);return n.set(e.id,t),t});r.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of n)t.setAttribute("aria-pressed",String(l.includes(e)))};return s(),t=s,{element:r,destroy:()=>{t===s&&(t=null);for(let e of n.values())e.removeEventListener("click",a);n.clear()}}}},repaint:()=>t?.()}}function Do(e){let t=P("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let r="",n=!1,o=r=>{let n=L("span","persona-composer-quote-bar"),o=L("div","persona-composer-quote-content");if(r.sourceLabel){let e=L("div","persona-composer-quote-source");e.textContent=r.sourceLabel,o.appendChild(e)}let a=P("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});a.textContent=Xr(r.text),o.appendChild(a);let s=P("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),i=K("x",12,"currentColor",2);i?s.appendChild(i):s.textContent="×",s.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(n,o,s)};return{element:t,render:e=>{if(n)return;let a=e?`${e.sourceLabel??""}\0${e.text}`:"";a!==r&&(r=a,e?(o(e),t.style.display="flex"):(t.replaceChildren(),t.style.display="none"))},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function Fo(e){let t=P("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let r,n=!1,o=(e,t,r,n)=>{let o=P("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":t,[r]:""}}),a=K(e,12,"currentColor",2);return a?o.appendChild(a):o.textContent=t,o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),n()}),o};return{element:t,render:a=>{if(n||a===r)return;if(r=a,!a)return t.replaceChildren(),void(t.style.display="none");let s=L("span","persona-composer-pending-badge");s.textContent=e.label??"Sends next";let i=P("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});i.textContent=(e=>{let t=Xr(e.text??"",90);if(t)return t;let r=e.contentParts?.length??0;return r>0?1===r?"1 attachment":`${r} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(", "):"Queued message"})(a),t.replaceChildren(s,i,o("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),o("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function Oo(e){let t=P("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),r=P("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});r.value=e.initialText;let n=()=>{r.style.height="auto",r.style.height=`${r.scrollHeight}px`};r.addEventListener("input",n);let o=L("div","persona-message-edit-actions"),a=(e,t,r,n)=>{let o=P("button",{className:`persona-message-edit-button ${t}`,attrs:{type:"button",[r]:""},text:e});return o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),n()}),o},s=()=>{let t=r.value.trim();t&&e.onSave(t)};return o.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",s)),r.addEventListener("keydown",t=>{"Escape"===t.key?(t.preventDefault(),t.stopPropagation(),e.onCancel()):"Enter"===t.key&&!t.shiftKey&&(t.preventDefault(),s())}),t.append(r,o),{element:t,getValue:()=>r.value,focus:()=>{r.focus();let e=r.value.length;r.setSelectionRange(e,e),n()},destroy:()=>{t.replaceChildren(),t.remove()}}}function zo(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 qo(e,t){return!1===t?{status:"canceled"}:(!t||"object"!=typeof t||("string"==typeof t.text&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options})),{status:"proceed"})}function jo(e,t,r){let n;try{n=e(zo(t),{signal:r})}catch(e){return{status:"error",error:e}}return(e=>"function"==typeof e?.then)(n)?Promise.resolve(n).then(e=>r.aborted?{status:"aborted"}:qo(t,e),e=>r.aborted?{status:"aborted"}:{status:"error",error:e}):qo(t,n)}let{setLoader:_o,load:Uo}=N({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),Vo=_o,Go=Uo,{setLoader:Ko,load:Jo}=N({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),Qo=Ko,Xo=Jo;function Yo(e){let{config:t,onOpen:r}=e,n=t.buttonIconName??"plus",o=t.buttonTooltipText??"Add context",a=L("div","persona-send-button-wrapper"),s=P("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Yn} ${Zn}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":o,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),i=K(n,24,"currentColor",1.5);return i?s.appendChild(i):s.textContent="+",s.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r()}),a.appendChild(s),qn({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??o}),{button:s,wrapper:a}}let Zo=e=>e?.launcher?.variant??(!0===e?.future?.v5Defaults?"circle":"pill"),ea={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"},ta="16px",ra="transparent",na={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]=0===t?"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"}},oa={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"}},aa={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:v,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ta,canvasBackground:ra,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"}}},sa=na.colors.gray,ia={...na,colors:{...na.colors,gray:sa}},la={...na,colors:{...na.colors,gray:{50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"}},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},da=ia,ca=oa,pa={...oa,colors:{...oa.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...oa.typography,fontSize:"14px",lineHeight:"1.5"}},ua=ca,ha=aa,ma={...aa,launcher:ea,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:{...aa.input,borderRadius:"palette.radius.full"},introCard:{...aa.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...aa.suggestion.chip,fontWeight:"400"},card:{...aa.suggestion.card,fontWeight:"400"},list:{...aa.suggestion.list,fontWeight:"400"}},panel:{...aa.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...aa.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:{...aa.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...aa.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:{...aa.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...aa.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)"}},ga=ha,fa=e=>"v5"===(e=>A({future:e}))(e)?{palette:la,semantic:pa,components:ma}:{palette:ia,semantic:ca,components:ha};function ya(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),n=e;for(let e of r){if(null==n)return;n=n[e]}return"string"==typeof n&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?ya(e,n):n}function ba(e){let t={};function r(n,o){for(let[a,s]of Object.entries(n)){let n=`${o}.${a}`;if("string"==typeof s){let r=ya(e,s);void 0!==r&&(t[n]={path:n,value:r,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else"object"==typeof s&&s&&r(s,n)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function va(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:0===t.length,errors:t,warnings:r}}function wa(e,t){let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];r[e]=t&&"object"==typeof t&&!Array.isArray(t)&&n&&"object"==typeof n&&!Array.isArray(n)?wa(t,n):n}return r}function xa(e,t){return t?wa(e,t):e}function Ca(e,t={}){let r=fa(t.future),n={palette:r.palette,semantic:r.semantic,components:r.components},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:xa(n.components,e?.components)},a=e?.components?.activity;for(let e of["toolBubble","reasoningBubble"])for(let t of["rowHeight","labelSize","iconSize","indent","bodySurface"])void 0!==a?.[t]&&(o.components[e][t]=a[t]);let s=e?.components?.collapsibleWidget?.surface;void 0!==s&&void 0===a?.bodySurface&&(o.components.activity={...o.components.activity,bodySurface:s});let i=e?.components?.header;void 0!==i?.padding&&void 0===i.minimalPadding&&(o.components.header.minimalPadding=o.components.header.padding);let l=e?.components?.message;if(void 0!==l?.gap&&void 0===l.fullscreenGap&&(o.components.message.fullscreenGap=o.components.message.gap),!1!==t.validate){let e=va(o);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(", ")}`)}if(t.plugins)for(let e of t.plugins)o=e.transform(o);return o}let Sa=e=>"0"===e.trim()?"0px":e,ka="--persona-",Aa=(e,t)=>{for(let[r,...n]of t){let t;for(let r of n)if(t=61===r.charCodeAt(0)?r.slice(1):e[ka+r],void 0!==t)break;void 0!==t&&(e[ka+r]=t)}};function Ma(e){let t=ba(e),r={};for(let[e,n]of Object.entries(t))r[`--persona-${e.replace(/\./g,"-")}`]=n.value;Aa(r,[["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 n=r["--persona-components-launcher-foreground"];r["--persona-launcher-fg-muted"]=n&&n!==r["--persona-primary"]?`color-mix(in srgb, ${n} 70%, transparent)`:r["--persona-muted"],Aa(r,[["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"]]),Aa(r,[["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"]]),r["--persona-panel-border"]=r["--persona-components-panel-border"]??`1px solid ${r["--persona-border"]}`,Aa(r,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),r["--persona-panel-inset"]=r["--persona-components-panel-inset"]??"16px",r["--persona-panel-canvas-bg"]=r["--persona-components-panel-canvasBackground"]??"transparent",Aa(r,[["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"]]),Aa(r,[["header-bg","components-header-background","surface"]]);let o=r["--persona-header-bg"],a=r["--persona-components-header-foreground"],s=a?`color-mix(in srgb, ${a} 72%, ${o})`:void 0;r["--persona-header-border"]=r["--persona-components-header-border"]??(a?`color-mix(in srgb, ${a} 14%, ${o})`:void 0)??r["--persona-divider"],Aa(r,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),r["--persona-header-title-fg"]=r["--persona-components-header-title-color"]??r["--persona-components-header-titleForeground"]??a??r["--persona-primary"],r["--persona-header-subtitle-fg"]=r["--persona-components-header-subtitle-color"]??r["--persona-components-header-subtitleForeground"]??s??r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=r["--persona-components-header-actionIconForeground"]??s??r["--persona-muted"],Aa(r,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let i=e.components?.header;i?.shadow&&(r["--persona-header-shadow"]=i.shadow),i?.borderBottom&&(r["--persona-header-border-bottom"]=i.borderBottom),i?.minHeight&&(r["--persona-header-min-height"]=i.minHeight);let l=r["--persona-components-history-railHeader-background"];l&&(r["--persona-history-rail-header-bg"]=l);let d=r["--persona-components-history-railHeader-border"];d&&(r["--persona-history-rail-header-border"]=d);let c=r["--persona-components-history-railHeader-minHeight"];c&&(r["--persona-history-rail-header-min-height"]=c);for(let[e,t]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let n=r[`--persona-components-history-overlay-${e}`];n&&(r[`--persona-history-overlay-${t}`]=n)}for(let[e,t]of[["background","bg"],["borderRadius","radius"]]){let n=r[`--persona-components-history-menu-${e}`];n&&(r[`--persona-history-menu-${t}`]=n)}let p=e.components?.history?.motion;if(p){let e=e=>{if(void 0===e)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},t=e(p.enterDurationMs);void 0!==t&&(r["--persona-history-enter-ms"]=t);let n=e(p.exitDurationMs);void 0!==n&&(r["--persona-history-exit-ms"]=n),p.enterEasing&&(r["--persona-history-enter-easing"]=p.enterEasing),p.exitEasing&&(r["--persona-history-exit-easing"]=p.exitEasing)}let u=r["--persona-components-history-dangerForeground"];u&&(r["--persona-history-danger-fg"]=u),r["--persona-danger"]=r["--persona-components-history-confirm-dangerBackground"]??r["--persona-palette-colors-error-700"]??"#b42318",r["--persona-danger-fg"]=r["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let e of["scrim","shadow"]){let t=r[`--persona-components-history-confirm-${e}`];t&&(r[`--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 n=r[`--persona-components-tooltip-${e}`];n&&(r[`--persona-tooltip-${t}`]=n)}!1===e.components?.tooltip?.arrow&&(r["--persona-tooltip-arrow-display"]="none");for(let[e,t]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let n=r[`--persona-components-messageActions-${e}`];n&&(r[`--persona-message-action-${t}`]=n)}Aa(r,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=r["--persona-components-introCard-background"],m=r["--persona-components-introCard-shadow"],g=!(h&&"transparent"!==h&&"none"!==h||m&&"none"!==m),f=r["--persona-components-introCard-padding"]??"1.5rem";r["--persona-intro-card-padding"]=g&&"1.5rem"===f?"1.5rem 0":f,Aa(r,[["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"]]),Aa(r,[["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 y=r["--persona-components-markdown-heading-h1-fontSize"];y&&(r["--persona-md-h1-size"]=y);let b=r["--persona-components-markdown-heading-h1-fontWeight"];b&&(r["--persona-md-h1-weight"]=b);let v=r["--persona-components-markdown-heading-h2-fontSize"];v&&(r["--persona-md-h2-size"]=v);let w=r["--persona-components-markdown-heading-h2-fontWeight"];w&&(r["--persona-md-h2-weight"]=w);let x=r["--persona-components-markdown-prose-fontFamily"];x&&"inherit"!==x&&(r["--persona-md-prose-font-family"]=x),Aa(r,[["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"]]),Aa(r,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Aa(r,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Aa(r,[["md-hr-color","components-markdown-hr-color","divider"]]),Aa(r,[["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 n=r[`--persona-components-collapsibleWidget-${e}`]??r[`--persona-${t}`];void 0!==n&&(r[`--persona-cw-${e}`]=n,r[`--cw-${e}`]=n)}Aa(r,[["message-border","components-message-border","border"]]),Aa(r,[["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 C=e.components,S=C?.iconButton;S&&(S.background&&(r["--persona-icon-btn-bg"]=S.background),S.border&&(r["--persona-icon-btn-border"]=S.border),S.color&&(r["--persona-icon-btn-color"]=S.color),S.padding&&(r["--persona-icon-btn-padding"]=S.padding),S.borderRadius&&(r["--persona-icon-btn-radius"]=S.borderRadius),S.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=S.hoverBackground),S.hoverColor&&(r["--persona-icon-btn-hover-color"]=S.hoverColor),S.activeBackground&&(r["--persona-icon-btn-active-bg"]=S.activeBackground),S.activeBorder&&(r["--persona-icon-btn-active-border"]=S.activeBorder));let k=C?.labelButton;k&&(k.background&&(r["--persona-label-btn-bg"]=k.background),k.border&&(r["--persona-label-btn-border"]=k.border),k.color&&(r["--persona-label-btn-color"]=k.color),k.padding&&(r["--persona-label-btn-padding"]=k.padding),k.borderRadius&&(r["--persona-label-btn-radius"]=k.borderRadius),k.hoverBackground&&(r["--persona-label-btn-hover-bg"]=k.hoverBackground),k.fontSize&&(r["--persona-label-btn-font-size"]=k.fontSize),k.gap&&(r["--persona-label-btn-gap"]=k.gap));let A=C?.toggleGroup;A&&(A.gap&&(r["--persona-toggle-group-gap"]=A.gap),A.borderRadius&&(r["--persona-toggle-group-radius"]=A.borderRadius));let M=C?.artifact;if(M?.toolbar){let t=M.toolbar;t.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=t.iconHoverColor),t.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=t.iconHoverBackground),t.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=t.iconPadding),t.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=t.iconBorderRadius),t.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=t.iconBorder),t.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=Sa(t.toggleGroupGap)),t.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=t.toggleBorderRadius),t.toggleGroupPadding&&(r["--persona-artifact-toolbar-toggle-group-padding"]=Sa(t.toggleGroupPadding)),t.toggleGroupBorder&&(r["--persona-artifact-toolbar-toggle-group-border"]=t.toggleGroupBorder),t.toggleGroupBorderRadius&&(r["--persona-artifact-toolbar-toggle-group-radius"]=t.toggleGroupBorderRadius),t.toggleGroupBackground&&(r["--persona-artifact-toolbar-toggle-group-bg"]=ya(e,t.toggleGroupBackground)??t.toggleGroupBackground),t.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=t.copyBackground),t.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=t.copyBorder),t.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=t.copyColor),t.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=Sa(t.copyBorderRadius)),t.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=t.copyPadding),t.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=t.copyMenuBackground,r["--persona-dropdown-bg"]=r["--persona-dropdown-bg"]??t.copyMenuBackground),t.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=t.copyMenuBorder,r["--persona-dropdown-border"]=r["--persona-dropdown-border"]??t.copyMenuBorder),t.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=t.copyMenuShadow,r["--persona-dropdown-shadow"]=r["--persona-dropdown-shadow"]??t.copyMenuShadow),t.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=t.copyMenuBorderRadius,r["--persona-dropdown-radius"]=r["--persona-dropdown-radius"]??t.copyMenuBorderRadius),t.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=t.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=r["--persona-dropdown-item-hover-bg"]??t.copyMenuItemHoverBackground),t.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=t.iconBackground),t.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=t.toolbarBorder)}if(M?.tab){let e=M.tab;e.background&&(r["--persona-artifact-tab-bg"]=e.background),e.activeBackground&&(r["--persona-artifact-tab-active-bg"]=e.activeBackground),e.activeBorder&&(r["--persona-artifact-tab-active-border"]=e.activeBorder),e.borderRadius&&(r["--persona-artifact-tab-radius"]=e.borderRadius),e.textColor&&(r["--persona-artifact-tab-color"]=e.textColor),e.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=e.hoverBackground),e.listBackground&&(r["--persona-artifact-tab-list-bg"]=e.listBackground),e.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=e.listBorderColor),e.listPadding&&(r["--persona-artifact-tab-list-padding"]=e.listPadding)}if(M?.pane){let t=M.pane;t.toolbarBackground&&(r["--persona-artifact-toolbar-bg"]=ya(e,t.toolbarBackground)??t.toolbarBackground)}if(M?.card){let e=M.card;e.background&&(r["--persona-artifact-card-bg"]=e.background),e.border&&(r["--persona-artifact-card-border"]=e.border),e.borderRadius&&(r["--persona-artifact-card-radius"]=e.borderRadius),e.hoverBackground&&(r["--persona-artifact-card-hover-bg"]=e.hoverBackground),e.hoverBorderColor&&(r["--persona-artifact-card-hover-border"]=e.hoverBorderColor)}if(M?.inline){let t=M.inline;t.background&&(r["--persona-artifact-inline-bg"]=ya(e,t.background)??t.background),t.border&&(r["--persona-artifact-inline-border"]=t.border),t.borderRadius&&(r["--persona-artifact-inline-radius"]=t.borderRadius),t.chromeBackground&&(r["--persona-artifact-inline-chrome-bg"]=ya(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(r["--persona-artifact-inline-chrome-border"]=ya(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(r["--persona-artifact-inline-title-color"]=ya(e,t.titleColor)??t.titleColor),t.mutedColor&&(r["--persona-artifact-inline-muted-color"]=ya(e,t.mutedColor)??t.mutedColor),t.frameHeight&&(r["--persona-artifact-inline-frame-height"]=t.frameHeight)}let I=C?.code;I&&(I.keywordColor&&(r["--persona-code-keyword-color"]=I.keywordColor),I.stringColor&&(r["--persona-code-string-color"]=I.stringColor),I.commentColor&&(r["--persona-code-comment-color"]=I.commentColor),I.numberColor&&(r["--persona-code-number-color"]=I.numberColor),I.tagColor&&(r["--persona-code-tag-color"]=I.tagColor),I.attrColor&&(r["--persona-code-attr-color"]=I.attrColor),I.propertyColor&&(r["--persona-code-property-color"]=I.propertyColor),I.lineNumberColor&&(r["--persona-code-line-number-color"]=I.lineNumberColor),I.gutterBorderColor&&(r["--persona-code-gutter-border-color"]=I.gutterBorderColor),I.background&&(r["--persona-code-bg"]=ya(e,I.background)??I.background));let T=r["--persona-surface"],E=r["--persona-container"],L=r["--persona-palette-colors-gray-100"]??"#f3f4f6",P=r["--persona-palette-colors-gray-200"]??"#e5e7eb",B=r["--persona-palette-colors-gray-300"]??"#d1d5db",N=!E||E===T,R=(e=>{if(!e)return;let t,r=e.trim().toLowerCase();if(35===r.charCodeAt(0)){let e=r.slice(1);if(!/^[0-9a-f]+$/.test(e))return;3===e.length||4===e.length?t=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(6===e.length||8===e.length)&&(t=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=r.match(/^rgba?\(([^)]+)\)$/);if(e){let r=e[1].split(/[,/\s]+/).filter(Boolean);r.length>=3&&(t=r.slice(0,3).map(e=>{let t=e.endsWith("%"),r=parseFloat(t?e.slice(0,-1):e);return t?r/100*255:r}))}}if(!t||t.some(e=>!Number.isFinite(e)))return;let[n,o,a]=t.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*n+.7152*o+.0722*a})(T??r["--persona-background"]),H=N&&void 0!==R&&R<.179,$=H?"rgba(255, 255, 255, 0.16)":B,W=N?H?"rgba(255, 255, 255, 0.08)":L:E,D=N?H?"rgba(255, 255, 255, 0.12)":P:E;return r["--persona-icon-btn-hover-bg"]=r["--persona-icon-btn-hover-bg"]??W,r["--persona-icon-btn-active-bg"]=r["--persona-icon-btn-active-bg"]??D,N&&(r["--persona-icon-btn-active-border"]=r["--persona-icon-btn-active-border"]??$),r["--persona-label-btn-hover-bg"]=r["--persona-label-btn-hover-bg"]??W,r["--persona-artifact-tab-hover-bg"]=r["--persona-artifact-tab-hover-bg"]??W,r["--persona-artifact-card-hover-bg"]=r["--persona-artifact-card-hover-bg"]??W,r}let Ia={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)"}}}},Ta={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"}}},Ea={...Ta,colors:{...Ta.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"}}},La=Ia,Pa={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:{...Ia.components,button:{...Ia.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:{...Ia.components?.eventStream,badge:{...Ia.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"}}}}},Ba=e=>{if(e&&"object"==typeof e&&!Array.isArray(e))return e},Na=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Ra=e=>(e=>{let t=e?.colorScheme??"light";return"light"===t?"light":"dark"===t?"dark":Na()})(e),Ha=e=>{let t=Ra(e),r=Ba(e?.theme),n=a({components:{launcher:"circle"===Zo(e)?ea:{...ha.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}}}},r),o=Ba(e?.darkTheme);return((e,t)=>{if(!t||!(e=>!!e&&"launcher"in e&&(!0===e.launcher?.sidebarMode||"docked"===e.launcher?.mountMode))(t))return e;let r=t.theme?.components?.panel?.width,n=t.darkTheme?.components?.panel?.width;return null==("dark"===Ra(t)?n??r:r)?{...e,components:{...e.components,panel:{...e.components.panel,width:"v5"===A(t)?"400px":"420px"}}}:e})("dark"===t?((e,t={})=>{let r=(e=>"v5"===A({future:e})?{palette:Ea,components:Pa}:{palette:Ta,components:La})(t.future),n=a(r.components,e??{})??{};return Ca({...n,palette:{...n.palette,colors:"v5"===A(t)?a(r.palette.colors,n.palette?.colors):{...r.palette.colors,...n.palette?.colors}}},{validate:!1,future:t.future})})(a(n??{},o??{}),{future:e?.future}):((e,t={})=>Ca(e,t))(n,{future:e?.future}),e)},$a=(e,t)=>{let r=(e=>Ma(e))(Ha(t));for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute("data-persona-color-scheme",Ra(t)),e.setAttribute("data-persona-defaults",A(t))},Wa=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let r=new MutationObserver(()=>{e(Na())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window<"u"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(Na());r.addEventListener?(r.addEventListener("change",n),t.push(()=>r.removeEventListener("change",n))):r.addListener&&(r.addListener(n),t.push(()=>r.removeListener(n)))}return()=>{t.forEach(e=>e())}},Da=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px"),Fa=(e,t)=>t||"overlay"!==e?.composer?.placement?"block":"overlay",Oa=e=>{if("string"!=typeof e)return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let r=Number(t[1])/100;return r>0&&r<1?r:null},za=()=>{if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},qa=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},ja=e=>{let t=e.toLowerCase().split("+").map(e=>e.trim()),r=t.pop(),n={key:r,mod:!1,shift:!1,alt:!1};for(let r of t)if("mod"===r||"cmd"===r||"ctrl"===r)n.mod=!0;else if("shift"===r)n.shift=!0;else{if("alt"!==r&&"option"!==r)return qa("unknown modifier in",e),null;n.alt=!0}return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(r)||!/^([^+\s]|[a-z]{2,12})$/.test(r)?(qa("unsupported",e),null):("space"===r&&(n.key=" "),n)},_a=(e,t)=>{let r=ja(e);if(!r)return"";let n=za(),o=(e=>"ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space".split(" ").find(t=>t.toLowerCase()===e)??(" "===e?"Space":1===e.length?e.toUpperCase():e[0].toUpperCase()+e.slice(1)))(r.key);if(!t&&n)return`${r.alt?"⌥":""}${r.shift?"⇧":""}⌘${o}`;let a=[t?n?"Meta":"Control":"Ctrl"];return r.alt&&a.push("Alt"),r.shift&&a.push("Shift"),a.push(o),a.join("+")},Ua=e=>_a(e,!1),Va=e=>_a(e,!0),Ga=(e,t)=>t.key?.toLowerCase()===e.key&&(za()?t.metaKey:t.ctrlKey)===e.mod&&!(za()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Ka=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t||e.isContentEditable},Ja=e=>{let t=new Map,r=e?.ownerDocument??(typeof document<"u"?document:null),n=(t,r)=>{if("page"===(t.scope??"widget"))return!0;if(!e)return!1;let n=r.composedPath?.();return n?.length?n.includes(e):e.contains(r.target)},o=e=>{if(e.isComposing||!t.size)return;let r=e.composedPath?.()[0]??e.target;for(let o of t.values())if(Ga(o.parsed,e)&&!1!==o.when?.()&&n(o,e)&&(o.allowInInput||!Ka(r))){e.preventDefault();try{o.run(e)}catch(e){qa(`${o.id} threw on`,o.combo),console.warn(e)}return}};return r?.addEventListener("keydown",o),{register(e){let r=ja(e.combo);if(!r)return()=>{};let n=`${r.mod?"m":""}${r.shift?"s":""}${r.alt?"a":""}${r.key}`,o=t.get(n);return o?(qa(`${o.id} already owns`,e.combo),()=>{}):(t.set(n,{...e,parsed:r}),e.element?.setAttribute("aria-keyshortcuts",Va(e.combo)),()=>{t.get(n)?.id===e.id&&t.delete(n),e.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),r?.removeEventListener("keydown",o)}}};var Qa=function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:e=>"true"===e.getAttribute("im-preserve"),shouldReAppend:e=>"true"===e.getAttribute("im-re-append"),shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0},r=function(){function e(e,t,r,o){if(!1===o.callbacks.beforeNodeAdded(t))return null;if(o.idMap.has(t)){let a=document.createElement(t.tagName);return e.insertBefore(a,r),n(a,t,o),o.callbacks.afterNodeAdded(a),a}{let n=document.importNode(t,!0);return e.insertBefore(n,r),o.callbacks.afterNodeAdded(n),n}}let t=function(){function e(e,t,r){let n=e.idMap.get(t),o=e.idMap.get(r);if(!o||!n)return!1;for(let e of n)if(o.has(e))return!0;return!1}function t(e,t){let r=e,n=t;return r.nodeType===n.nodeType&&r.tagName===n.tagName&&(!r.getAttribute?.("id")||r.getAttribute?.("id")===n.getAttribute?.("id"))}return function(r,n,o,a){let s=null,i=n.nextSibling,l=0,d=o;for(;d&&d!=a;){if(t(d,n)){if(e(r,d,n))return d;null===s&&(r.idMap.has(d)||(s=d))}if(null===s&&i&&t(d,i)&&(l++,i=i.nextSibling,l>=2&&(s=void 0)),r.activeElementAndParents.includes(d))break;d=d.nextSibling}return s||null}}();function r(e,t){if(e.idMap.has(t))s(e.pantry,t,null);else{if(!1===e.callbacks.beforeNodeRemoved(t))return;t.parentNode?.removeChild(t),e.callbacks.afterNodeRemoved(t)}}function o(e,t,n){let o=t;for(;o&&o!==n;){let t=o;o=o.nextSibling,r(e,t)}return o}function a(e,t,r,n){let o=n.target.getAttribute?.("id")===t&&n.target||n.target.querySelector(`[id="${t}"]`)||n.pantry.querySelector(`[id="${t}"]`);return function(e,t){let r=e.getAttribute("id");for(;e=e.parentNode;){let n=t.idMap.get(e);n&&(n.delete(r),n.size||t.idMap.delete(e))}}(o,n),s(e,o,r),o}function s(e,t,r){if(e.moveBefore)try{e.moveBefore(t,r)}catch{e.insertBefore(t,r)}else e.insertBefore(t,r)}return function(s,i,l,d=null,c=null){i instanceof HTMLTemplateElement&&l instanceof HTMLTemplateElement&&(i=i.content,l=l.content),d||=i.firstChild;for(let r of l.childNodes){if(d&&d!=c){let e=t(s,r,d,c);if(e){e!==d&&o(s,d,e),n(e,r,s),d=e.nextSibling;continue}}if(r instanceof Element){let e=r.getAttribute("id");if(s.persistentIds.has(e)){let t=a(i,e,d,s);n(t,r,s),d=t.nextSibling;continue}}let l=e(i,r,d,s);l&&(d=l.nextSibling)}for(;d&&d!=c;){let e=d;d=d.nextSibling,r(s,e)}}}(),n=function(){function e(e,r,n){let a=r.nodeType;if(1===a){let a=e,i=r,l=a.attributes,d=i.attributes;for(let e of d)o(e.name,a,"update",n)||a.getAttribute(e.name)!==e.value&&a.setAttribute(e.name,e.value);for(let e=l.length-1;0<=e;e--){let t=l[e];if(t&&!i.hasAttribute(t.name)){if(o(t.name,a,"remove",n))continue;a.removeAttribute(t.name)}}s(a,n)||t(a,i,n)}(8===a||3===a)&&e.nodeValue!==r.nodeValue&&(e.nodeValue=r.nodeValue)}function t(e,t,r){if(e instanceof HTMLInputElement&&t instanceof HTMLInputElement&&"file"!==t.type){let a=t.value,s=e.value;n(e,t,"checked",r),n(e,t,"disabled",r),t.hasAttribute("value")?s!==a&&(o("value",e,"update",r)||(e.setAttribute("value",a),e.value=a)):o("value",e,"remove",r)||(e.value="",e.removeAttribute("value"))}else if(e instanceof HTMLOptionElement&&t instanceof HTMLOptionElement)n(e,t,"selected",r);else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let n=t.value,a=e.value;if(o("value",e,"update",r))return;n!==a&&(e.value=n),e.firstChild&&e.firstChild.nodeValue!==n&&(e.firstChild.nodeValue=n)}}function n(e,t,r,n){let a=t[r];if(a!==e[r]){let s=o(r,e,"update",n);s||(e[r]=t[r]),a?s||e.setAttribute(r,""):o(r,e,"remove",n)||e.removeAttribute(r)}}function o(e,t,r,n){return!("value"!==e||!n.ignoreActiveValue||t!==document.activeElement)||!1===n.callbacks.beforeAttributeUpdated(e,t,r)}function s(e,t){return!!t.ignoreActiveValue&&e===document.activeElement&&e!==document.body}return function(t,n,o){return o.ignoreActive&&t===document.activeElement?null:(!1===o.callbacks.beforeNodeMorphed(t,n)||(t instanceof HTMLHeadElement&&o.head.ignore||(t instanceof HTMLHeadElement&&"morph"!==o.head.style?a(t,n,o):(e(t,n,o),s(t,o)||r(o,t,n))),o.callbacks.afterNodeMorphed(t,n)),t)}}();function o(e,t,r,n){if(e.head.block){let o=t.querySelector("head"),s=r.querySelector("head");if(o&&s){let t=a(o,s,e);return Promise.all(t).then(()=>n(Object.assign(e,{head:{block:!1,ignore:!0}})))}}return n(e)}function a(e,t,r){let n=[],o=[],a=[],s=[],i=new Map;for(let e of t.children)i.set(e.outerHTML,e);for(let t of e.children){let e=i.has(t.outerHTML),n=r.head.shouldReAppend(t),l=r.head.shouldPreserve(t);e||l?n?o.push(t):(i.delete(t.outerHTML),a.push(t)):"append"===r.head.style?n&&(o.push(t),s.push(t)):!1!==r.head.shouldRemove(t)&&o.push(t)}s.push(...i.values());let l=[];for(let t of s){let o=document.createRange().createContextualFragment(t.outerHTML).firstChild;if(!1!==r.callbacks.beforeNodeAdded(o)){if("href"in o&&o.href||"src"in o&&o.src){let e,t=new Promise(function(t){e=t});o.addEventListener("load",function(){e()}),l.push(t)}e.appendChild(o),r.callbacks.afterNodeAdded(o),n.push(o)}}for(let t of o)!1!==r.callbacks.beforeNodeRemoved(t)&&(e.removeChild(t),r.callbacks.afterNodeRemoved(t));return r.head.afterHeadMorphed(e,{added:n,kept:a,removed:o}),l}let s=function(){function e(e){let r=Object.assign({},t);return Object.assign(r,e),r.callbacks=Object.assign({},t.callbacks,e.callbacks),r.head=Object.assign({},t.head,e.head),r}function r(){let e=document.createElement("div");return e.hidden=!0,document.body.insertAdjacentElement("afterend",e),e}function n(e){let t=[],r=document.activeElement;if("BODY"!==r?.tagName&&e.contains(r))for(;r&&(t.push(r),r!==e);)r=r.parentElement;return t}function o(e){let t=Array.from(e.querySelectorAll("[id]"));return e.getAttribute?.("id")&&t.push(e),t}function a(e,t,r,n){for(let o of n){let n=o.getAttribute("id");if(t.has(n)){let t=o;for(;t;){let o=e.get(t);if(o??(o=new Set,e.set(t,o)),o.add(n),t===r)break;t=t.parentElement}}}}function s(e,t){let r=o(e),n=o(t),s=function(e,t){let r=new Set,n=new Map;for(let{id:t,tagName:o}of e)n.has(t)?r.add(t):n.set(t,o);let o=new Set;for(let{id:e,tagName:a}of t)o.has(e)?r.add(e):n.get(e)===a&&o.add(e);for(let e of r)o.delete(e);return o}(r,n),i=new Map;return a(i,s,e,r),a(i,s,t.__idiomorphRoot||t,n),{persistentIds:s,idMap:i}}return function(t,o,a){let{persistentIds:i,idMap:l}=s(t,o),d=e(a),c=d.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(c))throw`Do not understand how to morph style ${c}`;return{target:t,newContent:o,config:d,morphStyle:c,ignoreActive:d.ignoreActive,ignoreActiveValue:d.ignoreActiveValue,restoreFocus:d.restoreFocus,idMap:l,persistentIds:i,pantry:r(),activeElementAndParents:n(t),callbacks:d.callbacks,head:d.head}}}(),{normalizeElement:i,normalizeParent:l}=function(){let e=new WeakSet;class t{constructor(e){this.originalNode=e,this.realParentNode=e.parentNode,this.previousSibling=e.previousSibling,this.nextSibling=e.nextSibling}get childNodes(){let e=[],t=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;t&&t!=this.nextSibling;)e.push(t),t=t.nextSibling;return e}querySelectorAll(e){return this.childNodes.reduce((t,r)=>{if(r instanceof Element){r.matches(e)&&t.push(r);let n=r.querySelectorAll(e);for(let e=0;e<n.length;e++)t.push(n[e])}return t},[])}insertBefore(e,t){return this.realParentNode.insertBefore(e,t)}moveBefore(e,t){return this.realParentNode.moveBefore(e,t)}get __idiomorphRoot(){return this.originalNode}}return{normalizeElement:function(e){return e instanceof Document?e.documentElement:e},normalizeParent:function r(n){if(null==n)return document.createElement("div");if("string"==typeof n)return r(function(t){let r=new DOMParser,n=t.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(n.match(/<\/html>/)||n.match(/<\/head>/)||n.match(/<\/body>/)){let o=r.parseFromString(t,"text/html");if(n.match(/<\/html>/))return e.add(o),o;{let t=o.firstChild;return t&&e.add(t),t}}{let n=r.parseFromString("<body><template>"+t+"</template></body>","text/html").body.querySelector("template").content;return e.add(n),n}}(n));if(e.has(n))return n;if(n instanceof Node){if(n.parentNode)return new t(n);{let e=document.createElement("div");return e.append(n),e}}{let e=document.createElement("div");for(let t of[...n])e.append(t);return e}}}}();return{morph:function(e,t,n={}){e=i(e);let a=l(t),d=s(e,a,n),c=function(e,t){if(!e.config.restoreFocus)return t();let r=document.activeElement;if(!(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement))return t();let{id:n,selectionStart:o,selectionEnd:a}=r,s=t();return n&&n!==document.activeElement?.getAttribute("id")&&(r=e.target.querySelector(`[id="${n}"]`),r?.focus()),r&&!r.selectionEnd&&a&&r.setSelectionRange(o,a),s}(d,()=>o(d,e,a,t=>"innerHTML"===t.morphStyle?(r(t,e,a),Array.from(e.childNodes)):function(e,t,n){let o=l(t);return r(e,o,n,t,t.nextSibling),Array.from(o.childNodes)}(t,e,a)));return d.pantry.remove(),c},defaults:t}}();let Xa=(e,t,r={})=>{let{preserveTypingAnimation:n=!0}=r;Qa.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement&&n){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"))&&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}}}})},Ya={index:-1,draft:""};function Za(e){return"assistant"===e.role&&"tool"!==e.variant&&"reasoning"!==e.variant&&("approval"===e.variant||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length))}function es(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ts(e,t){return es(e)-e.scrollTop<=t}function rs(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))}}let ns="none",os="none",as=120,ss=1800,is="none",ls=["pre","code","a","script","style"],ds=e=>({type:e?.type??ns,placeholder:e?.placeholder??os,speed:e?.speed??as,duration:e?.duration??ss,buffer:e?.buffer??is}),cs=[{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"}],ps=new Map;for(let e of cs)ps.set(e.name,e);let us=["wipe","glyph-cycle"],hs=e=>{ps.set(e.name,e)},ms=(e,t)=>"none"===e?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:ps.get(e)??null,gs=(e,t,r,n,o)=>{if(!o)return e;if(r?.bufferContent)return r.bufferContent(e,n);if(!e)return e;if("word"===t){let t=e.search(/\s(?=\S*$)/);return t<0?"":e.slice(0,t)}if("line"===t){let t=e.lastIndexOf("\n");return t<0?"":e.slice(0,t)}return e},fs=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${r}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=t,o},ys=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${r}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=t,o},bs=/\s/,vs=(e,t)=>{let r=e.parentNode;for(;r;){if(1===r.nodeType){let e=r;if(t.has(e.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},ws=(e,t,r)=>{let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=e.nodeValue??"";if(!a)return;let s=n.createDocumentFragment(),i=0;for(;i<a.length;)if(bs.test(a[i])){let e=i;for(;e<a.length&&bs.test(a[e]);)e+=1;s.appendChild(n.createTextNode(a.slice(i,e))),i=e}else{let e=n.createElement("span");e.className="persona-stream-word-group";let o=i;for(;o<a.length&&!bs.test(a[o]);)e.appendChild(fs(n,a[o],t,r.value)),r.value+=1,o+=1;s.appendChild(e),i=o}o.replaceChild(s,e)},xs=(e,t,r)=>{let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=e.nodeValue??"";if(!a)return;let s=n.createDocumentFragment(),i=a.split(/(\s+)/);for(let e of i)e&&(/^\s+$/.test(e)?s.appendChild(n.createTextNode(e)):(s.appendChild(ys(n,e,t,r.value)),r.value+=1));o.replaceChild(s,e)},Cs=(e,t,r,n)=>{if(!e||typeof document>"u")return e;let o=document.createElement("div");o.innerHTML=e;let a=new Set((n?.skipTags??ls).map(e=>e.toLowerCase())),s=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],l=s.nextNode();for(;l;)vs(l,a)||i.push(l),l=s.nextNode();let d={value:n?.startIndex??0},c="char"===t?ws:xs;for(let e of i)c(e,r,d);return o.innerHTML},Ss=(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},ks=(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 r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},As=new WeakMap,Ms=new WeakMap,Is=e=>{let t=Ms.get(e);if(t){for(let e of t.values())"function"==typeof e&&e();t.clear()}},Ts=(e,t)=>{((e,t)=>{if(!e.styles)return;let r=As.get(t);if(r||(r=new Set,As.set(t,r)),r.has(e.name)){let n=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${n}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)})(e,t),((e,t)=>{if(!e.onAttach)return;let r=Ms.get(t);if(r||(r=new Map,Ms.set(t,r)),r.has(e.name))return;let n=e.onAttach(t);r.set(e.name,n)})(e,t)},{setLoader:Es,load:Ls}=N({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),Ps=Es,Bs=Ls;function Ns(e,t=1e5){let r=e.style.position,n=e.style.zIndex,o=e.style.isolation,a=getComputedStyle(e),s="static"===a.position||""===a.position;return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=n,e.style.isolation=o}}let Rs=0,Hs=null;function $s(e=document){if(Rs++,1===Rs){let t=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Hs={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:r},t.style.overflow="hidden",t.style.position="fixed",t.style.top=`-${r}px`,t.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Rs=Math.max(0,Rs-1),0===Rs&&Hs)){let t=e.body,r=e.defaultView??window;t.style.overflow=Hs.originalOverflow,t.style.position=Hs.originalPosition,t.style.top=Hs.originalTop,t.style.width=Hs.originalWidth,r.scrollTo(0,Hs.scrollY),Hs=null}}}let Ws="right",Ds="420px",Fs=!0,Os="resize",zs="100dvh",qs=e=>"docked"===(e?.launcher?.mountMode??"floating"),js=e=>"composer-bar"===(e?.launcher?.mountMode??"floating"),_s=e=>{let t=e?.launcher?.dock,r=f(e).dockWidth?t?.width:ya(Ha(e),"components.panel.width");return{side:t?.side??Ws,width:r??Ds,animate:t?.animate??Fs,reveal:t?.reveal??Os,maxHeight:t?.maxHeight??zs}},Us=e=>"followUp"===e?"follow-up":e,Vs=(e,t=0)=>{if("string"==typeof e){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:"default"}:null}let r=e.label.trim();if(!r)return null;let n=e.prompt?.trim()||r;return{id:e.id?.trim()||n||`suggestion-${t}`,label:r,prompt:n,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},Gs=new WeakSet,Ks=e=>{let{item:t,index:o,surface:a,source:s,variant:i,streaming:l,config:d,plugins:c,chipsConfig:p,session:u,getTextarea:h,eventTarget:m,submitPrompt:g}=e,f="followUp"===a,y=t.behavior,b=()=>{if(u.isStreaming())return;let e={suggestion:{...t},surface:a,source:s,behavior:y},r=m.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(f&&m.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!r)return;for(let e of c)if(!1===e.onSuggestionSelect?.({suggestion:{...t},surface:a,source:s,variant:i,config:d}))return;let n=h();"fill"===y?(n.value=t.prompt,n.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),n.focus()):g?g(t.prompt):(n.value="",u.sendMessage(t.prompt))},v=()=>{let e=L("button",`persona-suggestion persona-suggestion--${i}`);if(e.type="button",e.disabled=l,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=y,"chip"===i&&(p?.fontWeight&&(e.style.fontWeight=p.fontWeight),p?.paddingX&&(e.style.paddingLeft=p.paddingX,e.style.paddingRight=p.paddingX),p?.paddingY&&(e.style.paddingTop=p.paddingY,e.style.paddingBottom=p.paddingY)),t.icon){let r=K(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);r&&(r.classList.add("persona-suggestion__icon"),t.iconColor&&(r.style.color=t.iconColor),e.appendChild(r))}let o=L("span","persona-suggestion__copy");if(o.appendChild(P("span",{className:"persona-suggestion__label",text:t.label})),t.description&&"chip"!==i&&o.appendChild(P("span",{className:"persona-suggestion__description",text:t.description})),e.appendChild(o),"chip"!==i){let t=n(r.ArrowRight,16,"currentColor",1.8);t&&(t.classList.add("persona-suggestion__arrow"),e.appendChild(t))}return e.addEventListener("click",b),e},w=null;for(let e of c)if(e.renderSuggestion&&(w=e.renderSuggestion({suggestion:{...t},index:o,surface:a,source:s,variant:i,streaming:l,config:d,defaultRenderer:v,select:b}),w))break;return w??=v(),w.dataset.suggestionId||=t.id,w.dataset.behavior||=y,w.dataset.emphasis||=t.emphasis,w instanceof HTMLButtonElement||w.setAttribute("aria-disabled",l?"true":"false"),w},Js=e=>{let t=[],r=[],n=null,o=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(o=null,e.hidden||"chip"!==e.dataset.variant||"scroll"!==e.dataset.overflow)return void a();let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1)return void a();let r="rtl"===getComputedStyle(e).direction,n=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),s=n<=4,i=n>=t-4,l=r?!i:!s,d=r?!s:!i;e.toggleAttribute("data-scroll-left",l),e.toggleAttribute("data-scroll-right",d)},i=()=>{null!==o||"function"!=typeof requestAnimationFrame?"function"!=typeof requestAnimationFrame&&s():o=requestAnimationFrame(s)};e.addEventListener("scroll",i,{passive:!0});let l="function"==typeof ResizeObserver?new ResizeObserver(i):null;return l?.observe(e),{buttons:t,elements:r,destroy:()=>{e.removeEventListener("scroll",i),l?.disconnect(),null!==o&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(o),o=null},render:(o,l,d,c,p,u)=>{e.replaceChildren(),t.length=0,r.length=0;let h=u?.source??"config",m=u?.surface??("config"===h?"starter":"followUp"),g="followUp"===m,f=u?.variant??"chip",y=u?.behavior??"send",b=u?.overflow??"wrap",v=u?.config??{},w=u?.plugins??[],x="number"==typeof u?.maxItems?Math.max(0,Math.floor(u.maxItems)):void 0,C=g?"followUps":"starters";!Gs.has(v)&&!0===v.debug&&"chip"!==f&&void 0!==v.suggestions?.[C]?.overflow&&(Gs.add(v),console.info(`[persona] suggestions.${C}.overflow applies to the "chip" variant only; the "${f}" variant manages its own stacking.`));let S=e=>e.map(Vs).filter(e=>null!==e).map(e=>({...e,behavior:e.behavior??y})),k=S(o??[]);w.forEach(e=>{e.transformSuggestions&&(k=S(e.transformSuggestions({suggestions:k.map(e=>({...e})),surface:m,source:h,config:v})))});let A=void 0===x?k:k.slice(0,x);if(!A.length)return e.hidden=!0,n=null,void a();if(!g&&(c??l.getMessages()).some(e=>"user"===e.role))return e.hidden=!0,void(n=null);e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Us(m),e.dataset.variant=f,e.dataset.overflow=b;let M=document.createDocumentFragment(),I=l.isStreaming();A.forEach((n,o)=>{let a=Ks({item:n,index:o,surface:m,source:h,variant:f,streaming:I,config:v,plugins:w,chipsConfig:p,session:l,getTextarea:()=>d,eventTarget:e,submitPrompt:u?.submitPrompt});M.appendChild(a),r.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll("button"))].forEach(e=>{t.includes(e)||(e.disabled=I,t.push(e))})}),e.appendChild(M),s(),i();let T=JSON.stringify({normalized:A,surface:m,variant:f,source:h});T!==n&&(n=T,(e=>{typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||e.forEach((e,t)=>{"function"==typeof e.animate&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:60*t,easing:"ease-out",fill:"backwards"})})})(r),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:A.map(e=>({...e})),surface:m,source:h,variant:f},bubbles:!0,composed:!0})),g&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:A.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},Qs={"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"},Xs={x:[1.4,1.05]},Ys="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Zs=(e,t,r={})=>{let{iconSize:n,iconText:o}=r,[a,s]=Xs[t]??[1,1.5],i=!n;e.classList.toggle("persona-header-control--glyph",i),e.classList.toggle("persona-header-control--sparse",i&&1!==a);let l=K(t,`${Math.round((parseFloat(n??"")||20)*a)}px`,"currentColor",s);l?(l.style.display="block",i||(l.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((s/1.5).toFixed(4))})`),e.replaceChildren(l)):o&&(e.textContent=o)},ei=e=>{let{ariaLabel:t,tooltip:r=!0,tooltipHint:n,iconName:o,iconText:a,wrapperClassName:s=Ys,size:i,iconSize:l,color:d,backgroundColor:c,borderWidth:p,borderColor:u,borderRadius:h,paddingX:m,paddingY:g,hidden:f,extraClassName:y,attrs:b}=e,v=L("div",s),w=!(!p&&!u),x=P("button",{className:B("persona-header-control","persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"persona-bg-transparent hover:persona-bg-gray-100",!w&&"persona-border-none",!h&&"persona-rounded-full",y),attrs:{type:"button","aria-label":t,...b},style:{width:i,height:i,minWidth:i,minHeight:i,display:f?"none":void 0,color:d||ni.actionIconColor,backgroundColor:c,border:w?`${p||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:h,paddingLeft:m,paddingRight:m,paddingTop:g,paddingBottom:g}});return o?Zs(x,o,{iconSize:l,iconText:a}):a&&(x.textContent=a),v.appendChild(x),qn({anchor:x,trigger:v,text:()=>x.getAttribute("aria-label")??t,hint:n,enabled:r}),{button:x,wrapper:v}},ti=(e,t={})=>{let{showClose:r=!0,wrapperClassName:n=Ys,buttonSize:o,iconSize:a}=t,s=e?.launcher??{},i=s.closeButtonTooltipText??"Close chat",l=s.closeButtonShowTooltip??!0,{button:d,wrapper:c}=ei({ariaLabel:i,tooltip:l,iconName:s.closeButtonIconName??"x",iconText:s.closeButtonIconText??"×",wrapperClassName:n,size:o??s.closeButtonSize,iconSize:a,color:s.closeButtonColor,backgroundColor:s.closeButtonBackgroundColor,borderWidth:s.closeButtonBorderWidth,borderColor:s.closeButtonBorderColor,borderRadius:s.closeButtonBorderRadius,paddingX:s.closeButtonPaddingX,paddingY:s.closeButtonPaddingY,hidden:!r});return{button:d,wrapper:c}},ri=(e,t={})=>{let{wrapperClassName:r="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",buttonSize:n,iconSize:o}=t,a=(e?.launcher??{}).clearChat??{},s=a.tooltipText??"Clear chat",i=a.showTooltip??!0,{button:l,wrapper:d}=ei({ariaLabel:s,tooltip:i,iconName:a.iconName??"refresh-cw",wrapperClassName:r,size:n??a.size,iconSize:o,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:l,wrapper:d}},ni={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)"},oi={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)"},ai={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)"},si=e=>{let{config:t,showClose:r=!0}=e,n=P("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:ni.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)))"}}),o=t?.launcher??{},a=o.headerIconSize??"40px",s=o.closeButtonPlacement??"inline",i=o.headerIconHidden??!1,l=o.headerIconName,d=P("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(!i)if(l){let e=parseFloat(a)||24,r=K(l,.6*e,"currentColor",1);r?(r.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,r.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,d.replaceChildren(r)):d.textContent=t?.launcher?.agentIconText??"💬"}else if(t?.launcher?.iconUrl){let e=L("img");e.src=t.launcher.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=a,e.style.width=a,d.replaceChildren(e)}else d.textContent=t?.launcher?.agentIconText??"💬";let c=L("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=P("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:ni.titleColor,...oi}}),u=P("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:ni.subtitleColor,...ai}});c.append(p,u),i?n.append(c):n.append(d,c);let h=o.clearChat??{},m=h.enabled??!0,g=h.placement??"inline",f=null,y=null;if(m){let e=ri(t,{wrapperClassName:"top-right"===g?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});f=e.button,y=e.wrapper,"top-right"===g&&(y.style.right="48px"),"inline"===g&&n.appendChild(y)}let{button:b,wrapper:v}=ti(t,{showClose:r,wrapperClassName:"top-right"===s?"persona-absolute persona-top-4 persona-right-4 persona-z-50":m&&"inline"===g?"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"top-right"!==s&&n.appendChild(v),{header:n,iconHolder:d,headerTitle:p,headerSubtitle:u,closeButton:b,closeButtonWrapper:v,clearChatButton:f,clearChatButtonWrapper:y}},ii=(e,t,r)=>{let n=r?.launcher??{},o=n.closeButtonPlacement??"inline",a=n.clearChat?.placement??"inline";e.appendChild(t.header),"top-right"===o&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&"top-right"===a&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function li(e){let{items:t,onSelect:r,anchor:n,position:o="bottom-left",portal:a,onOpenChange:s}=e,i=L("div","persona-dropdown-menu persona-hidden");i.setAttribute("role","menu"),i.setAttribute("data-persona-theme-zone","dropdown"),a?(i.style.position="fixed",i.style.zIndex="100001"):(i.style.position="absolute",i.style.top="100%",i.style.marginTop="4px","bottom-right"===o?i.style.right="0":i.style.left="0");for(let e of t){if(e.dividerBefore){let e=document.createElement("hr");i.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 r=K(e.icon,16,"currentColor",1.5);r&&t.appendChild(r)}let n=document.createElement("span");n.textContent=e.label,t.appendChild(n),t.addEventListener("click",t=>{t.stopPropagation(),c(),r(e.id)}),i.appendChild(t)}let l=null;function d(){let e=i.classList.contains("persona-hidden");(function(){if(!a)return;let e=n.getBoundingClientRect();i.style.top=`${e.bottom+4}px`,"bottom-right"===o?(i.style.right=window.innerWidth-e.right+"px",i.style.left="auto"):(i.style.left=`${e.left}px`,i.style.right="auto")})(),i.classList.remove("persona-hidden"),e&&s?.(!0),requestAnimationFrame(()=>{let e=e=>{!i.contains(e.target)&&!n.contains(e.target)&&c()};document.addEventListener("click",e,!0),l=()=>document.removeEventListener("click",e,!0)})}function c(){let e=!i.classList.contains("persona-hidden");i.classList.add("persona-hidden"),l?.(),l=null,e&&s?.(!1)}return a&&a.appendChild(i),{element:i,show:d,hide:c,toggle:function(){i.classList.contains("persona-hidden")?d():c()},destroy:function(){c(),i.remove()}}}function di(e){let{icon:t,label:r,size:n,strokeWidth:o,className:a,chromeless:s,onClick:i,aria:l}=e,d=L("button",B(!s&&"persona-icon-btn",a));d.type="button",d.setAttribute("aria-label",r),d.title=r;let c=K(t,n??16,"currentColor",o??2);if(c&&d.appendChild(c),i&&d.addEventListener("click",i),l)for(let[e,t]of Object.entries(l))d.setAttribute(e,t);return d}function ci(e){let{icon:t,label:r,variant:n="default",size:o="sm",iconSize:a,className:s,onClick:i,aria:l}=e,d="persona-label-btn";"default"!==n&&(d+=" persona-label-btn--"+n),d+=" persona-label-btn--"+o,s&&(d+=" "+s);let c=L("button",d);if(c.type="button",c.setAttribute("aria-label",r),t){let e=K(t,a??14,"currentColor",2);e&&c.appendChild(e)}let p=L("span");if(p.textContent=r,c.appendChild(p),i&&c.addEventListener("click",i),l)for(let[e,t]of Object.entries(l))c.setAttribute(e,t);return c}function pi(e){let{label:t,icon:r="chevron-down",menuItems:n,onSelect:o,position:a="bottom-left",portal:s,className:i,hover:l}=e,d=L("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=L("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let p=K(r,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",d.appendChild(p)),l&&(d.style.borderRadius=l.borderRadius??"10px",d.style.padding=l.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=l.background??"",d.style.borderColor=l.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let u=li({items:n,onSelect:e=>{d.setAttribute("aria-expanded","false"),o(e)},anchor:d,position:a,portal:s});return s||d.appendChild(u.element),d.addEventListener("click",e=>{if(e.stopPropagation(),"true"===d.getAttribute("data-persona-menu-locked"))return;let t=!u.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",t?"false":"true"),u.toggle()}),d.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),d.click())}),{element:d,setLabel:e=>{c.textContent=e,d.setAttribute("aria-label",e)},open:()=>{d.setAttribute("aria-expanded","true"),u.show()},close:()=>{d.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let e=!u.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",e?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),d.remove()}}}let ui=e=>{let t=si({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=e.layoutHeaderConfig?.onTitleClick;if(r){let e=t.headerTitle.parentElement;e&&(e.style.cursor="pointer",e.setAttribute("role","button"),e.setAttribute("tabindex","0"),e.addEventListener("click",()=>r()),e.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),r())}))}return t},hi=e=>{let{config:t,showClose:r=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:a}=e,s=t?.launcher??{},i=L("div","persona-flex persona-items-center persona-justify-between");i.setAttribute("data-persona-theme-zone","header"),i.style.minHeight=ni.minHeight,i.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let l,d,c=o?.titleMenu;if(c){let e=pi({label:s.title??"Chat Assistant",menuItems:c.menuItems,onSelect:t=>{let r=r=>{!1===r&&e.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:t}}))},n=c.onSelect(t);n instanceof Promise?n.then(r,()=>{}):r(n)},hover:c.hover,className:""});l=e.element,l.style.color=ni.titleColor,d=l.querySelector(".persona-combo-btn-label")??l}else{if(l=L("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=L("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=ni.titleColor,Object.assign(d.style,oi),d.textContent=s.title??"Chat Assistant",l.appendChild(d),o?.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let e=o.onTitleClick;l.addEventListener("click",t=>{t.target.closest("button")||e()}),l.addEventListener("keydown",t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),e())})}let e=o?.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"}))}i.appendChild(l);let p="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:u,wrapper:h}=ti(t,{showClose:r,wrapperClassName:p});n&&u.addEventListener("click",n);let m=L("div","persona-flex persona-items-center persona-gap-1");c||function(e,t,r){if(t?.length)for(let n of t){let{button:t,wrapper:o}=ei({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?Ua(n.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(t.setAttribute("data-persona-header-action",n.id),n.shortcut){let e=Va(n.shortcut);e&&t.setAttribute("aria-keyshortcuts",e)}if(n.menuItems?.length){let e=li({items:n.menuItems,onSelect:e=>r?.(e),anchor:o,position:"bottom-right"});o.appendChild(e.element),t.addEventListener("click",t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener("click",()=>r?.(n.id));e.appendChild(o)}}(m,o?.trailingActions,o?.onAction??a);let g=s.clearChat??{},f=null,y=null;if(g.enabled??1){let e=g.placement??"inline",r=ri(t,{wrapperClassName:"top-right"===e?"persona-absolute persona-top-4 persona-z-50":p});f=r.button,y=r.wrapper,"top-right"===e?y.style.right="48px":m.appendChild(y)}m.appendChild(h),i.appendChild(m);let b=L("div");b.style.display="none";let v=L("span");return v.style.display="none",{header:i,iconHolder:b,headerTitle:d,headerSubtitle:v,closeButton:u,closeButtonWrapper:h,clearChatButton:f,clearChatButtonWrapper:y}},mi={default:ui,minimal:hi},gi=e=>mi[e]??mi.default,fi=(e,t,r)=>{if(t?.render){let n=t.render({config:e,onClose:r?.onClose,onClearChat:r?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),o=L("div");o.style.display="none";let a=L("span"),s=L("span"),i=L("button");i.style.display="none";let l=L("div");return l.style.display="none",{header:n,iconHolder:o,headerTitle:a,headerSubtitle:s,closeButton:i,closeButtonWrapper:l,clearChatButton:null,clearChatButtonWrapper:null}}let n=gi(t?.layout??"default")({config:e,showClose:t?.showCloseButton??r?.showClose??!0,onClose:r?.onClose,onClearChat:r?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(!1===t.showIcon&&(n.iconHolder.style.display="none"),!1===t.showTitle&&(n.headerTitle.style.display="none"),!1===t.showSubtitle&&(n.headerSubtitle.style.display="none"),!1===t.showCloseButton&&(n.closeButton.style.display="none"),!1===t.showClearChat&&n.clearChatButtonWrapper&&(n.clearChatButtonWrapper.style.display="none")),n},yi=e=>{let{config:t}=e,r=P("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"}}),n=io(),o=P("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:s}=to(t);s();let i=no(t),l=oo(t),d=ao(t),c=so(t),p=P("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});o.append(p),d&&(d.previewsContainer.style.gap="8px",p.append(d.previewsContainer),o.append(d.input)),o.append(a);let u=P("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=P("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),m=P("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return d&&h.append(d.wrapper),l&&m.append(l.wrapper),m.append(i.wrapper),u.append(h,m),o.append(u),o.addEventListener("click",e=>{e.target!==i.button&&e.target!==i.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&e.target!==d?.button&&e.target!==d?.wrapper&&a.focus()}),"transient"===t?.statusIndicator?.mode?r.append(n,c,o):r.append(n,o,c),{footer:r,suggestions:n,composerForm:o,header:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:h,rightActions:m,setSendButtonMode:i.setMode}},bi=()=>{let e=P("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=L("span","persona-pill-peek__icon"),o=n(r.MessageSquare,16,"currentColor",1.5);o&&t.appendChild(o);let a=L("span","persona-pill-peek__text"),s=L("span","persona-pill-peek__caret"),i=n(r.ChevronUp,16,"currentColor",1.5);return i&&s.appendChild(i),e.append(t,a,s),{root:e,textNode:a}},vi=e=>{let{config:t}=e,r=P("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=io(),o=so(t);o.style.display="none";let{textarea:a,attachAutoResize:s}=to(t,{defaultMaxLines:5});s();let i=no(t),l=oo(t),d=ao(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=P("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),p=P("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});d&&p.append(d.wrapper);let u=P("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});l&&u.append(l.wrapper),u.append(i.wrapper),c.addEventListener("click",e=>{e.target!==i.button&&e.target!==i.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&e.target!==d?.button&&e.target!==d?.wrapper&&a.focus()}),d&&c.append(d.input),c.append(p,a,u);let h=P("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(h),d&&h.append(d.previewsContainer),r.append(n,c,o);let m=c;return{footer:r,suggestions:n,composerForm:c,header:h,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:o,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:m,leftActions:p,rightActions:u,setSendButtonMode:i.setMode}};function wi(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let r=P("span",{className:B("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&&r.style.setProperty("--persona-mention-token-accent",e.color);let n=K(e.iconName??"at-sign",13,"currentColor",2);if(n){let e=L("span","persona-mention-token-icon");e.appendChild(n),r.appendChild(e)}return r.appendChild(P("span",{className:"persona-mention-token-label",text:`@${e.label}`})),r}let xi=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")||!/^(?:https?|blob):/i.test(e)&&!t.startsWith("data:")&&e.includes(":"))},Ci=e=>{if(!e||0===e.length)return null;let t=P("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let r of e){let e=P("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:r.label}}),n=L("span","persona-mention-chip-icon"),o=K(r.iconName??"at-sign",13,"currentColor",2);o&&n.appendChild(o),e.appendChild(n),e.appendChild(P("span",{className:"persona-mention-chip-label",text:r.label})),t.appendChild(e)}return t},Si=()=>{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 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="250ms";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="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(n),e.appendChild(o),e},ki=(e,t,r)=>{let n={config:r??{},streaming:!0,location:e,defaultRenderer:Si};if(t){let e=t(n);if(null!==e)return e}return Si()},Ai=(e,t,r="div")=>{let n=L(r,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return n.textContent=t.format?t.format(o):o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Mi=(e,t="bubble")=>{let r=["persona-message-bubble"];switch(t){case"flat":"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.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 r},Ii={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"}},Ti=e=>`custom:${e}`,Ei=(e,t)=>"user"!==t&&"assistant"!==t?[]:(e?.custom??[]).filter(e=>(e.roles??["assistant"]).includes(t)),Li=(e,t,r,n)=>{let o=t.showCopy??!0,a=t.showUpvote??!1,s=t.showDownvote??!1,i=t.showReadAloud??!1,l=(t.showRegenerate??!1)&&!0===n?.canRegenerate,d=(t.showEdit??!1)&&!0===n?.canEdit,c=(t.showQuote??!1)&&!1!==n?.canQuote,p=Ei(t,e.role);if(!(o||a||s||i||l||d||c||0!==p.length)){let t=L("div");return t.style.display="none",t.id=`actions-${e.id}`,t.setAttribute("data-actions-for",e.id),t}let u=t.visibility??"hover",h=t.align??"right",m=t.layout??"pill-inside",g=L("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${{left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h]} ${{"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[m]} ${"hover"===u?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(e,t,r)=>{let n=di({icon:e,label:t,size:14,className:"persona-message-action-btn",chromeless:!0});return n.setAttribute("data-action",r),n};o&&g.appendChild(f("copy","Copy message","copy")),i&&g.appendChild(f("volume-2","Read aloud","read-aloud")),a&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),l&&g.appendChild(f("refresh-cw","Regenerate response","regenerate")),d&&g.appendChild(f("pencil","Edit message","edit")),c&&g.appendChild(f("quote","Quote message","quote"));for(let e of p)g.appendChild(f(e.iconName??"ellipsis",e.label,Ti(e.id)));return g},Pi=(e,t,r,n,o,a)=>{let s=r??{},i=s.layout??"bubble",l=s.avatar,d=s.timestamp,c=l?.show??!1,p=d?.show??!1,u=l?.position??"left",h=d?.position??"below",m=Mi(e.role,i),g=L("div",m.join(" "));g.id=`bubble-${e.id}`,g.setAttribute("data-message-id",e.id),g.setAttribute("data-persona-theme-zone","user"===e.role?"user-message":"assistant-message");let f=fa(a?.widgetConfig?.future).components.message,y=a?.widgetConfig?.theme?.components?.message;((e,t,r="bubble",n)=>{if(!n)return;let o="user"===t?"user":"assistant",a=Ii[r??"bubble"]??Ii.bubble;n.padding&&(e.style.padding=`var(--persona-message-${o}-padding, ${a.padding})`),n.fontSize&&(e.style.fontSize=`var(--persona-message-${o}-font-size, ${a.fontSize})`),n.lineHeight&&(e.style.lineHeight=`var(--persona-message-${o}-line-height, ${a.lineHeight})`),n.fontFamily&&(e.style.fontFamily=`var(--persona-message-${o}-font-family, inherit)`)})(g,e.role,i,"user"===e.role?{...f.user,...y?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...f.assistant,...y?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),"flat"===i?(g.style.backgroundColor="transparent",g.style.color="user"===e.role?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):"user"===e.role?(g.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",g.style.color="var(--persona-message-user-text, white)"):"assistant"===e.role&&(g.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",g.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"image"===e.type&&"string"==typeof e.image&&e.image.trim().length>0):[])(e),v=e.content?.trim()??"",w=b.length>0&&"[Image]"===v,x=ds(a?.widgetConfig?.features?.streamAnimation),C=a?.widgetConfig?.features?.streamAnimation?.plugins,S="assistant"===e.role&&"none"!==x.type?ms(x.type,C):null,k="assistant"===e.role&&!0===S?.isAnimating?.(e),A="assistant"===e.role&&null!==S&&(!!e.streaming||k);A&&S?.bubbleClass&&g.classList.add(S.bubbleClass);let M=document.createElement("div");M.classList.add("persona-message-content"),e.streaming&&M.classList.add("persona-content-streaming"),A&&S&&(S.containerClass&&M.classList.add(S.containerClass),M.style.setProperty("--persona-stream-step",`${x.speed}ms`),M.style.setProperty("--persona-stream-duration",`${x.duration}ms`));let I=A?gs(e.content??"",x.buffer,S,e,!!e.streaming):e.content??"",T=()=>{let r=t({text:I,message:e,streaming:!!e.streaming,raw:e.rawContent});return A&&"char"===S?.wrap?Cs(r,"char",e.id,{skipTags:S.skipTags}):A&&"word"===S?.wrap?Cs(r,"word",e.id,{skipTags:S.skipTags}):r},E=null;if(w?(E=document.createElement("div"),E.innerHTML=T(),E.style.display="none",M.appendChild(E)):e.contentSegments?.length?((e,t,r,n)=>{let o=Math.random().toString(36).slice(2,8),a=e=>`${o}:${e}`,s=r(t.map((e,t)=>"text"===e.kind?e.text:a(t)).join(""));if(!t.every((e,t)=>"text"===e.kind||s.includes(a(t))))return void e.replaceChildren(((e,t)=>{let r=document.createDocumentFragment();for(let n of e)"text"===n.kind?r.appendChild(document.createTextNode(n.text)):r.appendChild(wi(n.ref,{readonly:!0,render:t}));return r})(t,n));e.innerHTML=s;let i=RegExp(`${o}:(\\d+)`),l=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),d=[];for(let e=l.nextNode();e;e=l.nextNode())d.push(e);for(let e of d){let r=e;for(let e=i.exec(r.data);e;e=i.exec(r.data)){let o=t[Number(e[1])],a=r.splitText(e.index);a.data=a.data.slice(e[0].length),"mention"===o?.kind&&a.parentNode?.insertBefore(wi(o.ref,{readonly:!0,render:n}),a),r=a}}})(M,e.contentSegments,r=>t({text:r,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):M.innerHTML=T(),A&&S?.useCaret&&!w&&v){let e=Ss(),t=M.querySelectorAll(".persona-stream-char, .persona-stream-word"),r=t[t.length-1];if(r?.parentNode)r.parentNode.insertBefore(e,r.nextSibling);else{let t=M.lastElementChild;t?t.appendChild(e):M.appendChild(e)}}if(p&&"inline"===h&&e.createdAt){let t=Ai(e,d,"span");t.classList.add("persona-timestamp-inline");let r=M.lastElementChild;r?r.appendChild(t):M.appendChild(t)}if(b.length>0){let e=((e,t,r)=>{if(0===e.length)return null;try{let n=L("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let o=0,a=!1,s=()=>{a||(a=!0,n.remove(),r?.())};return e.forEach((e,t)=>{let r=L("img");r.alt=e.alt?.trim()||`Attached image ${t+1}`,r.loading="lazy",r.decoding="async",r.referrerPolicy="no-referrer",r.style.display="block",r.style.width="100%",r.style.maxWidth="320px",r.style.maxHeight="320px",r.style.height="auto",r.style.objectFit="contain",r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let a=!1;o+=1,r.addEventListener("error",()=>{a||(a=!0,o=Math.max(0,o-1),r.remove(),0===o&&s())}),r.addEventListener("load",()=>{a=!0}),(e=>{let t=e.toLowerCase();return!(t.startsWith("data:image/svg+xml")||!/^(?:https?|blob):/i.test(e)&&!t.startsWith("data:image/")&&e.includes(":"))})(e.image)?(r.src=e.image,n.appendChild(r)):(a=!0,o=Math.max(0,o-1),r.remove())}),0===o?(s(),null):n}catch{return r?.(),null}})(b,!w&&!!v,()=>{w&&E&&(E.style.display="")});e?g.appendChild(e):w&&E&&(E.style.display="")}let P=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"audio"===e.type&&"string"==typeof e.audio&&e.audio.trim().length>0):[])(e);if(P.length>0){let e=(e=>{if(0===e.length)return null;try{let t=L("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(e=>{if(!xi(e.audio))return;let n=L("audio");n.controls=!0,n.preload="metadata",n.src=e.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth="320px",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(P);e&&g.appendChild(e)}let B=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"video"===e.type&&"string"==typeof e.video&&e.video.trim().length>0):[])(e);if(B.length>0){let e=(e=>{if(0===e.length)return null;try{let t=L("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(e=>{if(!xi(e.video))return;let n=L("video");n.controls=!0,n.preload="metadata",n.src=e.video,n.style.display="block",n.style.width="100%",n.style.maxWidth="320px",n.style.maxHeight="320px",n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(B);e&&g.appendChild(e)}let N=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"file"===e.type&&"string"==typeof e.data&&e.data.trim().length>0):[])(e);if(N.length>0){let e=(e=>{if(0===e.length)return null;try{let t=L("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(e=>{if(!xi(e.data))return;let n=L("a");n.href=e.data,n.download=e.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=e.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(N);e&&g.appendChild(e)}let R=e.contentSegments?.length?null:Ci(e.contextMentions);if(R&&g.appendChild(R),g.appendChild(M),p&&"below"===h&&e.createdAt){let t=Ai(e,d);t.classList.add("persona-mt-1"),g.appendChild(t)}let H="assistant"===e.role?((e,t)=>{if(!e)return null;let r=(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}})(e);if(null===r)return null;let n=t?.[e];return(void 0===n?r:n)||null})(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&"assistant"===e.role){let e=!(!I||!I.trim()),t="skeleton"===x.placeholder,r=t&&"line"===x.buffer&&e;if(e)r&&g.appendChild(ks());else if(t)g.appendChild(ks());else{let e=ki("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);e&&g.appendChild(e)}}H&&e.stopReason&&!e.streaming&&(v||(M.style.display="none"),g.appendChild(((e,t)=>{let r=L("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r})(e.stopReason,H)));let $="assistant"===e.role&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&!1!==n?.enabled,W=a?.actionEligibility,D="user"===e.role&&!e.streaming&&!1!==n?.enabled&&(!0===n?.showEdit&&!0===W?.canEdit||!0===n?.showQuote&&!0===W?.canQuote||Ei(n,"user").length>0);if(($||D)&&n){let t=Li(e,D?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,0,W);g.appendChild(t)}if(!c||"system"===e.role)return g;let F=L("div","persona-message-with-avatar persona-flex persona-gap-2 "+("user"===e.role?"persona-flex-row-reverse":"")),O=((e,t)=>{let r=L("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"),n="user"===t?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let e=L("img");e.src=n,e.alt="user"===t?"User":"Assistant",e.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(e)}else r.textContent=n,r.classList.add("user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent="user"===t?"U":"A",r.classList.add("user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r})(l,e.role);return"right"===u||"left"===u&&"user"===e.role?F.append(g,O):F.append(O,g),F},Bi=(e,t,r)=>{t.hidden=!r,t.style.display=r?"":"none",e.classList.toggle("persona-gap-6",r),e.classList.toggle("persona-gap-3",!r)},Ni=(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,((e,t)=>{if(e.replaceChildren(),t)if("function"==typeof t){let r=null;try{r=t()}catch(e){console.warn("[persona] welcome.icon renderer threw",e)}if(!r)return void(e.hidden=!0);e.appendChild(r),e.hidden=!1}else{if("lucide"===t.type){let r=K(t.name,40);if(!r)return void(e.hidden=!0);e.appendChild(r)}else"image"===t.type?e.appendChild(P("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(P("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1}else e.hidden=!0})(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"),"inline"===t.iconPlacement?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")},Ri="data-persona-welcome-overlay",Hi="persona-welcome-overlay-active",$i=new WeakMap,Wi=(e,t,r)=>{r.setAttribute("data-persona-welcome-plugin",""),t.appendChild(r),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(Ri,""),e.classList.contains(Hi)||($i.set(e,e.scrollTop),e.classList.add(Hi),e.scrollTop=0)},Di=(e,t,r)=>{r&&r!==t&&r.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(Ri),e.classList.contains(Hi)&&(e.classList.remove(Hi),e.scrollTop=$i.get(e)??e.scrollTop,$i.delete(e))},Fi=(e,t,r)=>{if(e.replaceChildren(),!t)return void(e.hidden=!0);let n=r?.layout?.messages?.layout??"bubble",o=P("div",{className:Mi("assistant",n).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:"flat"===n?{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(P("div",{className:"persona-flex"},o)),e.hidden=!1},Oi=()=>typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,zi=new WeakSet,qi=(e,t)=>!!e&&void 0!==e[t],ji=(e,t=!0===e?.launcher?.fullHeight&&!e.launcher.sidebarMode&&"docked"!==e.launcher.mountMode)=>{let r=e?.welcome,n=e?.copy,o=!0===e?.future?.v5Defaults,a=r?.layout??(o?"centered":"top"),s=qi(r,"variant")?r.variant:!1===n?.showWelcomeCard?"none":"card",i="hero"!==s||o||void 0!==r?.layout?qi(r,"dismiss")?r.dismiss:o||"hero"===s?"on-first-message":"never":"on-first-message",l=[];qi(r,"title")&&qi(n,"welcomeTitle")&&l.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),qi(r,"subtitle")&&qi(n,"welcomeSubtitle")&&l.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),qi(r,"variant")&&qi(n,"showWelcomeCard")&&l.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),"hero"===s&&qi(r,"message")&&l.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!o&&void 0===r?.layout&&"hero"===s&&qi(r,"dismiss")&&"on-first-message"!==r.dismiss&&l.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let d=r?.anchor??("centered"===a&&t?"center":"bottom"),c=null!==Oa(r?.anchorComposerTop);return qi(r,"anchorComposerTop")&&!c&&l.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),"center"!==d&&(qi(r,"anchorComposerTop")||qi(r,"composerGap"))&&l.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),((e,t)=>{e&&!0===e.debug&&t.length&&(zi.has(e)||(zi.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))})(e,l),{title:qi(r,"title")?r.title:n?.welcomeTitle??(o?"What can I help with?":"Hello 👋"),kicker:r?.kicker??"",subtitle:qi(r,"subtitle")?r.subtitle:n?.welcomeSubtitle??(o?"":"I can answer questions and help you get things done here."),icon:r?.icon,align:"start"===r?.align||"center"===r?.align?r.align:"centered"===a?"center":void 0,iconPlacement:r?.icon&&"function"!=typeof r.icon&&"inline"===r.icon.placement?"inline":"above",variant:s,dismiss:i,message:"hero"===s?void 0:r?.message,layout:a,anchor:d,anchorComposerTop:c?r.anchorComposerTop:"44%",composerGap:r?.composerGap?.trim()||"24px"}},_i=(e,t)=>"none"!==e.variant&&("never"===e.dismiss||!(t??[]).some(e=>"user"===e.role)),Ui="var(--persona-components-panel-height)",Vi=e=>{let t=f(e),r=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,n=e?.launcher?.heightOffset??0;return{width:r??"var(--persona-components-panel-width)",maxWidth:r??"var(--persona-components-panel-maxWidth)",height:0===n?`max(200px, ${Ui})`:`max(200px, calc(${Ui} - ${n}px))`,maxHeight:"var(--persona-components-panel-maxHeight)"}},Gi="16px",Ki="10px",Ji="14px",Qi=e=>{let t=P("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Us(e)}});return t.hidden=!0,t},Xi=(e,t)=>{let r=((e,t,r={})=>{let n=P("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});n.hidden=!0;let o=L("p","persona-welcome-kicker");o.hidden=!0;let a=L("h2","persona-welcome-title"),s=L("p","persona-welcome-subtitle"),i=P("div",{className:"persona-welcome-head-text"},o,a),l=P("div",{className:"persona-welcome-title-row"},n,i);return{host:P("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:r.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},l,s,t),iconHolder:n,kicker:o,title:a,subtitle:s,starterSuggestions:t}})(0,Qi("starter"),{flatShadow:qs(e)}),n=ji(e);Ni(r,n),Bi(t,r.host,_i(n,e?.initialMessages));let o=(()=>{let e=P("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e})();return Fi(o,n.message,e),{welcome:r,greetingHost:o}},Yi=(e,t)=>{let r=L("button");r.type="button",r.innerHTML='\n <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>\n <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />\n <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">\n <span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-launcher" data-role="launcher-title"></span>\n <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>\n </span>\n <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>\n ',r.addEventListener("click",t);let n=e=>{let t=e.launcher??{},n=qs(e),o="circle"===Zo(e);o?(r.dataset.personaLauncherVariant="circle",r.setAttribute("aria-label",t.title??"Open chat")):(r.removeAttribute("data-persona-launcher-variant"),r.removeAttribute("aria-label"));let a=r.querySelector("[data-role='launcher-title']");if(a){let e=t.title??"Chat Assistant";a.textContent=e,a.setAttribute("title",e)}let s=r.querySelector("[data-role='launcher-subtitle']");if(s){let e=t.subtitle??"Here to help you get answers fast";s.textContent=e,s.setAttribute("title",e)}let i=r.querySelector(".persona-flex-col");i&&(t.textHidden||n||o?i.style.display="none":i.style.display="");let l=r.querySelector("[data-role='launcher-icon']");if(l)if(t.agentIconHidden)l.style.display="none";else{let e=t.agentIconSize??"40px";if(l.style.height=e,l.style.width=e,t.agentIconBackgroundColor?(l.style.backgroundColor=t.agentIconBackgroundColor,l.classList.remove("persona-bg-persona-primary")):(l.style.backgroundColor="",l.classList.add("persona-bg-persona-primary")),l.innerHTML="",t.agentIconName){let r=parseFloat(e)||24,n=K(t.agentIconName,.6*r,"var(--persona-text-inverse, #ffffff)",1.5);n?(l.appendChild(n),l.style.display=""):(l.textContent=t.agentIconText??"💬",l.style.display="")}else t.iconUrl?l.style.display="none":(l.textContent=t.agentIconText??"💬",l.style.display="")}let d=r.querySelector("[data-role='launcher-image']");if(d){let e=t.agentIconSize??"40px";d.style.height=e,d.style.width=e,!t.iconUrl||t.agentIconName||t.agentIconHidden?d.style.display="none":(d.src=t.iconUrl,d.style.display="block")}let c=r.querySelector("[data-role='launcher-call-to-action-icon']");if(c){let e=t.callToActionIconSize??"32px";c.style.height=e,c.style.width=e,t.callToActionIconBackgroundColor?(c.style.backgroundColor=t.callToActionIconBackgroundColor,c.classList.remove("persona-bg-persona-primary")):(c.style.backgroundColor="",c.classList.add("persona-bg-persona-primary")),t.callToActionIconColor?(c.style.color=t.callToActionIconColor,c.classList.remove("persona-text-persona-call-to-action")):(c.style.color="",c.classList.add("persona-text-persona-call-to-action"));let r=0;if(t.callToActionIconPadding?(c.style.boxSizing="border-box",c.style.padding=t.callToActionIconPadding,r=2*(parseFloat(t.callToActionIconPadding)||0)):(c.style.boxSizing="",c.style.padding=""),t.callToActionIconHidden||o)c.style.display="none";else if(c.style.display=n?"none":"",c.innerHTML="",t.callToActionIconName){let n=Math.max((parseFloat(e)||24)-r,8),o=K(t.callToActionIconName,n,"currentColor",1.5);o?c.appendChild(o):c.textContent=t.callToActionIconText??"↗"}else c.textContent=t.callToActionIconText??"↗"}let p=t.position&&Qs[t.position]?Qs[t.position]:Qs["bottom-right"];r.className=n?"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 ${p}`,n||(r.style.zIndex=String(t.zIndex??1e5)),r.style.border=t.border??"1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",r.style.boxShadow=void 0===t.shadow?"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,n?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=t.collapsedMaxWidth??"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")};return e&&n(e),{element:r,update:n,destroy:()=>{r.removeEventListener("click",t),r.remove()}}},Zi=new Set,el=e=>{let t=e?.persistState;return`${("object"==typeof t?t?.keyPrefix:void 0)??"persona-"}teaser-dismissed`},tl=(e,t)=>{let r=L("div","persona-launcher-surface");r.setAttribute("data-persona-launcher-surface","true");let n=e??{},o=null,a=null,s=null,i=null,l=null,d=!1,c=!1,p=!1,u=!1,h=()=>"once"===(o?.frequency??"once")&&!1!==n.persistState,m=()=>{null!==l&&(clearTimeout(l),l=null)},g=e=>{m(),p=!0,a&&d&&(d=!1,a.hidden=!0),((e,t)=>{if(Zi.add(e),t)try{window.localStorage.setItem(e,"1")}catch{}})(el(n),e&&h())},f=e=>{o&&!p&&g("user"===e&&d)},y=()=>{l=null,a&&!p&&!u&&(c=!0,d=!0,a.hidden=!1,!(typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||"function"!=typeof a.animate)&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},b=()=>{g(h()),t()},v=e=>{e.stopPropagation(),g(h())},w=Yi(e,()=>{f("user"),t()}),x=()=>{m(),i?.removeEventListener("click",b),s?.removeEventListener("click",v),a?.remove(),a=null,i=null,s=null,d=!1},C=()=>{let e=n.launcher?.position??"bottom-right",t=Qs[e]??Qs["bottom-right"];a?(r.className=B("persona-launcher-surface",t),r.setAttribute("data-teaser",e),r.style.zIndex=String(n.launcher?.zIndex??1e5),w.element.style.position="static"):(r.className="persona-launcher-surface",r.removeAttribute("data-teaser"),r.style.zIndex="",w.element.style.position="")},S=e=>{let t=(e=>{let t=e?.launcher?.teaser;return t&&t.text&&!1!==e?.launcher?.enabled&&!qs(e??{})?t:null})(e);o=t,t?(a||(i=P("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),i.addEventListener("click",b),s=P("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"×"}),s.addEventListener("click",v),a=P("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},i,s),r.insertBefore(a,w.element)),i.textContent=t.text,s.hidden=!1===t.dismissible,s.setAttribute("aria-label",t.dismissLabel??"Dismiss message"),o&&a&&(p||c||u||((e,t)=>{if(Zi.has(e))return!0;if(!t)return!1;try{return"1"===window.localStorage.getItem(e)}catch{return!1}})(el(n),h())||(m(),l=setTimeout(y,Math.max(0,o.delayMs??0))))):x()};return r.appendChild(w.element),e&&(S(e),C()),{element:r,launcher:w,get teaser(){return a?{element:a,show:y,dismiss:g}:null},setPanelOpen:(e,t="user")=>{u=e,e&&f(t)},update:e=>{n=e,w.update(e),S(e),C()},destroy:()=>{x(),w.destroy(),r.remove()}}},rl=({config:e,showClose:t})=>{let{wrapper:r,panel:n,pillRoot:o}=(e=>{let t=e?.launcher?.enabled??!0,r=qs(e);if(js(e)){let t=e?.launcher?.composerBar??{},r=L("div","persona-widget-wrapper persona-fixed persona-transition");r.setAttribute("data-persona-composer-bar",""),r.dataset.state="collapsed",r.dataset.expandedSize=t.expandedSize??"anchored",r.style.zIndex=String(e?.launcher?.zIndex??1e5);let n=L("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");n.style.width="100%",r.appendChild(n);let o=L("div","persona-widget-pill-root");return o.setAttribute("data-persona-composer-bar",""),o.dataset.state="collapsed",o.dataset.expandedSize=t.expandedSize??"anchored",o.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:r,panel:n,pillRoot:o}}if(r){let e=L("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),t=L("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=L("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),r=L("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),n=f(e),o=n.launcherWidth||n.legacyLauncherWidth||void 0!==e?.theme?.components?.panel?.width?Vi(e).width:"100%";return t.style.width=o,r.style.width="100%",t.appendChild(r),{wrapper:t,panel:r}}let n=e?.launcher??{},o=n.position&&Qs[n.position]?Qs[n.position]:Qs["bottom-right"],a=L("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let s=L("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=Vi(e);return s.style.width=i.width,s.style.maxWidth=i.maxWidth,a.appendChild(s),{wrapper:a,panel:s}})(e),a=((e,t=!0)=>{if(js(e))return((e,t)=>{let r=L("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:o}=ti(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:Gi,iconSize:Ki});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let a=null,s=null;if(e?.launcher?.clearChat?.enabled??1){let t=ri(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Gi,iconSize:Ji});a=t.button,s=t.wrapper,s.style.position="absolute",s.style.top="8px",s.style.right="32px",s.style.zIndex="10"}let i=P("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=P("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:d,greetingHost:c}=Xi(e,l),{host:p,title:u,subtitle:h}=d,m=d.starterSuggestions,g=L("div","persona-widget-messages persona-flex persona-flex-col");g.style.gap="var(--persona-components-message-gap, 12px)";let f=Qi("followUp"),y=Da(e,!0);y&&(g.style.maxWidth=y,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),l.append(p,c,g,f);let b=P("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"}}),v=vi({config:e}),{root:w,textNode:x}=bi();return r.append(i,o,l,b),s&&r.appendChild(s),{container:r,body:l,messagesWrapper:g,starterSuggestions:m,transcriptSuggestions:f,composerOverlay:b,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,welcomeHost:p,welcomeIconHolder:d.iconHolder,greetingHost:c,introKicker:d.kicker,introTitle:u,introSubtitle:h,closeButton:n,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:s,iconHolder:L("span"),headerTitle:L("span"),headerSubtitle:L("span"),header:i,footer:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions,setSendButtonMode:v.setSendButtonMode,peekBanner:w,peekTextNode:x}})(e,t);let r=P("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"}}),n=e?.layout?.header,o=!1!==e?.layout?.showHeader,a=n?fi(e,n,{showClose:t}):si({config:e,showClose:t}),s=P("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"}});s.style.setProperty("scrollbar-gutter","stable");let{welcome:i,greetingHost:l}=Xi(e,s),{host:d,title:c,subtitle:p}=i,u=i.starterSuggestions,h=L("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let m=Qi("followUp"),g=Da(e,!1);g&&(h.style.maxWidth=g,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),s.append(d,l,h,m);let f=yi({config:e}),y=!1!==e?.layout?.showFooter;o||(a.header.style.display="none"),ii(r,a,e),r.append(s);let b=P("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 y||(f.footer.style.display="none"),r.append(f.footer),r.append(b),{container:r,body:s,messagesWrapper:h,starterSuggestions:u,transcriptSuggestions:m,composerOverlay:b,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,welcomeHost:d,welcomeIconHolder:i.iconHolder,greetingHost:l,introKicker:i.kicker,introTitle:c,introSubtitle:p,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:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}})(e,t),s={wrapper:r,panel:n,pillRoot:o},i={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},l={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={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:s,panelElements:a,transcript:i,header:l,composer:d,replaceHeader:e=>(l.element.replaceWith(e.header),l.element=e.header,l.iconHolder=e.iconHolder,l.headerTitle=e.headerTitle,l.headerSubtitle=e.headerSubtitle,l.closeButton=e.closeButton,l.closeButtonWrapper=e.closeButtonWrapper,l.clearChatButton=e.clearChatButton,l.clearChatButtonWrapper=e.clearChatButtonWrapper,e),replaceComposer:e=>{d.footer.replaceWith(e),d.footer=e}}},nl=({config:e,plugins:t,onToggle:r})=>{let n=t.find(e=>e.renderLauncher);if(n?.renderLauncher){let t=n.renderLauncher({config:e,defaultRenderer:()=>Yi(e,r).element,onToggle:r});if(t)return{instance:null,element:t}}let o=tl(e,r);return{instance:o,element:o.element}},ol=(e,t,r)=>{let n=r;for(let r of t){let t=L("span","persona-tool-char");t.style.setProperty("--char-index",String(n)),t.textContent=" "===r?" ":r,e.appendChild(t),n++}return n},al=(e,t,r)=>{re(e,t,{stateSet:r,previewKind:"reasoning",iconColor:"currentColor"})},sl=(e,t,r=new Set)=>{t=ne(t,"reasoning");let n=e.reasoning,o=Q("persona-reasoning-bubble",e.id);if(!n)return se(o,e,t,"reasoning");let a=t?.features?.reasoningDisplay??{},s=a.expandable??x.expandable,i=s&&r.has(e.id),l="complete"!==n.status,d=((e,t)=>{let r=e.reasoning?.chunks.join("").trim()??"";return r?r.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join("\n"):""})(e,a.previewMaxLines??x.previewMaxLines),c=X({expandable:s,expanded:i,bubbleType:"reasoning"}),p=L("div","persona-flex persona-flex-col persona-text-left"),u=L("span","persona-text-xs persona-text-persona-primary"),h="row"===oe(t,"reasoning"),m=h&&!l?`Thought for ${ae(n.durationMs??(void 0!==n.completedAt&&void 0!==n.startedAt?n.completedAt-n.startedAt:void 0))}`:"Thinking...",g=t?.reasoning??{},f=String(n.startedAt??Date.now()),y=()=>{let e=L("span","");return e.setAttribute("data-tool-elapsed",f),e.textContent=tr(n),e},b=g.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:m,previewText:d,isActive:l,config:t??{},elapsed:tr(n),createElapsedElement:y});"string"==typeof b&&b.trim()?(u.textContent=b,p.appendChild(u)):b instanceof HTMLElement?p.appendChild(b):(u.textContent=m,p.appendChild(u));let v=L("span","persona-text-xs persona-text-persona-primary");v.textContent=(e=>"complete"===e.status?(e=>{let t=e.completedAt??Date.now(),r=e.startedAt??t,n=(void 0===e.durationMs?Math.max(0,t-r):e.durationMs)/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`})(e):"pending"===e.status?"Waiting":"")(n),h||p.appendChild(v);let w=a.loadingAnimation??x.loadingAnimation,C=g.activeTextTemplate,S=g.completeTextTemplate,k=l?C:S,A=b instanceof HTMLElement,M=(e,t)=>{u.textContent="";let r=nr(e,""),o=0;for(let e of r){let r=e.styles.length>0?(()=>{let t=L("span",e.styles.map(e=>`persona-tool-text-${e}`).join(" "));return u.appendChild(t),t})():u;if(e.isDuration&&l)r.appendChild(y());else{let a=e.isDuration?tr(n):e.text;t?o=ol(r,a,o):r.appendChild(document.createTextNode(a))}}};if(!A&&k)if(v.style.display="none",u.style.display="",l&&"none"!==w){let e=g.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),"pulse"===w?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`),M(k,!1)):(u.classList.add(`persona-tool-loading-${w}`),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===w&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),M(k,!0))}else M(k,!1);else if(!A&&l&&"none"!==w){u.style.display="";let e=g.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),"pulse"===w)u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`);else{u.classList.add(`persona-tool-loading-${w}`),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===w&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let t=u.textContent||m;u.textContent="",ol(u,t,0)}"complete"===n.status&&!h&&(u.style.display="none")}else A||("complete"!==n.status||h?u.style.display="":u.style.display="none");if(a.iconName&&!A){let e=L("span","persona-reasoning-header-icon"),t=K(a.iconName,16,"currentColor",2);t&&(e.appendChild(t),c.appendChild(e))}let I="currentColor",T=Z(c,p,{expandable:s,expanded:i,iconColor:I,metaGap:!1}),E=ee({bubble:o,previewKind:"reasoning",expanded:i,isActive:l,previewText:d,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:d,isActive:l,config:t??{}})});if(!s)return o.append(c,E),se(o,e,t,"reasoning");let P=L("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");P.style.display=i?"":"none";let B=n.chunks.join(""),N=L("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return N.textContent=B||("complete"===n.status?"No additional context was shared.":"Waiting for details…"),P.appendChild(N),te({expanded:i,header:c,toggleIcon:T,content:P,collapsedPreview:E,iconColor:I}),o.append(c,E,P),se(o,e,t,"reasoning")},il=e=>{if(null==e)return!0;if("string"==typeof e){if(!e.trim())return!0;try{return il(JSON.parse(e))}catch{return!1}}return"object"==typeof e&&0===Object.keys(e).length},ll=e=>{if("object"==typeof e&&e)return!0;if("string"!=typeof e)return!1;try{let t=JSON.parse(e);return"object"==typeof t&&!!t}catch{return!1}},dl=new WeakMap;let cl=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),pl=(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)"},ul=(e,t)=>{let r=e.toolCall,n=t?.features?.toolCallDisplay,o=n?.collapsedMode??w.collapsedMode,a=!1===r?.success?r.error||"Tool failed":((e,t)=>{let r=e.toolCall;if(!r)return"";let n=(r.chunks??[]).join("").trim();if(n)return n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(-t).join("\n");let o=Yt(r.args).trim();return o?o.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join("\n"):""})(e,n?.previewMaxLines??w.previewMaxLines),s=r?"row"===oe(t,"tool")?`${"complete"===r.status?"Used":"Using"} ${r.name?.trim()||"tool"}`:(e=>"complete"===e.status?(e=>{let t=("number"==typeof e.duration?e.duration:"number"==typeof e.durationMs?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`})(e):"Using tool...")(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i="complete"!==r.status,l=t?.toolCall??{},d=s;return"tool-name"===o?d=r.name?.trim()||s:"tool-preview"===o&&a&&(d=a),i&&l.activeTextTemplate?d=rr(r,l.activeTextTemplate,d):!i&&l.completeTextTemplate&&(d=rr(r,l.completeTextTemplate,d)),!1===r.success?d+=" · Failed":r.superseded&&(d+=" · Approved, ran again below"),{summary:d,previewText:a,isActive:i}},hl=(e,t,r,n)=>{re(e,t,{stateSet:r,previewKind:"tool",iconColor:cl(n?.toolCall??{},t.classList.contains("persona-activity-row"))})},ml=(e,t,r=new Set)=>{t=ne(t,"tool");let n=e.toolCall,o=t?.toolCall??{},a=Q("persona-tool-bubble",e.id);if(o.backgroundColor&&(a.style.backgroundColor=o.backgroundColor),o.borderColor&&(a.style.borderColor=o.borderColor),o.borderWidth&&(a.style.borderWidth=o.borderWidth),o.borderRadius&&(a.style.borderRadius=o.borderRadius),a.style.boxShadow=void 0===o.shadow?"var(--persona-tool-bubble-shadow)":""===o.shadow.trim()?"none":o.shadow,!n)return se(a,e,t,"tool");let s=t?.features?.toolCallDisplay??{},i=s.expandable??w.expandable,l=i&&r.has(e.id),{summary:d,previewText:c,isActive:p}=ul(e,t),u=X({expandable:i,expanded:l,bubbleType:"tool"});o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let h=L("div","persona-flex persona-flex-col persona-text-left"),m=L("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let g=String(n.startedAt??Date.now()),f=()=>{let e=L("span","");return e.setAttribute("data-tool-elapsed",g),e.textContent=er(n),e},y=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:s.collapsedMode??w.collapsedMode,isActive:p,config:t??{},elapsed:er(n),createElapsedElement:f});"string"==typeof y&&y.trim()?(m.textContent=y,h.appendChild(m)):y instanceof HTMLElement?h.appendChild(y):(m.textContent=d,h.appendChild(m));let b=s.loadingAnimation??w.loadingAnimation,v=o.activeTextTemplate,x=o.completeTextTemplate,C=p?v:x,S=(e,t)=>{m.textContent="";let r=n.name?.trim()||"tool",o=nr(e,r),a=0;for(let e of o){let r=e.styles.length>0?(()=>{let t=L("span",e.styles.map(e=>`persona-tool-text-${e}`).join(" "));return m.appendChild(t),t})():m;if(e.isDuration&&p)r.appendChild(f());else{let o=e.isDuration?er(n):e.text;t?a=ol(r,o,a):r.appendChild(document.createTextNode(o))}}};if(!(y instanceof HTMLElement))if(p&&"none"!==b){let e=o.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),"pulse"===b)m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${e}ms`),C&&S(C,!1);else if(m.classList.add(`persona-tool-loading-${b}`),m.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===b&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),C)S(C,!0);else{let e=m.textContent||d;m.textContent="",ol(m,e,0)}}else C&&S(C,!1);let k=cl(o,"row"===oe(t,"tool")),A=Z(u,h,{expandable:i,expanded:l,iconColor:k,metaGap:!0}),M=ee({bubble:a,previewKind:"tool",expanded:l,isActive:p,previewText:c,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:c,isActive:p,config:t??{}})});if(!i)return a.append(u,M),se(a,e,t,"tool");let I=L("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(I.style.display=l?"":"none",o.contentBackgroundColor&&(I.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(I.style.color=o.contentTextColor),o.contentPaddingX&&(I.style.paddingLeft=o.contentPaddingX,I.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(I.style.paddingTop=o.contentPaddingY,I.style.paddingBottom=o.contentPaddingY),!0===t.future?.v5Defaults)!function(e,t,r){let n=t.toolCall;if(!n)return;let o=r.toolCall??{},a=(t,r)=>{let n=P("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":t.toLowerCase()},style:{backgroundColor:o.codeBlockBackgroundColor,borderColor:o.codeBlockBorderColor,borderWidth:o.codeBlockBorderColor?"1px":void 0}}),a=P("div",{className:"persona-tool-detail-label",text:t,style:{color:o.labelTextColor}}),s=Yt(r),i=P("pre",{className:"persona-tool-detail-value"+(ll(r)?" persona-tool-detail-code":""),text:s,attrs:s.length>420||s.split("\n").length>7?{tabindex:"0","aria-label":`${t} content`}:{},style:{color:o.codeBlockTextColor??o.contentTextColor}}),l=P("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${t.toLowerCase()}`,title:`Copy ${t.toLowerCase()}`}}),d=K("copy",14,"currentColor",1.7);d&&l.appendChild(d),n.append(a,i,l),e.appendChild(n)};il(n.args)||a("Request",n.args);let s="complete"===n.status&&void 0!==n.result?n.result:n.chunks?.join("");void 0!==s&&("string"!=typeof s||s.trim())&&a("Response",s),!1===n.success&&e.appendChild(P("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}(I,e,t);else{if(n.name){let e=L("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?e.style.color=o.contentTextColor:o.headerTextColor&&(e.style.color=o.headerTextColor),e.textContent=n.name,I.appendChild(e)}if(void 0!==n.args){let e=L("div","persona-space-y-1"),t=L("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(t.style.color=o.labelTextColor),t.textContent="Arguments";let r=L("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");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",pl(r,o),r.textContent=Yt(n.args),e.append(t,r),I.appendChild(e)}if(n.chunks&&n.chunks.length){let e=L("div","persona-space-y-1"),t=L("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(t.style.color=o.labelTextColor),t.textContent="Activity";let r=L("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");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",pl(r,o),r.textContent=n.chunks.join(""),e.append(t,r),I.appendChild(e)}if(!1===n.success&&I.appendChild(P("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),"complete"===n.status&&void 0!==n.result){let e=L("div","persona-space-y-1"),t=L("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(t.style.color=o.labelTextColor),t.textContent="Result";let r=L("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");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",pl(r,o),r.textContent=Yt(n.result),e.append(t,r),I.appendChild(e)}if("complete"===n.status&&"number"==typeof n.duration){let e=L("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(e.style.color=o.contentTextColor),e.textContent=`Duration: ${n.duration}ms`,I.appendChild(e)}}return te({expanded:l,header:u,toggleIcon:A,content:I,collapsedPreview:M,iconColor:k}),a.append(u,M,I),se(a,e,t,"tool")},{setLoader:gl,load:fl,provide:yl,getSync:bl}=N({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),vl=gl,wl=fl,xl=bl,{setLoader:Cl,load:Sl}=N({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),kl=Cl,Al=Sl,Ml=new class{constructor(){this.components=new Map,this.#e=new Map}#e;register(e,t,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t),r?this.#e.set(e,r):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)})}},Il=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:Tl,load:El,provide:Ll,getSync:Pl}=N({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),Bl=null,Nl=new Set,Rl=e=>{if(Bl)return Bl;Bl=e,e.initArtifactsUi({componentRegistry:Ml});for(let t of Il)Ml.has(t)||Ml.register(t,"PersonaArtifactCard"===t?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=ve();t?e.__provideMarkdownParsers(t):be(()=>{let t=ve();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>W());let r=[...Nl];Nl.clear();for(let e of r)try{e()}catch{}return e},Hl=Tl,$l=()=>El().then(Rl),Wl=()=>{if(Bl)return Bl;let e=Pl();return e?Rl(e):null},Dl=e=>Bl?()=>{}:(Nl.add(e),()=>{Nl.delete(e)});function Fl(e){return!0===e?.features?.artifacts?.enabled}function Ol(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"),!Fl(t))return;let r=t.features?.artifacts?.layout,n=r?.paneBorder?.trim(),o=r?.paneBorderLeft?.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}let zl=["panel","seamless","detached"];function ql(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&zl.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function jl(e){return!(!e||!Fl(e))&&"detached"===ql(e)}function _l(e,t){if(!Fl(t))return 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"),function(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")}(e),void Ol(e,t);let r=t.features?.artifacts?.layout,n="detached"===ql(t)?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",r?.splitGap??n),e.style.setProperty("--persona-artifact-pane-width",r?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",r?.paneMaxWidth??"28rem"),r?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",r.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),r?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=r?.paneBackground?.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let a=r?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=[[r?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[r?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[r?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[r?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[t,r]of s){let n=t?.trim();n?e.style.setProperty(r,n):e.style.removeProperty(r)}Ol(e,t)}function Ul(e,t){for(let t of zl)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"),!Fl(t))return;let r=t.features?.artifacts?.layout,n=ql(t);e.classList.add(`persona-artifact-appearance-${n}`);let o=r?.paneBorderRadius?.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=r?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=r?.chatShadow?.trim();s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}let Vl=new Set(["__proto__","prototype","constructor"]),Gl=new Set(["collapsed","card","panel","inline"]),Kl=new Set(["markdown","component"]),Jl=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ql=e=>"object"==typeof e&&!!e&&!Array.isArray(e),Xl=e=>!Vl.has(e),Yl=e=>"string"==typeof e&&Gl.has(e),Zl=e=>Object.keys(e).length>0;function ed(e,t,r,n){e.push({path:t,code:r,message:n})}let td="Ignored an unsupported value.",rd={kind:"mode",message:td},nd={kind:"string",message:"Expected a CSS length string."},od={kind:"boolean"},ad={kind:"object",message:"Expected a preference object.",children:{showToolCalls:od,showReasoning:od,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:td},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:td},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:td},expandable:od,grouped:od}},reasoningDisplay:{kind:"object",children:{expandable:od,activePreview:od}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:rd,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:rd,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Kl,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Kl}}},filePreview:{kind:"object",children:{enabled:od}},layout:{kind:"object",children:{paneWidth:nd,paneMaxWidth:nd,paneMinWidth:nd,expandedPanelWidth:nd,resizableMinWidth:nd,resizableMaxWidth:nd,expandLauncherPanelWhenOpen:od,resizable:od}}}}}};function sd(e,t,r,n){if(void 0!==e)switch(t.kind){case"boolean":return"boolean"==typeof e?e:ed(n,r,"invalid_type","Expected a boolean.");case"string":return"string"==typeof e?e:ed(n,r,"invalid_type",t.message);case"enum":return"string"==typeof e&&t.values.has(e)?e:ed(n,r,"invalid_value",t.message);case"mode":return Yl(e)?Vr(e):ed(n,r,"invalid_value",t.message);case"modeMap":{if(!Ql(e))return ed(n,r,"invalid_type","Expected an object.");let o="mediaType"===t.keys?void 0:t.keys,a={};for(let[t,s]of Object.entries(e)){let e=o?t:Gr(t);Xl(t)&&(o?o.has(t):Jl.test(e))?Yl(s)?a[e]=Vr(s):ed(n,`${r}.${t}`,"invalid_value","Expected collapsed, panel, or inline."):ed(n,`${r}.${t}`,o?"unknown_key":"invalid_value",o?"Ignored an unsupported selector.":'Expected a MIME type such as "text/html" or a wildcard such as "image/*".')}return Zl(a)?a:void 0}case"object":{if(t.bareMode&&Yl(e))return Vr(e);if(!Ql(e))return ed(n,r,"invalid_type",t.message??"Expected an object.");let o=Object.keys(t.children),a=e=>r?`${r}.${e}`:e;for(let t of Object.keys(e))(!Xl(t)||!o.includes(t))&&ed(n,a(t),"unknown_key","Ignored because this key is not part of the persisted preference schema.");let s={};for(let r of o){let o=t.children[r],i=sd(e[r],o,a(r),n);if(o.deprecated&&void 0!==e[r]&&ed(n,a(r),"deprecated_key",o.deprecated),void 0===i)continue;let l=o.alias??r,d=s[l];s[l]=Ql(d)&&Ql(i)?{...d,...i}:i}return Zl(s)?s:void 0}}}function id(e){let t=[];return{preferences:(null===e?void 0:sd(e,ad,"",t))??{},issues:t}}function ld(e){if(Array.isArray(e))return e.map(ld);if(!Ql(e))return e;let t={};for(let[r,n]of Object.entries(e))Xl(r)&&void 0!==n&&(t[r]=ld(n));return t}function dd(e,t){let r=ld(e);for(let[e,n]of Object.entries(t)){if(!Xl(e)||void 0===n)continue;let t=r[e];r[e]=Ql(t)&&Ql(n)?dd(t,n):ld(n)}return r}function cd(e,t){if(void 0===t)return void 0===e?void 0:ld(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},n=t.default??r.default,o={...r.byType,...r.byKind,...t.byType,...t.byKind},a=function(e,t){if(void 0===t)return void 0===e?void 0:ld(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},n=t.default??r.default,o={...r.byMediaType,...t.byMediaType},a={...n?{default:n}:{},...Zl(o)?{byMediaType:o}:{}};return Zl(a)?a:void 0}(r.files,t.files),s={...n?{default:n}:{},...Zl(o)?{byKind:o}:{},...void 0===a?{}:{files:a}};return Zl(s)?s:void 0}function pd(e={},t){let r=function(e){let t,r={};for(let n of e){let e=id(n).preferences;t=cd(t,e.artifacts?.display),r=dd(r,e)}let n=r;return n.artifacts&&(void 0===t?delete n.artifacts.display:n.artifacts.display=t),n}(t),n={...e};if(void 0!==r.showToolCalls&&(n.showToolCalls=r.showToolCalls),void 0!==r.showReasoning&&(n.showReasoning=r.showReasoning),r.toolCallDisplay&&(n.toolCallDisplay={...e.toolCallDisplay,...r.toolCallDisplay}),r.reasoningDisplay&&(n.reasoningDisplay={...e.reasoningDisplay,...r.reasoningDisplay}),r.artifacts){let t=e.artifacts??{},o={...t};if(void 0!==r.artifacts.display){let e=cd(t.display,r.artifacts.display);void 0!==e&&(o.display=e)}r.artifacts.filePreview&&(o.filePreview={...t.filePreview,enabled:r.artifacts.filePreview.enabled}),r.artifacts.layout&&(o.layout={...t.layout,...r.artifacts.layout}),n.artifacts=o}return n}function ud(e){let t=e.preferences;return t&&Zl(t)?{...e,features:pd(e.features??{},[t])}:e}function hd(e,t){let r=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",n=/^([\d.]+)px$/i.exec(r);if(n)return Number(n[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}let{setLoader:md,load:gd,provide:fd,getSync:yd}=N({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),bd=md,vd=gd,wd=yd,xd=new class{#e=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||0===e.length)return t;let r=new Set(e.map(e=>e.id));return[...t.filter(e=>!r.has(e.id)),...e].sort((e,t)=>(t.priority??0)-(e.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}},Cd=e=>"object"==typeof e&&!!e&&!Array.isArray(e),Sd=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),kd=(e,t,r)=>{if(!Cd(e)||!Cd(t)||Sd.has(r))return t;let n={...e};for(let o of Object.keys(t)){if(void 0===t[o]){delete n[o];continue}let a=r?`${r}.${o}`:o;n[o]=kd(e[o],t[o],a)}return n};function Ad(e,t){let r=l(k),n=function(e,t,r){let n=t[s];if(n)return n;let o=new Set(c(e,r));for(let e of r){let r=d(t,e);"clear"===r&&o.delete(e),"explicit"===r&&o.add(e)}return[...o]}(e,t,r),o=p(function(e,t,r){let n={...e};for(let e of t){if(r.includes(e))continue;let t=e.split("."),o=n;for(let e of t.slice(0,-1)){let t=o[e];if(!i(t)){o=void 0;break}o[e]={...t},o=o[e]}o&&delete o[t[t.length-1]]}return n}(kd(e,t,""),r,n),n);return y(E(o),((e,t)=>{let r=t[h];if(r)return{...r};let n=f(e);return m(t,"launcherWidth")&&(n.legacyLauncherWidth=void 0!==t.launcherWidth),m(t,"launcher")&&void 0===t.launcher?(n.launcherWidth=!1,n.sidebarWidth=!1,n.dockWidth=!1,n):(m(t.launcher,"width")&&(n.launcherWidth=void 0!==t.launcher?.width),m(t.launcher,"sidebarWidth")&&(n.sidebarWidth=void 0!==t.launcher?.sidebarWidth),m(t.launcher,"dock")&&void 0===t.launcher?.dock?n.dockWidth=!1:m(t.launcher?.dock,"width")&&(n.dockWidth=void 0!==t.launcher?.dock?.width),n)})(e,t))}let Md=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=(e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e})(e),r=(e=>{let t=e.trim(),r=t.indexOf("{");if(-1===r)return null;let n=0;for(let e=r;e<t.length;e+=1){let o=t[e];if("{"===o&&(n+=1),"}"===o&&(--n,0===n))return t.slice(r,e+1)}return null})(t);if(!r)return null;let n=JSON.parse(r);if(!n||"object"!=typeof n||!n.action)return null;let{action:o,...a}=n;return{type:String(o),payload:a,raw:n}}catch{return null}},Id=e=>"string"==typeof e?e:null==e?"":String(e),Td={message:e=>{if("message"===e.type)return{handled:!0,displayText:Id(e.payload.text)}},messageAndClick:(e,t)=>{if("message_and_click"!==e.type)return;let r=e.payload,n=Id(r.element);if(n&&t.document?.querySelector){let e=t.document.querySelector(n);e?setTimeout(()=>{e.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:Id(r.text)}}},Ed=e=>Array.isArray(e)?e.map(e=>String(e)):[],Ld=e=>{let t=new Set(Ed(e.getSessionMetadata().processedActionMessageIds));return{process:r=>{if(r.streaming||"assistant"!==r.message.role||!r.text||t.has(r.message.id))return null;let n="string"==typeof r.raw&&r.raw||"string"==typeof r.message.rawContent&&r.message.rawContent||"string"==typeof r.text&&r.text||null;!n&&"string"==typeof r.text&&r.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 o=n?e.parsers.reduce((e,t)=>e||t?.({text:n,message:r.message})||null,null):null;if(!o)return null;t.add(r.message.id),(()=>{let r=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:r}))})();let a={action:o,message:r.message};e.emit("action:detected",a);for(let t of e.handlers)if(t)try{let n=t(o,{message:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{e.emit("action:resubmit",a)}});if(!n)continue;if(n.handled){let e=!1!==n.persistMessage;return{text:void 0===n.displayText?"":n.displayText,persist:e,resubmit:n.resubmit}}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",e)}return{text:"",persist:!0}},syncFromMetadata:()=>{t=new Set(Ed(e.getSessionMetadata().processedActionMessageIds))}}},Pd=e=>e.map(e=>({...e,streaming:!1})),Bd=e=>e.map(e=>({...e,status:"complete"})),Nd=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?(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}})(r.getItem(e)):null},save:r=>{let n=t();if(n)try{let t={...r,messages:r.messages?Pd(r.messages):void 0,artifacts:r.artifacts?Bd(r.artifacts):void 0};n.setItem(e,JSON.stringify(t))}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",e)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}},Rd=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let r=await t.digest("SHA-256",(new TextEncoder).encode(e));return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{}return(e=>{let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")})(e)},Hd=(e,t,r)=>{let n="",o="",a="",s=!1,i=!1,l=0,d=null,c=null,p=new Set,u=()=>{if(r||s)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return s=!0,null}},h=()=>{let e=u();if(!e)return d;try{return e.getItem(n)}catch{return s=!0,d}},m=(e,t)=>{if(i||e===d)return;let r=d;d=e,l+=1;let n={previousToken:r,token:e,source:t,revision:l};for(let e of p)e(n)},g=e=>{i||(null===e.key||e.key===n)&&m(null===e.key?null:e.newValue??null,"external")},f=(async()=>{let s=await(async(e,t)=>{let r=await Rd(e);return{storageKey:`${t}visitor:${r}`,leaseKey:`${t}visitor-init-lock:${r}`,lockName:`persona-visitor-init:${await Rd(`${e}\0${t}`)}`}})(e,t);n=s.storageKey,o=s.leaseKey,a=s.lockName,d=h(),!r&&typeof window<"u"&&window.addEventListener("storage",g)})(),y=e=>new Promise(t=>setTimeout(t,e)),b=()=>{let e=u();if(!e)return null;try{let t=e.getItem(o);if(!t)return null;let r=JSON.parse(t);return"number"==typeof r?.expiresAt&&"string"==typeof r?.ownerNonce?r:null}catch{return null}},v=e=>{let t=u();if(t)try{b()?.ownerNonce===e&&t.removeItem(o)}catch{}},w=new Set,x=e=>i?Promise.reject(Error("Visitor store destroyed before its first init could start")):e(),C=e=>new Promise(t=>{let r=setTimeout(n,e);function n(){clearTimeout(r),w.delete(n),window.removeEventListener("storage",a),t()}function a(e){(null===e.key||e.key===o)&&n()}w.add(n),window.addEventListener("storage",a)});return{ready:f,get:async()=>(await f,m(h(),"external"),d),async set(e){await f;let t=u();if(t)try{t.setItem(n,e)}catch{s=!0}m(e,"local")},async clear(){await f;let e=u();if(e)try{e.removeItem(n)}catch{s=!0}m(null,"local")},revision:()=>l,subscribe:e=>(p.add(e),()=>{p.delete(e)}),async withFirstInitLock(e){await f;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):u()?(async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,r=Date.now()+15e3;for(;!i&&Date.now()<r;){let r=u();if(!r)break;let n=Date.now(),a=b();if(a&&a.expiresAt>n&&a.ownerNonce!==t)await C(Math.min(a.expiresAt-n,500));else{try{r.setItem(o,JSON.stringify({ownerNonce:t,expiresAt:n+1e4}))}catch{s=!0;break}if(await y(20+40*Math.random()),b()?.ownerNonce!==t)await C(500);else{c=t;try{return await x(e)}finally{c=null,v(t)}}}}return x(e)})(e):x(e)},matches:(n,o,a)=>n===e&&o===t&&a===r,destroy(){i=!0,p.clear(),typeof window<"u"&&window.removeEventListener("storage",g),c&&v(c);for(let e of[...w])e()}}},{setLoader:$d,load:Wd}=N({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),Dd=$d,Fd=Wd,{setLoader:Od,load:zd,provide:qd,getSync:jd}=N({fallbackImport:()=>import("./history-shell")}),_d=Od,Ud=zd,Vd=jd;function Gd(){return null}function Kd(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=t)return e;try{let t=function(e,t){if(!function(e){if(!e||"object"!=typeof e||!("component"in e))return!1;let t=e.component;return"string"==typeof t&&t.length>0}(e))return null;let r=e.props&&"object"==typeof e.props&&null!==e.props?e.props:{};return{component:e.component,props:r,raw:t}}((0,ut.parse)(r,ut.STR|ut.OBJ),r);t&&(e=t)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function Jd(e,t){let{config:r,message:n,onPropsUpdate:o}=t,a=Ml.get(e.component);if(!a){if(Il.includes(e.component)){$l().catch(()=>{});let e=L("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 s={message:n,config:r,updateProps:e=>{o&&o(e)}};try{return a(e.props,s)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function Qd(e){if("string"==typeof e.rawContent&&e.rawContent.length>0)return e.rawContent;if("string"==typeof e.content){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Xd(e){let t=Qd(e);if(!t)return!1;try{let e=JSON.parse(t);return"object"==typeof e&&!!e&&"component"in e&&"string"==typeof e.component}catch{return!1}}function Yd(e){let t=Qd(e);if(!t)return null;try{let e=JSON.parse(t);if("object"==typeof e&&e&&"component"in e&&"string"==typeof e.component){let r=e;return{component:r.component,props:r.props&&"object"==typeof r.props&&null!==r.props?r.props:{},raw:t}}}catch{}return null}let Zd=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ec(e){let{onSubmit:t,onDismiss:r,title:n="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:l=!0,ratingLabels:d=Zd}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let p=null,u=document.createElement("div");u.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let m=document.createElement("h3");m.className="persona-feedback-title",m.textContent=n,h.appendChild(m);let g=document.createElement("p");g.className="persona-feedback-subtitle",g.textContent=o,h.appendChild(g),u.appendChild(h);let f=document.createElement("div");f.className="persona-feedback-rating persona-feedback-rating-csat",f.setAttribute("role","radiogroup"),f.setAttribute("aria-label","Satisfaction rating from 1 to 5");let y=[];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":""}: ${d[e-1]}`),t.title=d[e-1],t.dataset.rating=String(e),t.innerHTML='\n <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <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>\n </svg>\n ',t.addEventListener("click",()=>{p=e,y.forEach((t,r)=>{let n=r<e;t.classList.toggle("selected",n),t.setAttribute("aria-checked",r===e-1?"true":"false")})}),y.push(t),f.appendChild(t)}u.appendChild(f);let b=null;if(l){let e=document.createElement("div");e.className="persona-feedback-comment-container",b=document.createElement("textarea"),b.className="persona-feedback-comment",b.placeholder=a,b.rows=3,b.setAttribute("aria-label","Additional comments"),e.appendChild(b),u.appendChild(e)}let v=document.createElement("div");v.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{r?.(),c.remove()});let x=document.createElement("button");return x.type="button",x.className="persona-feedback-btn persona-feedback-btn-submit",x.textContent=s,x.addEventListener("click",async()=>{if(null===p)f.classList.add("persona-feedback-shake"),setTimeout(()=>f.classList.remove("persona-feedback-shake"),500);else{x.disabled=!0,x.textContent="Submitting...";try{let e=b?.value.trim()||void 0;await t(p,e),c.remove()}catch(e){x.disabled=!1,x.textContent=s,console.error("[CSAT Feedback] Failed to submit:",e)}}}),v.appendChild(w),v.appendChild(x),u.appendChild(v),c.appendChild(u),c}function tc(e){let{onSubmit:t,onDismiss:r,title:n="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:l=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let u=null,h=document.createElement("div");h.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let g=document.createElement("h3");g.className="persona-feedback-title",g.textContent=n,m.appendChild(g);let f=document.createElement("p");f.className="persona-feedback-subtitle",f.textContent=o,m.appendChild(f),h.appendChild(m);let y=document.createElement("div");y.className="persona-feedback-rating persona-feedback-rating-nps",y.setAttribute("role","radiogroup"),y.setAttribute("aria-label","Likelihood rating from 0 to 10");let b=document.createElement("div");b.className="persona-feedback-labels";let v=document.createElement("span");v.className="persona-feedback-label-low",v.textContent=d;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=c,b.appendChild(v),b.appendChild(w);let x=document.createElement("div");x.className="persona-feedback-numbers";let C=[];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",()=>{u=e,C.forEach((t,r)=>{t.classList.toggle("selected",r===e),t.setAttribute("aria-checked",r===e?"true":"false")})}),C.push(t),x.appendChild(t)}y.appendChild(b),y.appendChild(x),h.appendChild(y);let S=null;if(l){let e=document.createElement("div");e.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=a,S.rows=3,S.setAttribute("aria-label","Additional comments"),e.appendChild(S),h.appendChild(e)}let k=document.createElement("div");k.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=i,A.addEventListener("click",()=>{r?.(),p.remove()});let M=document.createElement("button");return M.type="button",M.className="persona-feedback-btn persona-feedback-btn-submit",M.textContent=s,M.addEventListener("click",async()=>{if(null===u)x.classList.add("persona-feedback-shake"),setTimeout(()=>x.classList.remove("persona-feedback-shake"),500);else{M.disabled=!0,M.textContent="Submitting...";try{let e=S?.value.trim()||void 0;await t(u,e),p.remove()}catch(e){M.disabled=!1,M.textContent=s,console.error("[NPS Feedback] Failed to submit:",e)}}}),k.appendChild(A),k.appendChild(M),h.appendChild(k),p.appendChild(h),p}let rc="persona-chat-history",nc="data-persona-composer-reason",oc="data-persona-composer-notice",ac={"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 sc(e){if(!e)return[];let t=[],r=Array.from(e.items??[]);for(let e of r){if("file"!==e.kind||!e.type.startsWith("image/"))continue;let r=e.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let n=ac[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${n}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let r of Array.from(e.files??[]))r.type.startsWith("image/")&&t.push(r);return t}function ic(e){if(!e)return!1;let t=e.types;return!!t&&("function"==typeof t.contains?t.contains("Files"):Array.from(t).includes("Files"))}let lc=e=>e&&"object"==typeof e?{...e}:{},dc=e=>e.map(e=>({...e,streaming:!1})),cc=(e,t,r)=>{let n=e?.markdown?xe(e.markdown):null,o=Pe(e?.sanitize);e?.postprocessMessage&&o&&void 0===e?.sanitize&&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,s=a=>{let s=a.text??"",i=a.message.rawContent??null;if(t){let e=t.process({text:s,raw:i??s,message:a.message,streaming:a.streaming});null!==e&&(s=e.text,e.persist||(a.message.__skipPersist=!0),e.resubmit&&!a.streaming&&r&&r())}let l,d=null!==ve();if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:s,raw:i??a.text??""});l=o?o(t):t}else if(n){let e=a.streaming?(e=>{if(!e||!e.includes("|"))return e;let t=e.split("\n"),r=!1;for(let e=0;e<t.length-1;e++){let n=t[e],o=t[e+1];if(!Ne(n)||Be.test(n)||!Be.test(o))continue;let a=Re(n).length;if(a<1)continue;let s=$e(a);t[e+1]!==s&&(t[e+1]=s,r=!0);let i=e+2;for(;i<t.length;i++){let e=t[i];if(""===e.trim()||!Ne(e))break;let n=He(We(Re(e),a));t[i]!==n&&(t[i]=n,r=!0)}e=i-1}return r?t.join("\n"):e})(s):s,t=n(e);l=o&&d?o(t):t}else l=ke(s);return l};return e=>{try{return s(e)}catch(t){return a||(a=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",t)),ke(e.text??"")}}};function pc(e){let t=L("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),void 0!==e?.backdropBlur&&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 r=K(e?.iconName??"upload",e?.iconSize??"48px",e?.iconColor??"rgba(59, 130, 246, 0.6)",e?.iconStrokeWidth??.5);if(r&&t.appendChild(r),e?.label){let r=L("span","persona-drop-overlay-label");r.textContent=e.label,t.appendChild(r)}return t}let uc=(e,t)=>{let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];r[e]=t?{...t,...n}:n}return r},hc=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:uc(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),mc=(e,t,o)=>{if(null==e)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 s=E(t),i=new Set,l=new Set,d=function(e){let t=new Set,r=new Set,n=new Set,o=new Map,a=e=>{clearTimeout(o.get(e)),o.delete(e)};return{observe(a,s,i,l={}){let d="tool"===s?a.toolCall:a.reasoning;if(d&&!r.has(a.id)&&(!t.has(a.id)&&"complete"!==d.status&&d.chunks?.some(Boolean)&&(t.add(a.id),!1!==l.autoExpand&&i.add(a.id)),t.has(a.id)&&"complete"===d.status&&!n.has(a.id))){if(n.add(a.id),!1===l.autoCollapseDelay)return;o.set(a.id,setTimeout(()=>{o.delete(a.id),i.delete(a.id),e(a.id,s)},l.autoCollapseDelay??1e3))}},manual(e){r.add(e),a(e)},prune(e){for(let o of new Set([...t,...r,...n]))e.has(o)||(a(o),t.delete(o),r.delete(o),n.delete(o))},clear(){for(let e of o.keys())a(e);t.clear(),r.clear(),n.clear()}}}((e,t)=>{qa.delete(e);let r=Array.from(lt.querySelectorAll("[data-message-id]")).find(t=>t.dataset.messageId===e);r&&("tool"===t?hl(e,r,i,s):al(e,r,l))}),c=new Map,p=()=>{Wn({delayMs:s.tooltip?.delayMs??200,skipDelayMs:s.tooltip?.skipDelayMs??300})};p();let u=s.features;s=ud(s);let h=xd.getForInstance(s.plugins),m=Ja(e),g=[],y=!1,b=(e=>{let t=new Map,r=!1,n=()=>{if(r||!1===e()?.persistState)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return r=!0,null}};return o=>{let a=t=>((e,t,r)=>`${(e=>{let t=e?.persistState;return("object"==typeof t?t?.keyPrefix:void 0)??"persona-"})(e)}plugin:${t}:${r}`)(e(),o,t);return{get:e=>{let o=a(e),s=n();if(s)try{return s.getItem(o)}catch{r=!0}return t.get(o)??null},set:(e,o)=>{let s=a(e),i=n();if(i)try{return void i.setItem(s,o)}catch{r=!0}t.set(s,o)},remove:e=>{let o=a(e);t.delete(o);let s=n();if(s)try{s.removeItem(o)}catch{r=!0}}}}})(()=>s),v=null,w=null,x=null,C=!1,S=null,k=e=>{v=e,e.initApprovalUi({webMcpToolTitle:Ye});let t=e.createBuiltInApprovalPlugin(c);w=t.plugin,x=t.teardown},A=()=>{if(v)return v;let e=xl();return e?(k(e),e):(wl().then(e=>{C||v||(k(e),S?.())}).catch(()=>{}),null)},M=!1,I=!1,T=null,P=(e,t,r,n)=>{if(!e.querySelector("[data-tv-form]"))return;let o=wd();o?o.enhanceWithForms(e,t,r,n):vd().then(()=>{M||I||!T||(I=!0,T())}).catch(()=>{})};s.components&&Ml.registerAll(s.components);let B,N,R=(()=>{let e=new Map,t=(t,r)=>{e.get(t)?.delete(r)};return{on:(r,n)=>(e.has(r)||e.set(r,new Set),e.get(r).add(n),()=>t(r,n)),off:t,emit:(t,r)=>{e.get(t)?.forEach(e=>{try{e(r)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",e)}})}}})(),H=!1===s.persistState?null:s.storageAdapter??Nd(),$=!!s.clientToken&&"function"!=typeof s.reconnectStream,W={},D=null,F=new Promise(e=>{B=e}),O=()=>{},z=new Promise(e=>{O=e}),q=!1,j=e=>{if(s.onStateLoaded)try{let t=s.onStateLoaded(e);if(t&&"object"==typeof t&&"state"in t){let{state:e,open:r}=t;return r&&(q=!0),e}return t}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}return e};if(H?.load)try{let e=H.load();if(e&&"function"==typeof e.then)D=e.then(e=>j(e??{messages:[],metadata:{}}));else{let t=j(e??{messages:[],metadata:{}});t.metadata&&(W=lc(t.metadata)),t.messages?.length&&(s={...s,initialMessages:t.messages}),t.artifacts?.length&&(s={...s,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),N=t.draft}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",e)}else if(s.onStateLoaded)try{let e=j({messages:[],metadata:{}});e.messages?.length&&(s={...s,initialMessages:e.messages})}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}D||B();let _=()=>W,V=e=>{W=e({...W})??{},di()},G=s.actionParsers&&s.actionParsers.length?s.actionParsers:[Md],J=s.actionHandlers&&s.actionHandlers.length?s.actionHandlers:[Td.message,Td.messageAndClick],Q=Ld({parsers:G,handlers:J,getSessionMetadata:_,updateSessionMetadata:V,emit:R.emit,documentRef:typeof document<"u"?document:null});Q.syncFromMetadata();let X=s.launcher?.enabled??!0,Y=s.launcher?.autoExpand??!1,Z=s.autoFocusInput??!1,ee=Y,te=X,re=s.layout?.header?.layout,ne=!1,se=()=>js(s),pe=()=>X||se(),ue=!se()&&(!X||Y),he=!1,me=null,ge=()=>{he=!0,me&&clearTimeout(me),me=setTimeout(()=>{he&&=(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),!1)},1e4)},fe=cc(s,Q,ge),we=s.features?.showReasoning??!0,xe=s.features?.showToolCalls??!0,Ce=s.features?.showEventStreamToggle??!1,Se=s.features?.scrollToBottom??{},Ae=s.features?.scrollBehavior??{},Me=()=>("object"==typeof s.persistState?s.persistState?.keyPrefix:void 0)??"persona-",Ie=`${Me()}event-stream`,Te=null,Ee=s.features?.eventStream?.maxEvents??2e3,Le=null,Pe=null,Be=null,Ne=!1,Re=null,He=!1,$e=null,We=0,De=(e,t)=>{Le?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},Fe=(e,t)=>{Pe?.processEvent(e,t),Le?De(e,t):Be&&(Be.length>=Ee&&Be.shift(),Be.push({type:e,payload:t}))},Oe=()=>{!Le&&Ce&&(Be??=[],Al().then(e=>{if(Ne||Le||!Ce)return;Te=new e.EventStreamStore(Ie),Le=new e.EventStreamBuffer(Ee,Te),Pe??=new e.ThroughputTracker,Te.open().then(()=>Le?.restore()).catch(e=>{s.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",e)});let t=Be??[];Be=null;for(let e of t)Pe?.processEvent(e.type,e.payload),De(e.type,e.payload)}).catch(()=>{}))};Ce&&Oe();let qe=!1,je=null,_e=()=>{},Ue=()=>{},Ve=()=>{},Ke=()=>{},Je=()=>{},Qe=e=>{R.emit("message:copy",e),wa?.isClientTokenMode()&&wa.submitMessageFeedback(e.id,"copy").catch(e=>{s.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",e)}),s.messageActions?.onCopy?.(e)},Xe=e=>{R.emit("message:feedback",e),wa?.isClientTokenMode()&&wa.submitMessageFeedback(e.messageId,e.type).catch(e=>{s.debug&&console.error("[AgentWidget] Failed to submit feedback:",e)}),s.messageActions?.onFeedback?.(e)};s.statusIndicator;let Ze=(e,t=s.statusIndicator??{})=>"idle"===e?t.idleText??Sr.idle:"connecting"===e?t.connectingText??Sr.connecting:"connected"===e?t.connectedText??Sr.connected:"error"===e?t.errorText??Sr.error:"paused"===e?t.pausedText??Sr.paused:"resuming"===e?t.resumingText??Sr.resuming:Sr[e];function et(e,t,r,n){if(!se()&&("transient"===r.mode||e.classList.contains("persona-mb-2"))&&(de(e,mt,r),le(e,r,n)),!e.hasAttribute(nc)&&!e.hasAttribute(oc))if("idle"===n&&r.idleLink){e.textContent="";let n=document.createElement("a");n.href=r.idleLink,n.target="_blank",n.rel="noopener noreferrer",n.textContent=t,n.style.color="inherit",n.style.textDecoration="none",e.appendChild(n)}else e.textContent=t}let tt=rl({config:s,showClose:pe()}),{wrapper:rt,panel:nt,pillRoot:ot}=tt.shell,at=tt.panelElements,{container:st,body:it,messagesWrapper:lt,starterSuggestions:dt,transcriptSuggestions:ct,suggestions:pt,textarea:ut,sendButton:ht,composerForm:mt,statusText:gt,welcomeHost:ft,welcomeIconHolder:yt,greetingHost:bt,introKicker:vt,introTitle:wt,introSubtitle:xt,closeButton:St,iconHolder:At,headerTitle:Mt,headerSubtitle:It,header:Tt,footer:Et,actionsRow:Lt}=at,Pt=at.leftActions,Bt=at.rightActions,Nt=at.sendButtonWrapper,Rt=at.setSendButtonMode,Wt=at.micButton,Dt=at.micButtonWrapper,Ft=at.attachmentButton,zt=at.attachmentButtonWrapper,jt=at.attachmentInput,Ut=at.attachmentPreviewsContainer;st.classList.add("persona-relative"),it.classList.add("persona-relative");let Vt=()=>Se.label??"",Gt=()=>Ae.mode??"anchor-top",Kt=()=>"follow"===Gt()||"anchor-top"===Gt()&&ws,Jt=()=>Ae.anchorTopOffset??16,Qt=()=>!0===Ae.pauseOnInteraction,Xt=()=>!1!==Ae.showActivityWhilePinned,Yt=()=>!0===Ae.announce,er=()=>Ae.scrollbar??"on-scroll",tr=L("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");tr.type="button",tr.style.display="none",tr.setAttribute("data-persona-scroll-to-bottom","true");let rr=L("span","persona-flex persona-items-center"),nr=L("span",""),or=L("span","");or.setAttribute("data-persona-scroll-to-bottom-count",""),or.style.display="none",tr.append(rr,nr,or),st.appendChild(tr);let ar=L("div","persona-stream-anchor-spacer");ar.setAttribute("aria-hidden","true"),ar.setAttribute("data-persona-anchor-spacer",""),ar.style.flexShrink="0",ar.style.pointerEvents="none",ar.style.height="0px",ar.style.display="none",it.appendChild(ar);let sr=L("div","persona-sr-only");sr.setAttribute("aria-live","polite"),sr.setAttribute("aria-atomic","true"),sr.setAttribute("role","status"),sr.setAttribute("data-persona-live-region",""),Object.assign(sr.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"}),st.appendChild(sr);let ir=null,lr=null,dr=e=>{Yt()&&e&&(lr=e,null===ir&&(ir=setTimeout(()=>{ir=null,lr&&Yt()&&(sr.textContent=lr),lr=null},400)))},cr=()=>{let t=e.ownerDocument.defaultView??window;return(s.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(s.launcher?.mobileBreakpoint??640)&&(X||qs(s))||!0===s.launcher?.fullHeight&&!s.launcher.sidebarMode&&!qs(s)},pr=()=>ji(s,cr()),ur="empty",hr=0,mr=()=>hr||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,gr=()=>{let e="none"===Et.style.display?0:Et.offsetHeight;tr.style.bottom=`${e+mr()+12}px`};gr();let yr=()=>{an||(Et.style.marginBottom=hr>0?`${hr}px`:"")},vr=()=>{let t=Fa(s,se()),r=pr();e.setAttribute("data-persona-welcome-fullscreen",String(cr())),e.setAttribute("data-persona-welcome-layout",r.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",s.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom");let n="none"===Et.style.display?0:Et.offsetHeight,o="center"===r.anchor&&"empty"===ur?Oa(r.anchorComposerTop)??Oa("44%"):null,a=null!==o&&"centered"===r.layout&&void 0===s.welcome?.anchor&&void 0===s.welcome?.anchorComposerTop,i=a?getComputedStyle(it):null,l=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,d=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,c=Math.max(0,(parseFloat(i?.paddingBottom??"")||0)-("overlay"===t?l+d:0)),p=a?it.getBoundingClientRect().top-st.getBoundingClientRect().top:0,u=!a||ft.hidden?0:(ft.querySelector("[data-persona-welcome-plugin]")??ft).offsetHeight,h=null===o||se()?0:a?Math.max(0,Math.round((st.clientHeight-p-u-c-n)/2)):(e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight))({columnHeight:st.clientHeight,footerHeight:n,fraction:o});e.style.setProperty("--persona-composer-overlay-height",`${n}px`),e.style.setProperty("--persona-composer-lift",`${"overlay"===t?h:0}px`),hr="block"===t?h:0,yr(),gr()},wr=()=>{let e=!!Vt();tr.setAttribute("aria-label",Vt()||"Jump to latest"),tr.title=Vt(),tr.setAttribute("data-persona-scroll-to-bottom-has-label",e?"true":"false"),rr.innerHTML="";let t=K(Se.iconName??"arrow-down","14px","currentColor",2);t?(rr.appendChild(t),rr.style.display=""):rr.style.display="none",nr.textContent=Vt(),nr.style.display=e?"":"none"};wr();let xr=null,Cr=null,Ar=En();Ar.subscribe(e=>{try{st.dispatchEvent(new CustomEvent("persona:composer:state",{detail:e,bubbles:!0,composed:!0}))}catch{}});let Mr=()=>{Ar.setText(ut?.value??"")},Ir=()=>{Ar.setMentionRefs(Cr?.getMentionRefs()??[])},Tr=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}),Er=e=>{let t=Object.freeze(e.map(Tr));Ar.setAttachments(t);try{s.attachments?.onChange?.(t)}catch(e){console.error("[AgentWidget] attachments.onChange failed:",e)}ql()};Ar.setSelectedModelId(s.composer?.selectedModelId);let Lr=()=>s.composer?.modes??[],Br=()=>function(e,t){return e?.length?e.filter(e=>!Ho(e.groupId,t)&&!function(e,t){return!!e&&"hidden"===t?.find(t=>t.id===e)?.chipVisibility}(e.groupId,t)):[]}(Lr(),s.composer?.modeGroups);{let e=$o(s.composer?.defaultActiveModeIds??[],Lr());e.length&&Ar.setActiveModeIds(e)}function Nr(e){if(Ar.getState().selectedModelId!==e){Ar.setSelectedModelId(e),$r?.repaint();try{s.composer?.onModelChange?.(e)}catch(e){console.error("[AgentWidget] composer.onModelChange failed:",e)}}}function Rr(e){Ar.setActiveModeIds(e),Or?.render(e,Br()),zr.forEach(e=>e.repaint()),bn?.resolve(),Cd(),Tn()}function Hr(e){Rr(function(e,t,r,n){let o=r.find(e=>e.id===t);if(!o)return[...e];let a=e.includes(t),s=new Set(e);if(a)s.delete(t);else{if("single"===((e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null)(o,n)){let e=r.filter(e=>e.groupId===o.groupId).map(e=>e.id);s=new Set([...s].filter(t=>!e.includes(t)))}s.add(t)}return r.filter(e=>s.has(e.id)).map(e=>e.id)}(Ar.getState().activeModeIds,e,Lr(),s.composer?.modeGroups))}let $r=null,Fr=null,Or=null,zr=new Map,qr=null;function jr(e){Ar.setQuote(e),qr?.render(Ar.getState().quote),Tn(),hi()}let _r=!1;function Ur(){let e=s.composer?.streamingSubmitBehavior??"block";return"interrupt"===e?s.clientToken?"interrupt":(!_r&&!0===s.debug&&(_r=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block"):e}let Vr=null;function Gr(e){Ar.setPendingSubmission(e),Vr?.render(Ar.getState().pendingSubmission),Tn()}let Kr=()=>{let e=[],t=Ar.getState().activeModeIds,r=new Set;if(Lr().forEach((n,o)=>{if(Ho(n.groupId,s.composer?.modeGroups)){let t=n.groupId;if(r.has(t))return;r.add(t);let a=(e=>{let t=zr.get(e);if(t)return t;let r=Wo({groupId:e,getGroup:()=>s.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>Lr().filter(t=>t.groupId===e),getActiveIds:()=>Ar.getState().activeModeIds,onSelect:e=>Hr(e)});return zr.set(e,r),r})(t);a.action.order=No(o),a.action.label=s.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(a.action)}else e.push({id:Bo(n.id),kind:"button",placement:"start",order:No(o),presentation:n.presentation??"auto",label:n.label,shortLabel:n.shortLabel,iconName:n.iconName,pressed:t.includes(n.id),onSelect:()=>Hr(n.id)})}),s.composer?.models?.length&&!h.some(e=>e.renderComposer)){let t=s.composer?.modelPicker?.presentation??"native";(!$r||Fr!==t)&&(Fr=t,$r=Io({getModels:()=>s.composer?.models??[],getSelectedModelId:()=>Ar.getState().selectedModelId,onSelect:e=>Nr(e),presentation:t,getSuffix:()=>s.composer?.modelPicker?.suffix})),e.push($r.action)}return e},Qr=null,Xr=h.find(e=>e.renderHeader);if(Xr?.renderHeader){let e=Xr.renderHeader({config:s,defaultRenderer:()=>{let e=si({config:s,showClose:pe()});return ii(st,e,s),e.header},onClose:()=>Nl(!1,"user")});e&&Tt&&(Tt.replaceWith(e),Tt=e,tt.header.element=e)}let en=()=>{Re&&(it.style.display="none",Et.parentNode?.insertBefore(Re.element,Et),Re.update())},tn=()=>{if(!Le)return void Oe();if(He=!0,Re?en():Al().then(e=>{!Re&&He&&Le&&(Re=e.createEventStreamView({buffer:Le,getFullHistory:()=>Le.getAllFromStore(),onClose:()=>rn(),config:s,plugins:h,getThroughput:()=>Pe?.getMetric()??{status:"idle"},renderIconByName:K}),en())}).catch(()=>{rn()}),nn){nn.style.boxShadow=`inset 0 0 0 1.5px ${ni.actionIconColor}`;let e=s.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&nn.classList.add(e))}let e=()=>{if(!He)return;let t=Date.now();t-We>=200&&(Re?.update(),We=t),$e=requestAnimationFrame(e)};We=0,$e=requestAnimationFrame(e),Li(),R.emit("eventStream:opened",{timestamp:Date.now()})},rn=()=>{if(He){if(He=!1,Re&&Re.element.remove(),it.style.display="",nn){nn.style.boxShadow="";let e=s.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&nn.classList.remove(e))}null!==$e&&(cancelAnimationFrame($e),$e=null),Li(),R.emit("eventStream:closed",{timestamp:Date.now()})}},nn=null;if(Ce){let e=s.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:"");nn=L("button",t),nn.style.width="28px",nn.style.height="28px",nn.style.color=ni.actionIconColor,nn.type="button",nn.setAttribute("aria-label","Event Stream"),nn.title="Event Stream";let o=n(r.Activity,"18px","currentColor",1.5);o&&nn.appendChild(o);let a=at.clearChatButtonWrapper,i=at.closeButtonWrapper,l=a||i;l&&l.parentNode===Tt?Tt.insertBefore(nn,l):Tt.appendChild(nn),nn.addEventListener("click",()=>{He?rn():tn()})}let on=e=>{let t=s.attachments;if(!t?.enabled)return;let r=e.querySelector("[data-persona-composer-attachment-previews]")??e.querySelector(".persona-attachment-previews");if(!r){r=L("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let t=e.querySelector("[data-persona-composer-form]");t?.parentNode?t.parentNode.insertBefore(r,t):e.insertBefore(r,e.firstChild)}if(!(e.querySelector("[data-persona-composer-attachment-input]")??e.querySelector('input[type="file"]'))){let r=L("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??br).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label",t.buttonTooltipText??"Attach files"),e.appendChild(r)}},an=!1,sn=e=>{let t=h.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let r=s.composer,n=!!y&&wa.isStreaming();return t.renderComposer({config:s,defaultRenderer:e,requestRender:()=>iu(),storage:b(t.id),onSubmit:e=>{wa&&!wa.isStreaming()&&Qc(e.trim(),{consumeDraft:!1})},streaming:n,disabled:n,openAttachmentPicker:()=>{Hl()||jt?.click()},models:r?.models,selectedModelId:Ar.getState().selectedModelId??r?.selectedModelId,onModelChange:e=>Nr(e),onVoiceToggle:!0===s.voiceRecognition?.enabled?()=>{Qr?.()}:void 0})},ln=sn(()=>yi({config:s}).footer);ln&&(tt.replaceComposer(ln),Et=tt.composer.footer,an=!0);let pn=null;function un(){let e=ut;if(!e)return;let t=s.composer?.inputAttributes,r=t?.ariaLabel||e instanceof HTMLTextAreaElement?null:e.getAttribute("aria-label");Qn(e,t),r&&e.setAttribute("aria-label",r),Jn(e,{submitKey:s.composer?.submitKey,insertNewlineOnTouchEnter:s.composer?.insertNewlineOnTouchEnter,coarsePointer:Vn(e)}),Un(e,_n(s.composer?.maxLines,se()?5:3))}let hn=e=>{pn=Bn(e,{debug:!0===s.debug}),pn&&(e=>{mt=e.form,ut=e.input,Nt=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(ht=e.sendButton),e.micButton&&(Wt=e.micButton,Dt=e.micButton.parentElement),e.found.status&&(gt=e.found.status),e.found.suggestions&&(pt=e.found.suggestions),e.attachmentButton&&(Ft=e.attachmentButton,zt=e.attachmentButton.parentElement),jt=e.attachmentInput??null,Ut=e.attachmentPreviews??null,e.found.actionsRow&&(Lt=e.found.actionsRow),Pt=e.found.actionsStart,Bt=e.found.actionsEnd})(pn),un()};on(Et),hn(Et),Mr();let mn=Da(s,se());mn&&(lt.style.maxWidth=mn,lt.style.marginLeft="auto",lt.style.marginRight="auto",lt.style.width="100%",bt.style.maxWidth=mn,bt.style.marginLeft="auto",bt.style.marginRight="auto",bt.style.width="100%",dt.style.maxWidth=mn,ct.style.maxWidth=mn,ct.style.marginLeft="auto",ct.style.marginRight="auto",ct.style.width="100%");let gn=()=>{let e=Da(s,se());if(e&&!se())for(let t of[mt,pt,Ut,gt])t&&(t.style.maxWidth=e,t.style.marginLeft="auto",t.style.marginRight="auto",t.style.width="100%")};gn();let fn=()=>{s.attachments?.enabled&&jt&&Ut&&(xr?xr.remountPreviews(Ut):(xr=In.fromConfig(s.attachments,Er),xr.setPreviewsContainer(Ut)),pn?.addListener(jt,"change",e=>{let t=e.target;xr?.handleFileSelect(t.files),t.value=""}),st.querySelector(".persona-attachment-drop-overlay")||st.appendChild(pc(s.attachments.dropOverlay)))};fn();let yn=()=>{if(!s.contextMentions?.enabled||!ut)return;let e=Dr();if(!e){let e=ut;return void Wr().then(()=>{!Cr&&ut===e&&e.isConnected&&(yn(),bn?.resolve())},()=>{})}let t=pn?.header??null,r=t?Lo(t):void 0;if(Cr=e.createContextMentionOrchestrator({deps:{loadContextMentions:Go,loadContextMentionsInline:Xo,renderLucideIcon:K,createMentionButton:Yo},config:s,textarea:ut,anchor:mt??ut,getMessages:()=>wa.getMessages(),liveRegionHost:st,chipRow:r}),Cr&&!r){let e=ut;e.parentElement?.insertBefore(Cr.contextRow,e)}};yn();let bn=null,vn={getState:()=>Ar.getState(),getValue:()=>ut?.value??"",setValue:e=>{ut&&(ut.value=e,ut.dispatchEvent(new Event("input",{bubbles:!0})),Mr())},submit:()=>{!function(e){e&&("function"==typeof e.requestSubmit?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}(pn?.form??null)},openAttachmentPicker:()=>{Hl()||jt?.click()},toggleVoice:()=>{Qr?.()},requestRender:()=>bn?.resolve()},wn=()=>{let e=[];return(Cr?.affordanceButtons??[]).forEach((t,r)=>{e.push({id:`core:mention-${r}`,placement:"start",order:100+r,element:t,managed:!0})}),zt&&e.push({id:"core:attachment",placement:"start",order:200,element:zt}),Dt&&e.push({id:"core:mic",placement:"end",order:800,element:Dt}),Nt&&e.push({id:"core:send",placement:"end",order:mo,element:Nt}),e},xn=()=>{bn?.destroy(),bn=ko({getBindings:()=>pn,collect:()=>({builtIns:wn(),configActions:[...Kr(),...s.composer?.actions??[]],plugins:h,contributionContext:{config:s,getState:()=>Ar.getState(),requestRender:()=>bn?.resolve()},debug:!0===s.debug}),actionContext:vn,getState:()=>Ar.getState(),getOverflow:()=>s.composer?.actionOverflow,reportError:(e,t)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),bn.resolve()};xn();let Sn=()=>{if(Or?.destroy(),Or=null,!Br().length)return;let e=pn?.header;e&&(Or=Po({row:Lo(e),onRemove:e=>Hr(e),initialIds:Ar.getState().activeModeIds}),Or.render(Ar.getState().activeModeIds,Br()))};Sn();let kn=()=>{qr?.destroy(),qr=null,Vr?.destroy(),Vr=null;let e=pn?.header;e&&(qr=Do({onDismiss:()=>jr(void 0)}),e.appendChild(qr.element),qr.render(Ar.getState().quote),"defer-one"===Ur()&&(Vr=Fo({onEdit:()=>function(){let e=Ar.getState().pendingSubmission;e&&(Gr(void 0),ut&&(ut.value=e.text,ut.dispatchEvent(new Event("input",{bubbles:!0})),Mr()),e.options.selectedModelId&&(Ar.setSelectedModelId(e.options.selectedModelId),$r?.repaint()),e.options.activeModeIds?.length&&Rr(e.options.activeModeIds),e.options.quote&&jr(e.options.quote),ut?.focus())}(),onRemove:()=>Gr(void 0)}),e.appendChild(Vr.element),Vr.render(Ar.getState().pendingSubmission)))};kn();let An=function(){let e=!1;return{observe:(t,r)=>r?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}(),Mn=()=>{let e=pn?.header?.querySelector(To);if(e)return e.childElementCount>0;let t=Ar.getState();return t.mentionRefs.length>0||$o(t.activeModeIds,Br()).length>0};function Tn(){let e=Ar.getState(),t=An.observe(function(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let r=t.getComputedStyle(e),n=Number.parseFloat(r.lineHeight),o=Number.parseFloat(r.fontSize),a=Number.isFinite(n)&&n>0?n:Number.isFinite(o)&&o>0?1.4*o:0;if(!a)return!1;let s=(Number.parseFloat(r.paddingTop)||0)+(Number.parseFloat(r.paddingBottom)||0);return e.scrollHeight-s>1.5*a}(ut),e.text);Et.toggleAttribute("data-persona-composer-compact",function(e){return!e.wrapped&&!e.text.includes("\n")&&!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}({text:e.text,wrapped:t,hasAttachments:e.attachments.length>0,hasChips:Mn(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission}))}function Ln(){"single-row"!==s.composer?.layout||se()?Et.removeAttribute("data-persona-composer-layout"):Et.setAttribute("data-persona-composer-layout","single-row")}Ln(),Ar.subscribe(()=>{bn?.sync(),ql(),Vl(),Tn(),hi()}),Vl();let Pn=!1;(()=>{let e=s.layout?.slots??{};(e=>{if(Pn||!0!==s.debug)return;let t=["messages","composer"].filter(t=>e[t]);t.length&&(Pn=!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.`))})(e);let t=e=>{switch(e){case"body-top":return it.querySelector("[data-persona-intro-card]");case"messages":return lt;case"footer-top":return pt;case"composer":return mt;case"footer-bottom":return gt;default:return null}},r=(e,t)=>{switch(e){case"header-left":case"header-center":case"header-right":if("header-left"===e)Tt.insertBefore(t,Tt.firstChild);else if("header-right"===e)Tt.appendChild(t);else{let e=Tt.querySelector(".persona-flex-col");e?e.parentNode?.insertBefore(t,e.nextSibling):Tt.appendChild(t)}break;case"body-top":{let e=it.querySelector("[data-persona-intro-card]");e?e.replaceWith(t):it.insertBefore(t,it.firstChild);break}case"body-bottom":it.appendChild(t);break;case"footer-top":pt.replaceWith(t);break;case"footer-bottom":gt.replaceWith(t)}};for(let[n,o]of Object.entries(e))if(o)try{let e=o({config:s,defaultContent:()=>t(n)});e&&r(n,e)}catch(e){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${n}":`,e)}})(),lt.addEventListener("click",e=>{let t=e.target;if(!(t instanceof Element))return;let r=t.closest("button[data-persona-copy-tool-detail]");r&&(e.preventDefault(),e.stopPropagation(),async function(e){let t=e.closest("[data-persona-tool-detail]"),r=t?.querySelector("pre");if(!r)return;let n=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(dl.get(e));try{await navigator.clipboard.writeText(r.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let t=K("check",14,"currentColor",2);t&&e.replaceChildren(t)}catch{e.setAttribute("aria-label","Copy failed — try again"),e.title="Copy failed — try again"}dl.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",n),e.title=n;let t=K("copy",14,"currentColor",1.7);t&&e.replaceChildren(t),dl.delete(e)},1800))}(r))});let Nn=e=>{let t=e.target.closest('button[data-expand-header="true"]');if(!t)return;let r=t.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!r)return;let n=r.getAttribute("data-message-id");if(!n)return;Es(),Ri();let o=t.getAttribute("data-bubble-type");if(r.classList.contains("persona-activity-row")){d.manual(n);let e=r.parentElement?.closest("[data-persona-tool-group]");e?.dataset.messageId&&d.manual(e.dataset.messageId)}if("reasoning"===o)l.has(n)?l.delete(n):l.add(n),al(n,r,l);else if("tool"===o)i.has(n)?i.delete(n):i.add(n),hl(n,r,i,s);else if("approval"===o&&v){let e="expanded"===((!1===s.approval?void 0:s.approval)?.detailsDisplay??"collapsed"),t=c.get(n)??e;c.set(n,!t),v.updateApprovalDetailsUI(n,r,s,c)}qa.delete(n)};lt.addEventListener("pointerdown",e=>{e.target.closest('button[data-expand-header="true"]')&&(e.preventDefault(),Nn(e))}),lt.addEventListener("click",e=>{0===e.detail&&e.target.closest(".persona-activity-row")&&Nn(e)}),lt.addEventListener("keydown",e=>{let t=e.target;("Enter"===e.key||" "===e.key)&&t.closest('button[data-expand-header="true"]')&&(e.preventDefault(),Nn(e))}),lt.addEventListener("copy",e=>{let{clipboardData:t}=e;if(!t)return;let r=lt.getRootNode(),n="function"==typeof r.getSelection?r.getSelection():window.getSelection();if(!n||n.isCollapsed)return;let o=n.toString(),a=(e=>e.replace(/^\n+/,"").replace(/\s+$/,""))(o);a&&a!==o&&(t.setData("text/plain",a),e.preventDefault())});let Rn=new Map,Hn=null,$n="idle",Dn={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading…"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Fn=()=>{lt.querySelectorAll('[data-action="read-aloud"]').forEach(e=>{let t=e.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;((e,t)=>{let{icon:r,label:n}=Dn[t];e.setAttribute("aria-label",n),e.title=n,e.setAttribute("aria-pressed","idle"===t?"false":"true"),e.classList.toggle("persona-message-action-active","idle"!==t),e.classList.toggle("persona-message-action-loading","loading"===t);let o=K(r,14,"currentColor",2);o&&(e.innerHTML="",e.appendChild(o))})(e,t&&t===Hn?$n:"idle")})};lt.addEventListener("click",e=>{let t=e.target.closest(".persona-message-action-btn[data-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let o=t.closest("[data-actions-for]");if(!o)return;let a=o.getAttribute("data-actions-for");if(!a)return;let i=t.getAttribute("data-action");if("copy"===i){let e=wa.getMessages().find(e=>e.id===a);if(e&&Qe){let o=e.content||"";navigator.clipboard.writeText(o).then(()=>{t.classList.add("persona-message-action-success");let e=n(r.Check,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e)),setTimeout(()=>{t.classList.remove("persona-message-action-success");let e=n(r.Copy,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e))},2e3)}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",e)}),Qe(e)}}else if("read-aloud"===i)wa.toggleReadAloud(a);else if("upvote"===i||"downvote"===i){let e="upvote"===i?"thumbs-up":"thumbs-down";if((Rn.get(a)??null)===i){Rn.delete(a),t.classList.remove("persona-message-action-active");let r=K(e,14,"currentColor",2);r&&(t.innerHTML="",t.appendChild(r))}else{let r="upvote"===i?"downvote":"upvote",n=o.querySelector(`[data-action="${r}"]`);if(n){n.classList.remove("persona-message-action-active");let e=K("upvote"===r?"thumbs-up":"thumbs-down",14,"currentColor",2);e&&(n.innerHTML="",n.appendChild(e))}Rn.set(a,i),t.classList.add("persona-message-action-active");let s=K(e,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 l=wa.getMessages().find(e=>e.id===a);l&&Xe&&Xe({type:i,messageId:l.id,message:l})}}else if("regenerate"===i)On?.regenerate(a);else if("edit"===i)On?.edit(a);else if("quote"===i)On?.quote(a);else if(i?.startsWith("custom:")){let e=i.slice(7),r=s.messageActions?.custom?.find(t=>t.id===e),n=wa.getMessages().find(e=>e.id===a);if(!r||!n)return;try{r.onSelect(n)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let On=null;lt.addEventListener("click",e=>{let t=e.target.closest("button[data-approval-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.closest(".persona-approval-bubble");if(!r)return;let n=r.getAttribute("data-message-id");if(!n)return;let o=t.getAttribute("data-approval-action");if(!o)return;let a="approve"===o?"approved":"denied",s=wa.getMessages().find(e=>e.id===n);if(!s?.approval)return;let i=r.querySelector("[data-approval-buttons]");i&&i.querySelectorAll("button").forEach(e=>{e.disabled=!0,e.style.opacity="0.5",e.style.cursor="not-allowed"}),"webmcp"===s.approval.toolType?wa.resolveWebMcpApproval(n,a):wa.resolveApproval(s.approval,a)});let zn=null,jn=!1,Gn=null,eo=()=>{},to="none",no=null,ao={artifacts:[],selectedId:null},so=!1,io=!1,lo=!1,co=!1,po=()=>co||ao.artifacts.some(e=>"panel"===Jr(s.features?.artifacts,e)),uo=()=>ao.artifacts.length>0&&!so&&po(),ho={current:null},go=(e,t)=>{let r=wa.getArtifactById(t),n=r?.markdown,o=r?.title||"artifact",a=r?.file,s=r?.artifactType??"markdown";if(!n){let t=(e.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]"))?.getAttribute("data-message-id");if(t){let e=wa.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);n=t?.props?.markdown,o=t?.props?.title||o,t?.props?.file&&"object"==typeof t.props.file&&(a=t.props.file),!r&&"string"==typeof t?.props?.artifactType&&(s=t.props.artifactType)}catch{}}}return{markdown:n,title:o,file:a,artifactType:s}};lt.addEventListener("click",e=>{let t=e.target.closest("[data-download-artifact]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-download-artifact");if(!r||!0===s.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:r}))return;let{markdown:n,title:o,file:a}=go(t,r);if(!n)return;let i=Wl();i&&i.triggerArtifactDownload(i.downloadInfoFor({title:o,markdown:n,file:a}))}),lt.addEventListener("click",e=>{let t=e.target.closest("[data-artifact-custom-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-artifact-custom-action");if(!r)return;let n=t.closest("[data-artifact-inline]"),o=n?null:t.closest("[data-open-artifact]"),a=n?n.getAttribute("data-artifact-inline"):o?.getAttribute("data-open-artifact")??null,i=(n?s.features?.artifacts?.inlineActions:s.features?.artifacts?.cardActions)?.find(e=>e.id===r);if(!i)return;let{markdown:l,title:d,file:c,artifactType:p}=go(t,a??""),u={artifactId:a,title:d,artifactType:p,markdown:l,file:c};try{Promise.resolve(i.onClick(u)).catch(()=>{})}catch{}}),lt.addEventListener("click",e=>{let t=e.target.closest("[data-copy-artifact]");if(!t)return;e.preventDefault(),e.stopPropagation();let o=t.getAttribute("data-copy-artifact");if(!o)return;let a=wa.getArtifactById(o),s=Wl();if(!s)return;let i="";if(a)i=s.artifactCopyText(a);else{let{markdown:e,file:r,artifactType:n}=go(t,o);"markdown"===n&&(i=s.artifactCopyText({id:o,artifactType:"markdown",status:"complete",markdown:e??"",...r?{file:r}:{}}))}i&&navigator.clipboard.writeText(i).then(()=>{let e=n(r.Check,16,"currentColor",2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=n(r.Copy,16,"currentColor",2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),lt.addEventListener("click",e=>{let t=e.target.closest("[data-expand-artifact-inline]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-expand-artifact-inline");r&&!0!==s.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:r})&&(so=!1,co=!0,io=!0,lo=!0,wa.selectArtifact(r),ea())}),lt.addEventListener("click",e=>{let t=e.target;if(t.closest("[data-download-artifact]")||t.closest("[data-artifact-custom-action]"))return;let r=t.closest("[data-open-artifact]");if(!r)return;let n=r.getAttribute("data-open-artifact");n&&!0!==s.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:n})&&(e.preventDefault(),e.stopPropagation(),so=!1,co=!0,wa.selectArtifact(n),ea())}),lt.addEventListener("keydown",e=>{if("Enter"!==e.key&&" "!==e.key)return;let t=e.target;(t.hasAttribute("data-open-artifact")||t.hasAttribute("data-expand-artifact-inline"))&&(e.preventDefault(),t.click())});let fo=at.composerOverlay,yo=e=>{Wr().catch(()=>{}),Ht(e,s,fo)},bo=null,vo={mount:e,overlay:fo,sessionRef:ho,config:()=>s},wo=!1,xo=e=>t=>{let r=t.target,n=r?.closest?.("[data-persona-ask-sheet-for]");if(!n||!("click"===e?r?.closest("[data-ask-user-action]"):"Enter"===t.key&&r?.matches?.('[data-ask-free-text-input="true"]')))return;let o=r=>{bo??=r.createAskUserSheetHandlers(vo),bo[e](t)},a=Dr();a?o(a):wo||(wo=!0,Wr().then(e=>{wo=!1,n.isConnected&&o(e)},()=>{wo=!1}))};fo.addEventListener("click",xo("click")),fo.addEventListener("keydown",xo("keydown"));let Co=e=>{if(!/^[1-9]$/.test(e.key)||e.metaKey||e.ctrlKey||e.altKey)return;let t=e.target;if("INPUT"===t?.tagName||"TEXTAREA"===t?.tagName||t?.isContentEditable)return;let r=fo.querySelector("[data-persona-ask-sheet-for]");if(!r||"rows"!==r.getAttribute("data-ask-layout")||"true"===r.getAttribute("data-multi-select"))return;let n=Number(e.key),o=r.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[n-1];o&&(e.preventDefault(),o.click())};document.addEventListener("keydown",Co);let So=null,Ao=null,Mo=null,Eo=null,Ro=()=>{},qo=!1,_o="",Uo="";function Vo(){Eo?.(),Eo=null}let Ko=()=>{if(!So||!Ao)return;let t=e.classList.contains("persona-artifact-welded-split"),r=e.ownerDocument.defaultView??window,n=r.innerWidth<=640;if(!t||e.classList.contains("persona-artifact-narrow-host")||n)return Ao.style.removeProperty("position"),Ao.style.removeProperty("left"),Ao.style.removeProperty("top"),Ao.style.removeProperty("bottom"),Ao.style.removeProperty("width"),void Ao.style.removeProperty("z-index");let o=So.firstElementChild;if(!o||o===Ao)return;Ao.style.position="absolute",Ao.style.top="0",Ao.style.bottom="0",Ao.style.width="10px",Ao.style.zIndex="5";let a=hd(So,r),s=o.offsetWidth+a/2-5;Ao.style.left=`${Math.max(0,s)}px`},Jo=()=>{},Qo=()=>{let t=e.ownerDocument.defaultView??window,r=s.launcher?.mobileFullscreen??!0,n=s.launcher?.mobileBreakpoint??640;return!(!r||t.innerWidth>n)&&(X||qs(s))},Zo=()=>!Fl(s)||!uo()||e.classList.contains("persona-artifact-narrow-host")||Qo()||(e.ownerDocument.defaultView??window).innerWidth<641?"none":jl(s)?"detached":"welded",ea=()=>{if(!zn||!Fl(s))return;_l(e,s),Ul(e,s),Jo();let t=s.features?.artifacts?.layout?.narrowHostMaxWidth??520,r=nt.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",r>0&&r<=t);let n=uo();zn.setVisible(n),zn.update(ao),so?(zn.setMobileOpen(!1),zn.element.classList.add("persona-hidden"),zn.backdrop?.classList.add("persona-hidden"),io=!1,lo=!1):ao.artifacts.length>0&&po()?(zn.element.classList.remove("persona-hidden"),zn.setMobileOpen(!0)):(zn.setMobileOpen(!1),zn.element.classList.add("persona-hidden"),zn.backdrop?.classList.add("persona-hidden"),io=!1,lo=!1);let o=!0===s.features?.artifacts?.layout?.showExpandToggle;if(zn.setExpandToggleVisible(o),zn.setCopyButtonVisible(!0===s.features?.artifacts?.layout?.showCopyButton),zn.setRefreshButtonVisible("function"==typeof s.features?.artifacts?.layout?.onDocumentToolbarRefresh),zn.setCustomActions(s.features?.artifacts?.toolbarActions??[]),zn.setTabFade(s.features?.artifacts?.layout?.tabFade),zn.setRenderTabBar(s.features?.artifacts?.renderTabBar),!o&&!lo&&(io=!1),io!==qo){let e=zn.element;io?(_o=e.style.width,Uo=e.style.maxWidth,e.style.removeProperty("width"),e.style.removeProperty("max-width")):(_o&&(e.style.width=_o),Uo&&(e.style.maxWidth=Uo),_o="",Uo=""),qo=io}e.classList.toggle("persona-artifact-expanded",io),zn.setExpanded(io);let a=Zo();a!==to&&(to=a,eo()),Ro()};if(Fl(s)){nt.style.position="relative";let t=L("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),r=L("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");t.appendChild(st),So=r,r.appendChild(t),nt.appendChild(r);let n=e=>{jn||zn||(zn=e.createArtifactPane(s,{onSelect:e=>ho.current?.selectArtifact(e),onDismiss:()=>{so=!0,ea()},onToggleExpand:()=>{let e=!io,t=ao.selectedId??ao.artifacts[ao.artifacts.length-1]?.id??null;!0!==s.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:t,expanded:e})&&(io=e,e||(lo=!1),ea())}}),zn.element.classList.add("persona-hidden"),r.appendChild(zn.element),zn.backdrop&&nt.appendChild(zn.backdrop),Ro(),ea())},o=Wl();o?n(o):(Dl(()=>{let e=Wl();e&&n(e)}),$l().catch(()=>{})),Ro=()=>{if(So&&zn)if(!0!==s.features?.artifacts?.layout?.resizable)Mo?.(),Mo=null,Vo(),Ao&&=(Ao.remove(),null),zn.element.style.removeProperty("width"),zn.element.style.removeProperty("maxWidth");else{if(!Ao){let t=L("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 r=e.ownerDocument,n=r.defaultView??window,o=o=>{if(!zn||0!==o.button||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||n.innerWidth<=640)return;o.preventDefault(),Vo();let a=o.clientX,i=zn.element.getBoundingClientRect().width,l=s.features?.artifacts?.layout,d=r=>{let o=So.getBoundingClientRect().width,s=e.classList.contains("persona-artifact-welded-split"),d=hd(So,n),c=s?0:t.getBoundingClientRect().width||6,p=function(e,t,r,n,o,a,s=200){let i=function(e){if(!e?.trim())return 200;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):200}(o),l=function(e,t,r,n){let o=e-n-2*t-r;return Math.max(0,o)}(t,r,n,s);l=Math.max(i,l);let d=function(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}(a);return null!==d&&(l=Math.min(l,d)),function(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}(e,i,l)}(i-(r.clientX-a),o,d,c,l?.resizableMinWidth,l?.resizableMaxWidth,(()=>{let e=yc?.railShell?yc.railHost:null,t=e?.isConnected?e:null,r=t?t.getBoundingClientRect().width:0;return r<=0?200:r+360})());zn.element.style.width=`${p}px`,zn.element.style.maxWidth="none",Ko()},c=()=>{r.removeEventListener("pointermove",d),r.removeEventListener("pointerup",c),r.removeEventListener("pointercancel",c),Eo=null;try{t.releasePointerCapture(o.pointerId)}catch{}};Eo=c,r.addEventListener("pointermove",d),r.addEventListener("pointerup",c),r.addEventListener("pointercancel",c);try{t.setPointerCapture(o.pointerId)}catch{}};t.addEventListener("pointerdown",o),Ao=t,So.insertBefore(t,zn.element),Mo=()=>{t.removeEventListener("pointerdown",o)}}if(Ao){let e=uo();Ao.classList.toggle("persona-hidden",!e),Ko()}}},Jo=()=>{if(!X||!zn||s.launcher?.sidebarMode||qs(s)&&"emerge"===_s(s).reveal)return;let t=e.ownerDocument.defaultView??window,r=s.launcher?.mobileFullscreen??!0,n=s.launcher?.mobileBreakpoint??640;if(r&&t.innerWidth<=n||!function(e,t){return!(!t||!Fl(e))&&!1!==e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen}(s,X))return;let o=Vi(s).width,a=s.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";uo()?(nt.style.width=a,nt.style.maxWidth=a):(nt.style.width=o,nt.style.maxWidth=o)},typeof ResizeObserver<"u"&&(Gn=new ResizeObserver(()=>{ea()}),Gn.observe(nt))}else nt.appendChild(st);se()&&ot&&(at.peekBanner&&ot.appendChild(at.peekBanner),ot.appendChild(Et)),e.appendChild(rt),ot&&e.appendChild(ot);let ta=()=>{let t=Qo()||se()&&"fullscreen"===s.launcher?.composerBar?.expandedSize||!0===s.launcher?.fullHeight&&!s.launcher?.sidebarMode&&!qs(s);if(lt.style.gap=t?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",lt.style.setProperty("--persona-transcript-gap",lt.style.gap),se()){nt.style.width="100%",nt.style.maxWidth="100%";let e=s.launcher?.composerBar??{},t="expanded"===rt.dataset.state,r=e.expandedSize??"anchored";if(!t||"fullscreen"===r)return st.style.background="",st.style.border="",st.style.borderRadius="",st.style.overflow="",void(st.style.boxShadow="");let n=s.theme?.components?.panel,o=Ha(s),a=(e,t)=>null==e||""===e?t:ya(o,e)??e;return st.style.background="var(--persona-surface, #ffffff)",st.style.border=a(n?.border,"1px solid var(--persona-border)"),st.style.borderRadius=a(n?.borderRadius,"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))"),st.style.boxShadow=a(n?.shadow,"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))"),void(st.style.overflow="hidden")}let r=qs(s),n=s.launcher?.sidebarMode??!1,o=r||n||(s.launcher?.fullHeight??!1),i=!1===s.launcher?.enabled,l=!0===s.launcher?.detachedPanel,d=s.theme?.components?.panel,c=s.darkTheme?.components?.panel,p="dark"===Ra(s)?a(d??{},c??{}):d,u=Ha(s),h=(e,t)=>null==e||""===e?t:ya(u,e)??e,m=e.ownerDocument.defaultView??window,g=s.launcher?.mobileFullscreen??!0,y=s.launcher?.mobileBreakpoint??640,b=m.innerWidth<=y,v=g&&b&&X,w=r&&g&&b,x=s.launcher?.position??"bottom-left",C="bottom-left"===x||"top-left"===x,S=s.launcher?.zIndex??1e5,k=(e,t,r)=>`var(--persona-components-panel-modes-${e}-${t}, ${r})`,A=p?.modes?.floating,M=h(A?.border??p?.border,k("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),I=h(A?.shadow??p?.shadow,k("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),T=h(A?.borderRadius??p?.borderRadius,k("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),E=l&&!v&&!w,L=v||w?"mobile":E?"floating":r?"docked":n?"sidebar":i?"inline":"floating",P=p?.modes?.[L];E?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let B=E?M:n||v?"none":M,N=E?I:v?"none":n?C?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":i?"none":I;r&&!v&&!E&&(N="none",B="none");let R=E?T:n||v?"0":T,H=h(P?.border??p?.border,k(L,"border",B)),$=h(P?.shadow??p?.shadow,k(L,"shadow",N)),W=h(P?.borderRadius??p?.borderRadius,k(L,"borderRadius",R)),D=Zo(),F="detached"===D,O="welded"===D;e.classList.toggle("persona-artifact-detached-split",F),e.classList.toggle("persona-artifact-welded-split",O);let z="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)))))",q="flush"==("flush"===s.features?.artifacts?.layout?.chatSurface?"flush":"card")&&Fl(s)&&jl(s)&&i&&!r;e.classList.toggle("persona-artifact-chat-flush",q);let j=F||q?"none":$,_=F?M:O?"none":H,U=F?T:W;q&&(_="none",U="0");let V=null!=P?.borderRadius&&""!==P.borderRadius||null!=p?.borderRadius&&""!==p.borderRadius,G=q&&!V?"0":W,K=it.scrollTop;e.style.cssText="",rt.style.cssText="",nt.style.cssText="",st.style.cssText="",it.style.cssText="",an||(Et.style.cssText=""),He&&(it.style.display="none"),(o||i)&&(e.style.minWidth="0");let J=()=>{K<=0||(it.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(it.scrollTop===K)return;let e=it.scrollHeight-it.clientHeight;e<=0||(it.scrollTop=Math.min(K,e))})};if(v)return rt.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"),rt.style.cssText=`\n position: fixed !important;\n inset: 0 !important;\n width: 100% !important;\n height: 100% !important;\n max-height: 100% !important;\n margin: 0 !important;\n padding: 0 !important;\n display: flex !important;\n flex-direction: column !important;\n z-index: ${S} !important;\n background-color: var(--persona-surface, #ffffff) !important;\n `,nt.style.cssText="\n position: relative !important;\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n max-width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n margin: 0 !important;\n padding: 0 !important;\n box-shadow: none !important;\n border-radius: 0 !important;\n ",st.style.cssText="\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n max-height: 100% !important;\n overflow: hidden !important;\n border-radius: 0 !important;\n border: none !important;\n ",it.style.flex="1 1 0%",it.style.minHeight="0",it.style.overflowY="auto",Et.style.flexShrink="0",yr(),ne=!0,void J();let Q=Vi(s);if(n||r){if(r)if("emerge"!==_s(s).reveal||l)nt.style.width="100%",nt.style.maxWidth="100%";else{let e=_s(s).width;nt.style.width=e,nt.style.maxWidth=e}}else i&&o?(nt.style.width="100%",nt.style.maxWidth="100%"):(nt.style.width=Q.width,nt.style.maxWidth=Q.maxWidth);if(Jo(),nt.style.boxShadow=j,nt.style.borderRadius=G,F?nt.style.border="none":O&&(nt.style.border=H),st.style.border=_,st.style.borderRadius=U,st.style.boxShadow=F&&!q?z:"",q&&(st.style.background="transparent",it.style.background="transparent",Et.style.background="transparent",Et.style.borderTop="none"),O){let e=s.features?.artifacts?.layout;no=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||W}else no=null;let Y=null!=P?.border||null!=p?.border;if(r&&!v&&!E&&!F&&!O&&!Y&&(st.style.border="none","right"===_s(s).side?st.style.borderLeft="1px solid var(--persona-border)":st.style.borderRight="1px solid var(--persona-border)"),r&&!v&&O&&!Y&&("right"===_s(s).side?nt.style.borderLeft="1px solid var(--persona-border)":nt.style.borderRight="1px solid var(--persona-border)"),o&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",i&&(e.style.width="100%"),rt.style.display="flex",rt.style.flexDirection="column",rt.style.flex="1 1 0%",rt.style.minHeight="0",rt.style.maxHeight="100%",rt.style.height="100%",i&&(rt.style.overflow="hidden"),nt.style.display="flex",nt.style.flexDirection="column",nt.style.flex="1 1 0%",nt.style.minHeight="0",nt.style.maxHeight="100%",nt.style.height="100%",F||(nt.style.overflow="hidden"),st.style.display="flex",st.style.flexDirection="column",st.style.flex="1 1 0%",st.style.minHeight="0",st.style.maxHeight="100%",st.style.overflow="hidden",it.style.flex="1 1 0%",it.style.minHeight="0",it.style.overflowY="auto",Et.style.flexShrink="0"),i&&(E||F||q)&&!r&&(q||(rt.style.padding="var(--persona-panel-inset)"),rt.style.background="var(--persona-panel-canvas-bg)"),rt.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"),!n&&!i&&!r&&(Qs[x]??Qs["bottom-right"]).split(" ").forEach(e=>rt.classList.add(e)),n){let e=f(s).sidebarWidth?s.launcher?.sidebarWidth??"420px":ya(Ha(s),"components.panel.width")??"420px";rt.style.cssText=l?`\n position: fixed !important;\n top: var(--persona-panel-inset) !important;\n bottom: var(--persona-panel-inset) !important;\n width: ${e} !important;\n height: calc(100vh - (2 * var(--persona-panel-inset))) !important;\n max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;\n margin: 0 !important;\n padding: 0 !important;\n display: flex !important;\n flex-direction: column !important;\n z-index: ${S} !important;\n ${C?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}\n `:`\n position: fixed !important;\n top: 0 !important;\n bottom: 0 !important;\n width: ${e} !important;\n height: 100vh !important;\n max-height: 100vh !important;\n margin: 0 !important;\n padding: 0 !important;\n display: flex !important;\n flex-direction: column !important;\n z-index: ${S} !important;\n ${C?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}\n `,nt.style.cssText=`\n position: relative !important;\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n max-width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n margin: 0 !important;\n padding: 0 !important;\n box-shadow: ${j} !important;\n border-radius: ${G} !important;\n ${F?"border: none !important;":O?`border: ${H} !important;`:""}\n `,nt.style.setProperty("width","100%","important"),nt.style.setProperty("max-width","100%","important"),st.style.cssText=`\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n max-height: 100% !important;\n overflow: hidden !important;\n border-radius: ${U} !important;\n border: ${_} !important;\n ${F&&!q?`box-shadow: ${z} !important;`:""}\n ${q?"background: transparent !important;":""}\n `,an||(Et.style.cssText=`\n flex-shrink: 0 !important;\n border-top: none !important;\n padding: 8px 16px 12px 16px !important;\n ${q?"background: transparent !important;":""}\n `)}if(!i&&!r){let e=n?"":"padding-top: 1.25em !important;",t=n?"":`z-index: ${s.launcher?.zIndex??1e5} !important;`;rt.style.cssText+="max-height: -moz-available !important; max-height: stretch !important;"+e+t}yr(),J()},ra=()=>{e.style.setProperty("--persona-content-max-width",Da(s,se()))},na=!1;function oa(){s.layout?.topFade&&it.scrollTop>1?it.setAttribute("data-persona-top-fade","true"):it.removeAttribute("data-persona-top-fade")}let aa=()=>{oa();let t=Fa(s,se());se()&&s.composer?.placement&&!0===s.debug&&!na&&(na=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let r=pr();e.setAttribute("data-persona-composer-placement",t),e.setAttribute("data-persona-conversation-state",ur),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",r.composerGap??"24px"),vr()},sa=()=>{if(se())return;let t=qs(s),r=s.launcher?.sidebarMode??!1;if(t||r||s.launcher?.fullHeight||!X)return;let n=e.ownerDocument.defaultView??window,o=s.launcher?.mobileFullscreen??!0,a=s.launcher?.mobileBreakpoint??640;if(o&&n.innerWidth<=a)return;let i=Vi(s);nt.style.height=i.height,nt.style.maxHeight=i.maxHeight};ta(),$a(e,s),_l(e,s),Ul(e,s),ra(),aa(),eo=()=>{ta(),sa(),$a(e,s),_l(e,s),Ul(e,s),ra(),aa(),no?e.style.setProperty("--persona-artifact-welded-outer-radius",no):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Ue(),_e()};let ia=[];ia.push(()=>{jn=!0}),ia.push(()=>{g.forEach(e=>e()),m.destroy()}),ia.push(()=>{document.removeEventListener("keydown",Co)}),ia.push(()=>{null!==ir&&clearTimeout(ir)});let la=null,da=null;ia.push(()=>{la?.(),la=null,da?.(),da=null}),Gn&&ia.push(()=>{Gn?.disconnect(),Gn=null}),ia.push(()=>{Mo?.(),Mo=null,Vo(),Ao&&=(Ao.remove(),null),zn?.element.style.removeProperty("width"),zn?.element.style.removeProperty("maxWidth"),zn?.destroy()}),Ce&&ia.push(()=>{Ne=!0,Be=null,null!==$e&&(cancelAnimationFrame($e),$e=null),Re?.destroy(),Re=null,Le?.destroy(),Le=null,Te=null});let ca=null,pa=()=>{ca&&=(ca(),null),"auto"===s.colorScheme&&(ca=Wa(()=>{$a(e,s)}))};pa(),ia.push(()=>{ca&&=(ca(),null)}),ia.push(()=>{C=!0,x?.()}),ia.push(()=>{M=!0});let ua=!1;ia.push(()=>{ua=!0});let ha=(t,r)=>{let n=ms(t,r);return n||!us.includes(t)?n:(Bs().then(n=>{if(ua)return;hs(n.wipe),hs(n.glyphCycle);let o=ms(t,r);o&&Ts(o,e)}).catch(()=>{}),null)},ma=s.features?.streamAnimation;if(ma?.type&&"none"!==ma.type){let t=ha(ma.type,ma.plugins);t&&Ts(t,e),ia.push(()=>Is(e))}let ga=Js(pt),fa=Js(dt),ba=Js(ct),va=[ga,fa,ba];ia.push(()=>{va.forEach(e=>e.destroy())});let wa,xa=null,Ca=null,Sa=!1,ka=0,Aa=null,Ma=e=>e.reduce((e,t)=>"user"===t.role?e+1:e,0),Ia=e=>{for(let t=e.length-1;t>=0;t--)if(Ot(e[t]))return e[t].id??null;return null},Ta=!1,Ea=!1,La=!1,Pa=(e,t)=>{Ea||!0!==s.debug||t.enabled&&!t.expose&&(Sa||La&&(wa.isStreaming()||e.some(Ot)||(Ea=!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."))))},Ba=e=>{if(!wa)return;let t=e??wa.getMessages(),r=e=>{e.render([],wa,ut,t)},n=e=>{va.forEach(t=>{t!==e&&r(t)})};Ca&&(Ma(t)>ka||Ia(t)!==Aa)&&(Ca=null);let o=_t(s);Pa(t,o);let a=o.enabled?qt(t):null,i=Ca??a,l=Ca?"host":"agent";if(i){let e=s.suggestions?.followUps,r=e?.placement??(e?"auto":"composer"),o="after-message"===("auto"===r?se()?"composer":"after-message":r)?ba:ga;return n(o),void o.render(i,wa,ut,t,s.suggestionChipsConfig,{source:l,surface:"followUp",variant:e?.variant??"chip",behavior:e?.behavior??"send",overflow:e?.overflow??"wrap",maxItems:e?.maxItems??4,config:s,plugins:h,submitPrompt:Jc})}if(t.some(e=>"user"===e.role))return void va.forEach(r);let d=!0===s.future?.v5Defaults,c=cr(),p=s.suggestions?.starters??(d?{}:void 0);if(p){let e=_i(pr(),t),o=p.placement??"auto",a="auto"===o?e?"welcome":"composer":o;if("welcome"===a&&!e)return Ta||!0!==s.debug||(Ta=!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".')),void va.forEach(r);let i="welcome"===a?fa:ga;n(i),i.render(p.items??s.suggestionChips,wa,ut,t,s.suggestionChipsConfig,{surface:"starter",variant:p.variant??(d&&!c?"chip":"card"),behavior:p.behavior??"send",overflow:p.overflow??"wrap",maxItems:p.maxItems??(d&&!c?3:4),config:s,plugins:h,submitPrompt:Jc})}else n(ga),ga.render(s.suggestionChips,wa,ut,t,s.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:s,plugins:h,submitPrompt:Jc})},Na=()=>{Ca&&(Ca=null,Ba())},za=!1,qa=new Map,ja=new Map,_a=new Map,Ua=new Map,Va=null,Ga=null;function Ka(){if(!Va)return;let e=Va;Va=null,Ga?.destroy(),Ga=null,qa.delete(e),st.querySelector(`#wrapper-${e}`)?.removeAttribute("data-preserve-runtime"),wa&&yl(lt,wa.getMessages(),fe)}let Qa=0,ns=null!==ve(),os=function(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>!!t&&(t=!1,!0),resume:()=>!t&&(t=!0,!0)}}(),as=0,ss=null,is=!1,ls=!1,cs=0,ps=null,fs=null,ys=!1,bs=!1,vs=null,ws=!0,xs=!1,As=null,Ms=!1,Es=()=>{Ms=!0,Hs()},Ls=null,Ps=null,Rs=()=>{e.setAttribute("data-persona-scrollbar",er()),"on-scroll"!==er()&&(null!==Ps&&clearTimeout(Ps),Ps=null,it.removeAttribute("data-persona-scrollbar-visible"))},Hs=()=>{"on-scroll"===er()&&(it.setAttribute("data-persona-scrollbar-visible",""),null!==Ps&&clearTimeout(Ps),Ps=setTimeout(()=>{Ps=null,ts(it,24)&&it.removeAttribute("data-persona-scrollbar-visible")},1e3))};Rs(),ia.push(()=>{null!==Ps&&clearTimeout(Ps)});let Ws=new Map,Ds=!1,Fs=null,Os={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Tn();let zs=s.voiceRecognition?.autoResume??!1,Us=()=>wa.isVoiceActive()||wa.isBargeInActive(),Gs=!1,Xs=e=>{R.emit("voice:state",{active:Os.active,source:e,timestamp:Date.now()})},Ys=()=>{V(e=>({...e,voiceState:{active:Os.active,timestamp:Date.now(),manuallyDeactivated:Os.manuallyDeactivated}}))},ti=e=>{Gs=!e.persisted,Os.active&&Ys()};typeof window<"u"&&(window.addEventListener("pagehide",ti),ia.push(()=>window.removeEventListener("pagehide",ti)));let ri=()=>wa?dc(wa.getMessages()).filter(e=>!e.__skipPersist):[],oi=null,ai=(e,t)=>{typeof console<"u"&&console.error(e,t)},li=(e,t)=>{let r=()=>{try{let r=e();return r&&"function"==typeof r.then?Promise.resolve(r).catch(e=>{ai(t,e)}):null}catch(e){return ai(t,e),null}},n=oi?oi.then(()=>r()??void 0):r();if(!n)return;let o=n.finally(()=>{oi===o&&(oi=null)});oi=o};function di(e){if(!H?.save)return;let t=e?dc(e):wa?ri():[],r=$&&wa?.getResumableHandle();r&&(W={...W,durableResume:{executionId:r.executionId,after:r.lastEventId}});let n={messages:t,metadata:W,artifacts:ao.artifacts,selectedArtifactId:ao.selectedId,...ci?{draft:ci}:{}};li(()=>H.save(n),"[AgentWidget] Failed to persist state:")}let ci,pi=()=>!(!H?.save||!1===s.persistState||"object"==typeof s.persistState&&!1===s.persistState.persist?.draft),ui=function(e){let t=e.delay??500,r=null,n=!1,o=()=>{null!==r&&(clearTimeout(r),r=null)};return{schedule:()=>{n||(o(),r=setTimeout(()=>{r=null,e.write()},t))},flush:()=>{n||null===r||(o(),e.write())},cancel:o,destroy:()=>{n=!0,o()}}}({write:()=>{if(!pi())return;let e=Ar.getState(),t=function(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}}:{}}}({text:e.text,mentionRefs:e.mentionRefs,contentSegments:Oc(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(ci)&&(ci=t,di())}});function hi(){pi()&&ui.schedule()}function mi(){ui.flush()}function gi(e){if(!pi())return;let t=function(e,t){if(!e||"string"!=typeof e.text)return;let r=new Set(t.mentionSourceIds),n=(e.mentionRefs??[]).filter(e=>r.has(e.sourceId)),o=n.length===(e.mentionRefs?.length??0)&&n.length>0,a=new Set(t.modes.map(e=>e.id)),s=(e.activeModeIds??[]).filter(e=>a.has(e)),i=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...o?{mentionRefs:n}:{},...o&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...i?{selectedModelId:i}:{},...s.length?{activeModeIds:s}:{},...e.quote?.text?{quote:e.quote}:{}}}(e,{mentionSourceIds:(s.contextMentions?.sources??[]).map(e=>e.id),modelIds:(s.composer?.models??[]).map(e=>e.id),modes:s.composer?.modes??[]});t&&(ci=e,ut&&!ut.value&&(ut.value=t.text,ut.dispatchEvent(new Event("input",{bubbles:!0})),Mr()),t.selectedModelId&&(Ar.setSelectedModelId(t.selectedModelId),$r?.repaint()),Rr(t.activeModeIds??[]),t.quote&&jr(t.quote),ui.cancel())}function bi(){ui.cancel(),ci&&(ci=void 0,pi()&&di())}let wi=null,xi=()=>rt.querySelector("#persona-scroll-container")||it,Ci=()=>{null!==wi&&(cancelAnimationFrame(wi),wi=null),is=!1},ki=()=>{null!==ss&&(cancelAnimationFrame(ss),ss=null),ls=!1,Ci()},Ai=()=>{let e=Vt()||"Jump to latest",t=za&&Ti()&&("anchor-top"!==Gt()||Xt());tr.toggleAttribute("data-persona-scroll-to-bottom-streaming",t),cs>0?(or.textContent=String(cs),or.style.display="",tr.setAttribute("aria-label",`${e} (${cs} new)`)):(or.textContent="",or.style.display="none",tr.setAttribute("aria-label",t?`${e} (response streaming below)`:e))},Ii=()=>{0!==cs&&(cs=0,Ai())},Ti=()=>Kt()?!os.isFollowing():!(()=>{let e=ps?.spacerHeight??0;return e<=0?ts(it,24):Zi(e)-it.scrollTop-it.clientHeight<=24})(),Ei=()=>!!wa&&wa.getMessages().length>0,Li=()=>{if(!1===Se.enabled||He||qe&&"panel"===je)return tr.parentNode&&tr.remove(),void(tr.style.display="none");tr.parentNode!==st&&st.appendChild(tr),gr();let e=es(it)>0&&Ti()&&Ei();e?Ai():Ii(),tr.style.display=e?"":"none"},Ri=()=>{os.pause()&&(ki(),Li())},Hi=()=>{os.resume(),Ii(),Li()},$i=(e=!1)=>{Kt()&&Ei()&&os.isFollowing()&&(e||za)&&(null!==ss&&(cancelAnimationFrame(ss),ss=null),ls=!0,ss=requestAnimationFrame(()=>{ss=null,ls=!1,os.isFollowing()&&qi(xi(),e?220:140)}))},zi=(e,t,r,n=()=>!0)=>{let o=e.scrollTop,a=t(),s=a-o;if(Ci(),Math.abs(s)<1)return is=!0,e.scrollTop=a,as=e.scrollTop,void(is=!1);let i=performance.now();is=!0;let l=d=>{if(!n())return void Ci();let c=t();c!==a&&(a=c,s=a-o);let p=d-i,u=Math.min(p/r,1),h=(e=>1-(1-e)**3)(u);e.scrollTop=o+s*h,as=e.scrollTop,u<1?wi=requestAnimationFrame(l):(e.scrollTop=a,as=e.scrollTop,wi=null,is=!1)};wi=requestAnimationFrame(l)},qi=(e,t=500)=>{let r=es(e)-e.scrollTop;Math.abs(r)<1?as=e.scrollTop:Math.abs(r)>=80?(Ci(),is=!0,e.scrollTop=es(e),as=e.scrollTop,is=!1):zi(e,()=>es(e),t,()=>os.isFollowing())},Ui=()=>{if(!Ei())return void Li();let e=xi();is=!0,e.scrollTop=es(e),as=e.scrollTop,is=!1,Li()},Gi=e=>{let t=0,r=e;for(;r&&r!==it;)t+=r.offsetTop,r=r.offsetParent;return t},Qi=()=>function(e,t){return!(!e||e.isCollapsed)&&(t.contains(e.anchorNode)||t.contains(e.focusNode))}((()=>{let e=it.getRootNode();return("function"==typeof e.getSelection?e.getSelection():null)??it.ownerDocument.getSelection()})(),it),Xi=()=>{if("last-user-turn"!==(Ae.restorePosition??"bottom"))return!1;let e=wa?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>"user"===e.role);if(!t)return!1;let r=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(t.id):t.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=it.querySelector(`[data-message-id="${r}"]`);if(!n)return!1;let o=Math.min(Math.max(0,Gi(n)-Jt()),es(it));return is=!0,it.scrollTop=o,as=it.scrollTop,is=!1,"follow"===Gt()&&!ts(it,24)&&os.pause(),Li(),!0},Yi=e=>{let t=Math.max(0,Math.round(e));ar.style.height=`${t}px`,ar.style.display=t>0?"":"none",ps&&(ps.spacerHeight=Math.max(0,e))},Zi=e=>{let t=parseFloat(getComputedStyle(it).paddingBottom)||0,r=0;for(let e of Array.from(it.children)){if(e===ar||0===e.offsetHeight)continue;let t=Gi(e)+e.offsetHeight;t>r&&(r=t)}let n=it.scrollHeight-e;return r>0?Math.min(r+t,n):n},el=()=>{null!==fs&&(cancelAnimationFrame(fs),fs=null),Ci(),ps=null,ar.style.height="0px",ar.style.display="none"},tl=e=>typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),ol=e=>it.querySelector(`[data-message-id="${tl(e)}"]`),il=e=>{null!==fs&&cancelAnimationFrame(fs),fs=requestAnimationFrame(()=>{fs=null;let t=tl(e),r=it.querySelector(`[data-message-id="${t}"]`);if(!r)return;let n=Gi(r),o=Zi(ps?.spacerHeight??0),{targetScrollTop:a,spacerHeight:s}=rs({anchorOffsetTop:n,topOffset:Jt(),viewportHeight:it.clientHeight,contentHeight:o,slack:24});ps={initialSpacerHeight:s,contentHeightAtAnchor:o,spacerHeight:s},Yi(s),zi(it,()=>r.isConnected?Math.max(0,Gi(r)-Jt()):a,220)})},ll=()=>{if("anchor-top"!==Gt()||!ps||!As)return;let e=ol(As);if(!e)return;Ci();let t=ps.spacerHeight,r=Zi(t),{targetScrollTop:n,spacerHeight:o}=rs({anchorOffsetTop:Gi(e),topOffset:Jt(),viewportHeight:it.clientHeight,contentHeight:r,slack:24});ps={initialSpacerHeight:o,contentHeightAtAnchor:r,spacerHeight:o},Yi(o),is=!0,it.scrollTop=n,as=it.scrollTop,is=!1,Li()},cl=e=>{if(null===vs)return!0;let t=ol(vs),r=ol(e);if(!t||!r)return!0;let n=Gi(r)-Gi(t);return Jt()+n>it.clientHeight-96},pl=(e,t)=>{let r="user"===t?"user":"assistant",n=s.layout?.messages?.[r],o=n?.width??"content",a=n?.maxWidth??("full"===o?`var(--persona-message-${r}-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-${o}`),e.classList.toggle("persona-justify-end","user"===t),e.setAttribute("data-message-role",t),e.setAttribute("data-message-width",o),a?e.style.setProperty("--persona-message-row-max-width",a):e.style.removeProperty("--persona-message-row-max-width")},ul=(e,t)=>{let r=document.createElement("div");return r.className="persona-flex",r.id=`wrapper-${e}`,r.setAttribute("data-wrapper-id",e),pl(r,t),r},gl=!1,fl=()=>{gl||(gl=!0,Ge().catch(()=>{}),ye().catch(()=>{gl=!1}))},yl=(e,t,r)=>{t.length>0&&fl(),((e,t,r)=>{let n=new Set;for(let e of t){let t="tool"===e.variant?"tool":"reasoning"===e.variant?"reasoning":null;if(!t||"row"!==oe(s,t))continue;let r="tool"===t?s.features?.toolCallDisplay:s.features?.reasoningDisplay;!1!==r?.expandable&&(n.add(e.id),d.observe(e,t,"tool"===t?i:l,r))}let o=document.createElement("div"),a=(()=>{let e=h.find(e=>e.renderLoadingIndicator);return e?.renderLoadingIndicator?e.renderLoadingIndicator:s.loadingIndicator?.render?s.loadingIndicator.render:void 0})(),p=new Set,u=new Map,m=new Set,g=h.some(e=>e.renderAskUserQuestion),f=[],y=[],b=!1!==s.enableComponentStreaming,v=!1!==s.approval,x=[],C=s.messageActions,S=!0===C?.showRegenerate&&!1!==C.enabled&&!0!==ho.current?.isStreaming()?function(e){for(let t=e.length-1;t>=0;--t){let r=e[t];if("user"===r.role||r.streaming)return null;if("assistant"===r.role&&!r.variant)return Yr(e,r.id)?r.id:null}return null}(t):null,k=!0===C?.showEdit&&!1!==C.enabled,M=!0===C?.showQuote&&!1!==C.enabled,I=null,T=s.features?.reasoningDisplay?.completedVisibility,E=e=>"removed"===T||"removed-when-short"===T&&((e,t)=>{let r=t?.durationMs??15e3,n=t?.chars??1200;return"number"==typeof e.durationMs?e.durationMs<r:(e.chunks??[]).join("").length<n})(e,s.features?.reasoningDisplay?.shortThinkThreshold),L="removed"===s.features?.toolCallDisplay?.completedVisibility,B=e=>"reasoning"===e.variant&&"complete"===e.reasoning?.status?E(e.reasoning):L&&"tool"===e.variant&&"complete"===e.toolCall?.status;if(t.forEach(t=>{if(B(t))return;if(p.add(t.id),u.set(t.id,t.role),Va===t.id&&Ga){let e=ul(t.id,t.role);return e.setAttribute("data-persona-message-edit-stub","true"),e.setAttribute("data-preserve-runtime","true"),o.appendChild(e),void(I={messageId:t.id,element:Ga.element})}let n=g&&Ct(t),d=v&&"approval"===t.variant&&!!t.approval,C=!n&&"assistant"===t.role&&!t.variant&&b&&Xd(t);!d&&Ua.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),Ua.delete(t.id)),!C&&_a.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),_a.delete(t.id));let T=Ct(t)?`:${t.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:"",E={canRegenerate:S===t.id,canEdit:k&&Zr(t),canQuote:M&&!t.variant&&(t.content?.trim().length??0)>0},L=`${E.canRegenerate?"r":""}${E.canEdit?"e":""}${E.canQuote?"q":""}`,N=function(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)??"","string"==typeof e.toolCall?.args?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")}(t,Qa)+T+`:${L}`,R=n||d||C?null:function(e,t,r){let n=e.get(t);return n&&n.fingerprint===r?n.wrapper:null}(qa,t.id,N);if(R)return o.appendChild(R.cloneNode(!0)),void(Ct(t)&&t.toolCall?.id&&!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),yo(t)));let H=null,$=h.find(e=>!!("reasoning"===t.variant&&e.renderReasoning||"tool"===t.variant&&e.renderToolCall||!t.variant&&e.renderMessage)),W=s.layout?.messages;if(Ct(t)&&!0===t.agentMetadata?.askUserQuestionAnswered)return ja.delete(t.id),void e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime");if(Ot(t)&&_t(s).enabled)return;if(Ct(t)&&!1!==s.features?.askUserQuestion?.enabled){let e=h.find(e=>"function"==typeof e.renderAskUserQuestion);if(e&&ho.current){let r=ja.get(t.id),n=r!==N,a=null;if(n){let{payload:r,complete:n}=kt(t),o=t.id,i=()=>ho.current?.getMessages().find(e=>e.id===o);a=e.renderAskUserQuestion({message:t,payload:r,complete:n,resolve:e=>{let t=i();t&&ho.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=i();e?.agentMetadata?.awaitingLocalTool&&(ho.current?.markAskUserQuestionResolved(e),ho.current?.resolveAskUserQuestion(e,"(dismissed)"))},config:s})}if(n&&null===a&&null==r)return void(!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),yo(t)));let i=ul(t.id,t.role);return i.setAttribute("data-ask-plugin-stub","true"),i.setAttribute("data-preserve-runtime","true"),o.appendChild(i),void f.push({messageId:t.id,fingerprint:N,bubble:a})}return void(!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),yo(t)))}if(d){let r=A();if(!r)return void o.appendChild(ul(t.id,t.role));let n=h.find(e=>"function"==typeof e.renderApproval)??w,a=Ua.get(t.id)!==N,i=null;if(a&&n?.renderApproval){let e=t.id,o=(t,r)=>{let n=ho.current?.getMessages().find(t=>t.id===e);n?.approval&&("webmcp"===n.approval.toolType?ho.current?.resolveWebMcpApproval(n.id,t):ho.current?.resolveApproval(n.approval,t,r))};i=n.renderApproval({message:t,defaultRenderer:()=>r.createApprovalBubble(t,s,c),config:s,approve:e=>o("approved",e),deny:e=>o("denied",e)})}if(!a||null!==i){let e=ul(t.id,t.role);return e.setAttribute("data-approval-plugin-stub","true"),e.setAttribute("data-preserve-runtime","true"),o.appendChild(e),void x.push({messageId:t.id,fingerprint:N,bubble:i})}e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),Ua.delete(t.id),H=r.createApprovalBubble(t,s,c)}else if($)if("reasoning"===t.variant&&t.reasoning&&$.renderReasoning){if(!we)return;H=$.renderReasoning({message:t,defaultRenderer:()=>sl(t,s,l),config:s})}else if("tool"===t.variant&&t.toolCall&&$.renderToolCall){if(!xe)return;H=$.renderToolCall({message:t,defaultRenderer:()=>ml(t,s,i),config:s})}else $.renderMessage&&(H=$.renderMessage({message:t,defaultRenderer:()=>{let e=Pi(t,r,W,s.messageActions,0,{loadingIndicatorRenderer:a,widgetConfig:s,actionEligibility:E});return"user"!==t.role&&P(e,t,s,wa),e},config:s}));if(!H&&C){let n=Yd(t);if(n){let a=_a.get(t.id),i=a!==N,l=!1!==s.wrapComponentDirectiveInBubble&&!1!==Ml.getOptions(n.component)?.bubbleChrome,d=null;if(i){let o=Jd(n,{config:s,message:t,transform:r});if(o&&"PersonaArtifactInline"===n.component){let r=o.hasAttribute("data-artifact-inline")?o:o.querySelector("[data-artifact-inline]"),n=r?.getAttribute("data-artifact-inline")??"",a=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(n):n,s=n?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${a}"]`)??null:null;r&&s&&s!==r&&Wl()?.hasLiveInlineArtifactBlock(s)&&(r===o?o=s:r.replaceWith(s))}if(o)if(l){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 n=document.createElement("div");n.className="persona-mb-3 persona-text-sm persona-leading-relaxed",n.innerHTML=r({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(n)}e.appendChild(o),d=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 n=document.createElement("div");n.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",n.innerHTML=r({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(n)}e.appendChild(o),d=e}}if(d||null!=a){let e=ul(t.id,t.role);return e.setAttribute("data-component-directive-stub","true"),e.setAttribute("data-preserve-runtime","true"),o.appendChild(e),void y.push({messageId:t.id,fingerprint:N,bubble:d})}}}if(!H)if("reasoning"===t.variant&&t.reasoning){if(!we)return;H=sl(t,s,l)}else if("tool"===t.variant&&t.toolCall){if(!xe)return;H=ml(t,s,i)}else if("approval"===t.variant&&t.approval){if(!1===s.approval)return;let e=A();if(!e)return;H=e.createApprovalBubble(t,s,c)}else{let e=s.layout?.messages;H=e?.renderUserMessage&&"user"===t.role?e.renderUserMessage({message:t,config:s,streaming:!!t.streaming}):e?.renderAssistantMessage&&"assistant"===t.role?e.renderAssistantMessage({message:t,config:s,streaming:!!t.streaming}):Pi(t,r,e,s.messageActions,0,{loadingIndicatorRenderer:a,widgetConfig:s,actionEligibility:E}),"user"!==t.role&&H&&P(H,t,s,wa)}let D=ul(t.id,t.role);D.appendChild(H),function(e,t,r,n){e.set(t,{fingerprint:r,wrapper:n})}(qa,t.id,N,D),o.appendChild(D)}),at.composerOverlay&&at.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(e=>{let t=e.getAttribute("data-persona-ask-sheet-for");t&&!m.has(t)&&$t(at.composerOverlay,t)}),s.features?.toolCallDisplay?.grouped){let e=[],r=[],a="summary"===s.features.toolCallDisplay.groupedMode;t.forEach(t=>{if("tool"===t.variant&&t.toolCall&&xe){if(L&&"complete"===t.toolCall.status)return;r.push(t)}else("reasoning"!==t.variant||we&&("complete"!==t.reasoning?.status||!E(t.reasoning)))&&((r.length>1||a&&r.length>0)&&e.push(r),r=[])}),(r.length>1||a&&r.length>0)&&e.push(r),e.forEach(e=>{let t=e.map(e=>Array.from(o.children).find(t=>t instanceof HTMLElement&&t.getAttribute("data-wrapper-id")===e.id)).filter(e=>!!e);if(t.length<(a?1:2))return;let r=ul(`tool-group-${e[0].id}`,"assistant");if(r.setAttribute("data-persona-tool-group-row","true"),"collapsible"===s.features?.toolCallDisplay?.groupedMode){let o=`tool-group-${e[0].id}`,a=e.some(e=>"complete"!==e.toolCall?.status),l={...e[0],id:o,toolCall:{id:o,name:`${e.length} tools`,status:a?"running":"complete",chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>!1===e.toolCall?.success)}};n.add(o),d.observe(l,"tool",i,s.features.toolCallDisplay);let c=`${a?"Using":"Used"} ${e.length} tools`,p=s.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:c,config:s}),u=ie(l,s,i.has(o),p??c);return u.bubble.classList.add("persona-tool-group"),u.body.dataset.personaToolGroupStack="true",t[0].before(r),r.appendChild(u.bubble),void t.forEach((e,t)=>{e.style.setProperty("--persona-message-row-max-width","100%"),e.style.setProperty("--persona-activity-stagger",40*t+"ms"),e.classList.add("persona-activity-group-child"),u.body.appendChild(e)})}let l=document.createElement("div");l.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",l.setAttribute("data-persona-tool-group","true");let c=document.createElement("div");c.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",c.id=`tool-group-summary-${e[0].id}`;let p=`Called ${e.length} ${1===e.length?"tool":"tools"}`,u=s.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:p,config:s});((e,t)=>null!=t&&("string"==typeof t?(e.textContent=t,!0):(e.appendChild(t),!0)))(c,u)||(c.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"),l.appendChild(c),a||l.appendChild(h),r.appendChild(l),t[0].before(r),t.forEach((e,r)=>{if(a)return void e.remove();e.style.setProperty("--persona-message-row-max-width","100%");let n=document.createElement("div");n.className="persona-tool-group-item persona-relative",n.setAttribute("data-persona-tool-group-item","true"),r<t.length-1&&n.setAttribute("data-persona-tool-group-connector","true"),n.appendChild(e),h.appendChild(n)})})}d.prune(n),function(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}(qa,p);let N=e=>"tool"===e.variant&&!xe||"reasoning"===e.variant&&!we||B(e),R=t.some(e=>"assistant"===e.role&&e.streaming&&!N(e)),H=t.length-1;for(;H>=0&&N(t[H]);)H--;let $=H>=0?t[H]:void 0,W=H<t.length-1,D="assistant"===$?.role&&!$.streaming&&"approval"!==$.variant&&!W;if(za&&t.some(e=>"user"===e.role)&&!R&&!D){let e={config:s,streaming:!0,location:"standalone",defaultRenderer:Si},t=h.find(e=>e.renderLoadingIndicator),r=null;if(t?.renderLoadingIndicator&&(r=t.renderLoadingIndicator(e)),null===r&&s.loadingIndicator?.render&&(r=s.loadingIndicator.render(e)),null===r&&(r=Si()),r){let e=document.createElement("div"),t=!1!==s.loadingIndicator?.showBubble,n=s.layout?.messages?.layout??"bubble";e.className=t?Mi("assistant",n).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))","flat"!==n&&(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(r);let a=ul("typing-indicator","assistant");a.appendChild(e),o.appendChild(a)}}if(!za&&t.length>0){let e=t[t.length-1],r={config:s,lastMessage:e,messageCount:t.length},n=h.find(e=>e.renderIdleIndicator),a=null;if(n?.renderIdleIndicator&&(a=n.renderIdleIndicator(r)),null===a&&s.loadingIndicator?.renderIdle&&(a=s.loadingIndicator.renderIdle(r)),a){let e=document.createElement("div");e.className=!1===s.loadingIndicator?.showBubble?["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=ul("idle-indicator","assistant");t.appendChild(e),o.appendChild(t)}}if(function(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)})}(o),Xa(e,o),ze(e),I){let{messageId:t,element:r}=I,n=e.querySelector(`#wrapper-${t}`);n&&r.parentElement!==n&&(pl(n,u.get(t)??"user"),n.replaceChildren(r))}if(f.length>0)for(let{messageId:t,fingerprint:r,bubble:n}of f){let o=e.querySelector(`#wrapper-${t}`);o&&(pl(o,u.get(t)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),ja.set(t,r)))}if(ja.size>0)for(let e of ja.keys())p.has(e)||ja.delete(e);if(y.length>0)for(let{messageId:t,fingerprint:r,bubble:n}of y){let o=e.querySelector(`#wrapper-${t}`);o&&(pl(o,u.get(t)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),_a.set(t,r)))}if(_a.size>0)for(let e of _a.keys())p.has(e)||_a.delete(e);if(x.length>0)for(let{messageId:t,fingerprint:r,bubble:n}of x){let o=e.querySelector(`#wrapper-${t}`);o&&(pl(o,u.get(t)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),Ua.set(t,r)))}if(Ua.size>0)for(let e of Ua.keys())p.has(e)||Ua.delete(e)})(e,t,r),Fn()},bl=null,vl=()=>{if(bl)return;let t=e=>{let t=e.composedPath();t.includes(rt)||ot&&t.includes(ot)||Nl(!1,"user")};bl=t,(e.ownerDocument??document).addEventListener("pointerdown",t,!0)},Cl=()=>{bl&&=((e.ownerDocument??document).removeEventListener("pointerdown",bl,!0),null)};ia.push(()=>Cl());let Sl=null,kl=()=>{if(Sl)return;let t=e=>{"Escape"===e.key&&(e.isComposing||Nl(!1,"user"))};Sl=t,(e.ownerDocument??document).addEventListener("keydown",t,!0)},Il=()=>{Sl&&=((e.ownerDocument??document).removeEventListener("keydown",Sl,!0),null)};ia.push(()=>Il());let Tl=!1,El=new Set,Ll=()=>s.launcher?.composerBar?.peek?.streamAnimation||s.features?.streamAnimation,Pl=()=>{if(!se())return;let t=at.peekBanner,r=at.peekTextNode;if(!t||!r)return;if(ue)return void t.classList.remove("persona-pill-peek--visible");let n,o=wa?.getMessages()??[];for(let e=o.length-1;e>=0;e--){let t=o[e];if("assistant"===t.role&&t.content){n=t;break}}if(!n)return void t.classList.remove("persona-pill-peek--visible");let a=n.content,s=!!n.streaming,i=Ll(),l=ds(i),d="none"===l.type?null:ha(l.type,i?.plugins),c=!0===d?.isAnimating?.(n),p=null!==d&&(s||c);p&&d&&!El.has(d.name)&&(Ts(d,e),El.add(d.name));let u=p&&d?.containerClass?d.containerClass:null,h=r.dataset.personaPeekStreamClass??null;h&&h!==u&&(r.classList.remove(h),delete r.dataset.personaPeekStreamClass),u&&h!==u&&(r.classList.add(u),r.dataset.personaPeekStreamClass=u),p?(r.style.setProperty("--persona-stream-step",`${l.speed}ms`),r.style.setProperty("--persona-stream-duration",`${l.duration}ms`)):(r.style.removeProperty("--persona-stream-step"),r.style.removeProperty("--persona-stream-duration"));let m=p?gs(a,l.buffer,d,n,s):a;if(!p||"skeleton"!==l.placeholder||!s||m&&m.trim()){let e=Math.max(0,m.length-100),o=m.length>100?m.slice(-100):m,a=ke(o);if(p&&d){let s=a;("char"===d.wrap||"word"===d.wrap)&&(s=Cs(a,d.wrap,`peek-${n.id}`,{skipTags:d.skipTags,startIndex:e}));let i=document.createElement("div");if(i.innerHTML=s,d.useCaret&&o.length>0){let e=Ss(),t=i.querySelectorAll(".persona-stream-char, .persona-stream-word"),r=t[t.length-1];r?.parentNode?r.parentNode.insertBefore(e,r.nextSibling):i.appendChild(e)}Xa(r,i),d.onAfterRender?.({container:r,bubble:t,messageId:n.id,message:n,speed:l.speed,duration:l.duration})}else{let e=m.length>100?`…${o}`:o;r.textContent!==e&&(r.textContent=e)}}else{let e=document.createElement("div"),t=ks();t.classList.add("persona-pill-peek__skeleton"),e.appendChild(t),Xa(r,e)}let g=za||Tl;t.classList.toggle("persona-pill-peek--visible",g)};if(se()){let e=at.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),Nl(!0,"user")};e.addEventListener("pointerdown",t),ia.push(()=>{e.removeEventListener("pointerdown",t)})}let t=()=>{Tl||(Tl=!0,Pl())},r=()=>{Tl&&(Tl=!1,Pl())};nt.addEventListener("pointerenter",t),nt.addEventListener("pointerleave",r),ia.push(()=>{nt.removeEventListener("pointerenter",t),nt.removeEventListener("pointerleave",r)}),ot&&(ot.addEventListener("pointerenter",t),ot.addEventListener("pointerleave",r),ia.push(()=>{ot.removeEventListener("pointerenter",t),ot.removeEventListener("pointerleave",r)}))}let Bl=()=>{if(ue&&fl(),!pe())return;if(se()){let e=(s.launcher?.composerBar??{}).expandedSize??"anchored",t=ue?"expanded":"collapsed";return rt.dataset.state=t,rt.dataset.expandedSize=e,ot&&(ot.dataset.state=t,ot.dataset.expandedSize=e),rt.style.removeProperty("display"),rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),nt.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),(e=>{let t=s.launcher?.composerBar??{},r=t.expandedSize??"anchored",n=t.bottomOffset??"16px",o=t.collapsedMaxWidth,a=t.expandedMaxWidth??"880px",i=t.expandedTopOffset??"5vh",l=t.modalMaxWidth??"880px",d=t.modalMaxHeight??"min(90vh, 800px)",c="calc(100vw - 32px)",p=rt.style;if(p.left="",p.right="",p.top="",p.bottom="",p.transform="",p.width="",p.maxWidth="",p.height="",p.maxHeight="",ot){let e=ot.style;e.bottom=n,e.width=o??""}e&&"fullscreen"!==r&&("modal"===r?(p.top="50%",p.left="50%",p.transform="translate(-50%, -50%)",p.bottom="auto",p.right="auto",p.width=l,p.maxWidth=c,p.maxHeight=d,p.height=d):(p.left="50%",p.transform="translateX(-50%)",p.bottom=`calc(${n} + var(--persona-pill-area-height, 80px))`,p.top=i,p.width=a,p.maxWidth=c))})(ue),st.style.display=ue?"flex":"none",eo(),ue?(vl(),kl()):(Cl(),Il()),void Pl()}let t=qs(s),r=e.ownerDocument.defaultView??window,n=s.launcher?.mobileBreakpoint??640,o=s.launcher?.mobileFullscreen??!0,a=r.innerWidth<=n,i=o&&a&&X,l=_s(s).reveal;ue?(rt.style.removeProperty("display"),rt.style.display=t?"flex":"",rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),nt.classList.remove("persona-scale-95","persona-opacity-0"),nt.classList.add("persona-scale-100","persona-opacity-100"),Op?(Op.setPanelOpen(!0),Op.element.style.display="none"):zp&&(zp.style.display="none")):(t?!t||"overlay"!==l&&"push"!==l||i?(rt.style.setProperty("display","none","important"),rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),nt.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(rt.style.removeProperty("display"),rt.style.display="flex",rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),nt.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(rt.style.display="",rt.classList.add("persona-pointer-events-none","persona-opacity-0"),nt.classList.remove("persona-scale-100","persona-opacity-100"),nt.classList.add("persona-scale-95","persona-opacity-0")),Op?(Op.setPanelOpen(!1),Op.element.style.display=t?"none":""):zp&&(zp.style.display=t?"none":""))},Nl=(t,r="user")=>{if(!pe()||ue===t)return;let n=ue;ue=t,Bl();let o=(()=>{let t=s.launcher?.sidebarMode??!1,r=e.ownerDocument.defaultView??window,n=s.launcher?.mobileFullscreen??!0,o=s.launcher?.mobileBreakpoint??640,a=r.innerWidth<=o,i=qs(s)&&n&&a,l=se()&&"fullscreen"===(s.launcher?.composerBar?.expandedSize??"fullscreen");return t||n&&a&&X||i||l})();if(ue&&o){if(!la){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&(la=Ns(r,s.launcher?.zIndex??1e5))}da||=$s(e.ownerDocument)}else ue||(la?.(),la=null,da?.(),da=null);ue&&(Up(),Xi()||("follow"===Gt()?$i(!0):Ui()));let a={open:ue,source:r,timestamp:Date.now()};ue&&!n?R.emit("widget:opened",a):!ue&&n&&R.emit("widget:closed",a),R.emit("widget:state",{open:ue,launcherEnabled:X,voiceActive:Os.active,streaming:wa.isStreaming()})},Rl={inputDisabled:!1,sendDisabled:!1},Hl=()=>Rl.inputDisabled,Ol=()=>ce(s.voiceRecognition?.provider)&&!!wa&&(wa.isBargeInActive()||["listening","processing","speaking"].includes(wa.getVoiceStatus())),zl=()=>Rl.inputDisabled||Rl.sendDisabled;function ql(){if(!ht)return;if("streaming"===Ar.getState().phase)return void(ht.disabled=!1);let e=!!xr&&!xr.isReady();ht.disabled=zl()||e}function Vl(){if(!Nt)return;let e=Ar.getState(),t="when-text"===s.sendButton?.visibility&&"streaming"!==e.phase&&0===e.text.trim().length&&0===e.attachments.length;Nt.toggleAttribute("data-persona-send-hidden",t)}function Gl(){let e=Xn(s.composer?.inputDisabled),t=Xn(s.composer?.sendDisabled);Rl={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},Ar.setInputDisabled(e.disabled),Ar.setSendDisabled(t.disabled);let r="streaming"===Ar.getState().phase,n=e.disabled,o=r||n;ut&&(ut instanceof HTMLTextAreaElement?ut.disabled=n:ut.setAttribute("contenteditable",n?"false":"true"),ut.setAttribute("aria-disabled",n?"true":"false")),Ft&&(Ft.disabled=n),jt&&(jt.disabled=n);for(let e of Cr?.affordanceButtons??[])e.querySelectorAll("button").forEach(e=>{e.disabled=n});Wt&&(Wt.disabled=n||r&&!Ol()),va.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute("data-disabled",o),e instanceof HTMLButtonElement||e.setAttribute("aria-disabled",o?"true":"false")}),e.buttons.forEach(e=>{e.disabled=o})}),pd.forEach(e=>{e.toggleAttribute("data-disabled",o),e instanceof HTMLButtonElement?e.disabled=o:e.setAttribute("aria-disabled",o?"true":"false"),e.querySelectorAll("button").forEach(e=>{e.disabled=o})}),Et.dataset.personaComposerStreaming=r?"true":"false",Et.dataset.personaComposerInputDisabled=n?"true":"false",Et.dataset.personaComposerSendDisabled=zl()?"true":"false",Et.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=r)}),ql(),function(){let e=(Rl.inputDisabled?Rl.inputReason:void 0)??(Rl.sendDisabled?Rl.sendReason:void 0);if(se()){let t=mt??Et;e?t.setAttribute("title",e):t.removeAttribute("title"),Et.toggleAttribute(nc,!!e)}else if(e)gt.setAttribute("role","status"),gt.setAttribute("aria-live","polite"),gt.setAttribute(nc,""),gt.removeAttribute(oc),gt.textContent=e,le(gt,s.statusIndicator??{},"idle");else if(gt.hasAttribute(nc)&&(gt.removeAttribute("role"),gt.removeAttribute("aria-live"),gt.removeAttribute(nc),y)){let e=wa.getStatus();et(gt,Ze(e),s.statusIndicator??{},e)}}()}let Kl=e=>{Ar.setStreaming(e),Rt(e?"stop":"send"),Gl()},Jl=()=>{Os.active||ut&&ut.focus()};R.on("widget:opened",()=>{s.autoFocusInput&&setTimeout(()=>Jl(),200)});let Ql=null,Xl=!1,Yl=!ft.hidden,Zl=null,ed=!D,td=null;ia.push(()=>{td?.cancel(),td=null});let rd,nd,od=t=>{let r=(e=>(e??[]).some(e=>"user"===e.role)?"active":"empty")(t);if(r===ur)return;ur=r,e.setAttribute("data-persona-conversation-state",r);let n=mr();vr(),ed&&(td?.cancel(),td=((e,t,r,n=260)=>{if(t<=1||Oi()||"function"!=typeof e.animate||!e.isConnected)return null;let o="drop"===r?-t:t;return e.animate([{transform:`translateY(${o}px)`},{transform:"none"}],{duration:n,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})})(Et,"active"===r?n:mr(),"active"===r?"drop":"rise","centered"===pr().layout?320:260)),ll()},ad=null,sd=null,id=null,ld=!1,dd=e=>{let t=pr(),r=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??"bottom"}|${t.align??""}|${t.iconPlacement}|${t.kicker??""}|${t.title}|${t.subtitle}`;(r!==ad||t.icon!==rd)&&(ad=r,rd=t.icon,Ni({host:ft,iconHolder:yt,kicker:vt,title:wt,subtitle:xt,starterSuggestions:dt},t));let n=void 0===t.message?null:`${s.layout?.messages?.layout??"bubble"}|${t.message}`;n!==sd&&(sd=n,Fi(bt,t.message,s));let o=e??(wa?wa.getMessages():s.initialMessages);od(o);let a=Xl,i=!a&&_i(t,o),l=i!==Yl;if(Yl=i,id)return Zl?.cancel(),Zl=null,a!==ld&&(ld=a,a?Di(it,ft,null):Wi(it,ft,id)),void Bi(it,ft,!a);if(l&&!i&&!a&&"on-first-message"===t.dismiss&&ed)return void(Zl=((e,t)=>{if(Oi()||"function"!=typeof e.animate||!e.isConnected)return t(null),null;let r=e.getBoundingClientRect(),n=e.parentElement,o=0,a=0,s=0;if(n){let t=getComputedStyle(n);o=parseFloat(t.rowGap)||0;let i=e.previousElementSibling,l=e.nextElementSibling,d=n.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-n.scrollTop;a=Math.max(0,i?r.top-i.getBoundingClientRect().bottom-o:r.top-d),s=Math.max(0,l?l.getBoundingClientRect().top-r.bottom-o:0)}let i=e.style.overflow;e.style.overflow="hidden";let l=getComputedStyle(e),d=parseFloat(l.paddingTop)||0,c=parseFloat(l.paddingBottom)||0,p=e.animate([{opacity:"1",transform:"none",height:`${r.height}px`,minHeight:"0px",paddingTop:`${d}px`,paddingBottom:`${c}px`,marginTop:`${a}px`,marginBottom:`${s}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:-o+"px"}],{duration:180,easing:"ease-out",fill:"forwards"}),u=!1,h=()=>{u||(u=!0,e.style.overflow=i,t(p))};return p.finished.then(h).catch(h),p})(ft,e=>{Zl===e&&(Zl=null),!Yl&&!id&&(Bi(it,ft,!1),ll()),e?.cancel()}));if(Zl){if(!i&&!a)return;Zl.cancel(),Zl=null}let d=!ft.hidden;Bi(it,ft,i),!i&&d&&ll()},cd=[],pd=[],md=!1,gd=null,fd=()=>{pd.length=0;let e=cd.splice(0,cd.length);for(let t of e)try{t()}catch(e){console.warn("[persona] renderWelcome cleanup threw",e)}};ia.push(fd);let yd=(e,t)=>{let r=Vs(e,t);if(!r)return!0===s.debug&&console.warn("[persona] renderStarter received a suggestion with no label"),L("span");let n=s.suggestions?.starters,o=Ks({item:{...r,behavior:r.behavior??n?.behavior??"send"},index:t,surface:"starter",source:"config",variant:n?.variant??"card",streaming:!!y&&wa.isStreaming(),config:s,plugins:h,chipsConfig:s.suggestionChipsConfig,session:wa,getTextarea:()=>ut,eventTarget:ft,submitPrompt:Jc});return pd.push(o),o},bd=()=>{if(md)return;md=!0;let e=pr();gd=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`,nd=e.icon;try{fd(),Di(it,ft,id),id=null,ld=!1;let t=wa?wa.getMessages():s.initialMessages,r=_i(e,t),n=0,o=null;for(let t of h)if(t.renderWelcome&&(o=t.renderWelcome({config:e,variant:e.variant,visible:r,defaultRenderer:()=>ft,sendMessage:e=>{if(!wa||wa.isStreaming())return;let t=e.trim();t&&wa.sendMessage(t)},requestRender:()=>bd(),renderStarter:e=>yd(e,n++),storage:b(t.id),onCleanup:e=>{cd.push(e)}}),o))break;o&&o!==ft&&(id=o,Wi(it,ft,o))}finally{md=!1}dd()},Cd=()=>{dd(),an||(ut.placeholder=function(e,t){if(t?.length&&0!==e.length)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}(Ar.getState().activeModeIds,s.composer?.modes)??s.copy?.inputPlaceholder??"How can I help...",!s.sendButton?.useIcon&&!wa?.isStreaming()&&(ht.textContent=s.copy?.sendButtonLabel??"Send")),ut.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ut.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},Sd=!!s.setStoredConversationId,kd=e=>V(t=>{let r={...t};return delete r[e],r}),Id=e=>{let t=W[e];return"string"==typeof t?t:null},Ed=()=>{let e=W.durableResume;if(!e||"object"!=typeof e)return null;let t=e;return"string"==typeof t.executionId&&t.executionId.length>0&&"string"==typeof t.after&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};s.clientToken&&(s={...s,getStoredSessionId:()=>Id("sessionId"),setStoredSessionId:e=>{V(t=>({...t,sessionId:e}))},clearStoredSessionId:s.clearStoredSessionId??(()=>kd("sessionId")),getStoredConversationId:s.getStoredConversationId??(()=>Id("conversationId")),setStoredConversationId:s.setStoredConversationId??(e=>{V(t=>({...t,conversationId:e}))}),clearStoredConversationId:s.clearStoredConversationId??(()=>kd("conversationId"))});let Pd=()=>s.clientToken??null,Bd=e=>Hd(e,Me(),!1===s.persistState),Rd=Pd(),$d=Rd?Bd(Rd):null,Wd={...$d?{visitorStore:$d}:{},historyBootstrapReady:!0!==s.features?.history?.enabled||Vd()?F:Promise.all([F,z]).then(()=>{}),getStoredMessageCursor:()=>Id("historyMessageCursor"),setStoredMessageCursor:e=>{null===e?kd("historyMessageCursor"):V(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:()=>{let e=W.pendingDisplayProjections;if(!e||"object"!=typeof e)return null;let t=e;return"string"==typeof t.conversationId&&Array.isArray(t.messageIds)?{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>"string"==typeof e)}:null},setPendingDisplayProjections:e=>{e?V(t=>({...t,pendingDisplayProjections:e})):kd("pendingDisplayProjections")},getStoredResumableHandle:Ed,setStoredResumableHandle:e=>{e?V(t=>({...t,durableResume:e})):kd("durableResume")},shouldResumeDurableConversation:()=>$&&null!==Ed(),...Sd?{}:{getStoredConversationRevision:()=>Id("conversationRevision"),setStoredConversationRevision:e=>{null===e?kd("conversationRevision"):V(t=>({...t,conversationRevision:e}))}}};if($){let t=s.onExecutionState,r=e.ownerDocument.defaultView,n=!1,o=()=>n=!0,a=()=>n=!1;r?.addEventListener("pagehide",o),r?.addEventListener("pageshow",a),ia.push(()=>{r?.removeEventListener("pagehide",o),r?.removeEventListener("pageshow",a)}),s={...s,reconnectStream:s.reconnectStream??(e=>wa.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!n)&&Wd.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let Dd=()=>{let e=Pd();if(e&&$d?.matches(e,Me(),!1===s.persistState)||!e&&!$d)return;$d?.destroy(),$d=e?Bd(e):null;let t={...Wd};$d?t.visitorStore=$d:delete t.visitorStore,Wd=t,wa.setHistoryInternals(Wd)},Od=null,zd=(e,t)=>{if(Object.is(e,t))return!0;if(null===e||null===t||"object"!=typeof e||"object"!=typeof t)return!1;if(Array.isArray(e)||Array.isArray(t))return!(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)&&e.every((e,r)=>zd(e,t[r]));let r=e,n=t,o=Object.keys(r),a=Object.keys(n);return o.length===a.length&&o.every(e=>Object.prototype.hasOwnProperty.call(n,e)&&zd(r[e],n[e]))},qd=e=>{let{content:t,rawContent:r,llmContent:n,...o}=e;return o},jd=e=>!("assistant"!==e.role||!0!==e.streaming||e.variant||e.toolCall||e.tools||e.approval||e.reasoning||e.contentParts||e.stopReason||Xd(e)),_d=null,Kd=null,Qd=null,Zd=null,ac=null,uc=e=>{let t,r;_d=e,Kd=null;for(let n=e.length-1;n>=0;--n){let o=e[n];if(!t&&"user"===o.role&&(t=o),!r&&"assistant"===o.role&&(r=o),!Kd&&jd(o)&&(Kd={index:n,id:o.id}),t&&r&&Kd)break}yl(lt,e,fe),Wl()?.updateInlineArtifactBlocks(lt,ao.artifacts,{suppressTransition:za}),Od??=setInterval(()=>{let e=lt.querySelectorAll("[data-tool-elapsed]");if(0===e.length)return clearInterval(Od),void(Od=null);let t=Date.now();e.forEach(e=>{let r=Number(e.getAttribute("data-tool-elapsed"));r&&(e.textContent=e.closest(".persona-activity-row")?ae(t-r):Zt(t-r))})},100),dd(e),Ba(e),$i(!za),(e=>{let t=new Map;e.forEach(e=>{let r=Ws.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!r&&"assistant"===e.role&&(R.emit("assistant:message",e),!bs&&("anchor-top"!==Gt()||Xt())&&Ti()&&(cs+=1,Ai(),Li(),dr(1===cs?"1 new message below.":`${cs} new messages below.`))),"assistant"===e.role&&r?.streaming&&!1===e.streaming&&R.emit("assistant:complete",e),"approval"===e.variant&&e.approval&&(r?"pending"!==e.approval.status&&R.emit("approval:resolved",{approval:e.approval,decision:e.approval.status}):R.emit("approval:requested",{approval:e.approval,message:e}))}),Ws.clear(),t.forEach((e,t)=>{Ws.set(t,e)})})(e),0===e.length&&(el(),ws=!0,xs=!1,As=null,Ms=!1),!ys||bs?(ys=!0,vs=t?.id??null,Ls=r?.id??null):t&&t.id!==vs?(vs=t.id,(e=>{let t=Gt();"follow"===t?(Hi(),$i(!0)):"anchor-top"===t&&(ws=!1,xs=!0,Ms=!1,As=e,il(e))})(t.id)):r&&r.id!==Ls&&"anchor-top"===Gt()&&(xs?ws=!1:(ws=!0,el(),Hi(),$i(!0))),r&&(Ls=r.id),(e=>{if("anchor-top"!==Gt()||!xs||Ms||Qi())return;let t=null===vs;for(let r of e)if(t){if(Za(r)){if(r.id===As||!cl(r.id))return;return As=r.id,void il(r.id)}}else r.id===vs&&(t=!0)})(e);let n=Os.lastUserMessageId;t&&t.id!==n&&(Os.lastUserMessageId=t.id,R.emit("user:message",t)),Os.lastUserMessageWasVoice=!!t?.viaVoice,(e=>{if(!$)return di(e);ac=e,queueMicrotask(()=>{ac===e&&(ac=null,di(e))})})(e),Pl()},mc=()=>{null!==Zd&&(cancelAnimationFrame(Zd),Zd=null);let e=Qd;Qd=null,e&&uc(e)},gc=()=>{null!==Zd&&cancelAnimationFrame(Zd),Zd=null,Qd=null};wa=new Cn(s,{onMessagesChanged(e){(e=>{let t=Qd??_d;za&&t&&Kd&&((e,t,r)=>{if(e.length!==t.length)return!1;let n=e[r.index],o=t[r.index];return!(!n||!o||n.id!==r.id||o.id!==r.id)&&(!Object.is(n.content,o.content)||!Object.is(n.rawContent,o.rawContent)||!Object.is(n.llmContent,o.llmContent))&&jd(n)&&jd(o)&&zd(qd(n),qd(o))})(t,e,Kd)?(Qd=e,null===Zd&&(Zd=requestAnimationFrame(()=>{Zd=null;let e=Qd;Qd=null,e&&uc(e)}))):0===e.length?(gc(),uc(e)):(mc(),uc(e))})(e)},onStatusChanged(e){let t=s.statusIndicator??{};et(gt,(e=>"idle"===e?t.idleText??Sr.idle:"connecting"===e?t.connectingText??Sr.connecting:"connected"===e?t.connectedText??Sr.connected:"error"===e?t.errorText??Sr.error:"paused"===e?t.pausedText??Sr.paused:"resuming"===e?t.resumingText??Sr.resuming:Sr[e])(e),t,e),Je()},onStreamingChanged(e){e||(0===wa?.getMessages().length?gc():mc()),za=e,Kl(e),Je(),wa&&yl(lt,wa.getMessages(),fe),e||($i(!0),(()=>{if(!ps||ps.spacerHeight<=0)return;let e=Zi(ps.spacerHeight),t=Math.max(0,Math.round(it.scrollTop)+it.clientHeight-e+24);t<ps.spacerHeight&&(Yi(t),Li())})(),La=!0,wa&&Pa(wa.getMessages(),_t(s))),Li(),dr(e?"Responding…":"Response complete."),Pl()},onVoiceStatusChanged(e){if(R.emit("voice:status",{status:e,timestamp:Date.now()}),"disconnected"!==e&&!ce(s.voiceRecognition?.provider))return;let t=wa.getVoiceNotice();switch(t&&Uc(t,1e4),e){case"listening":if(!Ds){let e=wa.getVoiceDisclosure();e&&(Ds=!0,se()?(Fs=ut.placeholder,ut.placeholder=e,dr(e)):Uc(e,1e4))}Ap(),Cp();break;case"processing":Ap(),Sp();break;case"speaking":Ap(),kp();break;default:"idle"===e&&wa.isBargeInActive()?(Ap(),Cp(),Wt?.setAttribute("aria-label","End voice session")):(Os.active=!1,Ds=!1,null!==Fs&&(ut.placeholder=Fs,Fs=null),Ap(),Xs("system"),Gs||Ys())}},onArtifactsState(e){ao=e,0===e.artifacts.length&&(co=!1),Wl()?.updateInlineArtifactBlocks(lt,e.artifacts,{suppressTransition:za}),ea(),di()},onHistoryStateChanged(e){Ve(e)},onHistoryNotice(e){Ke(e)},onReconnect(e){let{executionId:t,lastEventId:r}=e.handle;"paused"===e.phase?R.emit("stream:paused",{executionId:t,after:r}):"resuming"===e.phase?R.emit("stream:resuming",{executionId:t,after:r,attempt:e.attempt??1}):R.emit("stream:resumed",{executionId:t,after:r})}},Wd),ho.current=wa,ia.push(()=>wa.cancel()),ia.push(()=>{wa.destroy(),$d?.destroy(),$d=null});let fc=null;if(wa.onReadAloudChange((e,t)=>{Hn=e,$n=t,Fn();let r=e??fc;e&&(fc=e);let n=r?wa.getMessages().find(e=>e.id===r)??null:null;R.emit("message:read-aloud",{messageId:r,message:n,state:t,timestamp:Date.now()}),"idle"===t&&(fc=null)}),y=!0,ys=!0,!0===s.voiceRecognition?.enabled&&ce(s.voiceRecognition.provider))try{wa.setupVoice()}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",e)}let yc=null,bc=null,vc=!1,wc=wa.getHistoryState(),xc=()=>!0===s.features?.history?.enabled,Cc=e=>{e&&(sr.textContent="",sr.textContent=e)},Sc=()=>{g.forEach(e=>e()),g=[];let t=yc,r=t?.railCollapseShortcut();t&&r&&g.push(m.register({id:"history-rail-collapse",combo:r.combo,scope:"page"===s.features?.history?.rail?.collapseShortcutScope?"page":"widget",when:()=>qe&&"rail"===je&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of s.layout?.header?.trailingActions??[])t.shortcut&&g.push(m.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let r=e.querySelector(`[data-persona-header-action="${t.id}"]`);r?r.click():s.layout?.header?.onAction?.(t.id)}}));for(let e of h)for(let t of e.shortcuts??[])g.push(m.register({...t,id:`${e.id}:${t.id}`}))};Sc();let kc=null,Ac=!1,Mc=()=>{if(!Mt)return;let e="conversation"===s.layout?.header?.titleSource,t=e&&kc?.trim()||null;Mt.textContent=t??s.launcher?.title??"Chat Assistant";let r=Mt.closest(".persona-combo-btn");if(!r)return;let n=!e||null!==wa.getActiveConversationId();r.setAttribute("data-persona-menu-locked",n?"false":"true"),r.setAttribute("aria-haspopup",n?"true":"false"),n||r.setAttribute("aria-expanded","false"),r.style.cursor=n?"pointer":"default";let o=r.querySelector("svg");o&&(o.style.display=n?"":"none")};Mc(),st.addEventListener("persona:title-menu-builtin",e=>{let t=e.detail?.actionId,r=wa.getActiveConversationId();r&&("delete"===t?Lc(e=>e.requestDeleteConversation(r)):"star"===t&&wa.canUpdateConversations()&&Lc(e=>e.updateHistoryConversation(r,{starred:!Ac})).catch(()=>{}))}),Ve=e=>{wc=e,yc?.historySurface?.view.setNewConversationRequired("new_conversation_required"===e.recovery),Kl(e.sendBlocked||za),yc?.syncEarlierMessagesPill()},Ke=e=>{("history_continuity_reset"===e.code||"conversation_deleted_recovered"===e.code)&&(qa.clear(),el(),Hi()),Cc(e.message),yc?.historySurface?.view.refresh()};let Ic={get actionManager(){return Q},get activeConversationTitle(){return kc},announceHistory:Cc,get applyRailChrome(){return Ue},set applyRailChrome(e){Ue=e},get artifactSplitRoot(){return So},get body(){return it},get config(){return s},get container(){return st},get conversationOpenPendingEl(){return Ql},set conversationOpenPendingEl(e){Ql=e},get conversationOpenTakeover(){return Xl},set conversationOpenTakeover(e){Xl=e},currentKeyPrefix:Me,destroyCallbacks:ia,eventBus:R,get footer(){return Et},get header(){return Tt},get historyChromeSync(){return Je},set historyChromeSync(e){Je=e},historyFeatureEnabled:xc,get historyInternals(){return Wd},set historyInternals(e){Wd=e},get historyPresentation(){return je},set historyPresentation(e){je=e},get historySessionState(){return wc},get historyVisible(){return qe},set historyVisible(e){qe=e},get isStreaming(){return za},jumpToBottomInstant:Ui,get lastAppliedMessages(){return _d},set lastAppliedMessages(e){_d=e},get launcherEnabled(){return X},get launcherSurfaceInstance(){return Op},maybeFocusInput:Jl,messageCache:qa,get messagesWrapper(){return lt},mount:e,get open(){return ue},panel:nt,panelElements:at,get persistentMetadata(){return W},set persistentMetadata(e){W=e},plugins:h,get reapplyHistoryHostChrome(){return _e},set reapplyHistoryHostChrome(e){_e=e},repinAnchoredMessage:ll,resetAnchorState:el,restoreScrollPosition:Xi,resumeAutoScroll:Hi,runStorageMutation:li,get session(){return wa},setActiveConversationSummary:e=>{Ac=!0===e?.starred,(e=>{e!==kc&&(kc=e,Mc())})(e&&e.title.trim()||null),Mc()},storageAdapter:H,get suppressScrollSend(){return bs},set suppressScrollSend(e){bs=e},syncScrollToBottomButton:Li,updateWelcome:dd,getHistoryProviderFactory:Gd,historyErrors:{HistoryClientError:kr,HistoryProviderError:Pr},isDockedMountMode:qs,renderLucideIcon:K,loadHistoryView:Fd,createHeaderIconButton:ei,attachTooltip:qn},Tc=e=>(!yc&&!vc&&(yc=e.createHistoryShell(Ic),yc.railCollapseShortcut()&&Sc()),yc),Ec=()=>{if(yc)return Promise.resolve(yc);let e=Vd();return e?Promise.resolve(Tc(e)):(bc??=Ud().then(Tc,e=>{throw bc=null,e}),bc)},Lc=e=>{let t=Vd(),r=yc??(t?Tc(t):null);return r?e(r):Ec().then(t=>{if(!t)throw Error("[AgentWidget] The widget was destroyed");return e(t)})},Pc=()=>{yc?.syncHistoryPresentation()};ia.push(()=>{vc=!0}),xc()&&Ec().catch(()=>{}).finally(O),s.clientToken&&(!0===s.features?.history?.enabled||"mount"===s.sessionInit)&&wa.initClientSession().then(()=>{let e=yc;if(e?.historyAvailable())return wa.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{yc?.syncEarlierMessagesPill()}).catch(e=>{s.debug&&console.warn("[AgentWidget] Pre-init client session failed:",e)});let Bc=()=>wa.warmClientSession(),Nc=e=>{let t=s.sessionInit??"input",r=pn?.input??ut,n=e.target;r&&("input"===e.type?("input"===t||"focus"===t)&&n===r&&e.inputType&&r.value.trim():"focus"===t&&("keyup"===e.type?n===r&&"Tab"===e.key:(pn?.form??mt)?.contains(n)))&&Bc()},Rc=["input","pointerdown","keyup"];Rc.forEach(t=>e.addEventListener(t,Nc));let Hc,$c,Wc=()=>{let e=$c;$c=void 0;try{"function"==typeof e&&e()}catch{}},Dc=()=>{let t=s.clientToken&&"function"==typeof s.sessionInit?s.sessionInit:void 0;if(t!==Hc){Wc(),Hc=t;try{$c=t?.({warm:Bc,mount:e})}catch{}}};Dc(),ia.push(()=>{Rc.forEach(t=>e.removeEventListener(t,Nc)),Wc()}),(Ce||s.onSSEEvent)&&wa.setSSEEventCallback((e,t)=>{s.onSSEEvent?.(e,t),Fe(e,t)});let Fc=()=>{let e=s.resume??($?Wd.getStoredResumableHandle?.():null);e&&"function"==typeof s.reconnectStream&&wa.resumeFromHandle(e)};D?D.then(e=>{if(e){if(e.metadata&&(W=lc(e.metadata),Q.syncFromMetadata()),e.messages?.length){bs=!0;try{wa.hydrateMessages(e.messages)}finally{bs=!1}fl()}e.artifacts?.length&&wa.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),gi(e.draft)}}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",e)}).finally(()=>{ed=!0,B(),Fc()}):(gi(N),Fc());let Oc=()=>{let e=ut.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>"mention"===e.kind)?e.contentSegments:void 0},zc=!1,qc=null,jc=()=>{ut.value="",ut.style.height="auto",Mr(),ep()},_c=null;function Uc(e,t=4e3){dr(e),!se()&&gt&&(gt.hasAttribute(nc)||(gt.setAttribute(oc,""),gt.setAttribute("role","status"),gt.setAttribute("aria-live","polite"),gt.textContent=e,le(gt,s.statusIndicator??{},"idle"),_c&&clearTimeout(_c),_c=setTimeout(()=>{if(_c=null,gt?.hasAttribute(oc)&&(gt.removeAttribute(oc),gt.removeAttribute("role"),gt.removeAttribute("aria-live"),y)){let e=wa.getStatus();et(gt,Ze(e),s.statusIndicator??{},e)}},t)))}let Vc=(e={})=>{let t=(e.overrideText??ut?.value??"").trim();return e.resolveInlineCommand&&t?(Cr?.takeInlineCommand(t)??Promise.resolve(null)).then(r=>Gc(e,t,r)):Gc(e,t,null)},Gc=(e,t,r)=>{if("action"===r?.kind)return jc(),Cr?.clear(),void Ir();let n="server"===r?.kind?r.mentions:null,o="prompt"===r?.kind?r.sendText:t,a=e.pending?.contentParts;if(!function(e){return!(!0===e.inputDisabled||!0===e.sendDisabled||e.hasAttachments&&!e.attachmentsReady)&&(!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions)}({text:o,hasAttachments:(xr?.hasAttachments()??!1)||(a?.length??0)>0,attachmentsReady:xr?.isReady()??!0,hasMentions:Cr?.hasMentions()??!1,hasServerMentions:!!n,inputDisabled:Hl(),sendDisabled:zl()}))return;let i=wa.isStreaming()?Ur():"block";if("defer-one"===i&&!e.pending)return Ar.getState().pendingSubmission?void Uc("One message is already queued. Edit or remove it first."):void function(e){let t=Ar.getState(),r=xr?.hasAttachments()??!1,n=r?[...xr.getContentParts()]:[];r&&e.sendText&&n.push(fr(e.sendText)),Gr(zo({text:e.sendText,contentParts:n.length?n:void 0,mentionRefs:[...Cr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:Oc(),options:{...t.selectedModelId&&{selectedModelId:t.selectedModelId},...t.activeModeIds.length>0&&{activeModeIds:[...t.activeModeIds]},...t.quote&&{quote:{...t.quote}}},viaVoice:e.intent.viaVoice})),!1!==e.intent.consumeDraft&&jc(),r&&xr.clearAttachments(),Cr?.clear(),Ir(),t.quote&&jr(void 0),bi(),An.release(),Tn(),dr("Message queued. It sends when the response finishes.")}({intent:e,sendText:o,serverMentions:n});let l={text:o,mentionRefs:[...Cr?.getMentionRefs()??[],...n?.refs??[]],contentSegments:"prompt"===r?.kind?void 0:Oc(),options:{...Ar.getState().selectedModelId&&{selectedModelId:Ar.getState().selectedModelId},...Ar.getState().activeModeIds.length>0&&{activeModeIds:[...Ar.getState().activeModeIds]},...Ar.getState().quote&&{quote:{...Ar.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(l.options={...e.pending.options},l.contentSegments=e.pending.contentSegments,l.mentionRefs=[...e.pending.mentionRefs],l.viaVoice=e.pending.viaVoice);let d=()=>{if(a?.length)return[...a];if(!xr?.hasAttachments())return;let e=[...xr.getContentParts()];return l.text&&e.push(fr(l.text)),e};l.contentParts=d();let c=()=>{Ka(),se()&&(ue||(s.launcher?.composerBar?.expandOnSubmit??1)&&Nl(!0,"auto"));let t=Cr?.collectForSubmit()??null,r=((e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[r,n]=await Promise.allSettled([e.finalize(),t.finalize()]),o=[];return"fulfilled"===r.status?o.push(r.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",r.reason),"fulfilled"===n.status?o.push(n.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",n.reason),hc(o)}}:e:t)(t,n),o=d();!1!==e.consumeDraft&&jc();let a={selectedModelId:l.options.selectedModelId,activeModeIds:l.options.activeModeIds},c="interrupt"===i;c&&wa.cancel(),wa.sendMessage(l.text,{contentParts:o,mentions:r??void 0,contentSegments:l.contentSegments,viaVoice:l.viaVoice,composerOptions:a,...l.options.quote&&{quote:l.options.quote},...c&&{interrupt:!0}}),xr?.hasAttachments()&&xr.clearAttachments(),t&&Cr?.clear(),Ir();let p=Ar.getState().activeModeIds,u=function(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&"once"!==(t.persistence??"sticky")).map(e=>e.id):[]}(p,s.composer?.modes);u.length!==p.length&&Rr(u),Ar.getState().quote&&jr(void 0),bi(),An.release(),Tn()},p=s.composer?.onBeforeSend;if(!p)return void c();let u=new AbortController;qc=u;let h=e=>{qc=null,"error"===e.status?(e=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",e)})(e.error):"proceed"===e.status&&c()},m=jo(p,l,u.signal);if(m instanceof Promise)return Ar.setPreparing(!0),m.then(h).finally(()=>Ar.setPreparing(!1));h(m)};On={regenerate:function(e){if(wa.isStreaming())return;let t=Yr(wa.getMessages(),e);t&&(Ka(),wa.resubmitFrom(t,{reason:"retry"})&&ll())},edit:function(e){if(!0!==s.messageActions?.showEdit)return;let t=wa.getMessages().find(t=>t.id===e);t&&Zr(t)&&Va!==e&&(Ka(),Va=e,Ga=Oo({messageId:e,initialText:t.content,onSave:t=>function(e,t){let r=Ga;Va=null,Ga=null,r?.destroy(),qa.delete(e),wa.resubmitFrom(e,{reason:"edit",replacement:{text:t,mentionRefs:[],options:{}}})?ll():yl(lt,wa.getMessages(),fe)}(e,t),onCancel:()=>Ka()}),qa.delete(e),yl(lt,wa.getMessages(),fe),Ga.focus())},quote:e=>{let t=wa.getMessages().find(t=>t.id===e)?.content?.trim();t&&(jr({text:t,messageId:e}),ut?.focus())}};let Kc=async e=>{if(!zc){zc=!0;try{await Vc({resolveInlineCommand:!0,...e})}finally{zc=!1}}};function Jc(e){zl()||(jc(),Qc(e,{consumeDraft:!1}))}let Qc=(e,t)=>{if(zc)return;zc=!0;let r=()=>{zc=!1};try{let n=Vc({...t,overrideText:e});n instanceof Promise?n.finally(r):r()}catch(e){throw r(),e}},Xc=e=>{e.preventDefault(),wa.isStreaming()?(wa.cancel(),Pe?.reset(),Re?.update()):zc||Kc()},Yc={...Ya},Zc=!1,ep=()=>{Yc={...Ya}},tp=e=>{"Escape"!==e.key||e.isComposing||e.composedPath().includes(st)&&(qc?(qc.abort(),qc=null,e.preventDefault(),e.stopImmediatePropagation()):wa.isStreaming()&&(wa.cancel(),Pe?.reset(),Re?.update(),ep(),e.preventDefault(),e.stopImmediatePropagation()))},rp=null,np=!1,op=null,ap=null,sp=()=>"review"===s.voiceRecognition?.completionBehavior;function ip(e){Wt?.setAttribute("data-state",e),"recording"===e?function(){if(null!==cp)return;if("function"!=typeof requestAnimationFrame)return void mp(y?wa.getVoiceLevel()??dp:dp);let e=()=>{cp=requestAnimationFrame(e);let t=y?wa.getVoiceLevel():null;null===t?mp(dp):(up+=.3*(t-up),mp(up))};cp=requestAnimationFrame(e)}():fp()}let lp="--persona-voice-level",dp=.5,cp=null,pp=-1,up=0,hp=()=>{let e=[],t=Dt??Wt?.parentElement??null;return t&&e.push(t),Et&&e.push(Et),e},mp=e=>{let t=Math.round(100*Math.max(0,Math.min(1,e)))/100;if(t!==pp){pp=t;for(let e of hp())e.style.setProperty(lp,String(t))}},gp=()=>{pp=-1,up=0;for(let e of hp())e.style.removeProperty(lp)};function fp(){null!==cp&&(cancelAnimationFrame(cp),cp=null),gp()}let yp=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,bp=(e="user")=>{if(np||wa.isStreaming())return;let t=yp();if(!t)return;rp=new t;let r=s.voiceRecognition??{},n=r.pauseDuration??2e3;rp.continuous=r.provider?.browser?.continuous??!0,rp.interimResults=!0,rp.lang=r.provider?.browser?.language??"en-US";let o=ut.value;rp.onresult=e=>{let t="",r="";for(let n=0;n<e.results.length;n++){let o=e.results[n],a=o[0].transcript;o.isFinal?t+=a+" ":r=a}let a=o+t+r;ut.value=a,Mr(),op&&clearTimeout(op),(t||r)&&(op=window.setTimeout(()=>{if(ut.value.trim()&&rp&&np){if(vp(),sp())return;Kc({viaVoice:!0})}},n))},rp.onerror=e=>{"no-speech"!==e.error&&vp()},rp.onend=()=>{if(np){let e=ut.value.trim();!sp()&&e&&e!==o.trim()&&Kc({viaVoice:!0}),vp()}};try{if(rp.start(),np=!0,Os.active=!0,"system"!==e&&(Os.manuallyDeactivated=!1),Xs(e),Ys(),Tn(),Wt){let e=s.voiceRecognition??{};ap={backgroundColor:Wt.style.backgroundColor,color:Wt.style.color,borderColor:Wt.style.borderColor,iconName:e.iconName??"mic",iconSize:parseFloat(e.iconSize??"")||24};let t=e.recordingBackgroundColor,r=e.recordingIconColor,n=e.recordingBorderColor;if(Wt.classList.add("persona-voice-recording"),ip("recording"),Wt.style.backgroundColor=t??"var(--persona-voice-recording-bg, #ef4444)",Wt.style.color=r??"var(--persona-voice-recording-indicator, #ffffff)",r){let e=Wt.querySelector("svg");e&&e.setAttribute("stroke",r)}n&&(Wt.style.borderColor=n),Wt.setAttribute("aria-label","Stop voice recognition")}}catch{vp("system")}},vp=(e="user")=>{if(np){if(np=!1,op&&=(clearTimeout(op),null),rp){try{rp.stop()}catch{}rp=null}if(Os.active=!1,Xs(e),Ys(),Tn(),Wt){if(Wt.classList.remove("persona-voice-recording"),ip("idle"),ap){Wt.style.backgroundColor=ap.backgroundColor,Wt.style.color=ap.color,Wt.style.borderColor=ap.borderColor;let e=Wt.querySelector("svg");e&&e.setAttribute("stroke",ap.color||"currentColor"),ap=null}Wt.setAttribute("aria-label","Start voice recognition")}}},wp=null,xp=e=>{let t=t=>{wp??=t.createMicStateStyles({mic:()=>Wt,config:()=>s,session:()=>wa,get original(){return ap},set original(e){ap=e},setMicState:ip,renderIcon:K,iconFallbackPx:24}),e(wp)},r=cn();r?t(r):dn().then(t,()=>{})},Cp=()=>xp(e=>e.recording()),Sp=()=>xp(e=>e.processing()),kp=()=>xp(e=>e.speaking()),Ap=()=>xp(e=>e.reset()),Mp=()=>{if(!Hl())if(ce(s.voiceRecognition?.provider)){let e=wa.getVoiceStatus(),t=wa.getVoiceInterruptionMode();if("none"===t&&("processing"===e||"speaking"===e))return;if("cancel"===t&&("processing"===e||"speaking"===e))return void wa.stopVoicePlayback();if(wa.isBargeInActive())return wa.stopVoicePlayback(),void wa.deactivateBargeIn().then(()=>{Os.active=!1,Os.manuallyDeactivated=!0,Ys(),Xs("user"),Ap()});wa.toggleVoice().then(()=>{Os.active=Us(),Os.manuallyDeactivated=!Os.active,Ys(),Xs("user"),Os.active?Cp():Ap()})}else if(np){let e=ut.value.trim();Os.manuallyDeactivated=!0,Ys(),vp("user"),e&&!sp()&&Kc()}else Os.manuallyDeactivated=!1,Ys(),bp("user")};Qr=Mp;let Ip=()=>wa.prewarmVoice(),Tp=()=>{let e=s.voiceRecognition;return!0===e?.enabled&&(e.prewarm??(!!s.clientToken&&"hover"))},Ep=e=>{"hover"===Tp()&&Wt?.contains(e.target)&&Ip()},Lp=["pointerover","pointerdown","focusin"];Lp.forEach(t=>e.addEventListener(t,Ep));let Pp,Bp,Np=null,Rp=()=>{let e=Bp;Bp=void 0;try{"function"==typeof e&&e()}catch{}},Hp=()=>{let t=Tp(),r="function"==typeof t&&Wt?t:void 0,n=r?Wt:null;if((r!==Pp||n!==Np)&&(Rp(),Pp=r,Np=n,r&&n))try{Bp=r({warm:Ip,micButton:n,mount:e})}catch{}};Hp(),ia.push(()=>{Lp.forEach(t=>e.removeEventListener(t,Ep)),Rp()}),Wt&&ia.push(()=>{ce(s.voiceRecognition?.provider)?(wa.isVoiceActive()&&wa.toggleVoice(),Ap()):vp("system")});let $p=R.on("assistant:complete",()=>{Ar.getState().pendingSubmission&&setTimeout(()=>{wa.isStreaming()||function(){let e=Ar.getState().pendingSubmission;e&&(Gr(void 0),Qc(e.text,{consumeDraft:!1,pending:e}))}()},0)});ia.push($p);let Wp=R.on("assistant:complete",()=>{zs&&(Os.active||Os.manuallyDeactivated||("assistant"!==zs||Os.lastUserMessageWasVoice)&&setTimeout(()=>{!Os.active&&!Os.manuallyDeactivated&&(ce(s.voiceRecognition?.provider)?wa.toggleVoice().then(()=>{Os.active=wa.isVoiceActive(),Xs("auto"),wa.isVoiceActive()&&Cp()}):bp("auto"))},600))});ia.push(Wp);let Dp=R.on("action:resubmit",()=>{setTimeout(()=>{wa&&!wa.isStreaming()&&wa.continueConversation()},100)});ia.push(Dp);let Fp=()=>{Nl(!ue,"user")},Op=null,zp=null;if(X&&!se()){let{instance:e,element:t}=nl({config:s,plugins:h,onToggle:Fp});Op=e,e||(zp=t)}Op?e.appendChild(Op.element):zp&&e.appendChild(zp),Bl(),Ba(),Cd(),bd(),Kl(wa.isStreaming()),Xi()||("follow"===Gt()?$i(!0):Ui()),(()=>{if(!1===s.voiceRecognition?.enabled)return;let e=lc(W.voiceState),t=!!e.active,r=Number(e.timestamp??0);Os.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-r<3e4&&setTimeout(()=>{Os.active||(Os.manuallyDeactivated=!1,ce(s.voiceRecognition?.provider)?wa.toggleVoice().then(()=>{Os.active=Us(),Xs("restore"),Os.active?Cp():(Ys(),Uc("Tap the mic to resume your voice call",1e4))}):bp("restore"))},ce(s.voiceRecognition?.provider)?0:1e3)})(),Z&&(!X||se()?setTimeout(()=>Jl(),0):ue&&setTimeout(()=>Jl(),200));let qp=null,jp=()=>{qp&&(qp.disconnect(),qp.observe(Et),qp.observe(st),qp.observe(ft))},_p=cr(),Up=()=>{if(se())return gr(),void Bl();let t=qs(s),r=s.launcher?.sidebarMode??!1,n=e.ownerDocument.defaultView??window,o=s.launcher?.mobileFullscreen??!0,a=s.launcher?.mobileBreakpoint??640,i=n.innerWidth<=a,l=o&&i&&X;try{if(l)return eo(),void(to=Zo());let e=!1;ne&&(ne=!1,eo(),e=!0);let n=Zo();if(!e&&n!==to&&(eo(),e=!0),to=n,e&&Ro(),!X&&!t)return nt.style.height="",void(nt.style.width="");if(!r&&!t){let e=Vi(s);nt.style.width=e.width,nt.style.maxWidth=e.maxWidth}Jo(),sa()}finally{gr(),vr();let t=cr();if(t!==_p&&(_p=t,dd(),Ba()),Bl(),ue&&X){let t=(e.ownerDocument.defaultView??window).innerWidth<=(s.launcher?.mobileBreakpoint??640),r=s.launcher?.sidebarMode??!1,n=s.launcher?.mobileFullscreen??!0,o=qs(s)&&n&&t,a=r||n&&t&&X||o;if(a&&!da){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&!la&&(la=Ns(r,s.launcher?.zIndex??1e5)),da=$s(e.ownerDocument)}else a||(la?.(),la=null,da?.(),da=null)}}};Up();let Vp=e.ownerDocument.defaultView??window;if(Vp.addEventListener("resize",Up),ia.push(()=>Vp.removeEventListener("resize",Up)),typeof ResizeObserver<"u"){qp=new ResizeObserver(()=>{vr()}),jp(),ia.push(()=>{qp?.disconnect(),qp=null});let e=new ResizeObserver(()=>{Pc()});e.observe(st),ia.push(()=>e.disconnect())}Vp.addEventListener("resize",Pc),ia.push(()=>Vp.removeEventListener("resize",Pc)),as=it.scrollTop;let Gp=es(it),Kp=()=>{oa();let e=it.scrollTop,t=es(it),r=t<Gp;if(Gp=t,!Kt())return as=e,void Li();let{action:n,nextLastScrollTop:o}=function(e){let{following:t,currentScrollTop:r,lastScrollTop:n,nearBottom:o,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:l=!0,resumeRequiresDownwardScroll:d=!1}=e,c=r-n;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:r}:!t&&o&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:r}:t&&i&&c<0||t&&l&&!o?{action:"pause",delta:c,nextLastScrollTop:r}:{action:"none",delta:c,nextLastScrollTop:r}}({following:os.isFollowing(),currentScrollTop:e,lastScrollTop:as,nearBottom:ts(it,24),userScrollThreshold:4,isAutoScrolling:is||ls||r,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});as=o,"resume"===n?Qi()||Hi():"pause"===n&&Ri()};if(it.addEventListener("scroll",Kp,{passive:!0}),ia.push(()=>it.removeEventListener("scroll",Kp)),typeof ResizeObserver<"u"){let e=new ResizeObserver(()=>{(()=>{if(Kt()){if(!os.isFollowing()||ts(it,1))return;$i(!za)}else{if(ps&&ps.initialSpacerHeight>0){let e=it.scrollHeight-ps.spacerHeight,t=function(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}({initialSpacerHeight:ps.initialSpacerHeight,contentHeightAtAnchor:ps.contentHeightAtAnchor,currentContentHeight:e});t!==ps.spacerHeight&&Yi(t)}Li()}})(),ze(lt)});e.observe(lt),e.observe(it),ia.push(()=>e.disconnect())}let Jp=()=>{Kt()&&os.isFollowing()&&Qi()&&Ri()},Qp=it.ownerDocument;Qp.addEventListener("selectionchange",Jp),ia.push(()=>{Qp.removeEventListener("selectionchange",Jp)});let Xp=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Yp=e=>{Xp.has(e.key)&&(Es(),Qt()&&Kt()&&os.isFollowing()&&Ri())},Zp=e=>{e.target?.closest("a, button, [tabindex], input, textarea, select")&&(Es(),Qt()&&Kt()&&os.isFollowing()&&Ri())};it.addEventListener("keydown",Yp),it.addEventListener("focusin",Zp),ia.push(()=>{it.removeEventListener("keydown",Yp),it.removeEventListener("focusin",Zp)});let eu=e=>{if(0!==e.deltaY&&Es(),!Kt())return;let t=function(e){let{following:t,deltaY:r,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=e;return t&&r<0?"pause":!t&&o&&r>0&&n?"resume":"none"}({following:os.isFollowing(),deltaY:e.deltaY,nearBottom:ts(it,24),resumeWhenNearBottom:!0});"pause"===t?Ri():"resume"===t&&!Qi()&&Hi()};it.addEventListener("wheel",eu,{passive:!0}),it.addEventListener("touchmove",Es,{passive:!0}),it.addEventListener("pointerdown",Es,{passive:!0}),ia.push(()=>{it.removeEventListener("touchmove",Es),it.removeEventListener("pointerdown",Es)}),ia.push(()=>it.removeEventListener("wheel",eu)),tr.addEventListener("click",()=>{el(),it.scrollTop=it.scrollHeight,as=it.scrollTop,Hi(),$i(!0),Li()}),ia.push(()=>tr.remove()),ia.push(()=>{ki(),el()});let tu=()=>{St&&(xa&&=(St.removeEventListener("click",xa),null),pe()?(St.style.display="",xa=()=>{Nl(!1,"user")},St.addEventListener("click",xa)):St.style.display="none")};tu(),(()=>{let{clearChatButton:e}=at;e&&e.addEventListener("click",()=>{let e=yc;if(e?.historyAvailable())return void e.startNewConversation({focusComposer:!0}).catch(e=>{s.debug&&console.warn("[AgentWidget] New conversation failed:",e)});wa.clearMessages(),s.layout?.topFade&&(it.scrollTop=0),it.removeAttribute("data-persona-top-fade"),qa.clear(),Hi(),$t(at.composerOverlay);try{localStorage.removeItem(rc),s.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${rc}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(s.clearChatHistoryStorageKey&&s.clearChatHistoryStorageKey!==rc)try{localStorage.removeItem(s.clearChatHistoryStorageKey),s.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${s.clearChatHistoryStorageKey}`)}catch(e){console.error("[AgentWidget] Failed to clear custom localStorage:",e)}let t=new CustomEvent("persona:clear-chat",{detail:{timestamp:(new Date).toISOString()}});window.dispatchEvent(t),H?.clear&&li(()=>H.clear(),"[AgentWidget] Failed to clear storage adapter:"),W={},Q.syncFromMetadata(),xr?.clearAttachments(),bi(),Gr(void 0),jr(void 0),Ka(),Le?.clear(),Pe?.reset(),Re?.update()})})();let ru=[["keydown",e=>{if(ut&&!Hl()&&(e.isComposing||!Cr?.handleKeydown(e))){if(!(!1===s.features?.composerHistory||"ArrowUp"!==e.key&&"ArrowDown"!==e.key||e.shiftKey||e.metaKey||e.ctrlKey||e.altKey||e.isComposing)){let t=0===ut.selectionStart&&0===ut.selectionEnd,r=function(e){let{direction:t,history:r,currentValue:n,atStart:o,state:a}=e,s=-1!==a.index;if(0===r.length)return{handled:!1,state:a};if("up"===t){if(!s&&!o)return{handled:!1,state:a};if(!s){let e=r.length-1;return{handled:!0,value:r[e],state:{index:e,draft:n}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:r[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let e=a.index+1;return{handled:!0,value:r[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}({direction:"ArrowUp"===e.key?"up":"down",history:wa.getMessages().filter(e=>"user"===e.role).map(e=>e.content??"").filter(e=>e.length>0),currentValue:ut.value,atStart:t,state:Yc});if(Yc=r.state,r.handled)return e.preventDefault(),void(void 0!==r.value&&(e=>{if(!ut)return;Zc=!0,ut.value=e,ut.dispatchEvent(new Event("input",{bubbles:!0})),Zc=!1;let t=ut.value.length;ut.setSelectionRange(t,t)})(r.value))}if(Kn(e,{submitKey:s.composer?.submitKey,insertNewlineOnTouchEnter:s.composer?.insertNewlineOnTouchEnter,coarsePointer:Vn(ut)}))if(wa.isStreaming()){if(e.preventDefault(),"block"===Ur()||zc||zl())return;ep(),Kc()}else zc||zl()?e.preventDefault():(ep(),e.preventDefault(),ht.click())}}],["input",e=>{Zc||(e.isComposing||Cr?.handleInput(e.inputType??void 0),ep())}],["input",Mr],["input",Ir],["keyup",Ir],["paste",async e=>{if(!0!==s.attachments?.enabled||!xr||Hl())return;let t=sc(e.clipboardData);0!==t.length&&(e.preventDefault(),await xr.handleFiles(t))}],["focus",()=>Cr?.prefetch()]],nu=e=>{if(e)for(let[t,r]of ru)pn?.addListener(e,t,r)},ou=()=>{pn&&(pn.addListener(pn.form,"submit",Xc),pn.addListener(pn.footer,"click",Ir),nu(ut),Wt&&pn.addListener(Wt,"click",Mp),Hp())};ou();let au=()=>{Cr?.onComposerSwap((e,t)=>{(e=>{if(e)for(let[t,r]of ru)pn?.removeListener(e,t,r)})(t),ut=e,pn&&(pn.input=e),nu(e),un(),Gl(),Mr()})};au();let su=!1;function iu(){if(!su){su=!0;try{let e=ut?.value??"",t=Et.ownerDocument??document,r=!!ut&&t.activeElement===ut;fp(),pn?.destroy(),pn=null,Cr?.destroy(),Cr=null;let n=null,o=()=>(n=se()?vi({config:s}):yi({config:s}),n.footer),a=sn(o)??o();tt.replaceComposer(a),Et=tt.composer.footer;let i=null!==n&&a===n.footer;an=!i,Rt=i?n.setSendButtonMode:()=>{},on(Et),hn(Et),gn(),fn(),yn(),au(),xn(),Sn(),kn(),ou();let l=va.indexOf(ga);if(ga.destroy(),ga=Js(pt),l>=0&&(va[l]=ga),ut&&(ut.value=e),Mr(),Ir(),Cd(),Ba(),Kl(wa.isStreaming()),"transient"===s.statusIndicator?.mode&&!se()){let e=wa.getStatus();et(gt,Ze(e),s.statusIndicator,e)}Os.active&&ip("recording"),eo(),jp(),gr(),Tn(),Vl(),r&&ut?.focus()}finally{su=!1}}}let lu=e.ownerDocument??document;lu.addEventListener("keydown",tp,!0);let du=()=>{mi()},cu=()=>{"hidden"===lu.visibilityState&&mi()};typeof window<"u"&&(window.addEventListener("pagehide",du),lu.addEventListener("visibilitychange",cu),ia.push(()=>{window.removeEventListener("pagehide",du),lu.removeEventListener("visibilitychange",cu)}));let pu="persona-attachment-drop-active",uu=0,hu=()=>{uu=0,st.classList.remove(pu)},mu=()=>!0===s.attachments?.enabled&&null!==xr&&!Hl(),gu=e=>{ic(e.dataTransfer)&&mu()&&(uu++,1===uu&&st.classList.add(pu))},fu=e=>{ic(e.dataTransfer)&&mu()&&(uu--,uu<=0&&hu())},yu=e=>{ic(e.dataTransfer)&&mu()&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},bu=e=>{if(!ic(e.dataTransfer)||!mu())return;e.preventDefault(),e.stopPropagation(),hu();let t=Array.from(e.dataTransfer.files??[]);0!==t.length&&xr.handleFiles(t)};st.addEventListener("dragenter",gu,!0),st.addEventListener("dragleave",fu,!0),e.addEventListener("dragover",yu,!0),e.addEventListener("drop",bu,!0);let vu=e.ownerDocument,wu=e=>{mu()&&e.preventDefault()},xu=e=>{mu()&&e.preventDefault()};vu.addEventListener("dragover",wu),vu.addEventListener("drop",xu),ia.push(()=>{pn?.destroy(),pn=null,fp(),bn?.destroy(),bn=null,Or?.destroy(),Or=null,qr?.destroy(),qr=null,Vr?.destroy(),Vr=null,$r=null,Fr=null,mi(),ui.destroy(),_c&&clearTimeout(_c),Ka(),qc?.abort(),qc=null,xr?.destroy(),xr=null,Ar.destroy(),lu.removeEventListener("keydown",tp,!0),Cr?.destroy()}),ia.push(()=>{st.removeEventListener("dragenter",gu,!0),st.removeEventListener("dragleave",fu,!0),e.removeEventListener("dragover",yu,!0),e.removeEventListener("drop",bu,!0),vu.removeEventListener("dragover",wu),vu.removeEventListener("drop",xu),hu()}),ia.push(()=>{wa.cancel()}),Op?ia.push(()=>{Op?.destroy()}):zp&&ia.push(()=>{zp?.remove()});let Cu={update(t){let o=!0===s.future?.v5Defaults,a=s.toolCall,i=s.messageActions,l=s.layout?.messages,d=s.colorScheme,c=s.loadingIndicator,m=s.iterationDisplay,g=s.features?.showReasoning,f=s.features?.showToolCalls,y=s.features?.toolCallDisplay,b=s.features?.reasoningDisplay,v=s.features?.streamAnimation?.type,w=!0===s.features?.history?.enabled,x=s.features?.history?.provider,C=s.getIdentityProof,S=s.clientToken,k=s.contextMentions;s=Ad({...s,features:u},t),u=s.features,s=ud(s),p(),ta(),$a(e,s),_l(e,s),Ul(e,s),Ue(),ea(),s.colorScheme!==d&&pa();let A=xd.getForInstance(s.plugins);h.length=0,h.push(...A),Sc(),X=s.launcher?.enabled??!0,Y=s.launcher?.autoExpand??!1,we=s.features?.showReasoning??!0,xe=s.features?.showToolCalls??!0,Se=s.features?.scrollToBottom??{};let M=Gt();Ae=s.features?.scrollBehavior??{},M!==Gt()&&(el(),Hi()),Rs(),wr(),Li();let I=Ce;if(Ce=s.features?.showEventStreamToggle??!1,Ce&&!I){if(Le||(Oe(),wa.setSSEEventCallback((e,t)=>{s.onSSEEvent?.(e,t),Fe(e,t)})),!nn&&Tt){let e=s.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:"");nn=L("button",t),nn.style.width="28px",nn.style.height="28px",nn.style.color=ni.actionIconColor,nn.type="button",nn.setAttribute("aria-label","Event Stream"),nn.title="Event Stream";let o=n(r.Activity,"18px","currentColor",1.5);o&&nn.appendChild(o);let a=at.clearChatButtonWrapper,i=at.closeButtonWrapper,l=a||i;l&&l.parentNode===Tt?Tt.insertBefore(nn,l):Tt.appendChild(nn),nn.addEventListener("click",()=>{He?rn():tn()})}}else!Ce&&I&&(rn(),nn&&=(nn.remove(),null),Le?.clear(),Te?.destroy(),Le=null,Te=null,Pe?.reset(),Pe=null,Be=null);if(!1===s.launcher?.enabled&&Op&&(Op.destroy(),Op=null),!1===s.launcher?.enabled&&zp&&(zp.remove(),zp=null),!1!==s.launcher?.enabled&&!Op&&!zp){let{instance:t,element:r}=nl({config:s,plugins:h,onToggle:Fp});Op=t,t||(zp=r),e.appendChild(r)}Op&&Op.update(s),Mc(),It&&void 0!==s.launcher?.subtitle&&(It.textContent=s.launcher.subtitle);let T=s.layout?.header;if(T?.layout!==re&&Tt){let e=T?fi(s,T,{showClose:pe(),onClose:()=>Nl(!1,"user")}):si({config:s,showClose:pe(),onClose:()=>Nl(!1,"user")});tt.replaceHeader(e),Tt=tt.header.element,At=tt.header.iconHolder,Mt=tt.header.headerTitle,It=tt.header.headerSubtitle,St=tt.header.closeButton,re=T?.layout,Mc()}else if(T){if(At&&(At.style.display=!1===T.showIcon?"none":""),Mt&&(Mt.style.display=!1===T.showTitle?"none":""),It&&(It.style.display=!1===T.showSubtitle?"none":""),St){let e=pe()&&!1!==T.showCloseButton;St.style.display=e?"":"none"}if(at.clearChatButtonWrapper){let e=T.showClearChat;if(void 0!==e){at.clearChatButtonWrapper.style.display=e?"":"none";let{closeButtonWrapper:t}=at;t&&!t.classList.contains("persona-absolute")&&(e?t.classList.remove("persona-ml-auto"):t.classList.add("persona-ml-auto"))}}}let E=!1!==s.layout?.showHeader;Tt&&(Tt.style.display=E?"":"none");let P=!1!==s.layout?.showFooter;Et&&(Et.style.display=P?"":"none"),gr(),Li(),X===te?Y!==ee&&Nl(Y,"auto"):X?Nl(Y,"auto"):(ue=!0,Bl()),ee=Y,te=X,Up(),tu();let B=JSON.stringify(s.toolCall)!==JSON.stringify(a),N=JSON.stringify(s.messageActions)!==JSON.stringify(i),H=JSON.stringify(s.layout?.messages)!==JSON.stringify(l),$=s.loadingIndicator?.render!==c?.render||s.loadingIndicator?.renderIdle!==c?.renderIdle||s.loadingIndicator?.showBubble!==c?.showBubble,W=s.iterationDisplay!==m,D=(s.features?.showReasoning??!0)!==(g??!0)||(s.features?.showToolCalls??!0)!==(f??!0)||JSON.stringify(s.features?.toolCallDisplay)!==JSON.stringify(y)||JSON.stringify(s.features?.reasoningDisplay)!==JSON.stringify(b);(!0===s.future?.v5Defaults!==o||B||N||H||$||W||D)&&wa&&(Qa++,yl(lt,wa.getMessages(),fe));let F=s.features?.streamAnimation?.type;if(F!==v&&F&&"none"!==F){let t=ha(F,s.features?.streamAnimation?.plugins);t&&Ts(t,e)}let O=s.launcher??{},z=O.headerIconHidden??!1,q=s.layout?.header?.showIcon,j=z||!1===q,U=O.headerIconName,G=O.headerIconSize??"40px";if(At){let e=Tt,t=e?.querySelector(".persona-flex-col");if(j)At.style.display="none",e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(At.style.display="",At.style.height=G,At.style.width=G,e&&t&&(e.contains(At)?At.nextSibling!==t&&(At.remove(),e.insertBefore(At,t)):e.insertBefore(At,t)),U){let e=parseFloat(G)||24,t=K(U,.6*e,"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))`,At.replaceChildren(t)):At.textContent=O.agentIconText??"💬"}else if(O.iconUrl){let e=At.querySelector("img");if(e)e.src=O.iconUrl,e.style.height=G,e.style.width=G;else{let e=document.createElement("img");e.src=O.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=G,e.style.width=G,At.replaceChildren(e)}}else{let e=At.querySelector("svg"),t=At.querySelector("img");(e||t)&&At.replaceChildren(),At.textContent=O.agentIconText??"💬"}let r=At.querySelector("img");r&&(r.style.height=G,r.style.width=G)}}let J=s.layout?.header?.showTitle,Z=s.layout?.header?.showSubtitle;if(Mt&&(Mt.style.display=!1===J?"none":""),It&&(It.style.display=!1===Z?"none":""),St){let e=pe()&&!1!==s.layout?.header?.showCloseButton;if(St.style.display=e?"":"none",!se()){let e=O.closeButtonSize??"";St.style.height=e,St.style.width=e,St.style.minWidth=e,St.style.minHeight=e}let t=O.closeButtonPlacement??"inline",{closeButtonWrapper:r}=at,n="top-right"===t,o=r?.classList.contains("persona-absolute");if(r&&n!==o)if(r.remove(),n){r.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let e=yc?.railColumn??st;e.style.position="relative",e.appendChild(r)}else{let e=O.clearChat?.placement??"inline";r.className=(O.clearChat?.enabled??1)&&"inline"===e?"":"persona-ml-auto",Tt&&Tt.appendChild(r)}if(St.style.color=O.closeButtonColor||ni.actionIconColor,O.closeButtonBackgroundColor?(St.style.backgroundColor=O.closeButtonBackgroundColor,St.classList.remove("hover:persona-bg-gray-100")):(St.style.backgroundColor="",St.classList.add("hover:persona-bg-gray-100")),O.closeButtonBorderWidth||O.closeButtonBorderColor){let e=O.closeButtonBorderWidth||"0px",t=O.closeButtonBorderColor||"transparent";St.style.border=`${e} solid ${t}`,St.classList.remove("persona-border-none")}else St.style.border="",St.classList.add("persona-border-none");O.closeButtonBorderRadius?(St.style.borderRadius=O.closeButtonBorderRadius,St.classList.remove("persona-rounded-full")):(St.style.borderRadius="",St.classList.add("persona-rounded-full")),O.closeButtonPaddingX?(St.style.paddingLeft=O.closeButtonPaddingX,St.style.paddingRight=O.closeButtonPaddingX):(St.style.paddingLeft="",St.style.paddingRight=""),O.closeButtonPaddingY?(St.style.paddingTop=O.closeButtonPaddingY,St.style.paddingBottom=O.closeButtonPaddingY):(St.style.paddingTop="",St.style.paddingBottom=""),Zs(St,O.closeButtonIconName??"x",{iconSize:se()?Ki:void 0,iconText:O.closeButtonIconText??"×"});let a=O.closeButtonTooltipText??"Close chat",i=O.closeButtonShowTooltip??!0;St.setAttribute("aria-label",a),r&&qn({anchor:St,trigger:r,text:()=>St?.getAttribute("aria-label")??a,enabled:i})}let{clearChatButton:ne,clearChatButtonWrapper:oe}=at;if(ne){let e=O.clearChat??{},t=e.enabled??!0,r=s.layout?.header?.showClearChat,n=void 0===r?t:r,o=e.placement??"inline";if(oe){oe.style.display=n?"":"none";let{closeButtonWrapper:e}=at;!se()&&e&&!e.classList.contains("persona-absolute")&&(n?e.classList.remove("persona-ml-auto"):e.classList.add("persona-ml-auto"));let t="top-right"===o,r=oe.classList.contains("persona-absolute");if(!se()&&t!==r&&n){if(oe.remove(),t){oe.className="persona-absolute persona-top-4 persona-z-50",oe.style.right="48px";let e=yc?.railColumn??st;e.style.position="relative",e.appendChild(oe)}else{oe.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",oe.style.right="";let e=at.closeButtonWrapper;Tt&&e&&e.parentElement===Tt?Tt.insertBefore(oe,e):Tt&&Tt.appendChild(oe)}let e=at.closeButtonWrapper;e&&!e.classList.contains("persona-absolute")&&(t?e.classList.add("persona-ml-auto"):e.classList.remove("persona-ml-auto"))}}if(n){if(!se()){let t=e.size??"";ne.style.height=t,ne.style.width=t,ne.style.minWidth=t,ne.style.minHeight=t}let t=e.iconColor??"";if(ne.style.color=t||ni.actionIconColor,Zs(ne,e.iconName??"refresh-cw",{iconSize:se()?Ji:void 0}),e.backgroundColor?(ne.style.backgroundColor=e.backgroundColor,ne.classList.remove("hover:persona-bg-gray-100")):(ne.style.backgroundColor="",ne.classList.add("hover:persona-bg-gray-100")),e.borderWidth||e.borderColor){let t=e.borderWidth||"0px",r=e.borderColor||"transparent";ne.style.border=`${t} solid ${r}`,ne.classList.remove("persona-border-none")}else ne.style.border="",ne.classList.add("persona-border-none");e.borderRadius?(ne.style.borderRadius=e.borderRadius,ne.classList.remove("persona-rounded-full")):(ne.style.borderRadius="",ne.classList.add("persona-rounded-full")),e.paddingX?(ne.style.paddingLeft=e.paddingX,ne.style.paddingRight=e.paddingX):(ne.style.paddingLeft="",ne.style.paddingRight=""),e.paddingY?(ne.style.paddingTop=e.paddingY,ne.style.paddingBottom=e.paddingY):(ne.style.paddingTop="",ne.style.paddingBottom="");let r=e.tooltipText??"Clear chat",n=e.showTooltip??!0;ne.setAttribute("aria-label",r),oe&&qn({anchor:ne,trigger:oe,text:()=>ne?.getAttribute("aria-label")??r,enabled:n})}}let ae=s.actionParsers&&s.actionParsers.length?s.actionParsers:[Md],ie=s.actionHandlers&&s.actionHandlers.length?s.actionHandlers:[Td.message,Td.messageAndClick];Q=Ld({parsers:ae,handlers:ie,getSessionMetadata:_,updateSessionMetadata:V,emit:R.emit,documentRef:typeof document<"u"?document:null}),fe=cc(s,Q,ge),Dd(),wa.updateConfig(s),Dc(),(!0===s.features?.history?.enabled!==w||s.features?.history?.provider!==x||s.getIdentityProof!==C||s.clientToken!==S)&&(yc?.closeHistory({restoreFocus:!1}),yc?.installHistoryProvider()),yc?.syncHistoryChromeImpl(),Pc(),xc()&&!yc&&Ec().catch(()=>{}),yl(lt,wa.getMessages(),fe),Ba(),Cd(),(()=>{let e=pr();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`!==gd||e.icon!==nd)&&bd()})(),Kl(wa.isStreaming()),k!==s.contextMentions&&iu();let he=!0===s.voiceRecognition?.enabled,me=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),ye=ce(s.voiceRecognition?.provider);if(he&&(me||ye))if(Wt&&Dt){let e=s.voiceRecognition??{},t=s.sendButton??{},r=e.iconName??"mic",n=e.iconSize,o=parseFloat(n??"")||24;Wt.classList.add(Yn),Wt.classList.toggle(Zn,!n),Wt.style.width=n??"",Wt.style.height=n??"",Wt.style.minWidth=n??"",Wt.style.minHeight=n??"";let a=e.iconColor??t.textColor;Wt.innerHTML="";let i=K(r,o,a||"currentColor",1.5);i?Wt.appendChild(i):Wt.textContent="🎤";let l=e.backgroundColor??t.backgroundColor;Wt.style.backgroundColor=l||"",Wt.style.color=a||"var(--persona-text, #111827)",e.borderWidth?(Wt.style.borderWidth=e.borderWidth,Wt.style.borderStyle="solid"):(Wt.style.borderWidth="",Wt.style.borderStyle=""),e.borderColor?Wt.style.borderColor=e.borderColor:Wt.style.borderColor="",e.paddingX?(Wt.style.paddingLeft=e.paddingX,Wt.style.paddingRight=e.paddingX):(Wt.style.paddingLeft="",Wt.style.paddingRight=""),e.paddingY?(Wt.style.paddingTop=e.paddingY,Wt.style.paddingBottom=e.paddingY):(Wt.style.paddingTop="",Wt.style.paddingBottom="");let d=e.tooltipText??"Start voice recognition",c=e.showTooltip??!1;Wt.setAttribute("aria-label",d),Dt&&qn({anchor:Wt,trigger:Dt,text:()=>Wt?.getAttribute("aria-label")??d,enabled:c}),Dt.style.display="",Wt.disabled=Hl()||wa.isStreaming()&&!Ol()}else{let e=oo(s);if(e){Wt=e.button,Dt=e.wrapper;let t=Nt&&Nt.parentElement===Bt?Nt:null;Bt?Bt.insertBefore(Dt,t):mt?.appendChild(Dt),pn&&(pn.micButton=Wt),pn?.addListener(Wt,"click",Mp),Wt.disabled=Hl()||wa.isStreaming()&&!Ol()}}else Wt&&Dt&&(Dt.style.display="none",ce(s.voiceRecognition?.provider)?wa.isVoiceActive()&&wa.toggleVoice():np&&vp());if(Hp(),!0===s.attachments?.enabled){if(zt&&Ft){zt.style.display="";let e=s.attachments??{};jt&&(jt.accept=(e.allowedTypes??br).join(","),jt.multiple=(e.maxFiles??4)>1),xr&&xr.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}else{let e=s.attachments??{};Ut||(Ut=L("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ut.style.display="none",(ut.parentElement??mt).insertBefore(Ut,ut)),jt||(jt=document.createElement("input"),jt.type="file",jt.accept=(e.allowedTypes??br).join(","),jt.multiple=(e.maxFiles??4)>1,jt.style.display="none",jt.setAttribute("aria-label","Attach files"),(ut.parentElement??mt).insertBefore(jt,ut)),zt=L("div","persona-send-button-wrapper"),Ft=L("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Yn} ${Zn}`),Ft.type="button",Ft.setAttribute("aria-label",e.buttonTooltipText??"Attach file");let t=e.buttonIconName??"paperclip";Ft.style.fontSize="18px",Ft.style.lineHeight="1";let r=K(t,24,"currentColor",1.5);r?Ft.appendChild(r):Ft.textContent="📎",Ft.addEventListener("click",e=>{e.preventDefault(),jt?.click()}),zt.appendChild(Ft);let n=e.buttonTooltipText??"Attach file";qn({anchor:Ft,trigger:zt,text:()=>Ft?.getAttribute("aria-label")??n}),Pt?Pt.append(zt):mt.appendChild(zt),pn&&(pn.attachmentButton=Ft,pn.attachmentInput=jt??void 0,pn.attachmentPreviews=Ut??void 0),!xr&&jt&&Ut&&(xr=In.fromConfig(e,Er),xr.setPreviewsContainer(Ut),pn?.addListener(jt,"change",async()=>{xr&&jt?.files&&(await xr.handleFileSelect(jt.files),jt.value="")}))}if(st.querySelector(".persona-attachment-drop-overlay")?.remove(),st.appendChild(pc(s.attachments?.dropOverlay)),Ft){let e=s.attachments??{},t=e.buttonTooltipText??"Attach file";Ft.setAttribute("aria-label",t),Ft.textContent="";let r=K(e.buttonIconName??"paperclip",24,"currentColor",1.5);r?Ft.appendChild(r):Ft.textContent="📎",zt&&qn({anchor:Ft,trigger:zt,text:()=>Ft?.getAttribute("aria-label")??t})}}else zt&&(zt.style.display="none"),xr&&xr.clearAttachments(),st.querySelector(".persona-attachment-drop-overlay")?.remove();let be=s.sendButton??{},ve=be.useIcon??!1,ke=be.iconText??"↑",Me=be.iconName,Ie=be.tooltipText??"Send message",Ee=be.showTooltip??!1,Ne=be.size,Re=parseFloat(Ne??"")||40,$e=be.backgroundColor,We=be.textColor;if(ve){if(ht.style.width=Ne??"",ht.style.height=Ne??"",ht.style.minWidth=Ne??"",ht.style.minHeight=Ne??"",ht.style.fontSize="18px",ht.style.lineHeight="1",ht.style.color=We||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!wa.isStreaming())if(ht.innerHTML="",Me){let e=parseFloat(be.iconSize??"")||Math.round(.5*Re),t=We?.trim()||"currentColor",r=be.iconStrokeWidth??2,n=K(Me,e,t,r),o=K(be.stopIconName??"square",e,t,r);n&&o?ht.appendChild(ro(n,o)):n?ht.appendChild(n):ht.textContent=ke}else ht.textContent=ke;ht.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Yn}`,$e?(ht.style.backgroundColor=$e,ht.classList.remove("persona-bg-persona-primary")):(ht.style.backgroundColor="",ht.classList.add("persona-bg-persona-primary"))}else ht.textContent=s.copy?.sendButtonLabel??"Send",ht.style.width="",ht.style.height="",ht.style.minWidth="",ht.style.minHeight="",ht.style.fontSize="",ht.style.lineHeight="",ht.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",$e?(ht.style.backgroundColor=$e,ht.classList.remove("persona-bg-persona-accent")):ht.classList.add("persona-bg-persona-accent"),We?ht.style.color=We:ht.classList.add("persona-text-white");be.borderWidth?(ht.style.borderWidth=be.borderWidth,ht.style.borderStyle="solid"):(ht.style.borderWidth="",ht.style.borderStyle=""),be.borderColor?ht.style.borderColor=be.borderColor:ht.style.borderColor="",be.paddingX?(ht.style.paddingLeft=be.paddingX,ht.style.paddingRight=be.paddingX):(ht.style.paddingLeft="",ht.style.paddingRight=""),be.paddingY?(ht.style.paddingTop=be.paddingY,ht.style.paddingBottom=be.paddingY):(ht.style.paddingTop="",ht.style.paddingBottom=""),wa.isStreaming()||ht.setAttribute("aria-label",Ie),Vl(),Nt&&qn({anchor:ht,trigger:Nt,text:()=>ht.getAttribute("aria-label")??Ie,enabled:Ee}),Ln(),aa();let De=$o(Ar.getState().activeModeIds,s.composer?.modes);Ar.setActiveModeIds(De),Br().length>0!=!!Or&&Sn(),Or?.render(De,Br());for(let e of[...zr.keys()])Ho(e,s.composer?.modeGroups)||zr.delete(e);zr.forEach(e=>e.repaint()),$r?.repaint(),bn?.resolve();let ze=Da(s,se());if(ra(),ze){lt.style.maxWidth=ze,lt.style.marginLeft="auto",lt.style.marginRight="auto",lt.style.width="100%",bt.style.maxWidth=ze,bt.style.marginLeft="auto",bt.style.marginRight="auto",bt.style.width="100%";for(let e of[mt,pt,Ut,gt])e&&(e.style.maxWidth=ze,e.style.marginLeft="auto",e.style.marginRight="auto",e.style.width="100%")}else{lt.style.maxWidth="",lt.style.marginLeft="",lt.style.marginRight="",lt.style.width="",bt.style.maxWidth="",bt.style.marginLeft="",bt.style.marginRight="",bt.style.width="";for(let e of[mt,pt,Ut,gt])e&&(e.style.maxWidth="",e.style.marginLeft="",e.style.marginRight="",e.style.width="")}let qe=s.statusIndicator??{};if(de(gt,mt,qe),le(gt,qe,wa?.getStatus()??"idle"),wa){let e=wa.getStatus();et(gt,(e=>"idle"===e?qe.idleText??Sr.idle:"connecting"===e?qe.connectingText??Sr.connecting:"connected"===e?qe.connectedText??Sr.connected:"error"===e?qe.errorText??Sr.error:"paused"===e?qe.pausedText??Sr.paused:"resuming"===e?qe.resumingText??Sr.resuming:Sr[e])(e),qe,e)}gt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let je="left"===qe.align?"persona-text-left":"center"===qe.align?"persona-text-center":"persona-text-right";gt.classList.add(je),un(),Gl(),Tn(),_e()},open(){pe()&&Nl(!0,"api")},close(){pe()&&Nl(!1,"api")},toggle(){pe()&&Nl(!ue,"api")},reconnect(){wa.reconnectNow()},clearChat(){so=!1,d.clear(),i.clear(),l.clear(),c.clear(),wa.clearMessages(),s.layout?.topFade&&(it.scrollTop=0),it.removeAttribute("data-persona-top-fade"),qa.clear(),Hi();try{localStorage.removeItem(rc),s.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${rc}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(s.clearChatHistoryStorageKey&&s.clearChatHistoryStorageKey!==rc)try{localStorage.removeItem(s.clearChatHistoryStorageKey),s.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${s.clearChatHistoryStorageKey}`)}catch(e){console.error("[AgentWidget] Failed to clear custom localStorage:",e)}let e=new CustomEvent("persona:clear-chat",{detail:{timestamp:(new Date).toISOString()}});window.dispatchEvent(e),H?.clear&&li(()=>H.clear(),"[AgentWidget] Failed to clear storage adapter:"),W={},Q.syncFromMetadata(),xr?.clearAttachments(),bi(),Gr(void 0),jr(void 0),Ka(),Le?.clear(),Pe?.reset(),Re?.update()},setMessage:e=>!(!ut||wa.isStreaming()||Hl()||(!ue&&pe()&&Nl(!0,"system"),ut.value=e,ut.dispatchEvent(new Event("input",{bubbles:!0})),0)),submitMessage(e){if(wa.isStreaming()||zl())return!1;let t=e?.trim()||ut.value.trim();return!!t&&(!ue&&pe()&&Nl(!0,"system"),ut.value="",ut.style.height="auto",Mr(),Qc(t,{consumeDraft:!1}),!0)},getComposerState:()=>Ar.getState(),setQuote(e){let t=e?.text?.trim();t&&jr({...e,text:t})},clearQuote(){jr(void 0)},startVoiceRecognition:()=>!wa.isStreaming()&&(ce(s.voiceRecognition?.provider)?(wa.isVoiceActive()||wa.isBargeInActive()||(!ue&&pe()&&Nl(!0,"system"),Os.manuallyDeactivated=!1,Ys(),wa.toggleVoice().then(()=>{Os.active=Us(),Ys(),Xs("user"),Os.active&&Cp()})),!0):!!np||!!yp()&&(!ue&&pe()&&Nl(!0,"system"),Os.manuallyDeactivated=!1,Ys(),bp("user"),!0)),stopVoiceRecognition:()=>ce(s.voiceRecognition?.provider)?!(!wa.isVoiceActive()&&!wa.isBargeInActive()||((wa.isBargeInActive()?wa.deactivateBargeIn():wa.toggleVoice()).then(()=>{Os.active=!1,Os.manuallyDeactivated=!0,Ys(),Xs("user"),Ap()}),0)):!!np&&(Os.manuallyDeactivated=!0,Ys(),vp("user"),!0),injectMessage:e=>(!ue&&pe()&&Nl(!0,"system"),wa.injectMessage(e)),injectAssistantMessage(e){!ue&&pe()&&Nl(!0,"system");let t=wa.injectAssistantMessage(e);return he&&(he=!1,me&&=(clearTimeout(me),null),setTimeout(()=>{wa&&!wa.isStreaming()&&wa.continueConversation()},100)),t},injectUserMessage:e=>(!ue&&pe()&&Nl(!0,"system"),wa.injectUserMessage(e)),injectSystemMessage:e=>(!ue&&pe()&&Nl(!0,"system"),wa.injectSystemMessage(e)),injectMessageBatch:e=>(!ue&&pe()&&Nl(!0,"system"),wa.injectMessageBatch(e)),injectComponentDirective:e=>(!ue&&pe()&&Nl(!0,"system"),wa.injectComponentDirective(e)),injectTestMessage(e){!ue&&pe()&&Nl(!0,"system"),wa.injectTestEvent(e)},connectStream:async(e,t)=>wa.connectStream(e,t),__pushEventStreamEvent(e){Ce&&(Oe(),Fe(e.type,e.payload))},showEventStream(){Ce&&tn()},hideEventStream(){He&&rn()},isEventStreamVisible:()=>He,listConversations:e=>wa.listConversations(e),getActiveConversationId:()=>wa.getActiveConversationId(),openConversation:(e,t)=>Lc(r=>r.openHistoryConversation(e,{focusComposer:!0===t?.focus})),startNewConversation:e=>Lc(t=>t.startNewConversation({focusComposer:!0===e?.focus})),warmSession(){Bc()},deleteConversation:e=>Lc(t=>t.deleteHistoryConversation(e)),renameConversation:(e,t)=>Lc(r=>r.updateHistoryConversation(e,{title:t})),setConversationStarred:(e,t)=>Lc(r=>r.updateHistoryConversation(e,{starred:t})),clearConversationHistory:e=>Lc(t=>t.clearConversationHistory(e)),resetHistoryIdentity:()=>Lc(e=>e.resetHistoryIdentity()),async getVisitorToken(){let e=$d;if(!e)return null;let t=await e.get();return e===$d?t:null},getHistoryIdentityStatus(){let e=yc?.historyProvider;return e?e.getIdentityStatus():xc()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory:e=>xc()?Lc(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...void 0===e?.focus?{}:{focus:e.focus}})):Promise.resolve(),hideHistory(e){yc?.closeHistory(void 0===e?.restoreFocus?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible:()=>qe,showArtifacts(){Fl(s)&&(so=!1,co=!0,ea(),zn?.setMobileOpen(!0))},hideArtifacts(){Fl(s)&&(so=!0,ea())},upsertArtifact:e=>Fl(s)?("panel"===Jr(s.features?.artifacts,{artifactType:e.artifactType,..."markdown"===e.artifactType&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})&&(so=!1,co=!0),wa.upsertArtifact(e)):null,selectArtifact(e){Fl(s)&&wa.selectArtifact(e)},clearArtifacts(){Fl(s)&&wa.clearArtifacts()},getArtifacts:()=>wa?.getArtifacts()??[],getSelectedArtifactId:()=>wa?.getSelectedArtifactId()??null,focusInput:()=>!(X&&!ue&&!se()||!ut||(ut.focus(),0)),async resolveApproval(e,t,r){let n=wa.getMessages().find(t=>"approval"===t.variant&&t.approval?.id===e);if(!n?.approval)throw Error(`Approval not found: ${e}`);if("webmcp"!==n.approval.toolType)return wa.resolveApproval(n.approval,t,r);wa.resolveWebMcpApproval(n.id,t)},setFollowUpSuggestions(e){(e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length)return void Na();let r=wa?wa.getMessages():[];Ca=t,Sa=!0,ka=Ma(r),Aa=Ia(r),Ba(r)})(e)},clearFollowUpSuggestions(){Na()},getMessages:()=>wa.getMessages(),getStatus:()=>wa.getStatus(),getPersistentMetadata:()=>({...W}),updatePersistentMetadata(e){V(e)},on:(e,t)=>R.on(e,t),off(e,t){R.off(e,t)},isOpen:()=>pe()&&ue,isVoiceActive:()=>Os.active,toggleReadAloud(e){wa.toggleReadAloud(e)},stopReadAloud(){wa.stopSpeaking()},getReadAloudState:e=>wa.getReadAloudState(e),onReadAloudChange:e=>wa.onReadAloudChange(e),getState:()=>({open:pe()&&ue,launcherEnabled:X,voiceActive:Os.active,streaming:wa.isStreaming()}),showCSATFeedback(e){!ue&&pe()&&Nl(!0,"system");let t=lt.querySelector(".persona-feedback-container");t&&t.remove();let r=ec({onSubmit:async(t,r)=>{wa.isClientTokenMode()&&await wa.submitCSATFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e});lt.appendChild(r),r.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(e){!ue&&pe()&&Nl(!0,"system");let t=lt.querySelector(".persona-feedback-container");t&&t.remove();let r=tc({onSubmit:async(t,r)=>{wa.isClientTokenMode()&&await wa.submitNPSFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e});lt.appendChild(r),r.scrollIntoView({behavior:"smooth",block:"end"})},submitCSATFeedback:async(e,t)=>wa.submitCSATFeedback(e,t),submitNPSFeedback:async(e,t)=>wa.submitNPSFeedback(e,t),destroy(){mc(),null!=Od&&(clearInterval(Od),Od=null),d.clear(),i.clear(),l.clear(),c.clear(),ia.forEach(e=>e()),rt.remove(),ot?.remove(),Op?.destroy(),zp?.remove(),xa&&St.removeEventListener("click",xa)}};if((o?.debugTools||s.debug)&&typeof window<"u"){let e=window.AgentWidgetBrowser,t={controller:Cu,getMessages:Cu.getMessages,getStatus:Cu.getStatus,getMetadata:Cu.getPersistentMetadata,updateMetadata:Cu.updatePersistentMetadata,clearHistory:()=>Cu.clearChat(),setVoiceActive:e=>e?Cu.startVoiceRecognition():Cu.stopVoiceRecognition()};window.AgentWidgetBrowser=t,ia.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),r=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Cu.focusInput()};if(window.addEventListener("persona:focusInput",r),ia.push(()=>{window.removeEventListener("persona:focusInput",r)}),Ce){let e=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Cu.showEventStream()},r=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Cu.hideEventStream()};window.addEventListener("persona:showEventStream",e),window.addEventListener("persona:hideEventStream",r),ia.push(()=>{window.removeEventListener("persona:showEventStream",e),window.removeEventListener("persona:hideEventStream",r)})}let n=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Cu.showHistory()},o=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Cu.hideHistory()};window.addEventListener("persona:showHistory",n),window.addEventListener("persona:hideHistory",o),ia.push(()=>{window.removeEventListener("persona:showHistory",n),window.removeEventListener("persona:hideHistory",o)});let a=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Cu.showArtifacts()},s=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Cu.hideArtifacts()},i=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==t||r?.artifact&&Cu.upsertArtifact(r.artifact)},l=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==t||"string"==typeof r?.id&&Cu.selectArtifact(r.id)},d=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Cu.clearArtifacts()};window.addEventListener("persona:showArtifacts",a),window.addEventListener("persona:hideArtifacts",s),window.addEventListener("persona:upsertArtifact",i),window.addEventListener("persona:selectArtifact",l),window.addEventListener("persona:clearArtifacts",d),ia.push(()=>{window.removeEventListener("persona:showArtifacts",a),window.removeEventListener("persona:hideArtifacts",s),window.removeEventListener("persona:upsertArtifact",i),window.removeEventListener("persona:selectArtifact",l),window.removeEventListener("persona:clearArtifacts",d)})}let Su=function(e){return e?!0===e?{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}(s.persistState);if(Su&&pe()){let t=function(e){try{let t="local"===e?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}(Su.storage),r=`${Su.keyPrefix}widget-open`,n=`${Su.keyPrefix}widget-voice`,o=`${Su.keyPrefix}widget-voice-mode`;if(t){let a=Su.persist?.openState&&"true"===t.getItem(r),s=Su.persist?.voiceState&&"true"===t.getItem(n),i=Su.persist?.voiceState&&"true"===t.getItem(o);if(a&&(Op?.setPanelOpen(!0,"auto"),setTimeout(()=>{Cu.open(),setTimeout(()=>{if(s||i)Cu.startVoiceRecognition();else if(Su.persist?.focusInput){let t=e.querySelector("textarea");t&&t.focus()}},100)},0)),Su.persist?.openState&&(R.on("widget:opened",()=>{t.setItem(r,"true")}),R.on("widget:closed",()=>{t.setItem(r,"false")})),Su.persist?.voiceState&&(R.on("voice:state",e=>{t.setItem(n,e.active?"true":"false")}),R.on("user:message",e=>{t.setItem(o,e.viaVoice?"true":"false")})),Su.clearOnChatClear){let e=()=>{t.removeItem(r),t.removeItem(n),t.removeItem(o)},a=()=>e();window.addEventListener("persona:clear-chat",a),ia.push(()=>{window.removeEventListener("persona:clear-chat",a)})}}}if(q&&pe()&&(Op?.setPanelOpen(!0,"auto"),setTimeout(()=>{Cu.open()},0)),Pl(),!ns){let e=be(()=>{wa&&(Qa++,qa.clear(),yl(lt,wa.getMessages(),fe))});ia.push(e)}S=()=>{wa&&(Qa++,qa.clear(),yl(lt,wa.getMessages(),fe))},wa.getMessages().length>0&&fl(),T=()=>{wa&&(Qa++,qa.clear(),yl(lt,wa.getMessages(),fe))};let ku=U(()=>{wa&&(Qa++,qa.clear(),yl(lt,wa.getMessages(),fe))});ia.push(ku);let Au=Dl(()=>{wa&&(Qa++,qa.clear(),yl(lt,wa.getMessages(),fe),Wl()?.updateInlineArtifactBlocks(lt,ao.artifacts,{suppressTransition:!0}),ea())});return ia.push(Au),Cu},gc=(e,t)=>{let r=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(r);return o?Math.max(0,t*parseFloat(o[1])/100):420},fc=(e,t)=>{let r=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=r?"":"100%",e.style.display=r?"":"flex",e.style.flexDirection=r?"":"column",e.style.flex=r?"":"1 1 auto",e.style.minHeight=r?"":"0",e.style.minWidth=r?"":"0"},yc=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=""},bc=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",yc(e)},vc=e=>{e.style.transition=""},wc=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=""},xc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Cc=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Sc=(e,t,r,n)=>{t?(e.style.boxSizing="border-box",e.style.padding=r,e.style.background=n):(e.style.padding="",e.style.background="",e.style.boxSizing="")},kc=(e,t)=>qs(t)?((e,t)=>{let{ownerDocument:r}=e,n=e.parentElement;if(!n)throw Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if("BODY"===o||"HTML"===o)throw Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),l=r.createElement("div"),d=r.createElement("aside"),c=r.createElement("div"),p=!(t?.launcher?.enabled??1)||(t?.launcher?.autoExpand??!1);i.dataset.personaDockRole="push-track",l.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),n.insertBefore(s,e),l.appendChild(e);let u=null,h=()=>{u?.disconnect(),u=null},m=null,g=()=>{m=!0===t?.launcher?.detachedPanel?(e=>{let t=Ha(e),r=t.components?.panel,n=(e,r)=>null==e||""===e?r:ya(t,e)??e;return{inset:n(r?.inset,ta),canvasBackground:n(r?.canvasBackground,ra)}})(t):null};g();let f=()=>{((e,t,r,n,o,a,s,i)=>{let l=_s(a),d="push"===l.reveal,c=null!=i,p=i?.inset??"",u=i?.canvasBackground??"";((e,t,r,n,o)=>{o?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,n),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(n))})(e,t,r,n,d),((e,t,r,n,o,a)=>{let s=a?t:e;"left"===o?s.firstElementChild!==n&&s.replaceChildren(n,r):s.lastElementChild!==n&&s.replaceChildren(r,n)})(e,t,r,n,l.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=l.side,e.dataset.personaDockOpen=s?"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",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let h=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,g=a?.launcher?.mobileBreakpoint??640,f=null!=h&&h.innerWidth<=g;if(m&&f&&s)e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),wc(t),vc(n),bc(n),xc(r),Cc(o,n),Sc(n,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String(a?.launcher?.zIndex??1e5),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(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",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");else if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),bc(n),((e,t)=>{!1===t?e.style.maxHeight="":(e.style.maxHeight="100vh",e.style.maxHeight=t)})(n,l.maxHeight),Sc(n,c&&s,p,u),"overlay"===l.reveal){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",wc(t),vc(n),xc(r),Cc(o,n);let a=l.animate?"transform 180ms ease":"none",i="right"===l.side?"translateX(100%)":"translateX(-100%)",d=s?"translateX(0)":i;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=l.width,n.style.maxWidth=l.width,n.style.minWidth=l.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=a,n.style.transform=d,n.style.pointerEvents=s?"auto":"none",n.style.zIndex="2","right"===l.side?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if("push"===l.reveal){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",vc(n),yc(n),Cc(o,n);let a=gc(l.width,e.clientWidth),i=Math.max(0,e.clientWidth),d=l.animate?"margin-left 180ms ease":"none",c="right"===l.side?s?-a:0:s?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=`${i+a}px`,t.style.transition=d,t.style.marginLeft=`${c}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${i}px`,r.style.maxWidth=`${i}px`,r.style.minWidth=`${i}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=l.width,n.style.minWidth=l.width,n.style.maxWidth=l.width,n.style.position="relative",n.style.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",wc(t),yc(n),xc(r),Cc(o,n);let a="emerge"===l.reveal;a?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let i=s?l.width:"0px",d=l.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease"+(c?", padding 180ms ease":""):"none",u=!s;if(n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${i}`,n.style.width=i,n.style.maxWidth=i,n.style.minWidth=i,n.style.minHeight="0",((e,t)=>{!1===t?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")})(n,l.maxHeight),n.style.overflow=a||u?"hidden":"visible",n.style.transition=d,a){n.style.alignItems="right"===l.side?"flex-start":"flex-end";let t=c?`calc(${gc(l.width,e.clientWidth)}px - (2 * ${p}))`:l.width;o.style.width=t,o.style.minWidth=t,o.style.maxWidth=t,o.style.boxSizing="border-box"}}})(s,i,l,d,c,t,p,m)},y=null,b=()=>{y?.(),y=null,!0===t?.launcher?.detachedPanel&&"auto"===t?.colorScheme&&(y=Wa(()=>{g(),f()}))},v=!1,w=()=>{f(),h(),"push"===_s(t).reveal&&typeof ResizeObserver<"u"&&(u=new ResizeObserver(()=>{f()}),u.observe(s)),p&&!v&&"true"!==s.dataset.personaDockMobileFullscreen&&(v=!0,((e,t)=>{let r=e.parentElement;if(!r)return;let n=e.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(n);let o=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),o&&!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."+(!1===t.maxHeight?" 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.")})(s,_s(t)))},x=s.ownerDocument.defaultView,C=()=>{w()};return x?.addEventListener("resize",C),"push"===_s(t).reveal?(i.appendChild(l),i.appendChild(d),s.appendChild(i)):(s.appendChild(l),s.appendChild(d)),w(),b(),{mode:"docked",host:c,shell:s,syncWidgetState(e){let t=!e.launcherEnabled||e.open;p!==t&&(p=t,w())},updateConfig(e){t=e,!1===(t?.launcher?.enabled??!0)&&(p=!0),g(),w(),b()},destroy(){x?.removeEventListener("resize",C),y?.(),y=null,h(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),s.remove()}}})(e,t):((e,t)=>{let r=e.ownerDocument.createElement("div");return fc(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(e){fc(r,e)},destroy(){r.remove()}}})(e,t),Ac=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let r=t.head.querySelector("link[data-persona]");if(!r)return;let n=r.cloneNode(!0);e.insertBefore(n,e.firstChild)},Mc=[],Ic=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Tc=new Set(["button","a","input","select","textarea","details","summary"]),Ec=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Lc=/\b(product|card|item|listing|result)\b/i,Pc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i;function Bc(e){let t="string"==typeof e.className?e.className:"";if(Lc.test(t)||e.id&&Lc.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&Lc.test(r.value))return!0}return!1}function Nc(e){return Pc.test((e.textContent??"").trim())}function Rc(e){let t=e.querySelectorAll("a[href]");for(let e=0;e<t.length;e++){let r=t[e].getAttribute("href")??"";if(r&&"#"!==r&&!r.toLowerCase().startsWith("javascript:"))return!0}return!1}function Hc(e){let t=e.match(Pc);return t?t[0]:null}function $c(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 r=e.querySelector("h1, h2, h3, h4, h5, h6");return r?.textContent?.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function Wc(e){return Bc(e)&&Nc(e)&&(Rc(e)||function(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}(e))?5200:0}function Dc(e){return!Bc(e)||Nc(e)||!Rc(e)||(e.textContent??"").trim().length<20||!e.querySelector("h1, h2, h3, h4, h5, h6, .title")&&!e.querySelector(".snippet, .description, p")?0:2800}let Fc=[{id:"commerce-card",scoreElement:e=>Wc(e),shouldSuppressDescendant(e,t,r){if(t===e||!e.contains(t))return!1;if("static"===r.interactivity){let e=r.text.trim();return!!(0===e.length||Pc.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(0===Wc(e))return null;let{title:r,href:n}=$c(e),o=Hc((e.textContent??"").trim())??Hc(t.text)??"",a=function(e){let t=[],r=e=>{let r=e.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(e=>r(e.textContent??"")),e.querySelectorAll('[role="button"]').forEach(e=>r(e.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(e=>{r(e.value??"")}),t.slice(0,6)}(e);return[n&&r?`[${r}](${n})${o?`: ${o}`:""}`:r?`${r}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join("\n")}},{id:"result-card",scoreElement:e=>Dc(e),formatSummary(e,t){if(0===Dc(e))return null;let{title:r,href:n}=$c(e);return[n&&r?`[${r}](${n})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join("\n")}}];function Oc(e){return typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}let zc=["data-testid","data-product","data-action","data-id","data-name","data-type"];function qc(e){let t=e.tagName.toLowerCase(),r=e.getAttribute("role");return"a"===t&&e.hasAttribute("href")?"navigable":"input"===t||"select"===t||"textarea"===t||"textbox"===r||"combobox"===r||"listbox"===r||"spinbutton"===r?"input":"button"===t||"button"===r||Tc.has(t)||r&&Ec.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||"true"===e.getAttribute("contenteditable")?"clickable":"static"}function jc(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility)return!1}catch{}return"none"!==e.style.display&&"hidden"!==e.style.visibility}function _c(e){let t={},r=e.id;r&&(t.id=r);let n=e.getAttribute("href");n&&(t.href=n);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let i=e.getAttribute("name");i&&(t.name=i);let l=e.getAttribute("role");l&&(t.role=l);for(let r=0;r<e.attributes.length;r++){let n=e.attributes[r];n.name.startsWith("data-")&&(t[n.name]=n.value)}return t}function Uc(e){let t=e.tagName.toLowerCase();if(e.id){let t=`#${Oc(e.id)}`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}for(let r of zc){let n=e.getAttribute(r);if(n){let o=`${t}[${r}="${Oc(n)}"]`;try{if(1===e.ownerDocument.querySelectorAll(o).length)return o}catch{}}}let r=Array.from(e.classList).filter(e=>e&&!e.startsWith("persona-")).slice(0,3);if(r.length>0){let n=`${t}.${r.map(e=>Oc(e)).join(".")}`;try{if(1===e.ownerDocument.querySelectorAll(n).length)return n}catch{}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0){let t=`${n}:nth-of-type(${r+1})`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}}}let n=e.parentElement;if(n){let r=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function Vc(e,t){let r=e.tagName.toLowerCase(),n=(e.textContent??"").trim().substring(0,t);return{selector:Uc(e),tagName:r,text:n,role:e.getAttribute("role"),interactivity:qc(e),attributes:_c(e)}}function Gc(e,t,r,n){let o=function(e){return"static"===e?100:3e3}(t.interactivity),a=null;for(let s of r){let r=s.scoreElement(e,t,n);r>0&&(o+=r,s.formatSummary&&!a&&(a=s))}return{score:o,formattingRule:a}}function Kc(e,t){for(let r of e)if(t.el!==r.el&&r.formattingRule?.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}let Jc={components:{panel:{borderRadius:"0",shadow:"none"}}},Qc={id:"shop",label:"Shopping Assistant",config:{theme:{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"}}},launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"🛍️",position:"bottom-right",width:v},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"]}},Xc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Jc}},Yc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Jc}},Zc={shop:Qc,minimal:Xc,fullscreen:Yc},ep=typeof document<"u"?document.currentScript?.src??null:null,tp=(e,t=`host ${e} alongside it`)=>()=>{let r=ep?.replace(/index\.global\.js($|\?)/,`${e}$1`);return r&&r!==ep?import(r):Promise.reject(Error(`Could not derive the ${e} URL from the widget script URL (${ep??"unavailable"}). Self-hosted deployments that rename index.global.js should ${t}.`))};return(e=>{Ze=e})(tp("webmcp-polyfill.js","install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp")),fe(tp("markdown-parsers.js")),Ve(tp("client-stream.js")),hr(tp("client-history.js")),$r(tp("ui-extras.js")),jr(tp("session-actions.js")),_d(tp("history-shell.js")),(e=>{un=e})(tp("runtype-tts.js","host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly")),Vo(tp("context-mentions.js")),Qo(tp("context-mentions-inline.js")),Dd(tp("history-view.js")),Ps(tp("animations-extra.js","host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin")),vl(tp("approval-ui.js")),ln(tp("voice-runtime.js")),Hl(tp("artifacts-ui.js")),bd(tp("forms-ui.js")),$(tp("icons-extra.js","host icons-extra.js alongside it, or register the icons they use via registerIcons()")),st(tp("webmcp-runtime.js")),fn(tp("session-reconnect.js")),kl(tp("event-stream-view.js")),e.ASK_USER_QUESTION_CLIENT_TOOL=Vt,e.ASK_USER_QUESTION_PARAMETERS_SCHEMA=Ut,e.ASK_USER_QUESTION_TOOL_NAME=ht,e.AgentWidgetClient=Lr,e.AgentWidgetSession=Cn,e.AttachmentManager=In,e.BrowserSpeechEngine=tn,e.DEFAULT_COMPONENTS=ga,e.DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH="440px",e.DEFAULT_FLOATING_LAUNCHER_WIDTH=v,e.DEFAULT_PALETTE=da,e.DEFAULT_SEMANTIC=ua,e.DEFAULT_WIDGET_CONFIG=I,e.HistoryProviderError=Pr,e.PRESETS=Zc,e.PRESET_FULLSCREEN=Yc,e.PRESET_MINIMAL=Xc,e.PRESET_SHOP=Qc,e.ReadAloudController=rn,e.SUGGEST_REPLIES_CLIENT_TOOL=Ft,e.SUGGEST_REPLIES_PARAMETERS_SCHEMA=Dt,e.SUGGEST_REPLIES_TOOL_NAME=Wt,e.THEME_ZONES={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"},e.VERSION=dr,e.WEBMCP_TOOL_PREFIX=Je,e.applyFeaturePreferences=pd,e.applyThemeVariables=$a,e.attachHeaderToContainer=ii,e.buildComposer=yi,e.buildDefaultHeader=ui,e.buildHeader=si,e.buildHeaderWithLayout=fi,e.buildMinimalHeader=hi,e.builtInClientToolsForDispatch=Gt,e.canonicalArtifactDisplayMode=Vr,e.collectEnrichedPageContext=function(e={}){let t=function(e){let t=e.options??{},r=t.maxElements??e.maxElements??80,n=t.excludeSelector??e.excludeSelector??".persona-host",o=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,s=t.root??e.root,i=t.mode??"structured",l=t.maxCandidates??Math.max(500,10*r),d=e.rules??Fc;return"simple"===i&&e.rules&&e.rules.length>0?(typeof console<"u"&&"function"==typeof console.warn&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.'),d=[]):"simple"===i&&(d=[]),{mode:i,maxElements:r,maxCandidates:l,excludeSelector:n,maxTextLength:o,visibleOnly:a,root:s,rules:d}}(e),r=t.root??document.body;return r?"simple"===t.mode?function(e,t){let r=[],n=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=o.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let t=a,s=t.tagName.toLowerCase();if(Ic.has(s)){a=o.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){a=o.nextNode();continue}}catch{}if(e.visibleOnly&&!jc(t)){a=o.nextNode();continue}let i=Vc(t,e.maxTextLength),l=i.text.length>0,d=Object.keys(i.attributes).length>0&&!Object.keys(i.attributes).every(e=>"role"===e);if(!l&&!d){a=o.nextNode();continue}n.has(i.selector)||(n.add(i.selector),r.push(i))}a=o.nextNode()}let s=[],i=[];for(let e of r)"static"===e.interactivity?i.push(e):s.push(e);return[...s,...i].slice(0,e.maxElements)}(t,r):function(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,o=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let t=i,l=t.tagName.toLowerCase();if(Ic.has(l)){i=s.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!jc(t)){i=s.nextNode();continue}let d=Vc(t,e.maxTextLength),c=d.text.length>0,p=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(e=>"role"===e);if(!c&&!p||n.has(d.selector)){i=s.nextNode();continue}n.add(d.selector);let{score:u,formattingRule:h}=Gc(t,d,e.rules,r);o.push({el:t,domIndex:a,enriched:d,score:u,formattingRule:h}),a+=1}i=s.nextNode()}o.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),n=+("static"===t.enriched.interactivity);return r===n?t.score===e.score?e.domIndex-t.domIndex:t.score-e.score:r-n});let l=[];for(let t of o){if(l.length>=e.maxElements)break;Kc(l,t)||l.push(t)}return l.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),n=+("static"===t.enriched.interactivity);return r===n?1===r&&t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex:r-n}),l.map(e=>{let t;if(e.formattingRule?.formatSummary){let n=e.formattingRule.formatSummary(e.el,e.enriched,r);n&&(t=n)}let n={...e.enriched};return t&&(n.formattedSummary=t),n})}(t,r):[]},e.componentRegistry=Ml,e.createActionManager=Ld,e.createAgentExperience=mc,e.createAskUserQuestionBubble=(e,t)=>{let r=L("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let n=St(t);Mt(r,n);let o=L("span","persona-ask-stub-label"),{complete:a}=kt(e);return o.textContent=a?"Awaiting your response…":"Preparing options…",r.appendChild(o),r},e.createBubbleWithLayout=(e,t,r,n,o,a)=>{let s=r??{};return"user"===e.role&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):"assistant"===e.role&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Pi(e,t,r,n,0,a)},e.createCSATFeedback=ec,e.createComboButton=pi,e.createComponentMiddleware=function(){let e=Kd();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}},e.createComponentStreamParser=Kd,e.createDefaultSanitizer=Le,e.createDirectivePostprocessor=e=>{let t=xe(e);return e=>{let r=[],n=Ie(e,r),o=t(n);return r.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n=`<div class="persona-form-directive" data-tv-form="${Ae(t)}"></div>`;o=o.replace(r,n)}),o}},e.createDropdownMenu=li,e.createFlexibleJsonStreamParser=e=>{let t=null,r=0,n=e||(e=>{if(!e||"object"!=typeof e)return null;let t=e=>"string"==typeof e?Xt(e):null;if(e.component&&"string"==typeof e.component)return"string"==typeof e.text?Xt(e.text):"";if("init"===e.type&&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 o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(e.length<=r)return null===t?null:{text:t,raw:e};try{let r=(0,ut.parse)(e,ut.STR|ut.OBJ),o=n(r);null!==o&&(t=o)}catch{}return r=e.length,{text:t||"",raw:e}},close:()=>{}}},e.createIconButton=di,e.createImagePart=function(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}},e.createJsonStreamParser=ir,e.createLabelButton=ci,e.createLocalStorageAdapter=Nd,e.createMarkdownProcessor=we,e.createMarkdownProcessorFromConfig=xe,e.createMessageActions=Li,e.createNPSFeedback=tc,e.createPlainTextParser=ar,e.createRegexJsonParser=sr,e.createSplitButton=function(e){let{label:t,icon:r,iconSize:n,iconOnly:o,menuItems:a,onSelect:s,onPrimary:i,position:l="bottom-left",portal:d,chevronLabel:c="More options",chevronIconSize:p,className:u,primaryClassName:h,chevronClassName:m}=e,g=L("div","persona-split-btn"+(u?" "+u:"")),f={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:i},y=o&&r?di({...f,icon:r,size:n??14}):ci({...f,icon:r,iconSize:n??14}),b=di({icon:"chevron-down",label:c,size:p??14,className:"persona-split-btn-chevron"+(m?" "+m:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});g.append(y,b);let v=null,w=()=>{if(v)return v;let e=("function"==typeof d?d():d)??void 0;return v=li({items:a,onSelect:s,anchor:g,position:l,portal:e,onOpenChange:e=>{b.setAttribute("aria-expanded",e?"true":"false")}}),e||g.appendChild(v.element),v};return g.isConnected?w():requestAnimationFrame(()=>{v||w()}),b.addEventListener("click",e=>{e.stopPropagation(),w().toggle()}),{element:g,primaryButton:y,chevronButton:b,openMenu:()=>w().show(),closeMenu:()=>v?.hide(),toggleMenu:()=>w().toggle(),destroy:()=>{v?.destroy(),g.remove()}}},e.createStandardBubble=Pi,e.createTextPart=fr,e.createTheme=Ca,e.createThemeObserver=Wa,e.createToggleGroup=function(e){let{items:t,selectedId:r,onSelect:n,className:o}=e,a=L("div","persona-toggle-group"+(o?" "+o:""));a.setAttribute("role","group");let s=r,i=[];function l(){for(let e of i)e.btn.setAttribute("aria-pressed",e.id===s?"true":"false")}for(let e of t){let t;e.icon?t=di({icon:e.icon,label:e.label,className:e.className,onClick:()=>{s=e.id,l(),n(e.id)}}):(t=L("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",()=>{s=e.id,l(),n(e.id)})),t.setAttribute("aria-pressed",e.id===s?"true":"false"),i.push({id:e.id,btn:t}),a.appendChild(t)}return{element:a,setSelected:function(e){s=e,l()}}},e.createTypingIndicator=Si,e.createWidgetHostLayout=kc,e.createXmlParser=lr,e.defaultActionHandlers=Td,e.defaultJsonActionParser=Md,e.defaultParseRules=Fc,e.detectColorScheme=Na,e.directivePostprocessor=e=>{let t=[],r=Ie(e,t),n=Se(r);return t.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=`<div class="persona-form-directive" data-tv-form="${Ae(t)}"></div>`;n=n.replace(r,o)}),n},e.ensureAskUserQuestionSheet=Ht,e.escapeHtml=ke,e.extractComponentDirectiveFromMessage=Yd,e.fileToImagePart=async function(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},n.onerror=()=>r(Error("Failed to read file")),n.readAsDataURL(e)})},e.formatEnrichedContext=function(e,t={}){if(0===e.length)return"No page elements found.";let r=t.mode??"structured",n=[];if("structured"===r){let t=e.map(e=>e.formattedSummary).filter(e=>!!e&&e.length>0);t.length>0&&n.push(`Structured summaries:\n${t.map(e=>`- ${e.split("\n").join("\n ")}`).join("\n")}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let t of e)"structured"===r&&t.formattedSummary||o[t.interactivity].push(t);if(o.clickable.length>0){let e=o.clickable.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}" (clickable)`);n.push(`Interactive elements:\n${e.join("\n")}`)}if(o.navigable.length>0){let e=o.navigable.map(e=>`- ${e.selector}${e.attributes.href?`[href="${e.attributes.href}"]`:""}: "${e.text.substring(0,100)}" (navigable)`);n.push(`Navigation links:\n${e.join("\n")}`)}if(o.input.length>0){let e=o.input.map(e=>`- ${e.selector}${e.attributes.type?`[type="${e.attributes.type}"]`:""}: "${e.text.substring(0,100)}" (input)`);n.push(`Form inputs:\n${e.join("\n")}`)}if(o.static.length>0){let e=o.static.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}"`);n.push(`Content:\n${e.join("\n")}`)}return n.join("\n\n")},e.generateAssistantMessageId=ct,e.generateMessageId=function(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`},e.generateStableSelector=Uc,e.generateUserMessageId=dt,e.getActiveTheme=Ha,e.getAgentWidgetHandles=()=>[...Mc],e.getColorScheme=Ra,e.getDisplayText=function(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("")},e.getHeaderLayout=gi,e.getImageParts=function(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)},e.getPreset=function(e){return Zc[e]},e.hasComponentDirective=Xd,e.hasImages=gr,e.headerLayouts=mi,e.initAgentWidget=e=>{let t,r=(e=>{if(typeof window>"u"||typeof document>"u")throw Error("Chat widget can only be mounted in a browser environment");if("string"==typeof e){let t=document.querySelector(e);if(!t)throw Error(`Chat widget target "${e}" was not found`);return t}return e})(e.target),n=!0===e.useShadowDom,o=r.ownerDocument,a=e.config,s=kc(r,a),i=[],l=(e,t)=>{let a=!(t?.launcher?.enabled??1)||qs(t),s=o.createElement("div");if(s.setAttribute("data-persona-root","true"),a&&(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0",s.style.minWidth="0"),n){let t=e.attachShadow({mode:"open"});t.appendChild(s),Ac(t,o)}else e.appendChild(s),Ac(e,o);return r.id&&s.setAttribute("data-persona-instance",r.id),s},d=()=>{s.syncWidgetState(t.getState())},c=()=>{let r=l(s.host,a);t=mc(r,a,{debugTools:e.debugTools}),i.forEach(e=>e()),i=[t.on("widget:opened",d),t.on("widget:closed",d)],d()},p=()=>{i.forEach(e=>e()),i=[],t.destroy()};c(),e.onChatReady?.();let u=e=>{p(),s.destroy(),s=kc(r,e),a=e,c()},h=new Proxy({update(e){let r=Ad(a??{},e),n=qs(a),o=qs(r),i=js(a),l=js(r);n!==o||i!==l?u(r):(a=r,s.updateConfig(a),t.update(e),d())},destroy(){p(),s.destroy();let t=Mc.indexOf(h);-1!==t&&Mc.splice(t,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},{get(e,r,n){if("host"===r)return s.host;if(r in e)return Reflect.get(e,r,n);let o=t[r];return"function"==typeof o?o.bind(t):o}});return Mc.push(h),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=h),h},e.isAskUserQuestionMessage=Ct,e.isComponentDirectiveType=function(e){return"object"==typeof e&&!!e&&"component"in e&&"string"==typeof e.component&&"props"in e&&"object"==typeof e.props},e.isDockedMountMode=qs,e.isHistoryProviderError=function(e){return e instanceof Pr},e.isSuggestRepliesMessage=Ot,e.isWebMcpToolName=rt,e.isWelcomeVisible=_i,e.latestAgentSuggestions=qt,e.listRegisteredStreamAnimations=()=>Array.from(ps.keys()),e.loadMarkdownParsers=ye,e.markdownPostprocessor=Se,e.mergeWithDefaults=E,e.normalizeContent=function(e){return"string"==typeof e?[{type:"text",text:e}]:e},e.normalizeMediaType=Gr,e.onMarkdownParsersReady=be,e.parseAskUserQuestionPayload=kt,e.parseSuggestRepliesPayload=zt,e.parseWidgetPreferenceSlice=id,e.pickBestVoice=en,e.pluginRegistry=xd,e.registerIcons=e=>{for(let[t,r]of Object.entries(e))O.set(t,r);V()>0&&!q&&_(!1)},e.registerStreamAnimationPlugin=hs,e.removeAskUserQuestionSheet=$t,e.renderComponentDirective=Jd,e.renderLoadingIndicatorWithFallback=ki,e.renderLucideIcon=K,e.resolveArtifactDisplay=Kr,e.resolveArtifactDisplayMode=Jr,e.resolveConfigPreferences=ud,e.resolveDockConfig=_s,e.resolveSanitizer=Pe,e.resolveTokens=ba,e.resolveWelcomeConfig=ji,e.stripWebMcpPrefix=tt,e.themeToCssVariables=Ma,e.unregisterStreamAnimationPlugin=e=>{cs.some(t=>t.name===e)||ps.delete(e)},e.validateImageFile=function(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10485760){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}},e.validateTheme=va,e}({});
8
+ e.Activity=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]],e.ArrowDown=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]],e.ArrowLeft=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]],e.ArrowRight=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]],e.ArrowUp=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]],e.ArrowUpRight=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]],e.AtSign=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]],e.Bot=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]],e.Check=[["path",{d:"M20 6 9 17l-5-5"}]],e.ChevronDown=[["path",{d:"m6 9 6 6 6-6"}]],e.ChevronLeft=[["path",{d:"m15 18-6-6 6-6"}]],e.ChevronRight=[["path",{d:"m9 18 6-6-6-6"}]],e.ChevronUp=[["path",{d:"m18 15-6-6-6 6"}]],e.Circle=[["circle",{cx:"12",cy:"12",r:"10"}]],e.Clipboard=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]],e.ClipboardCopy=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]],e.Clock=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]],e.CodeXml=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]],e.Copy=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]],e.Download=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]],e.Ellipsis=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]],e.EllipsisVertical=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]],e.ExternalLink=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]],e.Eye=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]],e.File=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]],e.FileCode=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]],e.FileSpreadsheet=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]],e.FileText=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]],e.History=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]],e.ImagePlus=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]],e.Loader=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]],e.LoaderCircle=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]],e.Maximize=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]],e.Menu=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]],e.MessageSquare=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]],e.Mic=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]],e.Minimize=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]],e.Minus=[["path",{d:"M5 12h14"}]],e.PanelLeft=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M9 3v18"}]],e.Paperclip=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]],e.Pencil=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]],e.Plus=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]],e.Quote=[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}]],e.RefreshCw=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]],e.Search=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]],e.Send=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]],e.ShieldAlert=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]],e.ShieldCheck=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]],e.ShieldX=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]],e.Square=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]],e.Star=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]],e.ThumbsDown=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]],e.ThumbsUp=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]],e.Trash=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]],e.Trash2=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]],e.Upload=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]],e.Volume2=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]],e.X=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]]})();let n=(e,t=24,r="currentColor",n=2)=>{if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],r=e[1];if(!r)return;let n=document.createElementNS("http://www.w3.org/2000/svg",t);Object.entries(r).forEach(([e,t])=>{"stroke"!==e&&n.setAttribute(e,String(t))}),o.appendChild(n)}),o},o=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function a(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];r[e]=o(t)&&o(n)?a(t,n):n}return r}let s=Symbol("persona.defaultsProvenance"),i=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function l(e,t=""){return Object.entries(e).flatMap(([e,r])=>{let n=t?`${t}.${e}`:e;return i(r)?l(r,n):[n]})}function d(e,t){for(let r of t.split(".")){if(!i(e)||!Object.prototype.hasOwnProperty.call(e,r))return"absent";if(void 0===(e=e[r]))return"clear"}return"explicit"}function c(e,t){return e?.[s]??t.filter(t=>"explicit"===d(e,t))}function p(e,t){return Object.defineProperty(e,s,{value:t,enumerable:!0,configurable:!0}),e}function u(e,t,r){return p(e,c(t,l(r)))}let h=Symbol("persona.panelAliasProvenance"),m=(e,t)=>null!=e&&Object.prototype.hasOwnProperty.call(e,t),g=(e,t)=>m(e,t)&&void 0!==e[t],f=e=>{let t=e?.[h];return t?{...t}:(e=>({launcherWidth:g(e?.launcher,"width"),legacyLauncherWidth:g(e,"launcherWidth"),sidebarWidth:g(e?.launcher,"sidebarWidth"),dockWidth:g(e?.launcher?.dock,"width")}))(e)},y=(e,t)=>(Object.defineProperty(e,h,{value:t,enumerable:!0,configurable:!0}),e),b=(e,t)=>y(e,f(t)),v="min(440px, calc(100vw - 24px))",w={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},x={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},C={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:{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:v,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",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)"},copy:{inputPlaceholder:"How can I help...",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:w,reasoningDisplay:x,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},S={},k={launcher:{variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},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"}}}};function A(e){return!0===e?.future?.v5Defaults?"v5":"v4"}function M(e){let t="v5"===A(e)?k:S;return a(C,t)}let I=M();function T(e,t){if(e||t)return e?t?a(e,t):e:t}function E(e){let t=M(e);return e?u(b({...t,...e,theme:T(t.theme,e.theme),darkTheme:T(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 r=t.features?.artifacts,n=e.features?.artifacts,o=t.features?.scrollToBottom,a=e.features?.scrollToBottom,s=t.features?.scrollBehavior,i=e.features?.scrollBehavior,l=t.features?.streamAnimation,d=e.features?.streamAnimation,c=t.features?.askUserQuestion,p=e.features?.askUserQuestion,u=t.features?.history,h=e.features?.history,m=void 0===r&&void 0===n?void 0:{...r,...n,layout:{...r?.layout,...n?.layout}},g=void 0===o&&void 0===a?void 0:{...o,...a},f=void 0===s&&void 0===i?void 0:{...s,...i},y=void 0===l&&void 0===d?void 0:{...l,...d},b=void 0===c&&void 0===p?void 0:{...c,...p,styles:{...c?.styles,...p?.styles}},v=void 0===u&&void 0===h?void 0:{...u,...h,copy:{...u?.copy,...h?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...void 0===g?{}:{scrollToBottom:g},...void 0===f?{}:{scrollBehavior:f},...void 0===m?{}:{artifacts:m},...void 0===y?{}:{streamAnimation:y},...void 0===b?{}:{askUserQuestion:b},...void 0===v?{}:{history:v}}})(),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,k):u(b(t),void 0,k)}let L=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},P=(e,t={},...r)=>{let n=document.createElement(e);if(t.className&&(n.className=t.className),void 0!==t.text&&(n.textContent=t.text),t.attrs)for(let[e,r]of Object.entries(t.attrs))n.setAttribute(e,r);if(t.style){let e=n.style,r=t.style;for(let t of Object.keys(r)){let n=r[t];null!=n&&(e[t]=n)}}let o=r.filter(e=>null!=e);return o.length>0&&n.append(...o),n},B=(...e)=>e.filter(Boolean).join(" "),N=e=>{let{fallbackImport:t,resetOnSetLoader:r=!1}=e,n=null,o=null,a=null;return{setLoader:e=>{n=e,r&&(o=null,a=null)},load:()=>o?Promise.resolve(o):a||(a=(n??t)().then(e=>(o=e,e)).catch(e=>{throw a=null,e}),a),provide:e=>{o=e},getSync:()=>o}},{setLoader:R,load:H}=N({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),$=R,W=H,D={activity:r.Activity,"arrow-down":r.ArrowDown,"arrow-up":r.ArrowUp,"arrow-up-right":r.ArrowUpRight,bot:r.Bot,"chevron-down":r.ChevronDown,"chevron-up":r.ChevronUp,"chevron-right":r.ChevronRight,"chevron-left":r.ChevronLeft,check:r.Check,clipboard:r.Clipboard,"clipboard-copy":r.ClipboardCopy,"code-xml":r.CodeXml,copy:r.Copy,file:r.File,"file-code":r.FileCode,"file-spreadsheet":r.FileSpreadsheet,"file-text":r.FileText,"image-plus":r.ImagePlus,loader:r.Loader,"loader-circle":r.LoaderCircle,mic:r.Mic,paperclip:r.Paperclip,quote:r.Quote,"refresh-cw":r.RefreshCw,search:r.Search,send:r.Send,"shield-alert":r.ShieldAlert,"shield-check":r.ShieldCheck,"shield-x":r.ShieldX,square:r.Square,"thumbs-down":r.ThumbsDown,"thumbs-up":r.ThumbsUp,upload:r.Upload,"volume-2":r.Volume2,x:r.X,"at-sign":r.AtSign,"arrow-left":r.ArrowLeft,"arrow-right":r.ArrowRight,"external-link":r.ExternalLink,ellipsis:r.Ellipsis,"ellipsis-vertical":r.EllipsisVertical,menu:r.Menu,"panel-left":r.PanelLeft,plus:r.Plus,minus:r.Minus,pencil:r.Pencil,trash:r.Trash,"trash-2":r.Trash2,download:r.Download,maximize:r.Maximize,minimize:r.Minimize,"message-square":r.MessageSquare,star:r.Star,eye:r.Eye,history:r.History},F="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("."),O=new Map(Object.entries(D)),z=new Set,q=!1,j=new Set,_=e=>{let t=[...j];e&&j.clear();for(let e of t)try{e()}catch{}},V=e=>q?()=>{}:(j.add(e),()=>{j.delete(e)}),U=()=>{let e=0;for(let t of[...z]){let r=O.get(t.name);if(!r)continue;z.delete(t),e++;let o=n(r,t.size,t.color,t.strokeWidth);if(o)for(t.el.removeAttribute("data-persona-icon-pending");o.firstChild;)t.el.appendChild(o.firstChild)}return e},G=!1,K=(e,t=24,r="currentColor",o=2)=>{let a=O.get(e);if(a)return n(a,t,r,o);if(F.includes(e)){G&&=!1;let n=((e,t,r)=>{let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",t),n.setAttribute("stroke-width",String(r)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("data-persona-icon-pending","true"),n})(t,r,o);if(z.size>=500){let e=z.values().next().value;e&&z.delete(e)}return z.add({el:n,name:e,size:t,color:r,strokeWidth:o}),W().then(e=>{if(!q){for(let[t,r]of Object.entries(e.EXTRA_LUCIDE_ICONS))O.has(t)||O.set(t,r);q=!0,U(),_(!0)}}).catch(e=>{G=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)}),n}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},J=["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"],Q=(e,t)=>{let r=L("div",["persona-message-bubble",e,...J].join(" "));return r.id=`bubble-${t}`,r.setAttribute("data-message-id",t),r},X=e=>{let t=L("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},Y=(e,t,o)=>{e.innerHTML="";let a=n(t?r.ChevronUp:r.ChevronDown,16,o,2);a?e.appendChild(a):e.textContent=t?"Hide":"Show"},Z=(e,t,r)=>{if(!r.expandable)return e.append(t),null;let n=L("div","persona-flex persona-items-center");Y(n,r.expanded,r.iconColor);let o=L("div",r.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return o.append(n),e.append(t,o),n},ee=e=>{let t=L("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 r=e.renderPreview?.();((e,t)=>null!=t&&("string"==typeof t?(e.textContent=t,!0):(e.appendChild(t),!0)))(t,r)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},te=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&Y(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"},re=(e,t,r)=>{let n=r.stateSet.has(e),o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),s=t.querySelector(`[data-persona-collapsed-preview="${r.previewKind}"]`);if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");i&&Y(i,n,r.iconColor),a.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")};function ne(e,t){let r="tool"===t?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[r]:{..."tool"===t?w:x,...!0===e?.future?.v5Defaults?k.features?.[r]:{},...e?.features?.[r]}}}}function oe(e,t){let r="tool"===t?"toolCallDisplay":"reasoningDisplay";return e?.features?.[r]?.variant??(e?.future?.v5Defaults?"row":"card")}function ae(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 se(e,t,o,a){if("row"!==oe(o,a))return e;e.className=`persona-message-bubble persona-${a}-bubble persona-activity-row`,e.dataset.activityKind=a,"tool"===a&&void 0===o.toolCall?.shadow&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let s=e.querySelector(":scope > button");if(!s)return e;s.className="persona-activity-header";let i="tool"===a?t.toolCall:t.reasoning,l="complete"!==i?.status,d=t.approval?.status??t.toolCall?.approvalStatus,c="denied"===d?"denied":"pending"===d?"awaiting-approval":!1===t.toolCall?.success?"error":l?"pending"===i?.status?"pending":"running":"done";e.dataset.activityState=c;let p=L("span","persona-activity-icon");p.dataset.activityIcon=c;let u="reasoning"===a?o.features?.reasoningDisplay?.iconName:void 0,h=u?K(u,16,"currentColor",2):"pending"===c?n(r.Circle,16,"currentColor",2):"awaiting-approval"===c?n(r.Clock,16,"currentColor",2):K({pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"}[c],16,"currentColor",2);h&&p.appendChild(h),s.querySelector(".persona-reasoning-header-icon")?.remove();let m="tool"===a?"toolCallDisplay":"reasoningDisplay",g=o.features?.[m]?.iconVisibility??(o.future?.v5Defaults?"active":"always");if(("always"===g||"active"===g&&"done"!==c)&&s.prepend(p),"tool"===a&&i){let e=L("span","persona-activity-duration");l&&i.startedAt&&e.setAttribute("data-tool-elapsed",String(i.startedAt));let r=("tool"===a?t.toolCall?.duration:void 0)??i.durationMs??(void 0!==i.completedAt&&void 0!==i.startedAt?i.completedAt-i.startedAt:void 0);e.textContent=void 0===r?"":ae(r),s.appendChild(e)}s.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),s.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let f=e.querySelector(":scope > .persona-border-t");return f?.classList.add("persona-activity-body"),f&&(f.id=`activity-details-${t.id}`,s.setAttribute("aria-controls",f.id)),e}function ie(e,t,r,n){let o=L("div","");o.id=`bubble-${e.id}`,o.dataset.messageId=e.id;let a=L("button","");a.type="button",a.dataset.expandHeader="true",a.dataset.bubbleType="tool",a.setAttribute("aria-expanded",String(r));let s=L("div","");"string"==typeof n?s.textContent=n:s.appendChild(n),Z(a,s,{expandable:!0,expanded:r,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let i=L("div","persona-border-t");return i.id=`activity-details-${e.id}`,i.style.display=r?"":"none",a.setAttribute("aria-controls",i.id),o.append(a,i),se(o,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),o.dataset.personaToolGroup="true","shimmer"===t.features?.toolCallDisplay?.loadingAnimation&&(o.dataset.activityGroupShimmer="true"),{bubble:o,body:i}}let le=(e,t,r)=>{let n="transient"===t.mode,o=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=((e,t)=>!1!==e.visible&&("transient"!==e.mode||"connecting"===t||"paused"===t||"resuming"===t||"error"===t))(t,r)||n&&o&&!1!==t.visible?"":"none",e.classList.toggle("persona-mt-2",!n),e.classList.toggle("persona-mb-2",n)},de=(e,t,r)=>{t.parentElement&&e.parentElement===t.parentElement&&("transient"===r.mode?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))};function ce(e){return"runtype"===e?.type||"custom"===e?.type}let{setLoader:pe,load:ue,provide:he,getSync:me}=N({fallbackImport:()=>import("./markdown-parsers-entry")}),ge=new Set,fe=pe,ye=()=>{let e=me();return e?Promise.resolve(e):ue().then(e=>((()=>{let e=[...ge];ge.clear();for(let t of e)try{t()}catch{}})(),e))},be=e=>me()?()=>{}:(ge.add(e),()=>{ge.delete(e)}),ve=me,we=e=>{let t=null;return r=>{let n=ve();if(!n)return ke(r);if(!t){let{Marked:r}=n,o=e?.markedOptions;t=new r({gfm:o?.gfm??!0,breaks:o?.breaks??!0,pedantic:o?.pedantic,silent:o?.silent});let a=(e=>{if(!e)return;let t={},r=e;if(r.heading){let e=r.heading;t.heading=(t,r,n)=>e({type:"heading",raw:n,depth:r,text:t,tokens:[]})}if(r.code){let e=r.code;t.code=(t,r,n)=>e({type:"code",raw:"",text:t,lang:r,escaped:n})}if(r.blockquote){let e=r.blockquote;t.blockquote=t=>e({type:"blockquote",raw:"",text:t,tokens:[]})}if(r.table){let e=r.table;t.table=(t,r)=>e({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:t,bodyHtml:r})}if(r.link){let e=r.link;t.link=(t,r,n)=>e({type:"link",raw:"",href:t,title:r??null,text:n,tokens:[]})}if(r.image){let e=r.image;t.image=(t,r,n)=>e({type:"image",raw:"",href:t,title:r??null,text:n})}if(r.list){let e=r.list;t.list=(t,r,n)=>e({type:"list",raw:"",ordered:r,start:n,loose:!1,items:[],itemsHtml:t})}if(r.listitem){let e=r.listitem;t.listitem=(t,r,n)=>e({type:"list_item",raw:"",task:r,checked:n,loose:!1,text:t,tokens:[]})}if(r.paragraph){let e=r.paragraph;t.paragraph=t=>e({type:"paragraph",raw:"",text:t,tokens:[]})}if(r.codespan){let e=r.codespan;t.codespan=t=>e({type:"codespan",raw:"",text:t})}if(r.strong){let e=r.strong;t.strong=t=>e({type:"strong",raw:"",text:t,tokens:[]})}if(r.em){let e=r.em;t.em=t=>e({type:"em",raw:"",text:t,tokens:[]})}if(r.del){let e=r.del;t.del=t=>e({type:"del",raw:"",text:t,tokens:[]})}if(r.html){let e=r.html;t.html=t=>e({type:"html",raw:t,text:t})}if(r.text){let e=r.text;t.text=t=>e({type:"text",raw:t,text:t})}if(r.checkbox){let e=r.checkbox;t.checkbox=t=>e({checked:t})}return r.hr&&(t.hr=r.hr),r.br&&(t.br=r.br),t})(e?.renderer);a&&t.use({renderer:a})}return t.parse(r)}},xe=e=>e?we({markedOptions:e.options,renderer:e.renderer}):we(),Ce=we(),Se=e=>Ce(e),ke=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Ae=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Me=e=>`%%FORM_PLACEHOLDER_${e}%%`,Ie=(e,t)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,r)=>{try{let e=JSON.parse(r.trim());if(e&&"object"==typeof e&&"form"===e.component&&e.type){let r=Me(t.length);return t.push({token:r,type:String(e.type)}),r}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,r)=>{let n=Me(t.length);return t.push({token:n,type:r}),n}),r},Te={ALLOWED_TAGS:"h1.h2.h3.h4.h5.h6.p.br.hr.div.span.ul.ol.li.dl.dt.dd.strong.em.b.i.u.s.del.ins.mark.small.sub.sup.abbr.kbd.var.samp.code.a.img.blockquote.pre.details.summary.table.thead.tbody.tfoot.tr.th.td.caption.colgroup.col.input.label.select.option.textarea.button".split("."),ALLOWED_ATTR:"href.src.alt.title.target.rel.loading.width.height.colspan.rowspan.scope.class.id.type.name.value.placeholder.disabled.checked.for.aria-label.aria-hidden.aria-expanded.role.tabindex.data-tv-form.data-message-id.data-persona-component-directive.data-preserve-animation.data-persona-instance".split(".")},Ee=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Le=()=>{let e=null;return t=>{let r=ve();if(!r)return ke(t);if(!e){let{DOMPurify:t}=r;e=t(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(e,t)=>{if("src"===t.attrName||"href"===t.attrName){let e=t.attrValue;e.toLowerCase().startsWith("data:")&&!Ee.test(e)&&(t.attrValue="",t.keepAttr=!1)}})}return e.sanitize(t,Te)}},Pe=e=>!1===e?null:"function"==typeof e?e:Le(),Be=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Ne=e=>e.includes("|"),Re=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())},He=e=>`| ${e.join(" | ")} |`,$e=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,We=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),De="var(--persona-md-table-scroll-fade, 24px)",Fe=new WeakSet;function Oe(e){let t=e.scrollWidth-e.clientWidth;if(t<=1)return void e.removeAttribute("data-persona-scroll-x");e.setAttribute("data-persona-scroll-x","");let r="rtl"===getComputedStyle(e).direction?t+e.scrollLeft:e.scrollLeft,n=t-r;e.style.setProperty("--persona-fade-l",r<=1?"0px":De),e.style.setProperty("--persona-fade-r",n<=1?"0px":De)}function ze(e){Fe.has(e)||(Fe.add(e),e.addEventListener("scroll",e=>{let t=e.target;t?.classList?.contains("persona-table-scroll")&&Oe(t)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Oe)}let{setLoader:qe,load:je,provide:_e,getSync:Ve}=N({fallbackImport:()=>import("./client-stream")}),Ue=qe,Ge=je,Ke=Ve,Je="webmcp:",Qe=new Map,Xe=e=>{Qe.clear();for(let t of e){let e=t.title?.trim();e&&Qe.set(t.name,e)}},Ye=e=>Qe.get(rt(e)),Ze=null;function et(e){if(0===e.length)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}:${function(e){return`${tt(e,0).toString(36)}.${tt(e,2654435761).toString(36)}`}(t.join(""))}`}function tt(e,t){let r=3735928559^t,n=1103547991^t;for(let t=0;t<e.length;t++){let o=e.charCodeAt(t);r=Math.imul(r^o,2654435761),n=Math.imul(n^o,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)}let rt=e=>e.startsWith("webmcp:")?e.slice(7):e,nt=e=>e.startsWith(Je),ot=()=>Ze?Ze():import("@mcp-b/webmcp-polyfill"),{setLoader:at,load:st}=N({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),it=at,lt=st,{setLoader:dt,load:ct}=N({fallbackImport:()=>import("@runtypelabs/persona/voice-client-tools")}),pt=dt,ut=ct;function ht(e){return e.startsWith("agent_")?{kind:"agentId",agentId:e}:e.startsWith("flow_")?{kind:"flowId",flowId:e}:null}function mt(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function gt(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}var ft=t(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow}),yt=t(e=>{var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var n in e)"default"!==n&&!Object.prototype.hasOwnProperty.call(r,n)&&t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let n=ft();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return n.Allow}}),r(ft(),e);var o=class extends Error{};e.PartialJSON=o;var a=class extends Error{};function s(e,t=n.Allow.ALL){if("string"!=typeof e)throw TypeError("expecting str, got "+typeof e);if(!e.trim())throw Error(`${e} is empty`);return i(e.trim(),t)}e.MalformedJSON=a,e.parseJSON=s;let i=(e,t)=>{let r=e.length,s=0,i=e=>{throw new o(`${e} at position ${s}`)},l=e=>{throw new a(`${e} at position ${s}`)},d=()=>(m(),s>=r&&i("Unexpected end of input"),'"'===e[s]?c():"{"===e[s]?p():"["===e[s]?u():"null"===e.substring(s,s+4)||n.Allow.NULL&t&&r-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||n.Allow.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||n.Allow.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||n.Allow.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||n.Allow._INFINITY&t&&1<r-s&&r-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):"NaN"===e.substring(s,s+3)||n.Allow.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):h()),c=()=>{let o=s,a=!1;for(s++;s<r&&('"'!==e[s]||a&&"\\"===e[s-1]);)a="\\"===e[s]&&!a,s++;if('"'==e.charAt(s))try{return JSON.parse(e.substring(o,++s-Number(a)))}catch(e){l(String(e))}else if(n.Allow.STR&t)try{return JSON.parse(e.substring(o,s-Number(a))+'"')}catch{return JSON.parse(e.substring(o,e.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},p=()=>{s++,m();let o={};try{for(;"}"!==e[s];){if(m(),s>=r&&n.Allow.OBJ&t)return o;let a=c();m(),s++;try{o[a]=d()}catch(e){if(n.Allow.OBJ&t)return o;throw e}m(),","===e[s]&&s++}}catch{if(n.Allow.OBJ&t)return o;i("Expected '}' at end of object")}return s++,o},u=()=>{s++;let r=[];try{for(;"]"!==e[s];)r.push(d()),m(),","===e[s]&&s++}catch{if(n.Allow.ARR&t)return r;i("Expected ']' at end of array")}return s++,r},h=()=>{if(0===s){"-"===e&&l("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(n.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}l(String(r))}}let o=s;for("-"===e[s]&&s++;e[s]&&-1===",]}".indexOf(e[s]);)s++;s==r&&!(n.Allow.NUM&t)&&i("Unterminated number literal");try{return JSON.parse(e.substring(o,s))}catch{"-"===e.substring(o,s)&&i("Not sure what '-' is");try{return JSON.parse(e.substring(o,e.lastIndexOf("e")))}catch(e){l(String(e))}}},m=()=>{for(;s<r&&" \n\r\t".includes(e[s]);)s++};return d()};e.parse=s})();let bt="ask_user_question",vt="data-persona-ask-sheet-for",wt="Type your own answer here",xt="Send",Ct="data-ask-question-count",St="data-ask-answers",kt="data-ask-grouped",At=!1,Mt=e=>e.replace(/["\\]/g,"\\$&"),It=e=>"tool"===e.variant&&!!e.toolCall&&"ask_user_question"===e.toolCall.name,Tt=e=>e?.features?.askUserQuestion??{},Et=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r="complete"===t.status;if(t.args&&"object"==typeof t.args)return{payload:t.args,complete:r};let n=t.chunks;if(!n||0===n.length)return{payload:null,complete:r};try{let e=n.join(""),t=(0,yt.parse)(e,yt.STR|yt.OBJ|yt.ARR);if(t&&"object"==typeof t)return{payload:t,complete:r}}catch{}return{payload:null,complete:r}},Lt=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!At&&(At=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},Pt=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},Bt=(e,t,r)=>{if("rows"!==e)return null;let n=L("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let e=L("span","persona-ask-row-check");n.appendChild(e)}else{let e=L("span","persona-ask-row-badge");e.textContent=String(r+1),n.appendChild(e)}return n},Nt=e=>{let t=L("span","rows"===e?"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},Rt=(e,t)=>{let r=L("div","rows"===t?"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");r.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=e.freeTextPlaceholder??wt,n.setAttribute("data-ask-free-text-input","true"),r.appendChild(n),"rows"!==t){let t=L("button","persona-ask-free-text-submit persona-pointer-events-auto");t.type="button",t.textContent=e.submitLabel??xt,t.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(t)}return r},Ht=e=>{let t=e.getAttribute(St);if(!t)return{};try{let e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch{return{}}},$t=e=>{let t=Number(e.getAttribute("data-ask-current-index")??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Wt=e=>{let t=Number(e.getAttribute("data-ask-question-count")??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Dt=e=>"true"===e.getAttribute(kt),Ft=(e,t,r)=>{let n=Tt(r),o=(e=>"pills"===e.getAttribute("data-ask-layout")?"pills":"rows")(e),{payload:a,complete:s}=Et(t),i=Dt(e),l=$t(e),d=Wt(e),c=i?((e,t)=>Lt(e)[t]??null)(a,l):(e=>Lt(e)[0]??null)(a),p=!!c?.multiSelect,u=e.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${l+1}/${d}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let m=e.querySelector('[data-ask-question="true"]');if(m){let e="string"==typeof c?.question?c.question:"";m.textContent=e,m.classList.toggle("persona-ask-question-skeleton",!e&&!s)}let g=e.querySelector('[data-ask-pill-list="true"]');if(g){let e=((e,t,r,n)=>{let o=L("div","rows"===n?"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");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,s=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&"string"==typeof e.label&&e.label.length>0);if(0===s.length&&!r){for(let e=0;e<3;e++)o.appendChild(Nt(n));return o}if(s.forEach((e,t)=>{o.appendChild(((e,t,r,n)=>{let o=L("button","rows"===r?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",n?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),"rows"===r){let a=L("span","persona-ask-row-content"),s=L("span","persona-ask-row-label");if(s.textContent=e.label,a.appendChild(s),e.description){let t=L("span","persona-ask-row-description");t.textContent=e.description,a.appendChild(t)}o.appendChild(a);let i=Bt(r,n,t);i&&o.appendChild(i)}else o.textContent=e.label,e.description&&(o.title=e.description);return o})(e,t,n,a))}),!1!==e?.allowFreeText){let e="rows"===n?"Other":"Other…";if("rows"===n){let r=L("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");r.setAttribute("data-ask-user-action","focus-free-text"),r.setAttribute("data-option-index",String(s.length)),r.setAttribute("data-ask-other-row","true");let i=L("span","persona-ask-row-content"),l=document.createElement("input");l.type="text",l.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",l.placeholder=t.freeTextPlaceholder??wt,l.setAttribute("data-ask-free-text-input","true"),l.setAttribute("aria-label",t.freeTextLabel??e),i.appendChild(l),r.appendChild(i);let d=Bt(n,a,s.length);d&&r.appendChild(d),o.appendChild(r)}else{let r=L("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");r.type="button",r.setAttribute("data-ask-user-action","open-free-text"),r.textContent=t.freeTextLabel??e,o.appendChild(r)}}return o})(c,n,s,o);g.replaceWith(e)}if("rows"!==o){let t=e.querySelector('[data-ask-free-text-row="true"]');t&&t.replaceWith(Rt(n,o))}let f=e.querySelector('[data-ask-multi-actions="true"]');i||!p||f?(!p||i)&&f&&f.remove():e.appendChild((e=>{let t=L("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=L("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=e.submitLabel??xt,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t})(n)),e.setAttribute("data-multi-select",p?"true":"false");let y=e.querySelector('[data-ask-nav-row="true"]');if(i){let t=((e,t,r)=>{let n=L("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=L("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=r.backLabel??"Back",o.setAttribute("data-ask-user-action","back"),o.disabled=0===e,n.appendChild(o);let a=L("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=L("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=r.skipLabel??"Skip",s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=L("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let l=e===t-1;return i.textContent=l?r.submitAllLabel??"Submit all":r.nextLabel??"Next",i.setAttribute("data-ask-user-action",l?"submit-all":"next"),i.disabled=!0,a.appendChild(i),n.appendChild(a),n})(l,d,n);y?y.replaceWith(t):e.appendChild(t)}else y&&y.remove();(e=>{let t=Ht(e)[$t(e)],r=new Set;"string"==typeof t?r.add(t):Array.isArray(t)&&t.forEach(e=>r.add(e));let n=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');n.forEach(e=>{let t=e.getAttribute("data-option-label")??"",n=r.has(t);e.setAttribute("aria-pressed",n?"true":"false"),e.classList.toggle("persona-ask-pill-selected",n)});let o=new Set(Array.from(n).map(e=>e.getAttribute("data-option-label")??"")),a=e.querySelector('[data-ask-free-text-input="true"]');a&&("string"==typeof t&&t.length>0&&!o.has(t)?(a.value=t,a.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):a.value="")})(e),(e=>{if(!Dt(e))return;let t=Ht(e)[$t(e)],r="string"==typeof t&&t.length>0||Array.isArray(t)&&t.length>0,n=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');n&&(n.disabled=!r);let o=e.querySelector('[data-ask-user-action="submit-multi"]');o&&(o.disabled=0===Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).length)})(e)},Ot=(e,t,r)=>{if(!r||!It(e)||!1===Tt(t).enabled)return;let n=e.toolCall.id;r.querySelectorAll(`[${vt}]`).forEach(e=>{e.getAttribute(vt)!==n&&e.remove()});let o=r.querySelector(`[${vt}="${Mt(n)}"]`);if(o)return void((e,t,r)=>{let{payload:n}=Et(t),o=Math.max(1,Lt(n).length);o>Wt(e)&&(e.setAttribute(Ct,String(o)),o>1&&!Dt(e)&&e.setAttribute(kt,"true")),Ft(e,t,r)})(o,e,t);let{payload:a}=Et(e),s=((e,t,r)=>{let n=Tt(t),o=(e=>"pills"===e.layout?"pills":"rows")(n),a=e.toolCall.id,s=Lt(r),i=Math.max(1,s.length),l=i>1,d=((e,t)=>{let r=e.agentMetadata?.askUserQuestionAnswers;if(!r||"object"!=typeof r)return{};let n={};return t.forEach((e,t)=>{let o="string"==typeof e?.question?e.question:"";if(o&&Object.prototype.hasOwnProperty.call(r,o)){let e=r[o];("string"==typeof e||Array.isArray(e))&&(n[t]=e)}}),n})(e,s),c=l?((e,t)=>{let r=e.agentMetadata?.askUserQuestionIndex;return"number"==typeof r&&Number.isFinite(r)?Math.max(0,Math.min(t-1,Math.floor(r))):0})(e,i):0,p=L("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(vt,a),p.setAttribute("data-tool-call-id",a),p.setAttribute("data-message-id",e.id),p.setAttribute(Ct,String(i)),p.setAttribute("data-ask-current-index",String(c)),p.setAttribute(kt,l?"true":"false"),p.setAttribute("data-ask-layout",o),((e,t)=>{e.setAttribute(St,JSON.stringify(t))})(p,d),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),void 0!==n.slideInMs&&p.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),Pt(p,n);let u=L("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=L("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",u.appendChild(h);let m=L("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",u.appendChild(m),p.appendChild(u);let g=L("div","rows"===o?"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 g.setAttribute("data-ask-pill-list","true"),g.setAttribute("role","group"),p.appendChild(g),"rows"!==o&&p.appendChild(Rt(n,o)),Ft(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p})(e,t,a);r.appendChild(s)},zt=(e,t)=>{if(!e)return;let r=t?`[${vt}="${Mt(t)}"]`:`[${vt}]`;e.querySelectorAll(r).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)})},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},_t={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}},Vt=e=>"tool"===e.variant&&"suggest_replies"===e.toolCall?.name,Ut=e=>{let t=e;if("string"==typeof t)try{t=JSON.parse(t)}catch{return[]}let r=t?.suggestions;if(!Array.isArray(r))return[];let n=r.flatMap(e=>{if("string"==typeof e){let t=e.trim();return t?[t]:[]}if(!e||"object"!=typeof e)return[];let t=e;if("string"!=typeof t.label||!t.label.trim())return[];let r={label:t.label.trim()};return"string"==typeof t.prompt&&t.prompt.trim()&&(r.prompt=t.prompt.trim()),"string"==typeof t.description&&t.description.trim()&&(r.description=t.description.trim()),[r]});return n.length>4?(console.warn(`[persona] suggest_replies: ${n.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),n.slice(0,4)):n},Gt=e=>{for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role)return null;if(!Vt(r))continue;let n=Ut(r.toolCall?.args);return n.length>0?n:null}return null},Kt=new Set,Jt=e=>{let t=e?.suggestions?.followUps,r=e?.features?.suggestReplies,n=e=>{let n=t?.[e],o=r?.[e];void 0!==n&&void 0!==o&&n!==o&&((e,t,r)=>{let n=`${e}:${t}:${r}`;Kt.has(n)||(Kt.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))})(e,o,n)};e&&(n("enabled"),n("expose"));let o=t?.enabled??r?.enabled??!0;return{enabled:o,expose:!!o&&(t?.expose??r?.expose??!1)}},Qt={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},Xt={name:bt,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:Qt,origin:"sdk",annotations:{readOnlyHint:!0}},Yt=e=>{let t=[],r=e?.features?.askUserQuestion;return!0===r?.expose&&!1!==r.enabled&&t.push(Xt),Jt(e).expose&&t.push(_t),t},Zt=e=>"object"==typeof e&&!!e&&!Array.isArray(e),er=e=>{if("tool"!==e.variant)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||void 0===t.result)return null;let r=(e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""))(t.toolName);return r?{call:{toolCallId:t.toolCallId,toolName:r,args:Zt(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:r,result:t.result}}:null},tr=(e,t)=>{let r,n=[],o=[],a=[],s="",i=()=>{0!==o.length&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:a}),o=[],a=[])};for(let l of e){let e=er(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(void 0===t||t!==r)&&i(),0===o.length&&(s=l.createdAt,r=t),o.some(t=>t.toolCallId===e.call.toolCallId)||(o.push(e.call),a.push(e.result));continue}let d=t(l);d&&(i(),n.push(d))}return i(),n},rr=e=>e.replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),nr=e=>{if(null===e)return"null";if(void 0===e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},or=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ar=e=>{let t="number"==typeof e.duration?e.duration:"number"==typeof e.durationMs?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return or(t)},sr=e=>{let t=void 0===e.durationMs?Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())):e.durationMs;return or(t)},ir=(e,t,r)=>{if(!t)return r;let n=e.name?.trim()||"tool",o=ar(e);return t.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},lr=(e,t)=>{let r,n=e.replace(/\{toolName\}/g,t),o=[],a=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0;for(;null!==(r=a.exec(n));)r.index>s&&dr(o,n.slice(s,r.index),[]),void 0===r[1]?void 0===r[2]?void 0!==r[3]&&dr(o,r[3],["dim"]):dr(o,r[2],["italic"]):dr(o,r[1],["bold"]),s=r.index+r[0].length;return s<n.length&&dr(o,n.slice(s),[]),o},dr=(e,t,r)=>{let n=t.split("{duration}");for(let t=0;t<n.length;t++)n[t]&&e.push({text:n[t],styles:r}),t<n.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},cr=()=>({processChunk:()=>null,getExtractedText:()=>null,__isPlainTextParser:!0}),pr=()=>{let e=(()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return null===e?null:{text:e,raw:r};let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let o=(e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/);if(t&&t[1])try{return t[1].replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return t[1]}let r=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/);if(r&&r[1])try{return r[1].replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return r[1]}return null})(r);return null!==o&&(e=o),t=r.length,null===e?null:{text:e,raw:r}},close:async()=>{}}})();return{processChunk:async t=>{let r=t.trim();return r.startsWith("{")||r.startsWith("[")?e.processChunk(t):null},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},ur=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=t)return null!==e||""===e?{text:e||"",raw:r}:null;try{let t=(0,yt.parse)(r,yt.STR|yt.OBJ);t&&"object"==typeof t&&(t.component&&"string"==typeof t.component?e="string"==typeof t.text?rr(t.text):"":"init"===t.type&&t.form?e="":"string"==typeof t.text&&(e=rr(t.text)))}catch{}return t=r.length,null===e?null:{text:e,raw:r}},close:()=>{}}},hr=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}},mr="4.29.0",{setLoader:gr,load:fr,provide:yr}=N({fallbackImport:()=>import("./client-history")}),br=gr,vr=fr;function wr(e){return"string"!=typeof e&&e.some(e=>"image"===e.type)}function xr(e){return{type:"text",text:e}}let Cr=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Sr=[...Cr,"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"];function kr(e){return function(e){return Cr.includes(e)||e.startsWith("image/")}(e.type)}function Ar(e,t=Sr,r=10485760){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Mr(e){let t=e.content;if("string"!=typeof t||""===t)return;let r=e.contentParts??e.llmContent??e.rawContent??t;return"string"!=typeof r||r!==t?t:void 0}function Ir(e,t){let r=new Map;for(let t of e)r.set(t.id,t);for(let e of t)r.set(e.id,e);return[...r.values()].sort((e,t)=>{let r=new Date(e.createdAt).getTime(),n=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(n)&&r!==n)return r-n;let o=e.sequence??0,a=t.sequence??0;return o===a?e.id.localeCompare(t.id):o-a})}let Tr={idle:"Online",connecting:"Connecting…",connected:"Streaming…",error:"Offline",paused:"Connection lost…",resuming:"Reconnecting…"};var Er=class extends Error{constructor(e,t,r){super(t),this.name="HistoryClientError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};let Lr=e=>"reason"in e?e.reason:void 0,Pr=(e,t)=>e instanceof Er&&e.code===t,Br=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),Nr=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),Rr=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});var Hr=class{#e;#t;#r;#n;#o;#a;#s;#i;#l;#d;#c;#p;#u;#h;#m;#g;#f;#y;#b;#v;#w;constructor(e={},t={}){if(this.config=e,this.historyInternals=t,this.#d=null,this.clientSession=null,this.#c=null,this.#p=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#u=null,this.#h=!1,this.#m=!1,this.#g=!1,this.#f=null,this.#y=new Set,this.#b=new Set,this.webMcpBridge=null,this.#v=null,this.#x=null,this.#C=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":mr,...e.headers},this.debug=!!e.debug,this.#r=e.streamParser??function(e){switch(e){case"json":return ur;case"regex-json":return pr;case"xml":return hr;default:return cr}}(e.parserType),this.#n=e.contextProviders??[],this.#o=e.requestMiddleware,this.#a=e.customFetch,this.#s=e.parseSSEEvent,this.#i=e.getHeaders,!0===e.webmcp?.enabled&&(this.#v=this.#S(e.webmcp))}#S(e){return lt().then(t=>{let r=new t.WebMcpBridge(e,{recordToolDisplayTitles:Xe,getToolDisplayTitle:Ye,loadPolyfill:ot});return void 0!==this.#w&&r.setConfirmHandler(this.#w),this.webMcpBridge=r,r}).catch(e=>(this.#v=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",e),null))}#k(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):!0===this.config.webmcp?.enabled?(this.#v||=this.#S(this.config.webmcp),this.#v):Promise.resolve(null)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#l=e}setWebMcpConfirmHandler(e){this.#w=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return!0===this.webMcpBridge?.isOperational()}getVoiceClientTools(){if(!0!==this.config.webmcp?.enabled)return null;let e=()=>this.#k(),t={open:async e=>(await ut()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await((await e())?.snapshotForDispatch())??[];return{tools:t,fingerprint:et(t)}},onChange:t=>{let r=null,n=!1;return e().then(e=>{e&&!n&&(r=e.watchToolChanges(t))}),()=>{n=!0,r?.()}},execute:async(t,r,n)=>{let o=await e();return o?o.executeVoiceToolCall(t,r,n):{status:"failed",error:{message:"WebMCP runtime failed to load."}}}};return t}executeWebMcpToolCall(e,t,r){return!0===this.config.webmcp?.enabled?this.#k().then(n=>n?n.executeToolCall(e,t,r):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]}):null}getSSEEventCallback(){return this.#l}isClientTokenMode(){return!!this.config.clientToken}#A(){let{agentId:e,flowId:t,target:r,targetProviders:n}=this.config;if(!r)return{agentId:e,flowId:t};let o=function(e,t){let r=e.trim();if(!r)throw Error("[Persona] `target` is empty.");let n=r.indexOf(":");if(n>0){let e=r.slice(0,n),o=r.slice(n+1);if("runtype"===e){let e=ht(o);if(e)return e;throw Error(`[Persona] target "runtype:${o}" 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(o).payload}}let o=ht(r);if(o)return o;let a=t?.default;if(a)return{kind:"payload",payload:a(r).payload};throw Error(`[Persona] target "${r}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${r}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}(r,n);return"agentId"===o.kind?{agentId:o.agentId}:"flowId"===o.kind?{flowId:o.flowId}:{targetPayload:o.payload}}isAgentMode(){return!(!this.config.agent&&!this.#A().agentId)}#M(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||"https://api.runtype.com"}#I(e){return`${this.#M()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),r=!1;for(;;){let n=t.conversationId,o=await this.readVisitorToken();if(!0!==t.durableRecovery?.enabled||!n||!o)throw new Er("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.#M()}/v1/client/conversations/${encodeURIComponent(n)}/executions/${encodeURIComponent(e.executionId)}/events`,s=new URLSearchParams({sessionId:t.sessionId,after:e.after}),i=await fetch(`${a}?${s}`,{method:"GET",headers:{"X-Persona-Version":mr,"X-Visitor-Token":o},signal:e.signal});if(401!==i.status||r){if(!i.ok)throw await(await vr()).historyErrorFor(this.#T(),i,!0);return i}{r=!0;let e=await vr();t=await e.recoverFromUnauthorized(this.#T(),await e.readErrorCode(this.#T(),i),null,!0)}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#c||e&&new Date<e.expiresAt||this.#p===e?null:(this.#p=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#c)return this.#c;let e=this.#c=this.#E().then(t=>this.#c===e?(this.clientSession=t,this.#p=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#c===e&&(this.#c=null)});return e}#L(){return!0===this.config.features?.history?.enabled&&this.isClientTokenMode()&&!this.#h}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#P(){if(!this.#h){this.#B({state:"unavailable",reason:"history_disabled"}),this.#h=!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.#b])e(!1)}}getHistoryIdentityStatus(){return this.#f??this.#N()}subscribeHistoryIdentityStatus(e){return this.#y.add(e),()=>{this.#y.delete(e)}}subscribeHistoryAvailability(e){return this.#b.add(e),this.#h&&e(!1),()=>{this.#b.delete(e)}}#N(){return this.isClientTokenMode()?!0!==this.config.features?.history?.enabled||this.#h?{state:"unavailable",reason:"history_disabled"}:this.#R():{state:"unavailable",reason:"ineligible_mode"}}#R(){let e=this.#f;return"browser_only"===e?.state?e:this.#H()}#H(){return"browser"===this.config.features?.history?.scope?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}#B(e){let t=this.getHistoryIdentityStatus(),r=t.state===e.state&&Lr(t)===Lr(e);if(this.#f=e,!r){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#y])t(e)}}async#$(e){let t=this.#L()&&!e.omitVisitorFields,r=!e.omitVisitorFields,n=null;(t||r)&&(await this.historyInternals.historyBootstrapReady,n=await this.readVisitorToken());let o=this.#A(),a=o.agentId??o.flowId,s=t||e.durableResume?e.conversationId:void 0,i={token:this.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...r&&{durableRecovery:!0},...(t||r)&&n?{visitorToken:n}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...s?{conversationId:s}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let l=await fetch(this.#I("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":mr},body:JSON.stringify(i),signal:e.signal});if(!l.ok){let r=await l.json().catch(()=>({error:"Session initialization failed"}));if(t&&403===l.status&&"visitor_history_disabled"===r.error){if(this.#P(),s)throw new Er("history_disabled","Visitor history is disabled for this surface");return this.#$({...e,omitVisitorFields:!0})}throw 403===l.status&&"durable_recovery_disabled"===r.error?new Er("history_disabled","Durable recovery is disabled for this surface"):(t||e.durableResume)&&401===l.status&&"visitor_required"===r.error?new Er("visitor_required","Visitor credential no longer resolves"):s&&404===l.status?new Er("not_found","Conversation not found"):401===l.status?Error(`Invalid client token: ${r.hint||r.error}`):403===l.status?Error(`Origin not allowed: ${r.hint||r.error}`):Error(r.error||"Failed to initialize session")}let d=await l.json();return d.visitor?.token&&await(this.historyInternals.visitorStore?.set(d.visitor.token)),{sessionId:d.sessionId,expiresAt:new Date(d.expiresAt),flow:d.flow,...d.conversationId?{conversationId:d.conversationId}:{},...d.targetId?{targetId:d.targetId}:{},...d.conversationRevision?{conversationRevision:d.conversationRevision}:{},...d.durableRecovery?{durableRecovery:d.durableRecovery}:{},...d.visitor?{visitor:d.visitor}:{},config:{welcomeMessage:d.config.welcomeMessage,placeholder:d.config.placeholder,theme:d.config.theme}}}async#E(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,t=!0===this.historyInternals.shouldResumeDurableConversation?.();if(!this.#L()&&!t)return this.#W(e,!1);let r=await this.readVisitorToken();if(e&&r)try{let r=await this.#$({conversationId:e,durableResume:t});return t&&!0!==r.durableRecovery?.enabled&&this.historyInternals.setStoredResumableHandle?.(null),this.#D(r,e,!1)}catch(r){if(!Pr(r,"not_found")&&!Pr(r,"visitor_required")&&!Pr(r,"history_disabled"))throw r;return t&&this.historyInternals.setStoredResumableHandle?.(null),this.#W(e,!0)}return this.#W(e,!1)}async#W(e,t){let r=this.historyInternals.visitorStore;return r&&!await this.readVisitorToken()?r.withFirstInitLock(()=>this.#F(e,t)):this.#F(e,t)}async#F(e,t){let r=this.config.getStoredSessionId?.()||null,n=await this.#$({storedSessionId:r}),o=await this.#O(n);return this.#D(o,e,t)}async#z(e){let t=this.config.getStoredSessionId?.()||null,r=this.config.getStoredConversationId?.()||null,n=await this.#$({storedSessionId:t,identityProof:e}),o=this.#D(n,r,!1);return this.clientSession=o,this.#c=null,this.#p=!1,this.resetClientToolsFingerprint(),o}async#O(e){if(!e.visitor?.token||this.#g||!this.#L()&&!0!==e.durableRecovery?.enabled)return e;this.#g=!0;try{return await this.#$({storedSessionId:e.sessionId})}catch{return e}finally{this.#g=!1}}#D(e,t,r){let n=e.conversationId;return n&&t&&(r||n!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:n}),this.config.setStoredSessionId?.(e.sessionId),n&&(this.config.setStoredConversationId?.(n),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#q(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#p=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error("prepareConversationSession() only available in client token mode");if(!this.#L())throw new Er("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let r=t?.proof??null;if(!await this.readVisitorToken()&&!r)throw new Er("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let n=await this.#$({conversationId:e,identityProof:r});return this.#q(n)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.#$({});return this.#q(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#L()&&this.#B(this.#H())}clearClientSession(){this.clientSession=null,this.#c=null,this.#p=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#u=null}#j(){return`${this.#M()}/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("csat"===e.type&&(void 0===e.rating||e.rating<1||e.rating>5))throw Error("CSAT rating must be between 1 and 5");if("nps"===e.type&&(void 0===e.rating||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}},r=await fetch(this.#j(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":mr},body:JSON.stringify(t)});if(!r.ok){let e=await r.json().catch(()=>({error:"Feedback submission failed"}));throw 401===r.status?(this.clientSession=null,this.#p=!1,this.config.onSessionExpired?.(),Error("Session expired. Please refresh to continue.")):Error(e.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let r=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async#_(e){e?.throwIfAborted();let t=this.config.identityProvider;if(void 0===t)return;let r,n,o=this.config.getIdentityProof;if(!t.trim()||!o)throw Error("Chat identity requires identityProvider and getIdentityProof.");try{let t=Promise.resolve().then(()=>o());r=e?await Promise.race([t,new Promise((t,r)=>{n=()=>r(e.reason),e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})]):await t}catch{throw e?.throwIfAborted(),Error("The identity proof provider failed.")}finally{n&&e?.removeEventListener("abort",n)}if("string"!=typeof r||!r.trim())throw Error("A fresh identity proof is required to send this message.");return{provider:t,token:r}}#x;#V(){let e=this;return this.#x??={get config(){return e.config},headers:this.#t,getHeaders:this.#i,debug:this.debug,clientApiBase:()=>e.#M(),getClientApiUrl:t=>e.#I(t),getWebMcpBridge:()=>e.#k(),sendWithClientToolsDiff:(t,r,n,o)=>e.#U(t,r,n,o),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#C;#T(){let e=this;return this.#C??={HistoryClientError:Er,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#M(),setHistoryIdentityStatus:t=>e.#B(t),browserOnlyStatus:()=>e.#R(),derivedBrowserOnly:()=>e.#H(),reinitWithProof:t=>e.#z(t),isHistoryCapable:()=>e.#L(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await vr()).listConversations(this.#T(),e)}async getConversation(e,t){return(await vr()).getConversation(this.#T(),e,t)}async finalizeDisplayProjections(e,t){return(await vr()).finalizeDisplayProjections(this.#T(),e,t)}async deleteConversation(e,t){return(await vr()).deleteConversation(this.#T(),e,t)}async deleteAllConversations(e){return(await vr()).deleteAllConversations(this.#T(),e)}async resetVisitor(){return(await vr()).resetVisitor(this.#T())}async dispatch(e,t){return e.signal?.throwIfAborted(),Ge().catch(()=>{}),this.isClientTokenMode()?this.#G(e,t):this.isAgentMode()?this.#K(e,t):this.#J(e,t)}async#G(e,t){let r=`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`;this.#d=r;let n=()=>this.#d===r,o=e=>{n()&&t(e)};t({type:"status",status:"connecting"});try{let t=()=>{if(e.signal?.throwIfAborted(),!n())throw new DOMException("Turn superseded","AbortError")},a=this.clientSession??await this.initSession();t();let s=async()=>{t();let r=a,n=!0===r.durableRecovery?.enabled;if(n&&(!r.conversationId||!await this.readVisitorToken()))throw Error("Renewing this conversation requires its visitor credential.");t();let o=await this.#$({...n||this.#L()?{conversationId:r.conversationId,durableResume:n}:{storedSessionId:r.sessionId},signal:e.signal});if(t(),r.conversationId&&o.conversationId!==r.conversationId||n&&!0!==o.durableRecovery?.enabled)throw Error("Session renewal did not preserve this conversation.");a=this.#D(o,r.conversationId??null,!1),this.clientSession=a,this.#p=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(a)};Date.now()>=a.expiresAt.getTime()-6e4&&await s();let i=await this.#Q(e.messages),l=i.metadata?Object.fromEntries(Object.entries(i.metadata).filter(([e])=>"sessionId"!==e&&"session_id"!==e)):void 0,d=this.#L(),c={sessionId:a.sessionId,messages:e.messages.filter(Br).map(e=>{let t=d?Mr(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...void 0!==t&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...l&&Object.keys(l).length>0&&{metadata:l},...i.inputs&&Object.keys(i.inputs).length>0&&{inputs:i.inputs},...i.context&&{context:i.context},turnId:r,...e.interrupt&&{submitMode:"interrupt"},...e.voiceSpoken&&{voice:{spoken:!0}}},p=async()=>{t();let r=!0===a.durableRecovery?.enabled?await this.readVisitorToken():null;return t(),this.#U(a.sessionId,i.clientTools,async n=>{t();let o=await this.#_(e.signal);t();let s={...c,sessionId:a.sessionId,...n,...o&&{identityProof:o}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...s,...o&&{identityProof:{provider:o.provider,token:"[REDACTED]"}}}),fetch(this.#I("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":mr,...r?{"X-Visitor-Token":r}:{}},body:JSON.stringify(s),signal:e.signal})})},u=await p();if(t(),401===u.response.status){let e=await u.response.clone().json().catch(()=>null);t(),"Session not found or expired"===e?.error&&(await s(),u=await p(),t())}let{response:h,commit:m}=u;if(!h.ok){let e=await h.json().catch(()=>({error:"Chat request failed"}));if(401===h.status&&"invalid_identity_proof"===e.error){let e=new Er("invalid_identity_proof","The identity proof was rejected");throw o({type:"error",error:e}),e}if(401===h.status){this.clearClientSession(),this.config.onSessionExpired?.();let e=Error("Session expired. Please refresh to continue.");throw o({type:"error",error:e}),e}if(429===h.status){let t=Error(e.hint||"Message limit reached for this session.");throw o({type:"error",error:t}),t}if(410===h.status&&"conversation_deleted"===e.error){let e=new Er("conversation_deleted","This conversation was deleted");throw o({type:"error",error:e}),e}let t=Error(e.error||"Failed to send message");throw o({type:"error",error:t}),t}if(!h.body){let e=Error("No response body received");throw o({type:"error",error:e}),e}m(),o({type:"status",status:"connected"});try{await this.#X(h.body,o,e.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof Er)&&!t.message.includes("Session expired")&&!t.message.includes("Message limit")&&o({type:"error",error:t}),t}}async#J(e,t){t({type:"status",status:"connecting"});let r=await this.#Q(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let n,o={...this.#t};if(this.#i)try{let e=await this.#i();o={...o,...e}}catch(e){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",e)}if(this.#a)try{n=await this.#a(this.#e,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(e){let r=e instanceof Error?e:Error(String(e));throw t({type:"error",error:r}),r}else n=await fetch(this.#e,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!n.ok||!n.body){let e=Error(`Chat backend request failed: ${n.status} ${n.statusText}`);throw t({type:"error",error:e}),e}t({type:"status",status:"connected"});try{await this.#X(n.body,t)}finally{t({type:"status",status:"idle"})}}async#K(e,t){t({type:"status",status:"connecting"});let r=await this.#Y(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let n,o={...this.#t};if(this.#i)try{let e=await this.#i();o={...o,...e}}catch(e){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",e)}if(this.#a)try{n=await this.#a(this.#e,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(e){let r=e instanceof Error?e:Error(String(e));throw t({type:"error",error:r}),r}else n=await fetch(this.#e,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!n.ok||!n.body){let e=Error(`Agent execution request failed: ${n.status} ${n.statusText}`);throw t({type:"error",error:e}),e}t({type:"status",status:"connected"});try{await this.#X(n.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,n){t({type:"status",status:"connected"});try{await this.#X(e,t,r,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){return(await Ge()).resolveApproval(this.#V(),e,t)}async#U(e,t,r,n){let o,a=!!(t&&t.length>0),s=a?et(t):void 0,i=this.clientToolsFingerprintSessionId===e,l=a&&i&&this.lastSentClientToolsFingerprint===s,d=!a&&!0===n?.emptyMeansReplace&&this.#u===e,c=!1;for(let e=0;o=await r({...a&&(c||!l)&&t?{clientTools:t}:{},...d?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),409===o.status&&0===e&&a&&"client_tools_resend_required"===(await o.clone().json().catch(()=>null))?.error;e++)c=!0,this.lastSentClientToolsFingerprint=null;return{response:o,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=e,a?this.#u=e:d&&(this.#u=null)}}}async resumeFlow(e,t,r){return(await Ge()).resumeFlow(this.#V(),e,t,r)}#Z(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role)return r.mentionContext&&Object.keys(r.mentionContext).length>0?{mentions:r.mentionContext}:null}return null}async#ee(e){let t={};this.#n.length&&await Promise.all(this.#n.map(async r=>{try{let n=await r({messages:e,config:this.config});n&&"object"==typeof n&&Object.assign(t,n)}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",e)}}));let r=this.#Z(e);return r&&Object.assign(t,r),Object.keys(t).length?t:null}#te(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}#re(e,t){let r=t?.selectedModelId;return r&&"model"in e&&this.config.composer?.models?.some(e=>e.id===r)?{...e,model:r}:e}async#Y(e,t){let r=this.#A().agentId;if(!this.config.agent&&!r)throw Error("Agent configuration required for agent mode");let n=tr(Nr(e),e=>!Br(e)||"user"!==e.role&&"assistant"!==e.role&&"system"!==e.role||e.variant&&"assistant"!==e.variant?null:Rr(e)),o=this.#te(t),a={agent:this.#re(this.config.agent??{agentId:r},o),messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};o&&(a.composerOptions=o);let s=[...Yt(this.config),...await((await this.#k())?.snapshotForDispatch())??[]];s.length>0&&(a.clientTools=s);let i=await this.#ee(e);return i&&(a.context=i),a}async#Q(e,t){let r=tr(Nr(e),e=>Br(e)?Rr(e):null),n=this.#A(),o={messages:r,...n.agentId?{agent:{agentId:n.agentId}}:n.flowId?{flowId:n.flowId}:{}};if(n.targetPayload)for(let[e,t]of Object.entries(n.targetPayload))"messages"!==e&&(o[e]=t);let a=[...Yt(this.config),...await((await this.#k())?.snapshotForDispatch())??[]];a.length>0&&(o.clientTools=a);let s=await this.#ee(e);s&&(o.context=s);let i=this.#te(t);if(i&&(o.composerOptions=i),this.#o)try{let e=await this.#o({payload:{...o},config:this.config});if(e&&"object"==typeof e){let t=e;return void 0!==o.clientTools&&!("clientTools"in t)&&(t.clientTools=o.clientTools),t}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",e)}return o}async#X(e,t,r,n){let{streamResponse:o}=Ke()??await Ge();return o({config:()=>this.config,createStreamParser:this.#r,parseSSEEvent:this.#s,onSSEEvent:(e,t)=>this.#l?.(e,t)},e,t,r,n)}},$r=class extends Error{constructor(e,t,r){super(t),this.name="HistoryProviderError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};let{setLoader:Wr,load:Dr,provide:Fr,getSync:Or}=N({fallbackImport:()=>import("./ui-extras-entry")}),zr=Wr,qr=Dr,jr=Or,{setLoader:_r,load:Vr,provide:Ur,getSync:Gr}=N({fallbackImport:()=>import("./session-actions")}),Kr=_r,Jr=Vr,Qr=Gr;function Xr(e){return"card"===e?"collapsed":e}function Yr(e){return e.split(";",1)[0].trim().toLowerCase()}function Zr(e,t){let r=e?.display,n="string"==typeof r?{default:r}:r??{};if(t.file&&n.files){if("string"==typeof n.files)return{mode:Xr(n.files),matchedBy:{type:"files"}};let e=t.file.mimeType?Yr(t.file.mimeType):void 0,r=e?function(e,t){if(!e)return;let r=Object.entries(e);for(let[e,n]of r)if(Yr(e)===t)return{mode:Xr(n),selector:Yr(e)};let n=`${t.split("/",1)[0]}/*`;for(let[e,t]of r)if(Yr(e)===n)return{mode:Xr(t),selector:n}}(n.files.byMediaType,e):void 0;if(e&&r)return{mode:r.mode,matchedBy:{type:"mediaType",mediaType:e,selector:r.selector}};if(n.files.default)return{mode:Xr(n.files.default),matchedBy:{type:"files"}}}let o=n.byKind?.[t.artifactType];if(o)return{mode:Xr(o),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=n.byType?.[t.artifactType];if(a)return{mode:Xr(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:Xr(s),matchedBy:{type:"preferredMode"}}:n.default?{mode:Xr(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function en(e,t){return Zr(e,t).mode}function tn(e,t){return JSON.stringify({component:"inline"===e?"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}:{},..."inline"===e&&t.component?{component:t.component}:{},..."inline"===e&&t.componentProps?{componentProps:t.componentProps}:{},...void 0===t.markdown?{}:{markdown:t.markdown}}})}function rn(e,t=140){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-1)}…`}function nn(e,t){let r=e.findIndex(e=>e.id===t);if(r<=0)return null;for(let t=r-1;t>=0;--t)if("user"===e[t].role)return e[t].id;return null}function on(e){return!("user"!==e.role||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||void 0!==e.rawContent||void 0!==e.llmContent&&e.llmContent!==e.content||e.quote)&&"string"==typeof e.content&&e.content.length>0}function an(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 r=e.find(e=>e.name===t);if(r)return r}return e.find(e=>e.lang.startsWith("en"))??e[0]}var sn=class e{constructor(e={}){this.options=e,this.id="browser",this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,r){if(!e.isSupported())return void r.onError?.(Error("Web Speech API is unavailable"));let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(t.text),a=n.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(o.voice=e)}else a.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(a):an(a));void 0!==t.rate&&(o.rate=t.rate),void 0!==t.pitch&&(o.pitch=t.pitch),o.onend=()=>r.onEnd?.(),o.onerror=e=>{let t=e.error;"canceled"===t||"interrupted"===t?r.onEnd?.():r.onError?.(Error(t||"Speech synthesis failed"))},setTimeout(()=>{n.speak(o),r.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},ln=class{#e=null;#t=null;#r="idle";#n=new Set;#o=0;#a;constructor(e){this.#a=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#t===e?this.#r:"idle"}activeMessageId(){return this.#t}onChange(e){return this.#n.add(e),()=>this.#n.delete(e)}toggle(e,t){if(this.#t===e){if("playing"===this.#r)return void(this.#e?.supportsPause?(this.#e.pause(),this.#s(e,"paused")):this.stop());if("paused"===this.#r)return this.#e?.resume(),void this.#s(e,"playing");if("loading"===this.#r)return void this.stop()}this.play(e,t)}async play(e,t){let r=++this.#o;this.#e?.stop(),this.#s(e,"loading");try{if(!this.#e){let e=await this.#a();if(r!==this.#o)return;if(!e)return void this.#s(null,"idle");this.#e=e}this.#e.speak(t,{onStart:()=>{r===this.#o&&this.#s(e,"playing")},onEnd:()=>{r===this.#o&&this.#s(null,"idle")},onError:()=>{r===this.#o&&this.#s(null,"idle")}})}catch{r===this.#o&&this.#s(null,"idle")}}stop(){this.#o++,this.#e?.stop(),this.#s(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#n.clear()}#s(e,t){this.#t="idle"===t?null:e,this.#r=t;for(let e of this.#n)e(this.#t,this.#r)}},dn=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)}};let{setLoader:cn,load:pn,getSync:un}=N({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),hn=cn,mn=pn,gn=un;function fn(e){if(!e)return"";let t=function(e){let t=e.trim(),r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(r&&(t=r[1].trim()),!t.startsWith("{"))return null;try{let e=JSON.parse(t);if(e&&"object"==typeof e&&"string"==typeof e.text)return e.text}catch{}return null}(e);return function(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,"\n"),t=t.replace(/\n{2,}/g,"\n"),t.trim()}(null===t?e:t)}let yn=null,bn=()=>yn?yn():import("./voice/runtype-tts-entry"),{setLoader:vn,load:wn}=N({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),xn=vn,Cn=wn,Sn="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(".");var kn=class extends Error{constructor(e,t){super(t),this.name="SessionHistoryError",this.code=e}};function An(e,t){let r=e instanceof Error?e:Error(String(e));if("string"==typeof t)return t;if("function"==typeof t)return t(r);let n="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 r.message?`${n}\n\n_Details: ${r.message}_`:n}let Mn=e=>nt(e)||"suggest_replies"===e;var In=class e{#e;#t;#r;#n;#o;#a;#s;#i;#l;#d;#c;#p;#u;#h;#m;#g;#f;#y;#b;#v;#w;#S;#k;#A;#M;#I;#L;#P;#N;#R;#H;#B;#$;#E;#W;#F;constructor(e={},t,r={}){this.config=e,this.callbacks=t,this.historyInternals=r,this.status="idle",this.streaming=!1,this.#e=new Map,this.abortController=null,this.#r=Date.now(),this.clientSession=null,this.agentExecution=null,this.#n=null,this.#o=null,this.#a=!1,this.#s=null,this.#i=null,this.#l=null,this.artifacts=new Map,this.#d=null,this.webMcpInflightKeys=new Set,this.webMcpResolvedKeys=new Set,this.webMcpResolveControllers=new Set,this.#c=0,this.webMcpApprovalResolvers=new Map,this.#p=0,this.approvalTokens=new Map,this.webMcpAwaitBatches=new Map,this.#u=null,this.#h=null,this.#m=0,this.#g=0,this.#f=!1,this.#y="disconnected",this.#b=null,this.#v=null,this.#w=null,this.#S=0,this.#k=!1,this.#A=null,this.#M=!1,this.#I=null,this.#L=new Map,this.#P=null,this.#N=new Map,this.#R=null,this.#H=null,this.#B=!1,this.#$=null,this.#E=null,this.#W=!1,this.#F=null,this.#D=null,this.#q=null,this.#j=new dn,this.#_=Promise.resolve(),this.#x=null,this.#V=null,this.ttsSpokenMessageIds=new Set,this.readAloud=new ln(()=>this.#C()),this.#ne=null,this.#oe=0,this.handleEvent=e=>{let t=this.#V,r=!1;if(t&&("error"===e.type||"status"===e.type&&"error"===e.status?t.failed=!0:"message"===e.type&&"assistant"===e.message.role&&(t.dropped||this.ttsSpokenMessageIds.add(e.message.id),t.ids.includes(e.message.id)||t.ids.push(e.message.id),r=!0)),"message"===e.type){this.upsertMessage(e.message),r&&t.onUpdate?.(),"approval"===e.message.variant&&e.message.approval&&"pending"!==e.message.approval.status&&this.#e.set(e.message.id,this.#t),"assistant"===e.message.role&&!e.message.variant&&e.message.streaming&&(this.#o=e.message.id),("approval"===e.message.variant||!0===e.message.agentMetadata?.awaitingLocalTool)&&Jr().catch(()=>{});let n=e.message.toolCall,o=!!n?.name&&(nt(n.name)||"suggest_replies"===n.name&&Jt(this.config).enabled);!0===e.message.agentMetadata?.awaitingLocalTool&&o&&this.#ae(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?void 0!==e.message.agentMetadata.iteration&&(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("cursor"===e.type)this.#se(e.id);else if("status"===e.type){if("idle"===e.status&&!e.terminal&&this.#ie())return void this.#le();if(this.#de(e.status),"connecting"===e.status)this.#ce(!0);else if("idle"===e.status||"error"===e.status){this.#pe()||this.#ue(),0===this.webMcpResolveControllers.size&&(this.#ce(!1),this.abortController=null,this.#he(),this.#me());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;"running"===this.agentExecution?.status&&("error"===e.status?this.agentExecution.status="error":t||(this.agentExecution.status="complete")),this.#ge()}}else"error"===e.type?(this.#de("error"),this.#ue(),0===this.webMcpResolveControllers.size&&(this.#ce(!1),this.abortController=null),"running"===this.agentExecution?.status&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):("artifact_start"===e.type||"artifact_delta"===e.type||"artifact_update"===e.type||"artifact_complete"===e.type)&&this.#fe(e)},this.historyInternals=this.#Z(r),this.messages=[...e.initialMessages??[]].map(e=>({...e,sequence:e.sequence??this.#ye()})),this.messages=this.#be(this.messages),this.client=new Hr(e,this.historyInternals),this.#ve(),this.#we();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:"complete"});null!=e.initialSelectedArtifactId&&(this.#d=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#xe(),this.callbacks.onStatusChanged(this.status),this.#O(),this.#z()}#z(){this.config.voiceRecognition?.provider&&mn().catch(()=>{})}#O(){let e=this.config.textToSpeech;if("runtype"!==e?.provider||e.createEngine)return;let t=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&r&&this.config.clientToken&&bn().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return"running"===this.agentExecution?.status}isVoiceSupported(){return function(e){try{if("custom"===e?.type&&e.custom){let t=e.custom,r="function"==typeof t?t():t;return!!r&&"function"==typeof r.startListening}return!("runtype"!==e?.type||!e.runtype)||typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window)}catch{return!1}}(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#f}getVoiceStatus(){return this.#y}getVoiceNotice(){return this.#u?.takeNotice?.()??null}getVoiceDisclosure(){return this.#u?.getDisclosure?.()??null}getVoiceLevel(){return this.#u?.onLevel?this.#g:null}getVoiceInterruptionMode(){return this.#u?.getInterruptionMode?this.#u.getInterruptionMode():"none"}stopVoicePlayback(){this.#u?.stopPlayback&&(this.#j.cancel(),this.#x?.cancel(),this.#u.stopPlayback())}isBargeInActive(){return this.#u?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#u?.deactivateBargeIn&&await this.#u.deactivateBargeIn()}#D;#q;#j;#_;#x;#V;#C(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=sn.isSupported()?new sn({pickVoice:e?.pickVoice}):null;if("runtype"===e?.provider){let r=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,o=this.config.clientToken,a=!1!==e.browserFallback;if(r&&n&&o)return bn().then(({RuntypeSpeechEngine:s,FallbackSpeechEngine:i})=>{let l=new s({host:r,agentId:n,clientToken:o,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new i(l,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):l});if(a&&t)return o&&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 r=this.#_,n=++this.#m;this.#h=mn().then(async e=>{await r,n===this.#m&&this.#T(e,e.createVoiceProvider(t))}).catch(e=>{console.error("Failed to setup voice:",e)}).finally(()=>{n===this.#m&&(this.#h=null)})}catch(e){console.error("Failed to setup voice:",e)}}#T(e,t){this.#u=t;let r=this;e.wireSessionVoice({session:this,provider:()=>r.#u,generation:()=>r.#m,get keyed(){return r.#x},set keyed(e){r.#x=e},get pendingUser(){return r.#D},set pendingUser(e){r.#D=e},get pendingAssistant(){return r.#q},set pendingAssistant(e){r.#q=e},turns:()=>r.#j,busy:()=>r.#G(),setStreaming:e=>r.#ce(e),setDelegation:e=>{r.#V=e},setLevel:e=>{r.#g=e},setStatus:e=>{r.#y=e,r.#f="listening"===e},settlePending:e=>r.#K(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#u&&this.#h&&await this.#h,this.#u)if(this.#f)await this.#u.stopListening();else{this.stopSpeaking();try{await this.#u.startListening()}catch(e){console.error("Failed to start voice:",e)}}else console.error("Voice not configured")}prewarmVoice(){if(!ce(this.config.voiceRecognition?.provider))return void this.warmClientSession();let e=this.#m,t=()=>{let t=this.#u;t?.prewarm&&e===this.#m&&(this.#f||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#u&&this.#h?this.#h.then(t,()=>{}):t()}#G(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#a||"resuming"===this.status}cleanupVoice(){let e=null!==this.#u;if(this.#m++,this.#h=null,this.#u){let e=this.#u;this.#u=null,this.#_=this.#J(e)}this.#f=!1,this.#y="disconnected",this.#K(!0),this.#x?.settle(),this.#x=null,this.#j=new dn,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#J(e){try{await e.disconnect()}catch(e){console.error("Failed to disconnect voice:",e)}}#K(e){let t=e?this.#D:null,r=this.#q;(t||r)&&(r&&this.#j.cancel(),e&&(this.#D=null),this.#q=null,r&&this.ttsSpokenMessageIds.add(r),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==r?[e]:e.id!==r||e.content.trim()?[{...e,streaming:!1,voiceProcessing:!1}]:[]),this.callbacks.onMessagesChanged([...this.messages]),r&&this.#ce(!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.#H=this.historyInternals.getStoredConversationRevision?.()??null,this.#B=!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.#U(e,t)}#U(e,t=!this.messages.length){if(this.#k||!e.config.welcomeMessage||!t)return;let r=this.messages[0],n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:r?.createdAt??(new Date).toISOString(),sequence:r?(r.sequence??0)-1:this.#ye()};this.#Ce(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return!!e&&new Date<e.expiresAt}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.#Z(e),this.client.setHistoryInternals(this.historyInternals),this.#ve()}destroy(){this.cleanupVoice(),this.#$?.(),this.#$=null,this.#E=null}#Z(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#Se(e),t?.(e)}}}get#ee(){return this.historyInternals.historyProvider??null}#te(){let e=this.#ee;if(!e)throw new kn("history_unavailable","No conversation history provider is installed");return e}#re(e){let t=this.#te(),r=e??this.config.features?.history?.scope,n=this.config.getIdentityProof?"verified-user":"browser",o=r??(t.capabilities.scopes.includes(n)?n:t.capabilities.scopes[0]??n);if(!t.capabilities.scopes.includes(o))throw new $r("unsupported_scope","This history scope is not supported.");return{scope:o}}getHistoryState(){return{activeConversationId:this.#b,conversationRevision:this.#v,nextMessageCursor:this.#w,recovery:this.#A,sendBlocked:this.#M}}getActiveConversationId(){return this.#b}#Y(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#Q(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#I;e&&await e.catch(()=>{});let t=this.#P;t&&await t.catch(()=>{})}#X(){if(this.streaming||"paused"===this.status||"resuming"===this.status)throw new kn("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.#te().list({...e?.cursor?{cursor:e.cursor}:{},...void 0===e?.limit?{}:{limit:e.limit},...void 0===e?.targetId?{}:{targetId:e.targetId},context:this.#re(e?.scope)})}async openConversation(e,t){let r=this.#te();this.#X();let n=this.#re(t?.scope);await this.awaitHistorySettled();let o=++this.#S,a=await r.getPage(e,{context:n});if(o!==this.#S)throw new kn("superseded","A later selection won");let s=await r.prepareOpen(e,{context:n});if(o!==this.#S)throw s.discard(),new kn("superseded","A later selection won");this.#k=!0;try{await this.#ke(s)}finally{this.#k=!1}this.#b=s.conversationId||e,this.#v=s.conversationRevision||a.conversationRevision||null,this.#w=a.nextCursor,this.#A=null,this.#M=!1,this.#Ae();for(let e of a.messages)this.#N.set(e.id,e.content);return this.#Me(),this.hydrateMessages(a.messages),this.#Y(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,t,r){let n=this.#te(),o=this.#re(r?.scope),a=t??this.#w;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let s=`${e} ${a}`,i=this.#L.get(s);if(i)return i;let l=this.#Ie(n,e,a,o).finally(()=>{this.#L.delete(s)});return this.#L.set(s,l),l}async#Ie(e,t,r,n){let o=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:r,...o?{beforeCreatedAt:o}:{},context:n});if(this.#b&&this.#b!==t)return{messages:[],nextMessageCursor:a.nextCursor};let s=Ir(this.messages,a.messages);this.messages=this.#be(s.map(e=>this.#Te(e))),this.#w=a.nextCursor;for(let e of a.messages)this.#N.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#Y(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let t=this.#te(),r=this.#re(e?.scope);await this.awaitHistorySettled();let n=++this.#S,o=await t.prepareStartNew({context:r});if(n!==this.#S)throw o.discard(),new kn("superseded","A later action won");await this.#Ee(o)}async#Ee(e){this.#Le(),await this.#ke(e),this.#b=e.conversationId||null,this.#v=e.conversationRevision||null,this.#w=null,this.#A=null,this.#M=!1,this.#Me(),this.#Y()}async deleteConversation(e,t){let r=this.#te(),n=this.#re(t?.scope);await this.awaitHistorySettled(),await r.delete(e,{context:n}),e===this.#b&&await this.#Pe(n)}async updateConversation(e,t,r){let n=this.#te();if(!n.update)throw new kn("history_unavailable","This history provider cannot update conversations");let o=this.#re(r?.scope);return await this.awaitHistorySettled(),n.update(e,t,{context:o})}canUpdateConversations(){return"function"==typeof this.#ee?.update}async clearConversationHistory(e){let t=this.#te(),r=this.#re(e?.scope);await this.awaitHistorySettled();let n=await t.deleteAll({...void 0===e?.targetId?{}:{targetId:e.targetId},context:r});return await this.#Pe(r),n}async resetHistoryDevice(){let e=this.#te();if(!e.resetDevice)throw new kn("history_unavailable","This history provider cannot reset the device");this.#S+=1,this.#P=null;try{return await e.resetDevice()}finally{this.#Le(),this.#b=null,this.#v=null,this.#w=null,this.#A=null,this.#M=!1,this.#Y()}}async#Pe(e){this.#S+=1,this.#P=null,this.#Le(),this.#b=null,this.#v=null,this.#w=null,this.#M=!0,this.#A=null,this.#Y(),await this.#Be(e)}async#Be(e){let t=this.#ee;if(t)try{let r=await t.prepareStartNew({context:e});await this.#Ee(r)}catch{this.#M=!0,this.#A="new_conversation_required",this.#Y(),this.#Q("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}else this.#M=!1,this.#Y()}async#Ne(){if("new_conversation_required"===this.#A&&this.#ee&&(this.#A=null,await this.#Be(this.#re()),"new_conversation_required"===this.#A))throw new kn("new_conversation_required","A new conversation is required before sending")}async#ke(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.#b=e.conversationId,this.#v=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#k||this.#U(e)}#Me(){this.#b?this.config.setStoredConversationId?.(this.#b):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#v),this.historyInternals.setStoredMessageCursor?.(this.#w)}#Ae(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Re(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#N.clear(),this.#He(null)}#Le(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#$e(),this.#We(),this.#oe++,this.messages=[],this.#Ae(),this.#L.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#ce(!1),this.#de("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Se(e){this.#S+=1,this.#P=null,this.#M=!0,this.#Le(),this.#b=e.conversationId,this.#v=null,this.#w=null,this.#A=null,this.#Y(),this.#Q("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#I=Promise.resolve().then(()=>{this.#M=!1,this.#I=null,this.#Y()})}#ve(){let e=this.historyInternals.visitorStore??null;e!==this.#E&&(this.#$?.(),this.#$=null,this.#E=e,e&&(this.#$=e.subscribe(e=>this.#De(e))))}#De(e){if("external"!==e.source||null===e.previousToken)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#S+=1,this.#P=null,this.#W=!0,this.#F=null;let t=this.messages.length>0;t||null!==this.#b||null!==(this.config.getStoredConversationId?.()??null)?this.#Le():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#L.clear(),this.#He(null)),this.#b=null,this.#v=null,this.#w=null,this.#A=null,this.#Y(),t&&this.#Q("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#Fe(){return this.#W?(this.#F||=this.#Oe().finally(()=>{this.#F=null}),this.#F):Promise.resolve()}async#Oe(){if(this.isClientTokenMode())try{this.bindActivatedSession(await this.client.initSession()),this.#W=!1}catch{}else this.#W=!1}reconcileBootConversation(e){let t=this.#ee,r=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#b;if(!t||!r)return Promise.resolve();let n=this.#re(e?.scope);this.#M=!0,this.#Y();let o=this.#ze(t,r,n).finally(()=>{this.#M=null!==this.#A,this.#I===o&&(this.#I=null),this.#Y()});return this.#I=o,o}async#ze(e,t,r){this.#b=t;let n=this.clientSession?.conversationRevision??this.#v??null,o=this.#B?this.#H:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#B=!1,this.#w=this.historyInternals.getStoredMessageCursor?.()??this.#w,await this.replayPendingProjections(),n&&o&&n===o)return void(this.#v=n);let a,s=await e.getPage(t,{context:r}),i=new Set(s.messages.map(e=>e.id)),l=this.messages.some(e=>i.has(e.id)),d=s.messages[0]?.createdAt;if(l){let e=this.#n?this.#o:null;a=Ir(this.messages.filter(t=>!(!i.has(t.id)&&t.id!==e)||void 0!==d&&t.createdAt<d),s.messages).map(e=>this.#Te(e))}else a=s.messages.map(e=>this.#Te(e));this.#w=s.nextCursor,this.#v=s.conversationRevision||n||null,this.#N.clear();for(let e of s.messages)this.#N.set(e.id,e.content);this.#Me(),this.messages=this.#be(a),this.callbacks.onMessagesChanged([...this.messages])}#qe(){return!0===this.config.features?.history?.enabled&&this.isClientTokenMode()}#He(e){this.#R=e,this.historyInternals.setPendingDisplayProjections?.(e)}#je(){return this.historyInternals.getPendingDisplayProjections?.()??this.#R}#_e(e){if(this.#qe())for(let t of e){let e=Mr(t);void 0!==e&&this.#N.set(t.id,e)}}#me(){if(!this.#qe())return;let e=this.#b;if(!e)return;let t=[];for(let e of this.messages){if("assistant"!==e.role||e.streaming)continue;let r=Mr(e);void 0!==r&&this.#N.get(e.id)!==r&&t.push({id:e.id,displayContent:r})}0!==t.length&&(this.#He({conversationId:e,messageIds:t.map(e=>e.id)}),this.#Ve(e,t))}#Ve(e,t){let r=(this.#P??Promise.resolve()).catch(()=>{}).then(()=>this.#Ue(e,t,!1)).finally(()=>{this.#P===r&&(this.#P=null)});this.#P=r}async#Ue(e,t,r){if(this.#b!==e)return;let n=t.filter(e=>this.#N.get(e.id)!==e.displayContent);if(0===n.length)this.#Ge(e,t);else try{let{conversationRevision:r}=await this.client.finalizeDisplayProjections(e,n);for(let e of n)this.#N.set(e.id,e.displayContent);this.#b===e&&r&&(this.#v=r),this.#Ge(e,t)}catch(o){if(!r&&this.#Ke(o))return void await this.#Ue(e,n,!0);if(o instanceof Er&&("not_found"===o.code||"conversation_deleted"===o.code))return void this.#Ge(e,t);this.#Q("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#Ke(e){return e instanceof Er?"request_failed"===e.code:e instanceof Error}#Ge(e,t){let r=this.#je();if(!r||r.conversationId!==e)return;let n=new Set(t.map(e=>e.id)),o=r.messageIds.filter(e=>!n.has(e));this.#He(o.length?{conversationId:e,messageIds:o}:null)}async replayPendingProjections(){if(!this.#qe())return;let e=this.#je();if(!e)return;if(this.#b&&e.conversationId!==this.#b)return void this.#He(null);let t=[];for(let r of e.messageIds){let e=this.messages.find(e=>e.id===r);e&&"string"==typeof e.content&&t.push({id:r,displayContent:e.content})}0===t.length?this.#He(null):(this.#Ve(e.conversationId,t),await(this.#P?.catch(()=>{})))}#he(){this.#b&&(this.#v=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Je(){await this.awaitHistorySettled(),await this.#Fe(),"new_conversation_required"===this.#A&&await this.#Ne()}static#Qe(e){return e instanceof Er&&"conversation_deleted"===e.code}async#Xe(t,r,n,o,a){this.#_e(t);try{return void await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:n,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken},this.handleEvent)}catch(t){if(!e.#Qe(t))throw t;let s=await this.#Ye(o);if(!s)throw t;this.#_e([s]),await this.client.dispatch({messages:[s],signal:r.signal,assistantMessageId:n,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken},this.handleEvent)}}async#Ye(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let r={...t};this.#S+=1,this.#P=null,this.#Le(),this.#b=null,this.#v=null,this.#w=null,this.#k=!0;try{let e=this.#ee;if(e){let t=await e.prepareStartNew({context:this.#re()});await this.#Ee(t)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#M=!0,this.#A="new_conversation_required",this.#Y(),this.#Q("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#k=!1}return this.#Ce(r),this.#ce(!0),this.#Q("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(e=>e.id===r.id)??r}updateConfig(e){let t=this.config.features?.artifacts?.display,r={...this.config,...e},n=function(e,t){let r=e.voiceRecognition,n=t.voiceRecognition;return!0===r?.enabled!=(!0===n?.enabled)||r?.provider?.type!==n?.provider?.type||r?.provider?.custom!==n?.provider?.custom||r?.provider?.runtype?.createPlaybackEngine!==n?.provider?.runtype?.createPlaybackEngine||JSON.stringify(r?.provider?.runtype)!==JSON.stringify(n?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}(this.config,r),o=function(e,t){return Sn.some(r=>e[r]!==t[r])}(this.config,r);this.config=r,n&&(this.cleanupVoice(),!0===r.voiceRecognition?.enabled&&ce(r.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(r.features?.artifacts?.display);if(!o)return this.client.updateConfig(r),void(a&&this.#Ze());this.#We(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.client=new Hr(this.config,this.historyInternals),a&&this.#Ze(),this.#we(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:n,contentParts:o,id:a,createdAt:s,sequence:i,streaming:l=!1,voiceProcessing:d,voiceCaption:c,rawContent:p}=e,u={id:a??("user"===t?mt():"assistant"===t?gt():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:r,createdAt:s??(new Date).toISOString(),sequence:i??this.#ye(),streaming:l,...void 0!==n&&{llmContent:n},...void 0!==o&&{contentParts:o},...void 0!==d&&{voiceProcessing:d},...c&&{voiceCaption:c},...void 0!==p&&{rawContent:p}};return this.upsertMessage(u),u}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 r of e){let{role:e,content:n,llmContent:o,contentParts:a,id:s,createdAt:i,sequence:l,streaming:d=!1,voiceProcessing:c,rawContent:p}=r,u={id:s??("user"===e?mt():"assistant"===e?gt():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:n,createdAt:i??(new Date).toISOString(),sequence:l??this.#ye(),streaming:d,...void 0!==o&&{llmContent:o},...void 0!==a&&{contentParts:a},...void 0!==c&&{voiceProcessing:c},...void 0!==p&&{rawContent:p}};t.push(u)}return this.messages=this.#be([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:n="",llmContent:o,id:a,createdAt:s,sequence:i}=e,l={text:n,component:t,props:r};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(l),...void 0!==o&&{llmContent:o},...void 0!==a&&{id:a},...void 0!==s&&{createdAt:s},...void 0!==i&&{sequence:i}})}async#et(e,t,r){let n;try{n=await r()}catch{return}let o=n.blocks.join("\n\n"),a=[o,t].filter(Boolean).join("\n\n"),s=Array.isArray(e.contentParts)&&e.contentParts.length>0,i=n.contentParts.length>0;if(s){let t=[];o&&t.push(xr(o)),t.push(...n.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(i){let t=[];a&&t.push(xr(a)),t.push(...n.contentParts),e.contentParts=t}else o&&(e.llmContent=a);Object.keys(n.context).length>0&&(e.mentionContext=n.context)}async sendMessage(e,t){let r=e.trim(),n=!!t?.replayFields&&(void 0!==t.replayFields.llmContent||void 0!==t.replayFields.rawContent||(t.replayFields.contextMentions?.length??0)>0);if(!(r||t?.contentParts&&0!==t.contentParts.length||t?.mentions&&0!==t.mentions.refs.length||n))return;this.#V&&!t?.voiceTurn&&(this.#V.failed=!0,this.#V=null),(this.#I||this.#P||this.#M||this.#W)&&await this.#Je(),this.stopSpeaking(),this.abortController?.abort(),this.#We(),this.#oe++,this.#$e();let o=t?.voiceTurn?.userMessageId,a=o?this.messages.find(e=>e.id===o&&"user"===e.role):void 0,s=a?.id??mt(),i=gt();this.#o=null;let l=t?.contentParts&&wr(t.contentParts)?"[Image]":"",d={id:s,role:"user",content:r||l,createdAt:(new Date).toISOString(),sequence:this.#ye(),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()!==r&&(a.llmContent=r),this.callbacks.onMessagesChanged([...this.messages])):this.#Ce(d),this.#ce(!0);let c=new AbortController;if(this.abortController=c,t?.mentions){let e=this.messages.find(e=>e.id===s)??d;if(await this.#et(e,r,t.mentions.finalize),c.signal.aborted||this.abortController!==c)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===s)??d,r=function(e){let t=function(e){let t=e?.text?.trim()??"";return t?function(e,t){let r="`".repeat(Math.max(3,function(e){let t=0;for(let r of e.split("\n")){let e=/^ {0,3}(`+)/.exec(r);e&&e[1].length>t&&(t=e[1].length)}return t}(t)+1));return`${r}${e}\n${t}\n${r}`}((e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text")(e),t):""}(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[xr(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join("\n\n")}:{}}({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});r.contentParts&&(e.contentParts=r.contentParts),void 0!==r.llmContent&&(e.llmContent=r.llmContent),(r.contentParts||void 0!==r.llmContent)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let p=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:(new Date).toISOString()}]:[...this.messages];try{await this.#Xe(p,c,i,s,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn})}catch(e){if("resuming"===this.status||this.#a)return;this.#V&&(this.#V.failed=!0);let t=e instanceof Error&&("AbortError"===e.name||e.message.includes("aborted")||e.message.includes("abort"));if(!t){let t=An(e,this.config.errorMessage);if(t){let e={id:i,role:"assistant",createdAt:(new Date).toISOString(),content:t,sequence:this.#ye()};this.#Ce(e)}}this.#de("idle"),this.#ce(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}resubmitFrom(e,t){let r=function(e,t){let r=e.findIndex(e=>e.id===t);if(-1===r||"user"!==e[r].role)return null;let n=r+1;for(;n<e.length&&"user"!==e[n].role;)n+=1;return{start:r,end:n}}(this.messages,e);if(!r)return!1;let n=this.messages[r.start],o=t.replacement,a=o?o.text:n.content,s=o?o.contentParts:n.contentParts;if(!(a?.trim()||(s?.length??0)>0||!o&&(n.llmContent?.trim()?.length??0)>0))return!1;let i=o?void 0:{...void 0!==n.llmContent&&{llmContent:n.llmContent},...void 0!==n.rawContent&&{rawContent:n.rawContent},...n.mentionContext&&{mentionContext:n.mentionContext},...n.contextMentions&&{contextMentions:n.contextMentions},...n.quote&&{quote:n.quote}},l=o?this.#tt(o.options):n.composerOptions,d=o?o.contentSegments:n.contentSegments,c=o?o.options?.quote:void 0,p=o?o.viaVoice:n.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,r.start),this.sendMessage(a??"",{...s?.length?{contentParts:[...s]}:{},...d?.length?{contentSegments:[...d]}:{},...l?{composerOptions:l}:{},...c?{quote:c}:{},...i&&Object.keys(i).length>0?{replayFields:i}:{},viaVoice:!0===p}),!0}#tt(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.#I||this.#P||this.#M||this.#W)&&await this.#Je(),this.abortController?.abort(),this.#$e();let e=gt();this.#o=null,this.#ce(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(t){if("resuming"===this.status||this.#a)return;let r=t instanceof Error&&("AbortError"===t.name||t.message.includes("aborted")||t.message.includes("abort"));if(!r){let r=An(t,this.config.errorMessage);if(r){let t={id:e,role:"assistant",createdAt:(new Date).toISOString(),content:r,sequence:this.#ye()};this.#Ce(t)}}this.#de("idle"),this.#ce(!1),this.abortController=null,r||(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.#o=t.assistantMessageId);let r=t?.preserveAssistantId?t.assistantMessageId:void 0,n=!1;for(let e of this.messages)e.streaming&&e.id!==r&&(e.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.#ce(!0);let o={};try{await this.client.processStream(e,e=>{let t=this.#t;this.#t=o;try{this.handleEvent(e)}finally{this.#t=t}},t?.assistantMessageId,t?.seedContent),this.#rt(o)}catch(e){if("resuming"===this.status||this.#a)return void this.#nt(o);this.#rt(o),this.#de("error"),0===this.webMcpResolveControllers.size&&(this.#ce(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#we(){let e=this.config.webmcp;!0===e?.enabled&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(!0===this.config.webmcp?.autoApprove?.(e))return Promise.resolve(!0)}catch{}if(e.signal?.aborted)return Promise.resolve(!1);let t={id:"webmcp-"+ ++this.#p,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(t=>{this.webMcpApprovalResolvers.set(r,t),e.signal?.addEventListener("abort",()=>this.resolveWebMcpApproval(r,"timeout"),{once:!0})})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let n=this.messages.find(t=>t.id===e);n?.approval&&this.upsertMessage({...n,approval:{...n.approval,status:t,resolvedAt:Date.now()}}),r("approved"===t)}#ne;#oe;#ot(e){let t=this.#ne??={s:this,setStreaming:e=>this.#ce(e),appendMessage:e=>this.#Ce(e),nextSequence:()=>this.#ye(),settleApprovalPausedToolCall:e=>this.#at(e),resumeAfter:e=>this.#n?.executionId===e?this.#n.lastEventId:void 0},r=Qr();if(r)return e(r,t);let n=this.#oe;return Jr().then(r=>n===this.#oe?e(r,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,r){return this.#ot((n,o)=>n.resolveApproval(o,e,t,r))}resolveAskUserQuestion(e,t){return this.#ot((r,n)=>r.resolveAskUserQuestion(n,e,t))}resolveWebMcpToolCall(e){return this.#ot((t,r)=>t.resolveWebMcpToolCall(r,e))}persistAskUserQuestionProgress(e,t){let r=this.messages.find(t=>t.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(t=>t.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#ae(e){let t=e.agentMetadata?.executionId,r=e.toolCall?.id;if(!t||!r){let t=this.#c;return void queueMicrotask(()=>{t===this.#c&&this.resolveWebMcpToolCall(e)})}let n=this.webMcpAwaitBatches.get(t);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,n)),!n.seen.has(r)&&(n.seen.add(r),n.snapshots.push(e))}#ge(){if(0===this.webMcpAwaitBatches.size)return;let e=this.#c;queueMicrotask(()=>{if(e===this.#c)for(let e of[...this.webMcpAwaitBatches.keys()])this.#st(e)})}#st(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;1===r.length?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.#ot((t,n)=>t.resolveWebMcpToolCallBatch(n,e,r))}#We(){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.#c++}cancel(){this.abortController?.abort(),this.abortController=null,this.#$e(),this.#We(),this.#oe++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#ce(!1),this.#de("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#$e(),this.#We(),this.#oe++,this.messages=[],this.agentExecution=null,this.#Re(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#ce(!1),this.#de("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#d}selectArtifact(e){this.#d=e,this.#xe()}clearArtifacts(){this.#Re()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,r="markdown"===e.artifactType?{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,r),this.#d=t,this.#xe(),!1!==e.transcript&&this.#it(r),r}#it(e){let t=`artifact-ref-${e.id}`,r=tn(en(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}:{},...void 0===e.markdown?{}:{markdown:e.markdown}}),n=this.messages.find(e=>e.id===t);n?(n.rawContent=r,n.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:"",rawContent:r})}#Ze(){let e=!1;for(let t of this.artifacts.values()){let r=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!r)continue;let n=tn(en(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}:{},...void 0===t.markdown?{}:{markdown:t.markdown}});r.rawContent!==n&&(r.rawContent=n,r.streaming="streaming"===t.status,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#Re(){(0!==this.artifacts.size||null!==this.#d)&&(this.artifacts.clear(),this.#d=null,this.#xe())}#xe(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#d})}#fe(e){switch(e.type){case"artifact_start":"markdown"===e.artifactType?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.#d=e.id;break;case"artifact_delta":{let t=this.artifacts.get(e.id);"markdown"===t?.artifactType&&(t.markdown=(t.markdown??"")+e.artDelta);break}case"artifact_update":{let t=this.artifacts.get(e.id);"component"===t?.artifactType&&(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.#xe()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#$e(),this.#We(),this.#oe++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#be(e.map(e=>({...e,streaming:!1,sequence:e.sequence??this.#ye()}))),this.#ce(!1),this.#de("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.#d=t,this.#xe()}#se(e){let t=this.agentExecution?.executionId;if(!t||!this.#o||"running"!==this.agentExecution?.status)return;let r=null===this.#n;this.#n={executionId:t,lastEventId:e,assistantMessageId:this.#o,status:"running"},this.#lt(r)}#ie(){return null!==this.#n&&"function"==typeof this.config.reconnectStream&&!0!==this.abortController?.signal.aborted&&0===this.webMcpResolveControllers.size&&0===this.webMcpAwaitBatches.size&&!this.#pe()}#pe(){return this.messages.some(e=>!0===e.agentMetadata?.awaitingLocalTool&&!0!==e.agentMetadata?.askUserQuestionAnswered||"approval"===e.variant&&"pending"===e.approval?.status)}#le(){this.#a||this.#n&&"function"==typeof this.config.reconnectStream&&(this.#a=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#n}),this.#ce(!0),this.#de("resuming"),this.#dt().then(e=>{this.#a&&this.#n&&e.begin()}))}#dt(){return this.#s?Promise.resolve(this.#s):(this.#i||(this.#i=Cn().then(({createReconnectController:e})=>{let t=e(this.#ct());return this.#s=t,t}),this.#i.catch(()=>{this.#i=null})),this.#i)}#ct(){let e=this;return{get config(){return e.config},getResumable:()=>e.#n,clearResumable:()=>e.#ue(),getStatus:()=>e.status,setStatus:t=>e.#de(t),setStreaming:t=>e.#ce(t),setReconnecting:t=>{e.#a=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,n)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:n}),appendMessage:t=>e.#Ce(t),nextSequence:()=>e.#ye(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>An(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#a?this.#s?.wake():this.#le()}resumeFromHandle(e){if("function"!=typeof this.config.reconnectStream||this.#a)return;let t=this.#pt();t||(t=gt(),this.#Ce({id:t,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,sequence:this.#ye()})),this.#o=t,this.agentExecution||={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0},this.#n={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.#le()}#pt(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if("assistant"===t.role&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if("user"===t.role)break}return null}#$e(){this.#a=!1,this.#s?.teardown(),this.#ue()}#ue(){this.#l&&=(clearTimeout(this.#l),null);let e=null!==this.#n;this.#n=null,e&&this.config.onExecutionState?.(null)}#lt(e){let t=this.config.onExecutionState;t&&(e?(this.#l&&=(clearTimeout(this.#l),null),t(this.#n)):this.#l||=setTimeout(()=>{this.#l=null,this.config.onExecutionState?.(this.#n)},500))}getResumableHandle(){return this.#n}#de(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#ce(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#rt(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||t.provider&&"browser"!==t.provider&&("runtype"!==t.provider||!t.browserFallback))return;let r=[...this.messages].reverse().find(e=>"assistant"===e.role&&e.content&&!e.voiceProcessing);if(!r||e&&!e.includes(r.id))return;if(this.ttsSpokenMessageIds.has(r.id))return void this.ttsSpokenMessageIds.delete(r.id);let n=fn(r.content);n.trim()&&this.readAloud.play(r.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return an(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||"assistant"!==t.role)return;let r=fn(t.content||"");if(!r.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:n?.voice,rate:n?.rate,pitch:n?.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()}#rt(e){for(let[t,r]of[...this.#e])r===e&&(this.#e.delete(t),this.#at(t))}#nt(e){for(let[t,r]of this.#e)r===e&&this.#e.set(t,void 0)}#at(e){let t=this.messages.find(t=>t.id===e)?.approval,r=t?.toolCallId,n=r&&this.messages.find(e=>e.toolCall?.id===r),o=n&&n.toolCall;if(!o||"complete"===o.status||"pending"===t.status)return;let a={...o,status:"complete",approvalStatus:t.status,completedAt:Date.now(),..."approved"===t.status?{superseded:!0}:{success:!1,error:"denied"===t.status?"Denied":"Approval timed out"}};this.upsertMessage({...n,streaming:!1,toolCall:a})}#Ce(e){let t=this.#Te(e);this.messages=this.#be([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#Te(e),r=this.messages.findIndex(e=>e.id===t.id);-1===r?this.#Ce(t):(this.messages=this.messages.map((e,n)=>{if(n!==r)return e;let o={...e,...t};!0===e.agentMetadata?.askUserQuestionAnswered&&t.agentMetadata&&(o.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),!0===e.agentMetadata?.suggestRepliesResolved&&t.agentMetadata&&(o.agentMetadata={...o.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&o.agentMetadata&&!o.agentMetadata.clientToolAnswer&&(o.agentMetadata={...o.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let r=e.approval,n=t.approval;o.approval={...r,...n,executionId:n.executionId||r.executionId,toolName:n.toolName||r.toolName,description:n.description||r.description,toolType:n.toolType??r.toolType,reason:n.reason??r.reason,parameters:n.parameters??r.parameters,toolCallId:n.toolCallId??r.toolCallId}}let s=t.toolCall?.name,i=t.agentMetadata?.executionId,l=t.toolCall?.id;if(s&&Mn(s)&&i&&l&&!0===t.agentMetadata?.awaitingLocalTool){let t=`${i}:${l}`,r=this.webMcpInflightKeys.has(t),n=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,s=e.agentMetadata?.executionId===i&&e.toolCall?.id===l&&void 0!==a&&Mn(a)&&"complete"===e.toolCall?.status;(r||n||s)&&(o.agentMetadata={...o.agentMetadata??{},awaitingLocalTool:!1},o.toolCall=e.toolCall,o.streaming=e.streaming)}return o}),this.messages=this.#be(this.messages),this.callbacks.onMessagesChanged([...this.messages]))}#Te(e){return void 0===e.sequence?{...e,sequence:this.#ye()}:{...e}}#ye(){return this.#r++}#be(e){return[...e].sort((e,t)=>{let r=new Date(e.createdAt).getTime(),n=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(n)&&r!==n)return r-n;let o=e.sequence??0,a=t.sequence??0;return o===a?e.id.localeCompare(t.id):o-a})}};let Tn={add:e=>async function(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result;kr(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},n.onerror=()=>r(Error("Failed to read file")),n.readAsDataURL(e)})}(e)},En={allowedTypes:Sr,maxFileSize:10485760,maxFiles:4};function Ln(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Pn(e){return"application/pdf"===e||e.startsWith("text/")||e.includes("word")?r.FileText:e.includes("excel")||e.includes("spreadsheet")?r.FileSpreadsheet:"application/json"===e?r.FileCode:r.File}var Bn=class e{#e;#t;#r;constructor(e={}){this.attachments=[],this.#e=null,this.#t=new Map,this.#r=!1,this.config={allowedTypes:e.allowedTypes??En.allowedTypes,maxFileSize:e.maxFileSize??En.maxFileSize,maxFiles:e.maxFiles??En.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#n(){return"function"==typeof this.config.adapter?.add}#o(){return this.#n()?this.config.adapter:Tn}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML="";for(let e of this.attachments)this.#d(e)}this.#u()}updateConfig(e){void 0!==e.allowedTypes&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:En.allowedTypes),void 0!==e.maxFileSize&&(this.config.maxFileSize=e.maxFileSize),void 0!==e.maxFiles&&(this.config.maxFiles=e.maxFiles),void 0!==e.onFileRejected&&(this.config.onFileRejected=e.onFileRejected),void 0!==e.onAttachmentsChange&&(this.config.onAttachmentsChange=e.onAttachmentsChange),void 0!==e.adapter&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>"ready"===e.status)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>null!==e)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){e&&0!==e.length&&await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#r)return;let t=[];for(let r of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(r,"count");continue}let e=Ar(r,this.config.allowedTypes,this.config.maxFileSize);if(!e.valid){let t=e.error?.includes("type")?"type":"size";this.config.onFileRejected?.(r,t);continue}let n={id:Ln(),file:r,previewUrl:kr(r)?URL.createObjectURL(r):null,contentPart:null,status:this.#n()?"uploading":"processing",progress:this.#n()?0:void 0};this.attachments.push(n),this.#d(n),t.push(n)}this.#u(),this.#l(),await Promise.all(t.map(e=>this.#a(e)))}async#a(e){let t=new AbortController;this.#t.set(e.id,t);let r=()=>this.#r||t.signal.aborted||this.#t.get(e.id)!==t||!this.attachments.includes(e);try{let n=await this.#o().add(e.file,{signal:t.signal,onProgress:t=>{r()||"uploading"!==e.status||(e.progress=(e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0)(t),this.#c(e),this.#l())}});if(r())return;e.contentPart=n,e.status="ready",e.progress=void 0,e.error=void 0}catch(t){if(r())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.#c(e),this.#l()}retryAttachment(e){let t=this.attachments.find(t=>t.id===e);!t||"error"!==t.status||this.#r||(t.status=this.#n()?"uploading":"processing",t.progress=this.#n()?0:void 0,t.error=void 0,this.#c(t),this.#l(),this.#a(t))}#s(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(-1===t)return;let r=this.attachments[t];this.#s(e),r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let n=this.#e?.querySelector(`[data-attachment-id="${e}"]`);n&&n.remove(),"ready"===r.status&&r.contentPart&&this.#i(r.contentPart),this.#u(),this.#l()}#i(e){let t=this.config.adapter?.remove;if(t)try{let r=t(e,{signal:(new AbortController).signal});r&&"function"==typeof r.catch&&r.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.#s(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=""),this.#u(),this.#l()}destroy(){if(!this.#r){this.#r=!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}}#l(){this.#r||this.config.onAttachmentsChange?.(this.getAttachments())}#d(e){if(!this.#e)return;let t=kr(e.file),o=L("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",t&&e.previewUrl){let t=L("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",o.appendChild(t)}else{let t=L("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=Pn(e.file.type),a=n(r,20,"var(--persona-muted, #6b7280)",1.5);a&&t.appendChild(a);let s=L("span");s.textContent=function(e,t){let r=function(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}(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]||r||"FILE"}(e.file.type,e.file.name),s.style.fontSize="8px",s.style.fontWeight="600",s.style.color="var(--persona-muted, #6b7280)",s.style.textTransform="uppercase",s.style.lineHeight="1",t.appendChild(s),o.appendChild(t)}let a=P("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=L("div","persona-attachment-progress");s.appendChild(L("div","persona-attachment-progress__bar"));let i=P("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=K("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):i.textContent="↻",i.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),a.append(s,i),o.appendChild(a);let d=L("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let c=n(r.X,10,"var(--persona-text-inverse, #ffffff)",2);c?d.appendChild(c):(d.textContent="×",d.style.color="var(--persona-text-inverse, #ffffff)",d.style.fontSize="14px",d.style.lineHeight="1"),d.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(d),this.#e.appendChild(o),this.#p(o,e)}#c(e){let t=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);t&&this.#p(t,e)}#p(e,t){e.dataset.status=t.status;let r="ready"!==t.status&&"error"!==t.status;e.setAttribute("aria-busy",r?"true":"false"),e.title="error"===t.status?`${t.file.name}: ${t.error??"Upload failed"}`:t.file.name;let n=e.querySelector(".persona-attachment-progress__bar");if(n){let e=t.progress;n.style.width="number"==typeof e?`${Math.round(100*e)}%`:""}}#u(){this.#e&&(this.#e.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:r,adapter:t?.adapter})}};let Nn=(e,t)=>e.length===t.length&&e.every((e,r)=>e===t[r]);function Rn(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,r=null,n=!1,o=!1,a=()=>(r||=(()=>{let t=e.preparing?"preparing":e.streaming?"streaming":"idle";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:"idle"!==t||e.sendDisabled||e.inputDisabled})})(),r),s=()=>{if(n=!1,o||0===t.size)return;let e=a();for(let r of[...t])try{r(e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",e)}},i=()=>{r=null,!o&&!n&&(n=!0,queueMicrotask(s))};return{getState:a,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,i())},setAttachments:t=>{((e,t)=>e.length===t.length&&e.every((e,r)=>{let n=t[r];return e.id===n.id&&e.name===n.name&&e.mimeType===n.mimeType&&e.size===n.size&&e.status===n.status&&e.progress===n.progress&&e.error===n.error}))(e.attachments,t)||(e.attachments=[...t],i())},setMentionRefs:t=>{Nn(e.mentionRefs,t)||(e.mentionRefs=[...t],i())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,i())},setActiveModeIds:t=>{Nn(e.activeModeIds,t)||(e.activeModeIds=[...t],i())},setQuote:t=>{let r=e.quote;(r?.text!==t?.text||r?.messageId!==t?.messageId||r?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,i())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,i())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,i())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,i())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,i())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,i())},flush:()=>{n&&s()},destroy:()=>{o=!0,n=!1,t.clear()}}}let Hn=(e,...t)=>{for(let r of t){let t=e.querySelector(r);if(t)return t}return null},$n=(e,t)=>{let r=L("div",e);return r.setAttribute(t,""),r.setAttribute("data-persona-composer-synthesized",""),r.style.display="contents",r};function Wn(e,t={}){let r=Hn(e,"[data-persona-composer-form]"),n=Hn(e,"[data-persona-composer-input]");if(!r||!n){let e=`[Persona] composer surface is missing required element(s): ${[!r&&"form",!n&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(r||n))throw Error(e);return typeof console<"u"&&console.warn(e),null}let o={header:Hn(e,"[data-persona-composer-header]"),body:Hn(e,"[data-persona-composer-body]"),actionsStart:Hn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Hn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Hn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Hn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Hn(e,"[data-persona-composer-status]")},a=new Set,s=o.header;s||(a.add("header"),s=$n("persona-widget-composer__header","data-persona-composer-header"),r.parentNode?r.parentNode.insertBefore(s,r):e.appendChild(s));let i=o.body??n.parentElement??r,l=(e,t,r,n,o)=>{if(t)return t;a.add(e);let s=$n(r,n);return o.appendChild(s),s},d=l("actionsStart",o.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",r),c=l("actionsEnd",o.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",r),p=l("suggestions",o.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),u=l("status",o.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[];return{footer:e,form:r,input:n,header:s,body:i,actionsStart:d,actionsEnd:c,suggestions:p,status:u,attachmentInput:Hn(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0,attachmentPreviews:Hn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Hn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Hn(e,"[data-persona-composer-submit]")??void 0,micButton:Hn(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:o,addListener:(e,t,r,n)=>{e.addEventListener(t,r,n),h.push({target:e,type:t,handler:r,options:n})},removeListener:(e,t,r,n)=>{e.removeEventListener(t,r,n),h=h.filter(n=>!((e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler)(n,{target:e,type:t,handler:r}))},destroy:()=>{for(let e of h)e.target.removeEventListener(e.type,e.handler,e.options);h=[]}}}let Dn=200,Fn=300,On=0,zn=e=>Math.max(0,e);function qn(e){void 0!==e.delayMs&&(Dn=zn(e.delayMs)),void 0!==e.skipDelayMs&&(Fn=zn(e.skipDelayMs))}let jn=new WeakMap,_n=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Vn=(e,t,r)=>Math.min(Math.max(e,t),Math.max(t,r)),Un=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"];function Gn(e){jn.get(e.anchor)?.destroy();let t,{anchor:r,trigger:n=r,text:o,hint:a,enabled:s=!0,gap:i=8,viewportPadding:l=8}=e,d=()=>r.ownerDocument,c=()=>d().defaultView??window,p=null,u=null,h=null,m=null,g=!1,f=!1,y=!1,b=()=>("function"==typeof o?o():o).trim(),v=()=>("function"==typeof a?a():a??"").trim(),w=()=>zn(e.delayMs??Dn),x=()=>zn(e.skipDelayMs??Fn),C=()=>{void 0!==t&&(c().clearTimeout(t),t=void 0)},S=()=>{C();let e=null!==p;m?.(),m=null,p?.remove(),p=null,u=null,h=null,e&&(e=>{On=e>0?Date.now()+e:0})(x())},k=()=>{if(!p)return;let e=d(),t=c(),n=r.getBoundingClientRect(),o=p.getBoundingClientRect(),a=e.documentElement.clientWidth||t.innerWidth,s=e.documentElement.clientHeight||t.innerHeight,u=a-l-o.width,h=n.left+n.width/2-o.width/2,m=Vn(h,l,u),g=n.top-l,f=s-l-n.bottom,y=g>=o.height+i||g>=f?"top":"bottom",b="top"===y?n.top-i-o.height:n.bottom+i,v=s-l-o.height,w=Vn(b,l,v),x=n.left+n.width/2,C=Math.max(10,o.width-10),S=Vn(x-m,10,C);p.dataset.placement=y,p.style.left=`${m}px`,p.style.top=`${w}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${S}px`)},A=()=>{if(y||!s||p||!r.isConnected||(e=>"function"==typeof e.closest&&null!==e.closest("[data-persona-tooltip-suppressed]"))(r))return;let e=b(),t=(e=>{let t=e.getRootNode?.();return _n(t)?t:e.ownerDocument.body})(r);if(!e||!t)return;let n=d(),o=c();p=n.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex="100001";let a=o.getComputedStyle?.(r);if(a){for(let e of Un){let t=a.getPropertyValue(e).trim();t&&p.style.setProperty(e,t)}a.fontFamily&&(p.style.fontFamily=a.fontFamily)}u=n.createElement("span"),u.className="persona-control-tooltip__label",u.textContent=e,p.appendChild(u);let i=v();i&&(h=n.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=i,p.appendChild(h));let l=n.createElement("span");l.className="persona-control-tooltip__arrow",p.appendChild(l),t.appendChild(p),k(),p.dataset.state="open";let g=()=>{r.isConnected?(u&&(u.textContent=b()),h&&(h.textContent=v()),k()):S()};o.addEventListener("scroll",g,!0),o.addEventListener("resize",g);let f=r.getRootNode(),w=_n(f)?f:n.documentElement,x=typeof MutationObserver>"u"?null:new MutationObserver(()=>{r.isConnected||S()});x?.observe(w,{childList:!0,subtree:!0}),m=()=>{o.removeEventListener("scroll",g,!0),o.removeEventListener("resize",g),x?.disconnect()}},M=()=>{g||f?(e=>{y||p||(C(),e||w()<=0||Date.now()<On?A():t=c().setTimeout(()=>{t=void 0,A()},w()))})(f):S()},I=()=>{let e=c();e.matchMedia&&e.matchMedia("(hover: none)").matches||(g=!0,M())},T=()=>{g=!1,M()},E=()=>{try{f=r.matches(":focus-visible")}catch{f=!0}M()},L=()=>{f=!1,M()},P=()=>{g=!1,f=!1,S()},B=e=>{"Escape"===e.key&&P()};n.addEventListener("mouseenter",I),n.addEventListener("mouseleave",T),r.addEventListener("focus",E),r.addEventListener("blur",L),r.addEventListener("keydown",B),r.addEventListener("click",P);let N={get isOpen(){return null!==p},show:A,hide:S,reposition:k,destroy:()=>{y||(y=!0,S(),n.removeEventListener("mouseenter",I),n.removeEventListener("mouseleave",T),r.removeEventListener("focus",E),r.removeEventListener("blur",L),r.removeEventListener("keydown",B),r.removeEventListener("click",P),jn.delete(r))}};return jn.set(r,N),N}function Kn(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let r=t.getComputedStyle(e).lineHeight;if(!r||!r.trim().endsWith("px"))return 20;let n=parseFloat(r);return Number.isFinite(n)&&n>0?n:20}function Jn(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function Qn(e,t){e.style.maxHeight=t*Kn(e)+"px",e.style.overflowY="auto"}function Xn(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||"function"!=typeof t.matchMedia)return!1;try{return!0===t.matchMedia("(pointer: coarse)").matches}catch{return!1}}function Yn(e){return!0===e.insertNewlineOnTouchEnter&&!0===e.coarsePointer}function Zn(e,t){if("Enter"!==e.key||e.shiftKey||e.isComposing)return!1;let r=!0===e.metaKey||!0===e.ctrlKey,n=t.submitKey??"enter";return"none"!==n&&("mod-enter"===n?r:r||!Yn(t))}function eo(e,t){e.setAttribute("enterkeyhint",function(e){return"enter"===(e.submitKey??"enter")?Yn(e)?"enter":"send":"enter"}(t))}function to(e,t){let r=t?.autocomplete;e.setAttribute("autocomplete","string"==typeof r&&r?r:"off");let n=(t,r)=>{void 0===r?e.removeAttribute(t):e.setAttribute(t,r)};n("autocapitalize","string"==typeof t?.autocapitalize?t.autocapitalize:void 0),n("spellcheck","boolean"==typeof t?.spellcheck?String(t.spellcheck):void 0),n("inputmode","string"==typeof t?.inputmode&&t.inputmode?t.inputmode:void 0),n("aria-label","string"==typeof t?.ariaLabel&&t.ariaLabel?t.ariaLabel:void 0)}function ro(e){return!0===e?{disabled:!0}:e&&"object"==typeof e?{disabled:!0,reason:"string"==typeof e.reason&&e.reason?e.reason:void 0}:{disabled:!1}}let no="persona-composer-control",oo="persona-composer-control--glyph",ao=(e,t,r)=>{let n=e.ownerDocument?.defaultView;if(!n)return;let o=n.getComputedStyle(e);for(let e of r){let r=o.getPropertyValue(e).trim();r?t.style.setProperty(e,r):t.style.removeProperty(e)}},so=(e,t)=>{let r=L("textarea");r.setAttribute("data-persona-composer-input",""),r.placeholder=e?.copy?.inputPlaceholder??"How can I help...",r.dir="auto",eo(r,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Xn(r)}),to(r,e?.composer?.inputAttributes),r.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",r.rows=1,r.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',r.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=Jn(e?.composer?.maxLines,t?.defaultMaxLines??3),o=20*n+"px";return r.style.maxHeight=o,r.style.overflowY="auto",r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.addEventListener("focus",()=>{r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.style.boxShadow="none"}),r.addEventListener("blur",()=>{r.style.border="none",r.style.outline="none"}),{textarea:r,attachAutoResize:()=>{r.addEventListener("input",()=>{r.style.height="auto";let e=Math.min(r.scrollHeight,(()=>{let e=r.style.maxHeight;if(e!==o){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=n*Kn(r);return o=`${t}px`,r.style.maxHeight=o,t})());r.style.height=`${e}px`})}}},io=(e,t,r="send")=>{let n=P("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":r,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),n.append(e,t),n},lo=e=>{let t=e?.sendButton??{},r=t.useIcon??!1,n=t.iconText??"↑",o=t.iconName,a=t.stopIconName??"square",s=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",l=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,p=t.size,u=parseFloat(p??"")||40,h=t.backgroundColor,m=t.textColor,g=L("div","persona-send-button-wrapper"),f=P("button",{className:B("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?`persona-flex persona-items-center persona-justify-center ${no}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!h&&"persona-bg-persona-primary",!r&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:r?p:void 0,height:r?p:void 0,minWidth:r?p:void 0,minHeight:r?p:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?m||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":m||void 0,backgroundColor:r&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:r?"0":t.paddingX||void 0,paddingRight:r?"0":t.paddingX||void 0,paddingTop:r?"0":t.paddingY||void 0,paddingBottom:r?"0":t.paddingY||void 0}}),y=null,b=null,v=null;if(r){let e=parseFloat(t.iconSize??"")||Math.round(.5*u),r=t.iconStrokeWidth??2,s=m?.trim()||"currentColor";if(o&&(y=K(o,e,s,r)),b=K(a,e,s,r),!t.iconSize)for(let t of[y,b])t&&(t.style.width=`var(--persona-components-composer-sendIconSize, ${e}px)`,t.style.height=`var(--persona-components-composer-sendIconSize, ${e}px)`);y&&b?(v=io(y,b),f.appendChild(v)):y?f.appendChild(y):(f.textContent=n,b=null)}else f.textContent=l;f.setAttribute("aria-label",s),g.appendChild(f),Gn({anchor:f,trigger:g,text:()=>f.getAttribute("aria-label")??"",enabled:c});let w="send";return{button:f,wrapper:g,setMode:e=>{if(e===w)return;w=e;let t="stop"===e?i:s;f.setAttribute("aria-label",t),f.setAttribute("data-persona-send-mode",e),r?(f.querySelector("[data-persona-glyph-stack]")??v)?.setAttribute("data-mode",e):f.textContent="stop"===e?d:l},glyphStack:v}},co=e=>{let t=e?.voiceRecognition??{};if(!0!==t.enabled)return null;let r=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),n="runtype"===t.provider?.type,o="custom"===t.provider?.type;if(!(r||n||o))return null;let a=t.iconName??"mic",s=t.iconSize,i=parseFloat(s??"")||24,l=t.backgroundColor??e?.sendButton?.backgroundColor,d=t.iconColor??e?.sendButton?.textColor,c=L("div","persona-send-button-wrapper"),p=P("button",{className:B("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",no,!s&&"persona-composer-control--glyph"),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",color:d||"var(--persona-text, #111827)",backgroundColor:l||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}}),u=K(a,i,d||"currentColor",1.5);u?p.appendChild(u):p.textContent="🎤",c.appendChild(p);let h=t.tooltipText??"Start voice recognition";return Gn({anchor:p,trigger:c,text:()=>p.getAttribute("aria-label")??h,enabled:t.showTooltip??!1}),{button:p,wrapper:c}},po=e=>{let t=e?.attachments??{};if(!0!==t.enabled)return null;let r=L("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let n=L("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??Sr).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let o=t.buttonIconName??"paperclip",a=L("div","persona-send-button-wrapper"),s=P("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${no} ${oo}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),i=K(o,24,"currentColor",1.5);i?s.appendChild(i):s.textContent="📎",s.addEventListener("click",e=>{e.preventDefault(),n.click()}),a.appendChild(s);let l=t.buttonTooltipText??"Attach file";return Gn({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??l}),{button:s,wrapper:a,input:n,previewsContainer:r}},uo=e=>{let t=e?.statusIndicator??{},r="left"===t.align?"persona-text-left":"center"===t.align?"persona-text-center":"persona-text-right",n=L("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status",""),le(n,t,"idle");let o=t.idleText??"Online";if(t.idleLink){let e=L("a");e.href=t.idleLink,e.target="_blank",e.rel="noopener noreferrer",e.textContent=o,e.style.color="inherit",e.style.textDecoration="none",n.appendChild(e)}else n.textContent=o;return n},ho=()=>P("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function mo(e){let{anchor:t,content:r,placement:n="bottom-start",offset:o=6,matchAnchorWidth:a=!1,horizontalOffset:s,verticalOffset:i,zIndex:l=2147483e3,onOpen:d,onDismiss:c}=e,p=e.container??function(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}(t),u=!1,h=null,m=()=>{if(!u)return;let e=t.getBoundingClientRect();r.style.position="fixed",a&&(r.style.minWidth=`${e.width}px`),s&&(r.style.maxWidth=`${e.width}px`);let l=r.getBoundingClientRect(),d=i?.()??null,c=null==d?e.top:e.top+d,p="top-start"===n||"top-end"===n?c-o-l.height:e.bottom+o,h="bottom-end"===n||"top-end"===n?e.right-l.width:e.left,m=s?.()??null;if(null!=m){let t=Math.max(e.left,e.right-l.width);h=Math.min(Math.max(e.left+m,e.left),t)}r.style.top=`${p}px`,r.style.left=`${h}px`},g=()=>{u&&(u=!1,h&&=(h(),null),r.remove())},f=()=>{if(u)return;u=!0,null!=l&&(r.style.zIndex=String(l)),p.appendChild(r),m();let e=(t.ownerDocument??document).defaultView??window,n=t.ownerDocument??document,o=()=>{t.isConnected?m():(g(),c?.("anchor-removed"))},a=e=>{let n="function"==typeof e.composedPath?e.composedPath():[];n.includes(r)||n.includes(t)||(g(),c?.("outside"))},s=e.setTimeout(()=>{n.addEventListener("pointerdown",a,!0)},0);e.addEventListener("scroll",o,!0),e.addEventListener("resize",o),h=()=>{e.clearTimeout(s),n.removeEventListener("pointerdown",a,!0),e.removeEventListener("scroll",o,!0),e.removeEventListener("resize",o)},d?.()};return{get isOpen(){return u},open:f,close:g,toggle:()=>u?g():f(),reposition:m,destroy:g}}let go=["--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"],fo="data-persona-menu-focus",yo=new Set(["ArrowDown","ArrowUp","Home","End"]);function bo(e){return"menuitem"===e.getAttribute("role")?e:e.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')??e}let vo=1e3,wo="data-persona-composer-action",xo="data-persona-composer-disable-when-streaming";function Co(e){let t=e.clientWidth;if(!t)return 0;let r=e.ownerDocument?.defaultView;if(!r?.getComputedStyle)return t;let n=r.getComputedStyle(e),o=(Number.parseFloat(n.paddingLeft)||0)+(Number.parseFloat(n.paddingRight)||0);return Math.max(0,t-o)}let So=(e,t)=>{e&&typeof console<"u"&&console.warn(t)},ko=e=>"plugin"===e.source?`plugin "${e.pluginId}"`:"config"===e.source?"composer.actions":"a core built-in",Ao=(e,t,r)=>void 0===e?r:"function"==typeof e?!0===e(t):!0===e;function Mo(e,t){if(!e||"always"===e)return!0;let r=(e=>"streaming"===e.phase||e.text.trim().length>0||e.attachments.length>0)(t);return"when-text"===e?r:!r}let Io=e=>"custom"===e.kind,To=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e;function Eo(e){let t=new Map,r=[],n=!1,o=()=>e.getButtonSize?.(),a=(e,t)=>{let r=e.button;if(!r)return;if(r.setAttribute("aria-label",t.label),void 0===t.pressed?r.removeAttribute("aria-pressed"):r.setAttribute("aria-pressed",t.pressed?"true":"false"),r.toggleAttribute(xo,!0===t.disableWhenStreaming),"menu"===e.mode)return e.tooltip?.destroy(),e.tooltip=void 0,void((e,t)=>{let r=e.button;if(!r)return;r.setAttribute("role","menuitem"),r.setAttribute("tabindex","-1"),r.className="persona-composer-overflow-menu__item";for(let e of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])r.style[e]="";r.style.lineHeight="1",t.tooltipText?r.setAttribute("title",t.tooltipText):r.removeAttribute("title"),r.replaceChildren();let n=L("span","persona-composer-overflow-menu__icon");if(t.iconName){let e=K(t.iconName,16,"currentColor",1.5);e&&n.appendChild(e)}let o=L("span","persona-composer-overflow-menu__label");o.textContent=t.shortLabel??t.label,r.append(n,o)})(e,t);r.removeAttribute("role"),r.removeAttribute("tabindex"),r.removeAttribute("title");let n=o(),a=!!t.shortLabel;if(r.className=B("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",no,oo,a&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),r.style.width=n&&!a?n:"",r.style.height=n??"",r.style.minWidth=n&&!a?n:"",r.style.minHeight=n??"",r.style.fontSize=a?"":"18px",r.style.lineHeight="1",r.style.color=t.iconColor??"",r.style.backgroundColor=t.backgroundColor??"",r.replaceChildren(),t.iconName){let e=K(t.iconName,24,"currentColor",1.5);e&&r.appendChild(e)}if(a){let e=L("span","persona-composer-action-button__label");e.textContent=t.shortLabel,r.appendChild(e)}else r.firstChild||(r.textContent=t.label);e.tooltip?.destroy(),e.tooltip=Gn({anchor:r,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,r)=>{let n=t.action,o=P("button",{attrs:{type:"button"}}),s=o;if("bar"===r){let e=L("div","persona-send-button-wrapper");e.appendChild(o),s=e}s.setAttribute(wo,t.id);let i={resolved:t,element:s,button:o,owned:!0,managed:!0,busy:!1,visible:!0,mode:r},l=t=>{if(t.preventDefault(),t.stopPropagation(),i.busy||o.disabled)return;let r,n=i.resolved.action;"menu"===i.mode&&u?.close(!0);try{r=n.onSelect(e.actionContext,t)}catch(t){return void e.reportError(t,{actionId:i.resolved.id})}r&&"function"==typeof r.then&&(i.busy=!0,o.setAttribute("aria-busy","true"),r.catch(t=>{e.reportError(t,{actionId:i.resolved.id})}).finally(()=>{i.busy=!1,o.removeAttribute("aria-busy")}))};return o.addEventListener("click",l),i.detach=()=>o.removeEventListener("click",l),a(i,n),i},i=t=>{let r,n=t.action;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(wo,t.id),r.element.toggleAttribute(xo,!0===n.disableWhenStreaming),{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:!0===e.builtIn.managed,busy:!1,visible:!0,mode:"bar"}:null}let r=e.action;return r?Io(r)?i(e):s(e,t):null},d=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(r){e.reportError(r,{actionId:t.resolved.id})}t.element.remove()}},c=(e,t)=>{for(let r=0;r<t.length;r++){let n=t[r];if(!n.managed)continue;let o=null;for(let n=r+1;n<t.length;n++){let r=t[n];if(!r.managed&&r.element.parentElement===e){o=r.element;break}}o?(n.element.parentElement!==e||n.element.nextSibling!==o)&&e.insertBefore(n.element,o):e.lastChild!==n.element&&e.appendChild(n.element)}},p=(e,t)=>{if(e.button)return void(e.button.disabled=t);if(!e.owned)return;let r=e.element;r.toggleAttribute("data-disabled",t),r.setAttribute("aria-disabled",t?"true":"false");let n=r instanceof HTMLButtonElement||r instanceof HTMLSelectElement||r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement?r:r.querySelector("button, select, input, textarea");n&&(n.disabled=t)},u=null,h=null,m=null,g=0,f=()=>(u?u.setLabel(e.getOverflowLabel?.()??"More actions"):u=function(e){let t=e.label,r=!1,n=L("div","persona-send-button-wrapper"),o=P("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${no} ${oo}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});n.appendChild(o);let a=P("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),s=()=>{let t=e.getButtonSize?.()??"";o.style.width=t,o.style.height=t,o.style.minWidth=t,o.style.minHeight=t,o.style.lineHeight="1",o.replaceChildren();let r=K("plus",24,"currentColor",1.5);r?o.appendChild(r):o.textContent="+"},i=()=>{o.setAttribute("aria-label",t),o.setAttribute("title",t),a.setAttribute("aria-label",t)};i(),s();let l=[],d=-1,c=!1,p=()=>{let e=(()=>{let e=a.getRootNode().activeElement;return e instanceof HTMLElement?e:null})();for(let t of l){let r=!!e&&bo(t)===e;t.toggleAttribute(fo,r&&c)}},u=()=>l.filter(e=>e.isConnected||a.contains(e)).map(bo).filter(e=>!(e=>!0===e.disabled||"true"===e.getAttribute("aria-disabled"))(e)),h=(e,t)=>{e.forEach((e,r)=>{e.setAttribute("tabindex",r===t?"0":"-1")})},m=e=>{let t=u();if(0===t.length)return;let r=(e%t.length+t.length)%t.length;d=r,h(t,r),t[r].focus(),p()},g=()=>n.ownerDocument??document,f=null,y=null,b=null,v=()=>{f&&=(g().removeEventListener("focusin",f,!0),null)},w=()=>{y&&=(a.removeEventListener("focusin",y),null),b&&=(a.removeEventListener("pointerdown",b,!0),null)},x=null,C=()=>!0===x?.isOpen,S=(e=!1)=>{if(C()){x?.close(),o.setAttribute("aria-expanded","false"),v(),w(),d=-1,c=!1;for(let e of l)e.removeAttribute(fo);e&&o.focus()}},k=(e=0,t=!1)=>{if(r||C())return;c=t,ao(o,a,go),(x||=mo({anchor:o,content:a,placement:"top-start",offset:6,onDismiss:()=>{o.setAttribute("aria-expanded","false"),v()}}),x).open(),o.setAttribute("aria-expanded","true");let s=u();h(s,-1),m(e<0?s.length-1:e),f=e=>{let t="function"==typeof e.composedPath?e.composedPath():[];t.includes(a)||t.includes(n)||S()},g().addEventListener("focusin",f,!0),y=()=>p(),a.addEventListener("focusin",y),b=()=>{c=!1},a.addEventListener("pointerdown",b,!0)},A=e=>{e.preventDefault(),e.stopPropagation(),C()?S(!0):k(0)},M=e=>{"ArrowDown"===e.key||"Enter"===e.key||" "===e.key?(e.preventDefault(),c=!0,C()?m(0):k(0,!0)):"ArrowUp"===e.key&&(e.preventDefault(),c=!0,C()?m(-1):k(-1,!0))},I=e=>{switch(yo.has(e.key)&&(c=!0),e.key){case"ArrowDown":return e.preventDefault(),void m(d+1);case"ArrowUp":return e.preventDefault(),void m(d-1);case"Home":return e.preventDefault(),void m(0);case"End":return e.preventDefault(),void m(u().length-1);case"Escape":return e.preventDefault(),e.stopPropagation(),void S(!0);case"Tab":return void S(!0)}};return o.addEventListener("click",A),o.addEventListener("keydown",M),a.addEventListener("keydown",I),{trigger:n,triggerButton:o,panel:a,setItems:e=>{for(let t of l)e.includes(t)||t.removeAttribute(fo);if(l=[...e],!C())return;let t=u();h(t,Math.min(d,t.length-1)),p()},isOpen:C,open:()=>k(0),close:S,setLabel:e=>{e!==t&&(t=e,i())},applyButtonSize:s,destroy:()=>{r=!0,v(),w(),o.removeEventListener("click",A),o.removeEventListener("keydown",M),a.removeEventListener("keydown",I),x?.destroy(),x=null,n.remove(),a.remove(),l=[]}}}({label:e.getOverflowLabel?.()??"More actions",getButtonSize:o}),u),y=(e,t,r)=>{if(!t)return"bar";if(e.resolved.builtIn){let r=(e=>"core:attachment"===e?"attachments":e.startsWith("core:mention")?"mentions":null)(e.resolved.id);return r&&t.includeBuiltIns?.includes(r)?"menu":"bar"}let n=e.resolved.presentation;return"overflow"===n||"auto"===n&&r?"menu":"bar"},b=e=>{let t=e.menuSlot;if(!t)return;if(!(e=>0===function(e){let t="",r=e=>{if(e.nodeType===Node.TEXT_NODE)return void(t+=e.nodeValue??"");if(e.nodeType!==Node.ELEMENT_NODE)return;let n=e;"function"==typeof n.matches&&n.matches('.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]')||e.childNodes.forEach(r)};return r(e),t.trim()}(e).length)(e.element))return e.menuLabel?.remove(),void(e.menuLabel=void 0);let r=(e=>{let t=To(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""})(e.element);r?(e.menuLabel||=L("span","persona-composer-overflow-menu__label"),e.menuLabel.textContent!==r&&(e.menuLabel.textContent=r),e.menuLabel.parentElement!==t&&t.appendChild(e.menuLabel)):(e.menuLabel?.remove(),e.menuLabel=void 0)},v=(e,r)=>{if(e.mode===r)return e;let n=e.resolved.action;if(n&&!Io(n)){d(e),t.delete(e.resolved.id);let n=s(e.resolved,r);return t.set(e.resolved.id,n),n}if("menu"===r){let t=P("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none","data-persona-tooltip-suppressed":""}});t.appendChild(e.element),function(e){jn.get(e)?.hide()}(To(e.element)),e.menuSlot=t;let r=t=>{let r=To(e.element);if(r.disabled)return;let n=t.target===r||r.contains(t.target);u?.close(!0),n||r.click()};t.addEventListener("click",r,!0),e.detachMenuSlot=()=>t.removeEventListener("click",r,!0),e.managed=!0,b(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=r,e},w=()=>{if(n)return;let o=e.getBindings();if(!o)return;let a=e.getState(),s="streaming"===a.phase,i=(()=>{let t=e.getOverflow?.();return!0===t?.enabled?t:void 0})();i&&(e=>{h!==e&&(m?.disconnect(),h=e,g=Co(e),typeof ResizeObserver<"u"&&(m=new ResizeObserver(t=>{let r=t[t.length-1]?.contentRect?.width??Co(e);r!==g&&(g=r,w())}),m.observe(e)))})(o.footer);let l=!!i&&((e,t)=>{let r=function(e,t){if(void 0===e)return null;if("number"==typeof e)return Number.isFinite(e)?e:null;let r=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(r))return r;let n=L("div");n.style.position="absolute",n.style.visibility="hidden",n.style.pointerEvents="none",n.style.height="0",n.style.width=e,t.appendChild(n);let o=n.getBoundingClientRect().width;return n.remove(),Number.isFinite(o)&&o>0?o:Number.isFinite(r)?r:null}(e.collapseAutoActionsBelow,t);if(null===r)return!1;let n=g||Co(t);return n>0&&n<r})(i,o.footer),d={start:[],end:[]},x=[];for(let e of r){let r=t.get(e.id);if(!r)continue;let n=e.action,o=!n||Ao(n.visible,a,!0)&&Mo(n.visibility,a);if(r.visible!==o&&(r.visible=o,!o&&r.managed&&(r.menuSlot??r.element).remove()),o){if(r=v(r,y(r,i,l)),n){let e=Ao(n.disabled,a,!1)||!0===n.disableWhenStreaming&&s;p(r,e),!Io(n)&&void 0!==n.pressed&&r.button?.setAttribute("aria-pressed",n.pressed?"true":"false")}"menu"===r.mode?(b(r),x.push(r)):d[e.placement].push(r)}}if(x.length>0){let e=f();((e,t)=>{let r=t.map(e=>e.menuSlot??e.element);for(r.forEach((t,r)=>{let n=e.children[r];n!==t&&(n?e.insertBefore(t,n):e.appendChild(t))});e.children.length>r.length;)e.lastElementChild?.remove()})(e.panel,x),e.setItems(x.map(e=>e.menuSlot??e.element)),e.applyButtonSize();let t=Number.isFinite(i?.order)?i?.order:900,r=d.start.findIndex(e=>e.resolved.order>t),n={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"};d.start.splice(r<0?d.start.length:r,0,n)}else u&&(u.close(),u.trigger.remove(),u.setItems([]));c(o.actionsStart,d.start),c(o.actionsEnd,d.end)};return{resolve:()=>{if(n)return;let o=function(e){let{debug:t}=e,r=[],n=new Map,o=0,a=e=>{let o=n.get(e.id);o?So(t,`[Persona] composer action "${e.id}" is already contributed by ${ko(o)}; the ${ko(e)} copy is ignored.`):(n.set(e.id,e),r.push(e))};for(let t of e.builtIns)a({id:t.id,placement:t.placement,presentation:"bar",order:t.order,sequence:o++,source:"core",builtIn:t});let s=(e,r,n)=>{let s=n?((e,t)=>t.includes(":")?t:`${e}:${t}`)(n,e.id):e.id,i=e.order??500;"end"===e.placement&&i>=vo&&(So(t,`[Persona] composer action "${s}" ordered at ${i} would render after send; clamped to 999.`),i=999),a({id:s,placement:e.placement,presentation:e.presentation??"bar",order:i,sequence:o++,source:r,pluginId:n,action:e})};for(let t of e.configActions??[])s(t,"config");for(let t of e.plugins){if(!t.contributeComposerActions)continue;let r;try{r=t.contributeComposerActions(e.contributionContext)}catch(e){typeof console<"u"&&console.error(`[Persona] plugin "${t.id}" contributeComposerActions failed:`,e);continue}for(let e of r??[])s(e,"plugin",t.id)}return r.sort((e,t)=>e.order===t.order?e.sequence-t.sequence:e.order-t.order)}(e.collect()),s=new Set(o.map(e=>e.id));for(let[e,r]of t)s.has(e)||(d(r),t.delete(e));for(let e of o){let r=t.get(e.id);if(!r){let r=l(e,"bar");r&&t.set(e.id,r);continue}let n=r.resolved.action,o=e.action;if(!!n!=!!o||n&&o&&Io(n)!==Io(o)||n&&o&&Io(n)&&Io(o)&&n.render!==o.render){d(r),t.delete(e.id);let n=l(e,r.mode);n&&t.set(e.id,n)}else r.resolved=e,e.builtIn?(r.managed=!0===e.builtIn.managed||"menu"===r.mode,e.builtIn.element&&"bar"===r.mode&&(r.element=e.builtIn.element)):o&&!Io(o)?a(r,o):o&&r.element.toggleAttribute(xo,!0===o.disableWhenStreaming)}r=o,w()},sync:w,getResolved:()=>r,getOverflowMenu:()=>u,destroy:()=>{if(!n){n=!0,m?.disconnect(),m=null,h=null;for(let e of t.values())d(e);t.clear(),u?.destroy(),u=null,r=[]}}}}let Lo=["--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"],Po=()=>({wrapper:P("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),chevron:P("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}})});function Bo(e){let t=e.label??"Model",r=e.presentation??"native",n=null,o=t=>{let r=e.getSelectedModelId();return t.find(e=>e.id===r)??t[0]};return{action:{id:"core:model",kind:"custom",placement:"end",order:700,presentation:"popover"===r?"bar":"auto",label:t,render:()=>"popover"===r?(()=>{let r=P("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=L("span","persona-composer-model-picker-label"),s=L("span","persona-composer-model-picker-suffix");r.append(a,s);let i=P("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),l=new Map,d="",c=null,p=()=>!0===c?.isOpen,u=(e=!1)=>{p()&&(c?.close(),r.setAttribute("aria-expanded","false"),e&&r.focus())},h=e=>{let t=[...l.values()];0!==t.length&&t[(e%t.length+t.length)%t.length].focus()},m=t=>{if(p())return;c||=mo({anchor:r,content:i,placement:"top-start",offset:6,onDismiss:()=>r.setAttribute("aria-expanded","false")}),ao(r,i,Lo),c.open(),r.setAttribute("aria-expanded","true");let n=[...l.keys()].indexOf(o(e.getModels())?.id??"");h(t??(n>=0?n:0))},g=t=>{u(!0),e.onSelect(t)},f=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute("data-persona-model-option");t&&g(t)},y=()=>{let n=e.getModels(),c=n.map(e=>`${e.id}:${e.label}:${e.icon??""}:${e.description??""}`).join("|");if(c!==d){d=c;for(let e of l.values())e.removeEventListener("click",f);l.clear(),i.replaceChildren(...n.map(e=>{let t=(e=>{let t=P("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 r=K(e.icon,16,"currentColor",1.5);if(r){let e=L("span","persona-composer-model-option-icon");e.appendChild(r),t.appendChild(e)}}let r=L("span","persona-composer-model-option-body"),n=L("span","persona-composer-model-option-label");if(n.textContent=e.label,r.appendChild(n),e.description){let t=L("span","persona-composer-model-option-description");t.textContent=e.description,r.appendChild(t)}t.appendChild(r);let o=L("span","persona-composer-model-option-check");o.setAttribute("aria-hidden","true");let a=K("check",16,"currentColor",2);return a&&o.appendChild(a),t.appendChild(o),t.addEventListener("click",f),t})(e);return l.set(e.id,t),t}))}let p=o(n);for(let[e,t]of l)t.setAttribute("aria-selected",String(e===p?.id));a.textContent=p?.label??"";let u=e.getSuffix?.()??"";s.textContent=u,r.setAttribute("aria-label",[t,[p?.label,u].filter(Boolean).join(" ")].filter(Boolean).join(": "))};y(),n=y;let b=e=>{e.preventDefault(),e.stopPropagation(),p()?u(!0):m()},v=e=>{"ArrowDown"===e.key?(e.preventDefault(),p()?h(0):m(0)):"ArrowUp"===e.key&&(e.preventDefault(),p()?h(-1):m(-1))},w=e=>{let t=[...l.values()],r=t.indexOf(e.target?.closest?.(".persona-composer-model-option"));switch(e.key){case"ArrowDown":return e.preventDefault(),void h(r+1);case"ArrowUp":return e.preventDefault(),void h(r-1);case"Home":return e.preventDefault(),void h(0);case"End":return e.preventDefault(),void h(t.length-1);case"Escape":return e.preventDefault(),e.stopPropagation(),void u(!0);case"Tab":return void u(!0)}};r.addEventListener("click",b),r.addEventListener("keydown",v),i.addEventListener("keydown",w);let{wrapper:x,chevron:C}=Po();return x.append(r,C),{element:x,destroy:()=>{n===y&&(n=null),r.removeEventListener("click",b),r.removeEventListener("keydown",v),i.removeEventListener("keydown",w);for(let e of l.values())e.removeEventListener("click",f);l.clear(),c?.destroy(),c=null,i.remove()}}})():(()=>{let r=P("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),a="",s=()=>{let t=e.getModels(),n=t.map(e=>`${e.id}:${e.label}`).join("|");n!==a&&(a=n,r.replaceChildren(...t.map(e=>{let t=P("option",{attrs:{value:e.id}});return t.textContent=e.label,t}))),r.value=o(t)?.id??""};s(),n=s;let i=()=>{r.value&&e.onSelect(r.value)};r.addEventListener("change",i);let l=e=>e.stopPropagation();r.addEventListener("click",l);let{wrapper:d,chevron:c}=Po();return d.append(r,c),{element:d,destroy:()=>{n===s&&(n=null),r.removeEventListener("change",i),r.removeEventListener("click",l)}}})()},repaint:()=>n?.()}}let No="[data-persona-composer-chip-row]";function Ro(e){e.style.display=e.childElementCount>0?"flex":"none"}function Ho(e){let t=e.querySelector(No);if(t)return t;let r=P("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});r.style.display="none";let n=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return n?.parentElement===e?e.insertBefore(r,n):e.appendChild(r),r}function $o(e){let t=e.row,r="",n=!1,o=new Set(e.initialIds??[]),a=t=>{let r=P("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=L("span","persona-mention-chip-icon"),n=K(t.iconName,12,"currentColor",1.5);n&&e.appendChild(n),r.appendChild(e)}let n=L("span","persona-mention-chip-label");n.textContent=t.shortLabel??t.label,r.appendChild(n);let o=P("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${t.label}`}}),a=K("x",12,"currentColor",2);return a?o.appendChild(a):o.textContent="×",o.addEventListener("click",r=>{r.preventDefault(),r.stopPropagation(),e.onRemove(t.id)}),r.appendChild(o),r},s=()=>Array.from(t.querySelectorAll(":scope > [data-persona-composer-mode]")),i=e=>{e.setAttribute("data-persona-chip-exit",""),e.setAttribute("aria-hidden","true"),e.style.pointerEvents="none";let r=()=>{e.remove(),Ro(t)},n=t.ownerDocument.defaultView,o="function"==typeof n?.getComputedStyle?n.getComputedStyle(e).animationName:"";o&&"none"!==o?(e.addEventListener("animationend",r,{once:!0}),e.addEventListener("animationcancel",r,{once:!0})):r()};return{element:t,render:(e,l)=>{if(n)return;let d=l.filter(t=>e.includes(t.id)),c=d.map(e=>`${e.id}:${e.shortLabel??e.label}`).join("|");if(c===r)return;r=c;let p=new Map;for(let e of s()){let t=e.getAttribute("data-persona-composer-mode");t&&d.some(e=>e.id===t)&&!e.hasAttribute("data-persona-chip-exit")?p.set(t,e):e.hasAttribute("data-persona-chip-exit")||i(e)}let u=t.firstChild;for(let e of d){let r=p.get(e.id);r||(r=a(e),o.has(e.id)||(r.setAttribute("data-persona-chip-enter",""),r.addEventListener("animationend",()=>r?.removeAttribute("data-persona-chip-enter"),{once:!0}))),o.delete(e.id),r!==u&&t.insertBefore(r,u),u=r.nextSibling}Ro(t)},destroy:()=>{n=!0,(()=>{for(let e of s())e.remove()})(),Ro(t)}}}let Wo=e=>`core:mode:${e}`,Do=e=>Math.min(300+e,499),Fo=e=>`core:mode-group:${e}`;function Oo(e,t){return!!e&&"segmented"===t?.find(t=>t.id===e)?.presentation}function zo(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function qo(e){let t=null;return{action:{id:Fo(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let r=P("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),n=new Map,o="",a=t=>{t.preventDefault(),t.stopPropagation();let r=t.currentTarget.getAttribute("data-persona-composer-mode");r&&(e.getActiveIds().includes(r)&&"single"===e.getGroup()?.selection||e.onSelect(r))},s=()=>{let t=e.getGroup();t?.label?(r.setAttribute("role","group"),r.setAttribute("aria-label",t.label)):(r.removeAttribute("role"),r.removeAttribute("aria-label"));let s=e.getModes(),i=s.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??""}`).join("|");if(i!==o){o=i;for(let e of n.values())e.removeEventListener("click",a);n.clear();let e=s.map(e=>{let t=(e=>{let t=P("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let r=K(e.iconName,16,"currentColor",1.5);r&&t.appendChild(r)}let r=L("span","persona-composer-segmented-label");return r.textContent=e.shortLabel??e.label,t.appendChild(r),t.addEventListener("click",a),t})(e);return n.set(e.id,t),t});r.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of n)t.setAttribute("aria-pressed",String(l.includes(e)))};return s(),t=s,{element:r,destroy:()=>{t===s&&(t=null);for(let e of n.values())e.removeEventListener("click",a);n.clear()}}}},repaint:()=>t?.()}}function jo(e){let t=P("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let r="",n=!1,o=r=>{let n=L("span","persona-composer-quote-bar"),o=L("div","persona-composer-quote-content");if(r.sourceLabel){let e=L("div","persona-composer-quote-source");e.textContent=r.sourceLabel,o.appendChild(e)}let a=P("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});a.textContent=rn(r.text),o.appendChild(a);let s=P("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),i=K("x",12,"currentColor",2);i?s.appendChild(i):s.textContent="×",s.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(n,o,s)};return{element:t,render:e=>{if(n)return;let a=e?`${e.sourceLabel??""}\0${e.text}`:"";a!==r&&(r=a,e?(o(e),t.style.display="flex"):(t.replaceChildren(),t.style.display="none"))},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function _o(e){let t=P("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let r,n=!1,o=(e,t,r,n)=>{let o=P("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":t,[r]:""}}),a=K(e,12,"currentColor",2);return a?o.appendChild(a):o.textContent=t,o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),n()}),o};return{element:t,render:a=>{if(n||a===r)return;if(r=a,!a)return t.replaceChildren(),void(t.style.display="none");let s=L("span","persona-composer-pending-badge");s.textContent=e.label??"Sends next";let i=P("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});i.textContent=(e=>{let t=rn(e.text??"",90);if(t)return t;let r=e.contentParts?.length??0;return r>0?1===r?"1 attachment":`${r} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(", "):"Queued message"})(a),t.replaceChildren(s,i,o("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),o("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function Vo(e){let t=P("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),r=P("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});r.value=e.initialText;let n=()=>{r.style.height="auto",r.style.height=`${r.scrollHeight}px`};r.addEventListener("input",n);let o=L("div","persona-message-edit-actions"),a=(e,t,r,n)=>{let o=P("button",{className:`persona-message-edit-button ${t}`,attrs:{type:"button",[r]:""},text:e});return o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),n()}),o},s=()=>{let t=r.value.trim();t&&e.onSave(t)};return o.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",s)),r.addEventListener("keydown",t=>{"Escape"===t.key?(t.preventDefault(),t.stopPropagation(),e.onCancel()):"Enter"===t.key&&!t.shiftKey&&(t.preventDefault(),s())}),t.append(r,o),{element:t,getValue:()=>r.value,focus:()=>{r.focus();let e=r.value.length;r.setSelectionRange(e,e),n()},destroy:()=>{t.replaceChildren(),t.remove()}}}function Uo(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 Go(e,t){return!1===t?{status:"canceled"}:(!t||"object"!=typeof t||("string"==typeof t.text&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options})),{status:"proceed"})}function Ko(e,t,r){let n;try{n=e(Uo(t),{signal:r})}catch(e){return{status:"error",error:e}}return(e=>"function"==typeof e?.then)(n)?Promise.resolve(n).then(e=>r.aborted?{status:"aborted"}:Go(t,e),e=>r.aborted?{status:"aborted"}:{status:"error",error:e}):Go(t,n)}let{setLoader:Jo,load:Qo}=N({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),Xo=Jo,Yo=Qo,{setLoader:Zo,load:ea}=N({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),ta=Zo,ra=ea;function na(e){let{config:t,onOpen:r}=e,n=t.buttonIconName??"plus",o=t.buttonTooltipText??"Add context",a=L("div","persona-send-button-wrapper"),s=P("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${no} ${oo}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":o,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),i=K(n,24,"currentColor",1.5);return i?s.appendChild(i):s.textContent="+",s.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r()}),a.appendChild(s),Gn({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??o}),{button:s,wrapper:a}}let oa=e=>e?.launcher?.variant??(!0===e?.future?.v5Defaults?"circle":"pill"),aa={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"},sa="16px",ia="transparent",la={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]=0===t?"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"}},da={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"}},ca={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:v,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:sa,canvasBackground:ia,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"}}},pa=la.colors.gray,ua={...la,colors:{...la.colors,gray:pa}},ha={...la,colors:{...la.colors,gray:{50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"}},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},ma=ua,ga=da,fa={...da,colors:{...da.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...da.typography,fontSize:"14px",lineHeight:"1.5"}},ya=ga,ba=ca,va={...ca,launcher:aa,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:{...ca.input,borderRadius:"palette.radius.full"},introCard:{...ca.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...ca.suggestion.chip,fontWeight:"400"},card:{...ca.suggestion.card,fontWeight:"400"},list:{...ca.suggestion.list,fontWeight:"400"}},panel:{...ca.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...ca.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:{...ca.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...ca.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:{...ca.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...ca.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)"}},wa=ba,xa=e=>"v5"===(e=>A({future:e}))(e)?{palette:ha,semantic:fa,components:va}:{palette:ua,semantic:ga,components:ba};function Ca(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),n=e;for(let e of r){if(null==n)return;n=n[e]}return"string"==typeof n&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Ca(e,n):n}function Sa(e){let t={};function r(n,o){for(let[a,s]of Object.entries(n)){let n=`${o}.${a}`;if("string"==typeof s){let r=Ca(e,s);void 0!==r&&(t[n]={path:n,value:r,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else"object"==typeof s&&s&&r(s,n)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function ka(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:0===t.length,errors:t,warnings:r}}function Aa(e,t){let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];r[e]=t&&"object"==typeof t&&!Array.isArray(t)&&n&&"object"==typeof n&&!Array.isArray(n)?Aa(t,n):n}return r}function Ma(e,t){return t?Aa(e,t):e}function Ia(e,t={}){let r=xa(t.future),n={palette:r.palette,semantic:r.semantic,components:r.components},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:Ma(n.components,e?.components)},a=e?.components?.activity;for(let e of["toolBubble","reasoningBubble"])for(let t of["rowHeight","labelSize","iconSize","indent","bodySurface"])void 0!==a?.[t]&&(o.components[e][t]=a[t]);let s=e?.components?.collapsibleWidget?.surface;void 0!==s&&void 0===a?.bodySurface&&(o.components.activity={...o.components.activity,bodySurface:s});let i=e?.components?.header;void 0!==i?.padding&&void 0===i.minimalPadding&&(o.components.header.minimalPadding=o.components.header.padding);let l=e?.components?.message;if(void 0!==l?.gap&&void 0===l.fullscreenGap&&(o.components.message.fullscreenGap=o.components.message.gap),!1!==t.validate){let e=ka(o);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(", ")}`)}if(t.plugins)for(let e of t.plugins)o=e.transform(o);return o}let Ta=e=>"0"===e.trim()?"0px":e,Ea="--persona-",La=(e,t)=>{for(let[r,...n]of t){let t;for(let r of n)if(t=61===r.charCodeAt(0)?r.slice(1):e[Ea+r],void 0!==t)break;void 0!==t&&(e[Ea+r]=t)}};function Pa(e){let t=Sa(e),r={};for(let[e,n]of Object.entries(t))r[`--persona-${e.replace(/\./g,"-")}`]=n.value;La(r,[["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 n=r["--persona-components-launcher-foreground"];r["--persona-launcher-fg-muted"]=n&&n!==r["--persona-primary"]?`color-mix(in srgb, ${n} 70%, transparent)`:r["--persona-muted"],La(r,[["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"]]),La(r,[["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"]]),r["--persona-panel-border"]=r["--persona-components-panel-border"]??`1px solid ${r["--persona-border"]}`,La(r,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),r["--persona-panel-inset"]=r["--persona-components-panel-inset"]??"16px",r["--persona-panel-canvas-bg"]=r["--persona-components-panel-canvasBackground"]??"transparent",La(r,[["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"]]),La(r,[["header-bg","components-header-background","surface"]]);let o=r["--persona-header-bg"],a=r["--persona-components-header-foreground"],s=a?`color-mix(in srgb, ${a} 72%, ${o})`:void 0;r["--persona-header-border"]=r["--persona-components-header-border"]??(a?`color-mix(in srgb, ${a} 14%, ${o})`:void 0)??r["--persona-divider"],La(r,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),r["--persona-header-title-fg"]=r["--persona-components-header-title-color"]??r["--persona-components-header-titleForeground"]??a??r["--persona-primary"],r["--persona-header-subtitle-fg"]=r["--persona-components-header-subtitle-color"]??r["--persona-components-header-subtitleForeground"]??s??r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=r["--persona-components-header-actionIconForeground"]??s??r["--persona-muted"],La(r,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let i=e.components?.header;i?.shadow&&(r["--persona-header-shadow"]=i.shadow),i?.borderBottom&&(r["--persona-header-border-bottom"]=i.borderBottom),i?.minHeight&&(r["--persona-header-min-height"]=i.minHeight);let l=r["--persona-components-history-railHeader-background"];l&&(r["--persona-history-rail-header-bg"]=l);let d=r["--persona-components-history-railHeader-border"];d&&(r["--persona-history-rail-header-border"]=d);let c=r["--persona-components-history-railHeader-minHeight"];c&&(r["--persona-history-rail-header-min-height"]=c);for(let[e,t]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let n=r[`--persona-components-history-overlay-${e}`];n&&(r[`--persona-history-overlay-${t}`]=n)}for(let[e,t]of[["background","bg"],["borderRadius","radius"]]){let n=r[`--persona-components-history-menu-${e}`];n&&(r[`--persona-history-menu-${t}`]=n)}let p=e.components?.history?.motion;if(p){let e=e=>{if(void 0===e)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},t=e(p.enterDurationMs);void 0!==t&&(r["--persona-history-enter-ms"]=t);let n=e(p.exitDurationMs);void 0!==n&&(r["--persona-history-exit-ms"]=n),p.enterEasing&&(r["--persona-history-enter-easing"]=p.enterEasing),p.exitEasing&&(r["--persona-history-exit-easing"]=p.exitEasing)}let u=r["--persona-components-history-dangerForeground"];u&&(r["--persona-history-danger-fg"]=u),r["--persona-danger"]=r["--persona-components-history-confirm-dangerBackground"]??r["--persona-palette-colors-error-700"]??"#b42318",r["--persona-danger-fg"]=r["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let e of["scrim","shadow"]){let t=r[`--persona-components-history-confirm-${e}`];t&&(r[`--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 n=r[`--persona-components-tooltip-${e}`];n&&(r[`--persona-tooltip-${t}`]=n)}!1===e.components?.tooltip?.arrow&&(r["--persona-tooltip-arrow-display"]="none");for(let[e,t]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let n=r[`--persona-components-messageActions-${e}`];n&&(r[`--persona-message-action-${t}`]=n)}La(r,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=r["--persona-components-introCard-background"],m=r["--persona-components-introCard-shadow"],g=!(h&&"transparent"!==h&&"none"!==h||m&&"none"!==m),f=r["--persona-components-introCard-padding"]??"1.5rem";r["--persona-intro-card-padding"]=g&&"1.5rem"===f?"1.5rem 0":f,La(r,[["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"]]),La(r,[["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 y=r["--persona-components-markdown-heading-h1-fontSize"];y&&(r["--persona-md-h1-size"]=y);let b=r["--persona-components-markdown-heading-h1-fontWeight"];b&&(r["--persona-md-h1-weight"]=b);let v=r["--persona-components-markdown-heading-h2-fontSize"];v&&(r["--persona-md-h2-size"]=v);let w=r["--persona-components-markdown-heading-h2-fontWeight"];w&&(r["--persona-md-h2-weight"]=w);let x=r["--persona-components-markdown-prose-fontFamily"];x&&"inherit"!==x&&(r["--persona-md-prose-font-family"]=x),La(r,[["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"]]),La(r,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),La(r,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),La(r,[["md-hr-color","components-markdown-hr-color","divider"]]),La(r,[["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 n=r[`--persona-components-collapsibleWidget-${e}`]??r[`--persona-${t}`];void 0!==n&&(r[`--persona-cw-${e}`]=n,r[`--cw-${e}`]=n)}La(r,[["message-border","components-message-border","border"]]),La(r,[["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 C=e.components,S=C?.iconButton;S&&(S.background&&(r["--persona-icon-btn-bg"]=S.background),S.border&&(r["--persona-icon-btn-border"]=S.border),S.color&&(r["--persona-icon-btn-color"]=S.color),S.padding&&(r["--persona-icon-btn-padding"]=S.padding),S.borderRadius&&(r["--persona-icon-btn-radius"]=S.borderRadius),S.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=S.hoverBackground),S.hoverColor&&(r["--persona-icon-btn-hover-color"]=S.hoverColor),S.activeBackground&&(r["--persona-icon-btn-active-bg"]=S.activeBackground),S.activeBorder&&(r["--persona-icon-btn-active-border"]=S.activeBorder));let k=C?.labelButton;k&&(k.background&&(r["--persona-label-btn-bg"]=k.background),k.border&&(r["--persona-label-btn-border"]=k.border),k.color&&(r["--persona-label-btn-color"]=k.color),k.padding&&(r["--persona-label-btn-padding"]=k.padding),k.borderRadius&&(r["--persona-label-btn-radius"]=k.borderRadius),k.hoverBackground&&(r["--persona-label-btn-hover-bg"]=k.hoverBackground),k.fontSize&&(r["--persona-label-btn-font-size"]=k.fontSize),k.gap&&(r["--persona-label-btn-gap"]=k.gap));let A=C?.toggleGroup;A&&(A.gap&&(r["--persona-toggle-group-gap"]=A.gap),A.borderRadius&&(r["--persona-toggle-group-radius"]=A.borderRadius));let M=C?.artifact;if(M?.toolbar){let t=M.toolbar;t.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=t.iconHoverColor),t.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=t.iconHoverBackground),t.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=t.iconPadding),t.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=t.iconBorderRadius),t.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=t.iconBorder),t.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=Ta(t.toggleGroupGap)),t.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=t.toggleBorderRadius),t.toggleGroupPadding&&(r["--persona-artifact-toolbar-toggle-group-padding"]=Ta(t.toggleGroupPadding)),t.toggleGroupBorder&&(r["--persona-artifact-toolbar-toggle-group-border"]=t.toggleGroupBorder),t.toggleGroupBorderRadius&&(r["--persona-artifact-toolbar-toggle-group-radius"]=t.toggleGroupBorderRadius),t.toggleGroupBackground&&(r["--persona-artifact-toolbar-toggle-group-bg"]=Ca(e,t.toggleGroupBackground)??t.toggleGroupBackground),t.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=t.copyBackground),t.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=t.copyBorder),t.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=t.copyColor),t.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=Ta(t.copyBorderRadius)),t.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=t.copyPadding),t.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=t.copyMenuBackground,r["--persona-dropdown-bg"]=r["--persona-dropdown-bg"]??t.copyMenuBackground),t.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=t.copyMenuBorder,r["--persona-dropdown-border"]=r["--persona-dropdown-border"]??t.copyMenuBorder),t.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=t.copyMenuShadow,r["--persona-dropdown-shadow"]=r["--persona-dropdown-shadow"]??t.copyMenuShadow),t.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=t.copyMenuBorderRadius,r["--persona-dropdown-radius"]=r["--persona-dropdown-radius"]??t.copyMenuBorderRadius),t.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=t.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=r["--persona-dropdown-item-hover-bg"]??t.copyMenuItemHoverBackground),t.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=t.iconBackground),t.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=t.toolbarBorder)}if(M?.tab){let e=M.tab;e.background&&(r["--persona-artifact-tab-bg"]=e.background),e.activeBackground&&(r["--persona-artifact-tab-active-bg"]=e.activeBackground),e.activeBorder&&(r["--persona-artifact-tab-active-border"]=e.activeBorder),e.borderRadius&&(r["--persona-artifact-tab-radius"]=e.borderRadius),e.textColor&&(r["--persona-artifact-tab-color"]=e.textColor),e.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=e.hoverBackground),e.listBackground&&(r["--persona-artifact-tab-list-bg"]=e.listBackground),e.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=e.listBorderColor),e.listPadding&&(r["--persona-artifact-tab-list-padding"]=e.listPadding)}if(M?.pane){let t=M.pane;t.toolbarBackground&&(r["--persona-artifact-toolbar-bg"]=Ca(e,t.toolbarBackground)??t.toolbarBackground)}if(M?.card){let e=M.card;e.background&&(r["--persona-artifact-card-bg"]=e.background),e.border&&(r["--persona-artifact-card-border"]=e.border),e.borderRadius&&(r["--persona-artifact-card-radius"]=e.borderRadius),e.hoverBackground&&(r["--persona-artifact-card-hover-bg"]=e.hoverBackground),e.hoverBorderColor&&(r["--persona-artifact-card-hover-border"]=e.hoverBorderColor)}if(M?.inline){let t=M.inline;t.background&&(r["--persona-artifact-inline-bg"]=Ca(e,t.background)??t.background),t.border&&(r["--persona-artifact-inline-border"]=t.border),t.borderRadius&&(r["--persona-artifact-inline-radius"]=t.borderRadius),t.chromeBackground&&(r["--persona-artifact-inline-chrome-bg"]=Ca(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(r["--persona-artifact-inline-chrome-border"]=Ca(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(r["--persona-artifact-inline-title-color"]=Ca(e,t.titleColor)??t.titleColor),t.mutedColor&&(r["--persona-artifact-inline-muted-color"]=Ca(e,t.mutedColor)??t.mutedColor),t.frameHeight&&(r["--persona-artifact-inline-frame-height"]=t.frameHeight)}let I=C?.code;I&&(I.keywordColor&&(r["--persona-code-keyword-color"]=I.keywordColor),I.stringColor&&(r["--persona-code-string-color"]=I.stringColor),I.commentColor&&(r["--persona-code-comment-color"]=I.commentColor),I.numberColor&&(r["--persona-code-number-color"]=I.numberColor),I.tagColor&&(r["--persona-code-tag-color"]=I.tagColor),I.attrColor&&(r["--persona-code-attr-color"]=I.attrColor),I.propertyColor&&(r["--persona-code-property-color"]=I.propertyColor),I.lineNumberColor&&(r["--persona-code-line-number-color"]=I.lineNumberColor),I.gutterBorderColor&&(r["--persona-code-gutter-border-color"]=I.gutterBorderColor),I.background&&(r["--persona-code-bg"]=Ca(e,I.background)??I.background));let T=r["--persona-surface"],E=r["--persona-container"],L=r["--persona-palette-colors-gray-100"]??"#f3f4f6",P=r["--persona-palette-colors-gray-200"]??"#e5e7eb",B=r["--persona-palette-colors-gray-300"]??"#d1d5db",N=!E||E===T,R=(e=>{if(!e)return;let t,r=e.trim().toLowerCase();if(35===r.charCodeAt(0)){let e=r.slice(1);if(!/^[0-9a-f]+$/.test(e))return;3===e.length||4===e.length?t=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(6===e.length||8===e.length)&&(t=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=r.match(/^rgba?\(([^)]+)\)$/);if(e){let r=e[1].split(/[,/\s]+/).filter(Boolean);r.length>=3&&(t=r.slice(0,3).map(e=>{let t=e.endsWith("%"),r=parseFloat(t?e.slice(0,-1):e);return t?r/100*255:r}))}}if(!t||t.some(e=>!Number.isFinite(e)))return;let[n,o,a]=t.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*n+.7152*o+.0722*a})(T??r["--persona-background"]),H=N&&void 0!==R&&R<.179,$=H?"rgba(255, 255, 255, 0.16)":B,W=N?H?"rgba(255, 255, 255, 0.08)":L:E,D=N?H?"rgba(255, 255, 255, 0.12)":P:E;return r["--persona-icon-btn-hover-bg"]=r["--persona-icon-btn-hover-bg"]??W,r["--persona-icon-btn-active-bg"]=r["--persona-icon-btn-active-bg"]??D,N&&(r["--persona-icon-btn-active-border"]=r["--persona-icon-btn-active-border"]??$),r["--persona-label-btn-hover-bg"]=r["--persona-label-btn-hover-bg"]??W,r["--persona-artifact-tab-hover-bg"]=r["--persona-artifact-tab-hover-bg"]??W,r["--persona-artifact-card-hover-bg"]=r["--persona-artifact-card-hover-bg"]??W,r}let Ba={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)"}}}},Na={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"}}},Ra={...Na,colors:{...Na.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"}}},Ha=Ba,$a={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:{...Ba.components,button:{...Ba.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:{...Ba.components?.eventStream,badge:{...Ba.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"}}}}},Wa=e=>{if(e&&"object"==typeof e&&!Array.isArray(e))return e},Da=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Fa=e=>(e=>{let t=e?.colorScheme??"light";return"light"===t?"light":"dark"===t?"dark":Da()})(e),Oa=e=>{let t=Fa(e),r=Wa(e?.theme),n=a({components:{launcher:"circle"===oa(e)?aa:{...ba.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}}}},r),o=Wa(e?.darkTheme);return((e,t)=>{if(!t||!(e=>!!e&&"launcher"in e&&(!0===e.launcher?.sidebarMode||"docked"===e.launcher?.mountMode))(t))return e;let r=t.theme?.components?.panel?.width,n=t.darkTheme?.components?.panel?.width;return null==("dark"===Fa(t)?n??r:r)?{...e,components:{...e.components,panel:{...e.components.panel,width:"v5"===A(t)?"400px":"420px"}}}:e})("dark"===t?((e,t={})=>{let r=(e=>"v5"===A({future:e})?{palette:Ra,components:$a}:{palette:Na,components:Ha})(t.future),n=a(r.components,e??{})??{};return Ia({...n,palette:{...n.palette,colors:"v5"===A(t)?a(r.palette.colors,n.palette?.colors):{...r.palette.colors,...n.palette?.colors}}},{validate:!1,future:t.future})})(a(n??{},o??{}),{future:e?.future}):((e,t={})=>Ia(e,t))(n,{future:e?.future}),e)},za=(e,t)=>{let r=(e=>Pa(e))(Oa(t));for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute("data-persona-color-scheme",Fa(t)),e.setAttribute("data-persona-defaults",A(t))},qa=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let r=new MutationObserver(()=>{e(Da())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window<"u"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(Da());r.addEventListener?(r.addEventListener("change",n),t.push(()=>r.removeEventListener("change",n))):r.addListener&&(r.addListener(n),t.push(()=>r.removeListener(n)))}return()=>{t.forEach(e=>e())}},ja=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px"),_a=(e,t)=>t||"overlay"!==e?.composer?.placement?"block":"overlay",Va=e=>{if("string"!=typeof e)return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let r=Number(t[1])/100;return r>0&&r<1?r:null},Ua=()=>{if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},Ga=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Ka=e=>{let t=e.toLowerCase().split("+").map(e=>e.trim()),r=t.pop(),n={key:r,mod:!1,shift:!1,alt:!1};for(let r of t)if("mod"===r||"cmd"===r||"ctrl"===r)n.mod=!0;else if("shift"===r)n.shift=!0;else{if("alt"!==r&&"option"!==r)return Ga("unknown modifier in",e),null;n.alt=!0}return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(r)||!/^([^+\s]|[a-z]{2,12})$/.test(r)?(Ga("unsupported",e),null):("space"===r&&(n.key=" "),n)},Ja=(e,t)=>{let r=Ka(e);if(!r)return"";let n=Ua(),o=(e=>"ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space".split(" ").find(t=>t.toLowerCase()===e)??(" "===e?"Space":1===e.length?e.toUpperCase():e[0].toUpperCase()+e.slice(1)))(r.key);if(!t&&n)return`${r.alt?"⌥":""}${r.shift?"⇧":""}⌘${o}`;let a=[t?n?"Meta":"Control":"Ctrl"];return r.alt&&a.push("Alt"),r.shift&&a.push("Shift"),a.push(o),a.join("+")},Qa=e=>Ja(e,!1),Xa=e=>Ja(e,!0),Ya=(e,t)=>t.key?.toLowerCase()===e.key&&(Ua()?t.metaKey:t.ctrlKey)===e.mod&&!(Ua()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Za=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t||e.isContentEditable},es=e=>{let t=new Map,r=e?.ownerDocument??(typeof document<"u"?document:null),n=(t,r)=>{if("page"===(t.scope??"widget"))return!0;if(!e)return!1;let n=r.composedPath?.();return n?.length?n.includes(e):e.contains(r.target)},o=e=>{if(e.isComposing||!t.size)return;let r=e.composedPath?.()[0]??e.target;for(let o of t.values())if(Ya(o.parsed,e)&&!1!==o.when?.()&&n(o,e)&&(o.allowInInput||!Za(r))){e.preventDefault();try{o.run(e)}catch(e){Ga(`${o.id} threw on`,o.combo),console.warn(e)}return}};return r?.addEventListener("keydown",o),{register(e){let r=Ka(e.combo);if(!r)return()=>{};let n=`${r.mod?"m":""}${r.shift?"s":""}${r.alt?"a":""}${r.key}`,o=t.get(n);return o?(Ga(`${o.id} already owns`,e.combo),()=>{}):(t.set(n,{...e,parsed:r}),e.element?.setAttribute("aria-keyshortcuts",Xa(e.combo)),()=>{t.get(n)?.id===e.id&&t.delete(n),e.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),r?.removeEventListener("keydown",o)}}};var ts=function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:e=>"true"===e.getAttribute("im-preserve"),shouldReAppend:e=>"true"===e.getAttribute("im-re-append"),shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0},r=function(){function e(e,t,r,o){if(!1===o.callbacks.beforeNodeAdded(t))return null;if(o.idMap.has(t)){let a=document.createElement(t.tagName);return e.insertBefore(a,r),n(a,t,o),o.callbacks.afterNodeAdded(a),a}{let n=document.importNode(t,!0);return e.insertBefore(n,r),o.callbacks.afterNodeAdded(n),n}}let t=function(){function e(e,t,r){let n=e.idMap.get(t),o=e.idMap.get(r);if(!o||!n)return!1;for(let e of n)if(o.has(e))return!0;return!1}function t(e,t){let r=e,n=t;return r.nodeType===n.nodeType&&r.tagName===n.tagName&&(!r.getAttribute?.("id")||r.getAttribute?.("id")===n.getAttribute?.("id"))}return function(r,n,o,a){let s=null,i=n.nextSibling,l=0,d=o;for(;d&&d!=a;){if(t(d,n)){if(e(r,d,n))return d;null===s&&(r.idMap.has(d)||(s=d))}if(null===s&&i&&t(d,i)&&(l++,i=i.nextSibling,l>=2&&(s=void 0)),r.activeElementAndParents.includes(d))break;d=d.nextSibling}return s||null}}();function r(e,t){if(e.idMap.has(t))s(e.pantry,t,null);else{if(!1===e.callbacks.beforeNodeRemoved(t))return;t.parentNode?.removeChild(t),e.callbacks.afterNodeRemoved(t)}}function o(e,t,n){let o=t;for(;o&&o!==n;){let t=o;o=o.nextSibling,r(e,t)}return o}function a(e,t,r,n){let o=n.target.getAttribute?.("id")===t&&n.target||n.target.querySelector(`[id="${t}"]`)||n.pantry.querySelector(`[id="${t}"]`);return function(e,t){let r=e.getAttribute("id");for(;e=e.parentNode;){let n=t.idMap.get(e);n&&(n.delete(r),n.size||t.idMap.delete(e))}}(o,n),s(e,o,r),o}function s(e,t,r){if(e.moveBefore)try{e.moveBefore(t,r)}catch{e.insertBefore(t,r)}else e.insertBefore(t,r)}return function(s,i,l,d=null,c=null){i instanceof HTMLTemplateElement&&l instanceof HTMLTemplateElement&&(i=i.content,l=l.content),d||=i.firstChild;for(let r of l.childNodes){if(d&&d!=c){let e=t(s,r,d,c);if(e){e!==d&&o(s,d,e),n(e,r,s),d=e.nextSibling;continue}}if(r instanceof Element){let e=r.getAttribute("id");if(s.persistentIds.has(e)){let t=a(i,e,d,s);n(t,r,s),d=t.nextSibling;continue}}let l=e(i,r,d,s);l&&(d=l.nextSibling)}for(;d&&d!=c;){let e=d;d=d.nextSibling,r(s,e)}}}(),n=function(){function e(e,r,n){let a=r.nodeType;if(1===a){let a=e,i=r,l=a.attributes,d=i.attributes;for(let e of d)o(e.name,a,"update",n)||a.getAttribute(e.name)!==e.value&&a.setAttribute(e.name,e.value);for(let e=l.length-1;0<=e;e--){let t=l[e];if(t&&!i.hasAttribute(t.name)){if(o(t.name,a,"remove",n))continue;a.removeAttribute(t.name)}}s(a,n)||t(a,i,n)}(8===a||3===a)&&e.nodeValue!==r.nodeValue&&(e.nodeValue=r.nodeValue)}function t(e,t,r){if(e instanceof HTMLInputElement&&t instanceof HTMLInputElement&&"file"!==t.type){let a=t.value,s=e.value;n(e,t,"checked",r),n(e,t,"disabled",r),t.hasAttribute("value")?s!==a&&(o("value",e,"update",r)||(e.setAttribute("value",a),e.value=a)):o("value",e,"remove",r)||(e.value="",e.removeAttribute("value"))}else if(e instanceof HTMLOptionElement&&t instanceof HTMLOptionElement)n(e,t,"selected",r);else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let n=t.value,a=e.value;if(o("value",e,"update",r))return;n!==a&&(e.value=n),e.firstChild&&e.firstChild.nodeValue!==n&&(e.firstChild.nodeValue=n)}}function n(e,t,r,n){let a=t[r];if(a!==e[r]){let s=o(r,e,"update",n);s||(e[r]=t[r]),a?s||e.setAttribute(r,""):o(r,e,"remove",n)||e.removeAttribute(r)}}function o(e,t,r,n){return!("value"!==e||!n.ignoreActiveValue||t!==document.activeElement)||!1===n.callbacks.beforeAttributeUpdated(e,t,r)}function s(e,t){return!!t.ignoreActiveValue&&e===document.activeElement&&e!==document.body}return function(t,n,o){return o.ignoreActive&&t===document.activeElement?null:(!1===o.callbacks.beforeNodeMorphed(t,n)||(t instanceof HTMLHeadElement&&o.head.ignore||(t instanceof HTMLHeadElement&&"morph"!==o.head.style?a(t,n,o):(e(t,n,o),s(t,o)||r(o,t,n))),o.callbacks.afterNodeMorphed(t,n)),t)}}();function o(e,t,r,n){if(e.head.block){let o=t.querySelector("head"),s=r.querySelector("head");if(o&&s){let t=a(o,s,e);return Promise.all(t).then(()=>n(Object.assign(e,{head:{block:!1,ignore:!0}})))}}return n(e)}function a(e,t,r){let n=[],o=[],a=[],s=[],i=new Map;for(let e of t.children)i.set(e.outerHTML,e);for(let t of e.children){let e=i.has(t.outerHTML),n=r.head.shouldReAppend(t),l=r.head.shouldPreserve(t);e||l?n?o.push(t):(i.delete(t.outerHTML),a.push(t)):"append"===r.head.style?n&&(o.push(t),s.push(t)):!1!==r.head.shouldRemove(t)&&o.push(t)}s.push(...i.values());let l=[];for(let t of s){let o=document.createRange().createContextualFragment(t.outerHTML).firstChild;if(!1!==r.callbacks.beforeNodeAdded(o)){if("href"in o&&o.href||"src"in o&&o.src){let e,t=new Promise(function(t){e=t});o.addEventListener("load",function(){e()}),l.push(t)}e.appendChild(o),r.callbacks.afterNodeAdded(o),n.push(o)}}for(let t of o)!1!==r.callbacks.beforeNodeRemoved(t)&&(e.removeChild(t),r.callbacks.afterNodeRemoved(t));return r.head.afterHeadMorphed(e,{added:n,kept:a,removed:o}),l}let s=function(){function e(e){let r=Object.assign({},t);return Object.assign(r,e),r.callbacks=Object.assign({},t.callbacks,e.callbacks),r.head=Object.assign({},t.head,e.head),r}function r(){let e=document.createElement("div");return e.hidden=!0,document.body.insertAdjacentElement("afterend",e),e}function n(e){let t=[],r=document.activeElement;if("BODY"!==r?.tagName&&e.contains(r))for(;r&&(t.push(r),r!==e);)r=r.parentElement;return t}function o(e){let t=Array.from(e.querySelectorAll("[id]"));return e.getAttribute?.("id")&&t.push(e),t}function a(e,t,r,n){for(let o of n){let n=o.getAttribute("id");if(t.has(n)){let t=o;for(;t;){let o=e.get(t);if(o??(o=new Set,e.set(t,o)),o.add(n),t===r)break;t=t.parentElement}}}}function s(e,t){let r=o(e),n=o(t),s=function(e,t){let r=new Set,n=new Map;for(let{id:t,tagName:o}of e)n.has(t)?r.add(t):n.set(t,o);let o=new Set;for(let{id:e,tagName:a}of t)o.has(e)?r.add(e):n.get(e)===a&&o.add(e);for(let e of r)o.delete(e);return o}(r,n),i=new Map;return a(i,s,e,r),a(i,s,t.__idiomorphRoot||t,n),{persistentIds:s,idMap:i}}return function(t,o,a){let{persistentIds:i,idMap:l}=s(t,o),d=e(a),c=d.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(c))throw`Do not understand how to morph style ${c}`;return{target:t,newContent:o,config:d,morphStyle:c,ignoreActive:d.ignoreActive,ignoreActiveValue:d.ignoreActiveValue,restoreFocus:d.restoreFocus,idMap:l,persistentIds:i,pantry:r(),activeElementAndParents:n(t),callbacks:d.callbacks,head:d.head}}}(),{normalizeElement:i,normalizeParent:l}=function(){let e=new WeakSet;class t{constructor(e){this.originalNode=e,this.realParentNode=e.parentNode,this.previousSibling=e.previousSibling,this.nextSibling=e.nextSibling}get childNodes(){let e=[],t=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;t&&t!=this.nextSibling;)e.push(t),t=t.nextSibling;return e}querySelectorAll(e){return this.childNodes.reduce((t,r)=>{if(r instanceof Element){r.matches(e)&&t.push(r);let n=r.querySelectorAll(e);for(let e=0;e<n.length;e++)t.push(n[e])}return t},[])}insertBefore(e,t){return this.realParentNode.insertBefore(e,t)}moveBefore(e,t){return this.realParentNode.moveBefore(e,t)}get __idiomorphRoot(){return this.originalNode}}return{normalizeElement:function(e){return e instanceof Document?e.documentElement:e},normalizeParent:function r(n){if(null==n)return document.createElement("div");if("string"==typeof n)return r(function(t){let r=new DOMParser,n=t.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(n.match(/<\/html>/)||n.match(/<\/head>/)||n.match(/<\/body>/)){let o=r.parseFromString(t,"text/html");if(n.match(/<\/html>/))return e.add(o),o;{let t=o.firstChild;return t&&e.add(t),t}}{let n=r.parseFromString("<body><template>"+t+"</template></body>","text/html").body.querySelector("template").content;return e.add(n),n}}(n));if(e.has(n))return n;if(n instanceof Node){if(n.parentNode)return new t(n);{let e=document.createElement("div");return e.append(n),e}}{let e=document.createElement("div");for(let t of[...n])e.append(t);return e}}}}();return{morph:function(e,t,n={}){e=i(e);let a=l(t),d=s(e,a,n),c=function(e,t){if(!e.config.restoreFocus)return t();let r=document.activeElement;if(!(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement))return t();let{id:n,selectionStart:o,selectionEnd:a}=r,s=t();return n&&n!==document.activeElement?.getAttribute("id")&&(r=e.target.querySelector(`[id="${n}"]`),r?.focus()),r&&!r.selectionEnd&&a&&r.setSelectionRange(o,a),s}(d,()=>o(d,e,a,t=>"innerHTML"===t.morphStyle?(r(t,e,a),Array.from(e.childNodes)):function(e,t,n){let o=l(t);return r(e,o,n,t,t.nextSibling),Array.from(o.childNodes)}(t,e,a)));return d.pantry.remove(),c},defaults:t}}();let rs=(e,t,r={})=>{let{preserveTypingAnimation:n=!0}=r;ts.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement&&n){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"))&&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}}}})},ns={index:-1,draft:""};function os(e){return"assistant"===e.role&&"tool"!==e.variant&&"reasoning"!==e.variant&&("approval"===e.variant||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length))}function as(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ss(e,t){return as(e)-e.scrollTop<=t}function is(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))}}let ls="none",ds="none",cs=120,ps=1800,us="none",hs=["pre","code","a","script","style"],ms=e=>({type:e?.type??ls,placeholder:e?.placeholder??ds,speed:e?.speed??cs,duration:e?.duration??ps,buffer:e?.buffer??us}),gs=[{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"}],fs=new Map;for(let e of gs)fs.set(e.name,e);let ys=["wipe","glyph-cycle"],bs=e=>{fs.set(e.name,e)},vs=(e,t)=>"none"===e?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:fs.get(e)??null,ws=(e,t,r,n,o)=>{if(!o)return e;if(r?.bufferContent)return r.bufferContent(e,n);if(!e)return e;if("word"===t){let t=e.search(/\s(?=\S*$)/);return t<0?"":e.slice(0,t)}if("line"===t){let t=e.lastIndexOf("\n");return t<0?"":e.slice(0,t)}return e},xs=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${r}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=t,o},Cs=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${r}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=t,o},Ss=/\s/,ks=(e,t)=>{let r=e.parentNode;for(;r;){if(1===r.nodeType){let e=r;if(t.has(e.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},As=(e,t,r)=>{let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=e.nodeValue??"";if(!a)return;let s=n.createDocumentFragment(),i=0;for(;i<a.length;)if(Ss.test(a[i])){let e=i;for(;e<a.length&&Ss.test(a[e]);)e+=1;s.appendChild(n.createTextNode(a.slice(i,e))),i=e}else{let e=n.createElement("span");e.className="persona-stream-word-group";let o=i;for(;o<a.length&&!Ss.test(a[o]);)e.appendChild(xs(n,a[o],t,r.value)),r.value+=1,o+=1;s.appendChild(e),i=o}o.replaceChild(s,e)},Ms=(e,t,r)=>{let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=e.nodeValue??"";if(!a)return;let s=n.createDocumentFragment(),i=a.split(/(\s+)/);for(let e of i)e&&(/^\s+$/.test(e)?s.appendChild(n.createTextNode(e)):(s.appendChild(Cs(n,e,t,r.value)),r.value+=1));o.replaceChild(s,e)},Is=(e,t,r,n)=>{if(!e||typeof document>"u")return e;let o=document.createElement("div");o.innerHTML=e;let a=new Set((n?.skipTags??hs).map(e=>e.toLowerCase())),s=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],l=s.nextNode();for(;l;)ks(l,a)||i.push(l),l=s.nextNode();let d={value:n?.startIndex??0},c="char"===t?As:Ms;for(let e of i)c(e,r,d);return o.innerHTML},Ts=(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},Es=(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 r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},Ls=new WeakMap,Ps=new WeakMap,Bs=e=>{let t=Ps.get(e);if(t){for(let e of t.values())"function"==typeof e&&e();t.clear()}},Ns=(e,t)=>{((e,t)=>{if(!e.styles)return;let r=Ls.get(t);if(r||(r=new Set,Ls.set(t,r)),r.has(e.name)){let n=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${n}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)})(e,t),((e,t)=>{if(!e.onAttach)return;let r=Ps.get(t);if(r||(r=new Map,Ps.set(t,r)),r.has(e.name))return;let n=e.onAttach(t);r.set(e.name,n)})(e,t)},{setLoader:Rs,load:Hs}=N({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),$s=Rs,Ws=Hs;function Ds(e,t=1e5){let r=e.style.position,n=e.style.zIndex,o=e.style.isolation,a=getComputedStyle(e),s="static"===a.position||""===a.position;return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=n,e.style.isolation=o}}let Fs=0,Os=null;function zs(e=document){if(Fs++,1===Fs){let t=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Os={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:r},t.style.overflow="hidden",t.style.position="fixed",t.style.top=`-${r}px`,t.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Fs=Math.max(0,Fs-1),0===Fs&&Os)){let t=e.body,r=e.defaultView??window;t.style.overflow=Os.originalOverflow,t.style.position=Os.originalPosition,t.style.top=Os.originalTop,t.style.width=Os.originalWidth,r.scrollTo(0,Os.scrollY),Os=null}}}let qs="right",js="420px",_s=!0,Vs="resize",Us="100dvh",Gs=e=>"docked"===(e?.launcher?.mountMode??"floating"),Ks=e=>"composer-bar"===(e?.launcher?.mountMode??"floating"),Js=e=>{let t=e?.launcher?.dock,r=f(e).dockWidth?t?.width:Ca(Oa(e),"components.panel.width");return{side:t?.side??qs,width:r??js,animate:t?.animate??_s,reveal:t?.reveal??Vs,maxHeight:t?.maxHeight??Us}},Qs=e=>"followUp"===e?"follow-up":e,Xs=(e,t=0)=>{if("string"==typeof e){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:"default"}:null}let r=e.label.trim();if(!r)return null;let n=e.prompt?.trim()||r;return{id:e.id?.trim()||n||`suggestion-${t}`,label:r,prompt:n,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},Ys=new WeakSet,Zs=e=>{let{item:t,index:o,surface:a,source:s,variant:i,streaming:l,config:d,plugins:c,chipsConfig:p,session:u,getTextarea:h,eventTarget:m,submitPrompt:g}=e,f="followUp"===a,y=t.behavior,b=()=>{if(u.isStreaming())return;let e={suggestion:{...t},surface:a,source:s,behavior:y},r=m.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(f&&m.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!r)return;for(let e of c)if(!1===e.onSuggestionSelect?.({suggestion:{...t},surface:a,source:s,variant:i,config:d}))return;let n=h();"fill"===y?(n.value=t.prompt,n.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),n.focus()):g?g(t.prompt):(n.value="",u.sendMessage(t.prompt))},v=()=>{let e=L("button",`persona-suggestion persona-suggestion--${i}`);if(e.type="button",e.disabled=l,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=y,"chip"===i&&(p?.fontWeight&&(e.style.fontWeight=p.fontWeight),p?.paddingX&&(e.style.paddingLeft=p.paddingX,e.style.paddingRight=p.paddingX),p?.paddingY&&(e.style.paddingTop=p.paddingY,e.style.paddingBottom=p.paddingY)),t.icon){let r=K(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);r&&(r.classList.add("persona-suggestion__icon"),t.iconColor&&(r.style.color=t.iconColor),e.appendChild(r))}let o=L("span","persona-suggestion__copy");if(o.appendChild(P("span",{className:"persona-suggestion__label",text:t.label})),t.description&&"chip"!==i&&o.appendChild(P("span",{className:"persona-suggestion__description",text:t.description})),e.appendChild(o),"chip"!==i){let t=n(r.ArrowRight,16,"currentColor",1.8);t&&(t.classList.add("persona-suggestion__arrow"),e.appendChild(t))}return e.addEventListener("click",b),e},w=null;for(let e of c)if(e.renderSuggestion&&(w=e.renderSuggestion({suggestion:{...t},index:o,surface:a,source:s,variant:i,streaming:l,config:d,defaultRenderer:v,select:b}),w))break;return w??=v(),w.dataset.suggestionId||=t.id,w.dataset.behavior||=y,w.dataset.emphasis||=t.emphasis,w instanceof HTMLButtonElement||w.setAttribute("aria-disabled",l?"true":"false"),w},ei=e=>{let t=[],r=[],n=null,o=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(o=null,e.hidden||"chip"!==e.dataset.variant||"scroll"!==e.dataset.overflow)return void a();let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1)return void a();let r="rtl"===getComputedStyle(e).direction,n=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),s=n<=4,i=n>=t-4,l=r?!i:!s,d=r?!s:!i;e.toggleAttribute("data-scroll-left",l),e.toggleAttribute("data-scroll-right",d)},i=()=>{null!==o||"function"!=typeof requestAnimationFrame?"function"!=typeof requestAnimationFrame&&s():o=requestAnimationFrame(s)};e.addEventListener("scroll",i,{passive:!0});let l="function"==typeof ResizeObserver?new ResizeObserver(i):null;return l?.observe(e),{buttons:t,elements:r,destroy:()=>{e.removeEventListener("scroll",i),l?.disconnect(),null!==o&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(o),o=null},render:(o,l,d,c,p,u)=>{e.replaceChildren(),t.length=0,r.length=0;let h=u?.source??"config",m=u?.surface??("config"===h?"starter":"followUp"),g="followUp"===m,f=u?.variant??"chip",y=u?.behavior??"send",b=u?.overflow??"wrap",v=u?.config??{},w=u?.plugins??[],x="number"==typeof u?.maxItems?Math.max(0,Math.floor(u.maxItems)):void 0,C=g?"followUps":"starters";!Ys.has(v)&&!0===v.debug&&"chip"!==f&&void 0!==v.suggestions?.[C]?.overflow&&(Ys.add(v),console.info(`[persona] suggestions.${C}.overflow applies to the "chip" variant only; the "${f}" variant manages its own stacking.`));let S=e=>e.map(Xs).filter(e=>null!==e).map(e=>({...e,behavior:e.behavior??y})),k=S(o??[]);w.forEach(e=>{e.transformSuggestions&&(k=S(e.transformSuggestions({suggestions:k.map(e=>({...e})),surface:m,source:h,config:v})))});let A=void 0===x?k:k.slice(0,x);if(!A.length)return e.hidden=!0,n=null,void a();if(!g&&(c??l.getMessages()).some(e=>"user"===e.role))return e.hidden=!0,void(n=null);e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Qs(m),e.dataset.variant=f,e.dataset.overflow=b;let M=document.createDocumentFragment(),I=l.isStreaming();A.forEach((n,o)=>{let a=Zs({item:n,index:o,surface:m,source:h,variant:f,streaming:I,config:v,plugins:w,chipsConfig:p,session:l,getTextarea:()=>d,eventTarget:e,submitPrompt:u?.submitPrompt});M.appendChild(a),r.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll("button"))].forEach(e=>{t.includes(e)||(e.disabled=I,t.push(e))})}),e.appendChild(M),s(),i();let T=JSON.stringify({normalized:A,surface:m,variant:f,source:h});T!==n&&(n=T,(e=>{typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||e.forEach((e,t)=>{"function"==typeof e.animate&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:60*t,easing:"ease-out",fill:"backwards"})})})(r),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:A.map(e=>({...e})),surface:m,source:h,variant:f},bubbles:!0,composed:!0})),g&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:A.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},ti={"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"},ri={x:[1.4,1.05]},ni="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",oi=(e,t,r={})=>{let{iconSize:n,iconText:o}=r,[a,s]=ri[t]??[1,1.5],i=!n;e.classList.toggle("persona-header-control--glyph",i),e.classList.toggle("persona-header-control--sparse",i&&1!==a);let l=K(t,`${Math.round((parseFloat(n??"")||20)*a)}px`,"currentColor",s);l?(l.style.display="block",i||(l.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((s/1.5).toFixed(4))})`),e.replaceChildren(l)):o&&(e.textContent=o)},ai=e=>{let{ariaLabel:t,tooltip:r=!0,tooltipHint:n,iconName:o,iconText:a,wrapperClassName:s=ni,size:i,iconSize:l,color:d,backgroundColor:c,borderWidth:p,borderColor:u,borderRadius:h,paddingX:m,paddingY:g,hidden:f,extraClassName:y,attrs:b}=e,v=L("div",s),w=!(!p&&!u),x=P("button",{className:B("persona-header-control","persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"persona-bg-transparent hover:persona-bg-gray-100",!w&&"persona-border-none",!h&&"persona-rounded-full",y),attrs:{type:"button","aria-label":t,...b},style:{width:i,height:i,minWidth:i,minHeight:i,display:f?"none":void 0,color:d||li.actionIconColor,backgroundColor:c,border:w?`${p||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:h,paddingLeft:m,paddingRight:m,paddingTop:g,paddingBottom:g}});return o?oi(x,o,{iconSize:l,iconText:a}):a&&(x.textContent=a),v.appendChild(x),Gn({anchor:x,trigger:v,text:()=>x.getAttribute("aria-label")??t,hint:n,enabled:r}),{button:x,wrapper:v}},si=(e,t={})=>{let{showClose:r=!0,wrapperClassName:n=ni,buttonSize:o,iconSize:a}=t,s=e?.launcher??{},i=s.closeButtonTooltipText??"Close chat",l=s.closeButtonShowTooltip??!0,{button:d,wrapper:c}=ai({ariaLabel:i,tooltip:l,iconName:s.closeButtonIconName??"x",iconText:s.closeButtonIconText??"×",wrapperClassName:n,size:o??s.closeButtonSize,iconSize:a,color:s.closeButtonColor,backgroundColor:s.closeButtonBackgroundColor,borderWidth:s.closeButtonBorderWidth,borderColor:s.closeButtonBorderColor,borderRadius:s.closeButtonBorderRadius,paddingX:s.closeButtonPaddingX,paddingY:s.closeButtonPaddingY,hidden:!r});return{button:d,wrapper:c}},ii=(e,t={})=>{let{wrapperClassName:r="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",buttonSize:n,iconSize:o}=t,a=(e?.launcher??{}).clearChat??{},s=a.tooltipText??"Clear chat",i=a.showTooltip??!0,{button:l,wrapper:d}=ai({ariaLabel:s,tooltip:i,iconName:a.iconName??"refresh-cw",wrapperClassName:r,size:n??a.size,iconSize:o,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:l,wrapper:d}},li={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)"},di={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)"},ci={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)"},pi=e=>{let{config:t,showClose:r=!0}=e,n=P("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:li.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)))"}}),o=t?.launcher??{},a=o.headerIconSize??"40px",s=o.closeButtonPlacement??"inline",i=o.headerIconHidden??!1,l=o.headerIconName,d=P("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(!i)if(l){let e=parseFloat(a)||24,r=K(l,.6*e,"currentColor",1);r?(r.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,r.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,d.replaceChildren(r)):d.textContent=t?.launcher?.agentIconText??"💬"}else if(t?.launcher?.iconUrl){let e=L("img");e.src=t.launcher.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=a,e.style.width=a,d.replaceChildren(e)}else d.textContent=t?.launcher?.agentIconText??"💬";let c=L("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=P("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:li.titleColor,...di}}),u=P("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:li.subtitleColor,...ci}});c.append(p,u),i?n.append(c):n.append(d,c);let h=o.clearChat??{},m=h.enabled??!0,g=h.placement??"inline",f=null,y=null;if(m){let e=ii(t,{wrapperClassName:"top-right"===g?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});f=e.button,y=e.wrapper,"top-right"===g&&(y.style.right="48px"),"inline"===g&&n.appendChild(y)}let{button:b,wrapper:v}=si(t,{showClose:r,wrapperClassName:"top-right"===s?"persona-absolute persona-top-4 persona-right-4 persona-z-50":m&&"inline"===g?"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"top-right"!==s&&n.appendChild(v),{header:n,iconHolder:d,headerTitle:p,headerSubtitle:u,closeButton:b,closeButtonWrapper:v,clearChatButton:f,clearChatButtonWrapper:y}},ui=(e,t,r)=>{let n=r?.launcher??{},o=n.closeButtonPlacement??"inline",a=n.clearChat?.placement??"inline";e.appendChild(t.header),"top-right"===o&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&"top-right"===a&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function hi(e){let{items:t,onSelect:r,anchor:n,position:o="bottom-left",portal:a,onOpenChange:s}=e,i=L("div","persona-dropdown-menu persona-hidden");i.setAttribute("role","menu"),i.setAttribute("data-persona-theme-zone","dropdown"),a?(i.style.position="fixed",i.style.zIndex="100001"):(i.style.position="absolute",i.style.top="100%",i.style.marginTop="4px","bottom-right"===o?i.style.right="0":i.style.left="0");for(let e of t){if(e.dividerBefore){let e=document.createElement("hr");i.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 r=K(e.icon,16,"currentColor",1.5);r&&t.appendChild(r)}let n=document.createElement("span");n.textContent=e.label,t.appendChild(n),t.addEventListener("click",t=>{t.stopPropagation(),c(),r(e.id)}),i.appendChild(t)}let l=null;function d(){let e=i.classList.contains("persona-hidden");(function(){if(!a)return;let e=n.getBoundingClientRect();i.style.top=`${e.bottom+4}px`,"bottom-right"===o?(i.style.right=window.innerWidth-e.right+"px",i.style.left="auto"):(i.style.left=`${e.left}px`,i.style.right="auto")})(),i.classList.remove("persona-hidden"),e&&s?.(!0),requestAnimationFrame(()=>{let e=e=>{!i.contains(e.target)&&!n.contains(e.target)&&c()};document.addEventListener("click",e,!0),l=()=>document.removeEventListener("click",e,!0)})}function c(){let e=!i.classList.contains("persona-hidden");i.classList.add("persona-hidden"),l?.(),l=null,e&&s?.(!1)}return a&&a.appendChild(i),{element:i,show:d,hide:c,toggle:function(){i.classList.contains("persona-hidden")?d():c()},destroy:function(){c(),i.remove()}}}function mi(e){let{icon:t,label:r,size:n,strokeWidth:o,className:a,chromeless:s,onClick:i,aria:l}=e,d=L("button",B(!s&&"persona-icon-btn",a));d.type="button",d.setAttribute("aria-label",r),d.title=r;let c=K(t,n??16,"currentColor",o??2);if(c&&d.appendChild(c),i&&d.addEventListener("click",i),l)for(let[e,t]of Object.entries(l))d.setAttribute(e,t);return d}function gi(e){let{icon:t,label:r,variant:n="default",size:o="sm",iconSize:a,className:s,onClick:i,aria:l}=e,d="persona-label-btn";"default"!==n&&(d+=" persona-label-btn--"+n),d+=" persona-label-btn--"+o,s&&(d+=" "+s);let c=L("button",d);if(c.type="button",c.setAttribute("aria-label",r),t){let e=K(t,a??14,"currentColor",2);e&&c.appendChild(e)}let p=L("span");if(p.textContent=r,c.appendChild(p),i&&c.addEventListener("click",i),l)for(let[e,t]of Object.entries(l))c.setAttribute(e,t);return c}function fi(e){let{label:t,icon:r="chevron-down",menuItems:n,onSelect:o,position:a="bottom-left",portal:s,className:i,hover:l}=e,d=L("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=L("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let p=K(r,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",d.appendChild(p)),l&&(d.style.borderRadius=l.borderRadius??"10px",d.style.padding=l.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=l.background??"",d.style.borderColor=l.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let u=hi({items:n,onSelect:e=>{d.setAttribute("aria-expanded","false"),o(e)},anchor:d,position:a,portal:s});return s||d.appendChild(u.element),d.addEventListener("click",e=>{if(e.stopPropagation(),"true"===d.getAttribute("data-persona-menu-locked"))return;let t=!u.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",t?"false":"true"),u.toggle()}),d.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),d.click())}),{element:d,setLabel:e=>{c.textContent=e,d.setAttribute("aria-label",e)},open:()=>{d.setAttribute("aria-expanded","true"),u.show()},close:()=>{d.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let e=!u.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",e?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),d.remove()}}}let yi=e=>{let t=pi({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=e.layoutHeaderConfig?.onTitleClick;if(r){let e=t.headerTitle.parentElement;e&&(e.style.cursor="pointer",e.setAttribute("role","button"),e.setAttribute("tabindex","0"),e.addEventListener("click",()=>r()),e.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),r())}))}return t},bi=e=>{let{config:t,showClose:r=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:a}=e,s=t?.launcher??{},i=L("div","persona-flex persona-items-center persona-justify-between");i.setAttribute("data-persona-theme-zone","header"),i.style.minHeight=li.minHeight,i.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let l,d,c=o?.titleMenu;if(c){let e=fi({label:s.title??"Chat Assistant",menuItems:c.menuItems,onSelect:t=>{let r=r=>{!1===r&&e.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:t}}))},n=c.onSelect(t);n instanceof Promise?n.then(r,()=>{}):r(n)},hover:c.hover,className:""});l=e.element,l.style.color=li.titleColor,d=l.querySelector(".persona-combo-btn-label")??l}else{if(l=L("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=L("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=li.titleColor,Object.assign(d.style,di),d.textContent=s.title??"Chat Assistant",l.appendChild(d),o?.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let e=o.onTitleClick;l.addEventListener("click",t=>{t.target.closest("button")||e()}),l.addEventListener("keydown",t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),e())})}let e=o?.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"}))}i.appendChild(l);let p="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:u,wrapper:h}=si(t,{showClose:r,wrapperClassName:p});n&&u.addEventListener("click",n);let m=L("div","persona-flex persona-items-center persona-gap-1");c||function(e,t,r){if(t?.length)for(let n of t){let{button:t,wrapper:o}=ai({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?Qa(n.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(t.setAttribute("data-persona-header-action",n.id),n.shortcut){let e=Xa(n.shortcut);e&&t.setAttribute("aria-keyshortcuts",e)}if(n.menuItems?.length){let e=hi({items:n.menuItems,onSelect:e=>r?.(e),anchor:o,position:"bottom-right"});o.appendChild(e.element),t.addEventListener("click",t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener("click",()=>r?.(n.id));e.appendChild(o)}}(m,o?.trailingActions,o?.onAction??a);let g=s.clearChat??{},f=null,y=null;if(g.enabled??1){let e=g.placement??"inline",r=ii(t,{wrapperClassName:"top-right"===e?"persona-absolute persona-top-4 persona-z-50":p});f=r.button,y=r.wrapper,"top-right"===e?y.style.right="48px":m.appendChild(y)}m.appendChild(h),i.appendChild(m);let b=L("div");b.style.display="none";let v=L("span");return v.style.display="none",{header:i,iconHolder:b,headerTitle:d,headerSubtitle:v,closeButton:u,closeButtonWrapper:h,clearChatButton:f,clearChatButtonWrapper:y}},vi={default:yi,minimal:bi},wi=e=>vi[e]??vi.default,xi=(e,t,r)=>{if(t?.render){let n=t.render({config:e,onClose:r?.onClose,onClearChat:r?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),o=L("div");o.style.display="none";let a=L("span"),s=L("span"),i=L("button");i.style.display="none";let l=L("div");return l.style.display="none",{header:n,iconHolder:o,headerTitle:a,headerSubtitle:s,closeButton:i,closeButtonWrapper:l,clearChatButton:null,clearChatButtonWrapper:null}}let n=wi(t?.layout??"default")({config:e,showClose:t?.showCloseButton??r?.showClose??!0,onClose:r?.onClose,onClearChat:r?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(!1===t.showIcon&&(n.iconHolder.style.display="none"),!1===t.showTitle&&(n.headerTitle.style.display="none"),!1===t.showSubtitle&&(n.headerSubtitle.style.display="none"),!1===t.showCloseButton&&(n.closeButton.style.display="none"),!1===t.showClearChat&&n.clearChatButtonWrapper&&(n.clearChatButtonWrapper.style.display="none")),n},Ci=e=>{let{config:t}=e,r=P("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"}}),n=ho(),o=P("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:s}=so(t);s();let i=lo(t),l=co(t),d=po(t),c=uo(t),p=P("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});o.append(p),d&&(d.previewsContainer.style.gap="8px",p.append(d.previewsContainer),o.append(d.input)),o.append(a);let u=P("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=P("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),m=P("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return d&&h.append(d.wrapper),l&&m.append(l.wrapper),m.append(i.wrapper),u.append(h,m),o.append(u),o.addEventListener("click",e=>{e.target!==i.button&&e.target!==i.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&e.target!==d?.button&&e.target!==d?.wrapper&&a.focus()}),"transient"===t?.statusIndicator?.mode?r.append(n,c,o):r.append(n,o,c),{footer:r,suggestions:n,composerForm:o,header:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:h,rightActions:m,setSendButtonMode:i.setMode}},Si=()=>{let e=P("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=L("span","persona-pill-peek__icon"),o=n(r.MessageSquare,16,"currentColor",1.5);o&&t.appendChild(o);let a=L("span","persona-pill-peek__text"),s=L("span","persona-pill-peek__caret"),i=n(r.ChevronUp,16,"currentColor",1.5);return i&&s.appendChild(i),e.append(t,a,s),{root:e,textNode:a}},ki=e=>{let{config:t}=e,r=P("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=ho(),o=uo(t);o.style.display="none";let{textarea:a,attachAutoResize:s}=so(t,{defaultMaxLines:5});s();let i=lo(t),l=co(t),d=po(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=P("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),p=P("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});d&&p.append(d.wrapper);let u=P("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});l&&u.append(l.wrapper),u.append(i.wrapper),c.addEventListener("click",e=>{e.target!==i.button&&e.target!==i.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&e.target!==d?.button&&e.target!==d?.wrapper&&a.focus()}),d&&c.append(d.input),c.append(p,a,u);let h=P("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(h),d&&h.append(d.previewsContainer),r.append(n,c,o);let m=c;return{footer:r,suggestions:n,composerForm:c,header:h,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:o,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:m,leftActions:p,rightActions:u,setSendButtonMode:i.setMode}};function Ai(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let r=P("span",{className:B("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&&r.style.setProperty("--persona-mention-token-accent",e.color);let n=K(e.iconName??"at-sign",13,"currentColor",2);if(n){let e=L("span","persona-mention-token-icon");e.appendChild(n),r.appendChild(e)}return r.appendChild(P("span",{className:"persona-mention-token-label",text:`@${e.label}`})),r}let Mi=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")||!/^(?:https?|blob):/i.test(e)&&!t.startsWith("data:")&&e.includes(":"))},Ii=e=>{if(!e||0===e.length)return null;let t=P("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let r of e){let e=P("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:r.label}}),n=L("span","persona-mention-chip-icon"),o=K(r.iconName??"at-sign",13,"currentColor",2);o&&n.appendChild(o),e.appendChild(n),e.appendChild(P("span",{className:"persona-mention-chip-label",text:r.label})),t.appendChild(e)}return t},Ti=()=>{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 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="250ms";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="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(n),e.appendChild(o),e},Ei=(e,t,r)=>{let n={config:r??{},streaming:!0,location:e,defaultRenderer:Ti};if(t){let e=t(n);if(null!==e)return e}return Ti()},Li=(e,t,r="div")=>{let n=L(r,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return n.textContent=t.format?t.format(o):o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Pi=(e,t="bubble")=>{let r=["persona-message-bubble"];switch(t){case"flat":"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.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 r},Bi={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"}},Ni=e=>`custom:${e}`,Ri=(e,t)=>"user"!==t&&"assistant"!==t?[]:(e?.custom??[]).filter(e=>(e.roles??["assistant"]).includes(t)),Hi=(e,t,r,n)=>{let o=t.showCopy??!0,a=t.showUpvote??!1,s=t.showDownvote??!1,i=t.showReadAloud??!1,l=(t.showRegenerate??!1)&&!0===n?.canRegenerate,d=(t.showEdit??!1)&&!0===n?.canEdit,c=(t.showQuote??!1)&&!1!==n?.canQuote,p=Ri(t,e.role);if(!(o||a||s||i||l||d||c||0!==p.length)){let t=L("div");return t.style.display="none",t.id=`actions-${e.id}`,t.setAttribute("data-actions-for",e.id),t}let u=t.visibility??"hover",h=t.align??"right",m=t.layout??"pill-inside",g=L("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${{left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h]} ${{"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[m]} ${"hover"===u?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(e,t,r)=>{let n=mi({icon:e,label:t,size:14,className:"persona-message-action-btn",chromeless:!0});return n.setAttribute("data-action",r),n};o&&g.appendChild(f("copy","Copy message","copy")),i&&g.appendChild(f("volume-2","Read aloud","read-aloud")),a&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),l&&g.appendChild(f("refresh-cw","Regenerate response","regenerate")),d&&g.appendChild(f("pencil","Edit message","edit")),c&&g.appendChild(f("quote","Quote message","quote"));for(let e of p)g.appendChild(f(e.iconName??"ellipsis",e.label,Ni(e.id)));return g},$i=(e,t,r,n,o,a)=>{let s=r??{},i=s.layout??"bubble",l=s.avatar,d=s.timestamp,c=l?.show??!1,p=d?.show??!1,u=l?.position??"left",h=d?.position??"below",m=Pi(e.role,i),g=L("div",m.join(" "));g.id=`bubble-${e.id}`,g.setAttribute("data-message-id",e.id),g.setAttribute("data-persona-theme-zone","user"===e.role?"user-message":"assistant-message");let f=xa(a?.widgetConfig?.future).components.message,y=a?.widgetConfig?.theme?.components?.message;((e,t,r="bubble",n)=>{if(!n)return;let o="user"===t?"user":"assistant",a=Bi[r??"bubble"]??Bi.bubble;n.padding&&(e.style.padding=`var(--persona-message-${o}-padding, ${a.padding})`),n.fontSize&&(e.style.fontSize=`var(--persona-message-${o}-font-size, ${a.fontSize})`),n.lineHeight&&(e.style.lineHeight=`var(--persona-message-${o}-line-height, ${a.lineHeight})`),n.fontFamily&&(e.style.fontFamily=`var(--persona-message-${o}-font-family, inherit)`)})(g,e.role,i,"user"===e.role?{...f.user,...y?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...f.assistant,...y?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),"flat"===i?(g.style.backgroundColor="transparent",g.style.color="user"===e.role?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):"user"===e.role?(g.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",g.style.color="var(--persona-message-user-text, white)"):"assistant"===e.role&&(g.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",g.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"image"===e.type&&"string"==typeof e.image&&e.image.trim().length>0):[])(e),v=e.content?.trim()??"",w=b.length>0&&"[Image]"===v,x=ms(a?.widgetConfig?.features?.streamAnimation),C=a?.widgetConfig?.features?.streamAnimation?.plugins,S="assistant"===e.role&&"none"!==x.type?vs(x.type,C):null,k="assistant"===e.role&&!0===S?.isAnimating?.(e),A="assistant"===e.role&&null!==S&&(!!e.streaming||k);A&&S?.bubbleClass&&g.classList.add(S.bubbleClass);let M=document.createElement("div");M.classList.add("persona-message-content"),e.streaming&&M.classList.add("persona-content-streaming"),A&&S&&(S.containerClass&&M.classList.add(S.containerClass),M.style.setProperty("--persona-stream-step",`${x.speed}ms`),M.style.setProperty("--persona-stream-duration",`${x.duration}ms`));let I=A?ws(e.content??"",x.buffer,S,e,!!e.streaming):e.content??"",T=()=>{let r=t({text:I,message:e,streaming:!!e.streaming,raw:e.rawContent});return A&&"char"===S?.wrap?Is(r,"char",e.id,{skipTags:S.skipTags}):A&&"word"===S?.wrap?Is(r,"word",e.id,{skipTags:S.skipTags}):r},E=null;if(w?(E=document.createElement("div"),E.innerHTML=T(),E.style.display="none",M.appendChild(E)):e.contentSegments?.length?((e,t,r,n)=>{let o=Math.random().toString(36).slice(2,8),a=e=>`${o}:${e}`,s=r(t.map((e,t)=>"text"===e.kind?e.text:a(t)).join(""));if(!t.every((e,t)=>"text"===e.kind||s.includes(a(t))))return void e.replaceChildren(((e,t)=>{let r=document.createDocumentFragment();for(let n of e)"text"===n.kind?r.appendChild(document.createTextNode(n.text)):r.appendChild(Ai(n.ref,{readonly:!0,render:t}));return r})(t,n));e.innerHTML=s;let i=RegExp(`${o}:(\\d+)`),l=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),d=[];for(let e=l.nextNode();e;e=l.nextNode())d.push(e);for(let e of d){let r=e;for(let e=i.exec(r.data);e;e=i.exec(r.data)){let o=t[Number(e[1])],a=r.splitText(e.index);a.data=a.data.slice(e[0].length),"mention"===o?.kind&&a.parentNode?.insertBefore(Ai(o.ref,{readonly:!0,render:n}),a),r=a}}})(M,e.contentSegments,r=>t({text:r,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):M.innerHTML=T(),A&&S?.useCaret&&!w&&v){let e=Ts(),t=M.querySelectorAll(".persona-stream-char, .persona-stream-word"),r=t[t.length-1];if(r?.parentNode)r.parentNode.insertBefore(e,r.nextSibling);else{let t=M.lastElementChild;t?t.appendChild(e):M.appendChild(e)}}if(p&&"inline"===h&&e.createdAt){let t=Li(e,d,"span");t.classList.add("persona-timestamp-inline");let r=M.lastElementChild;r?r.appendChild(t):M.appendChild(t)}if(b.length>0){let e=((e,t,r)=>{if(0===e.length)return null;try{let n=L("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let o=0,a=!1,s=()=>{a||(a=!0,n.remove(),r?.())};return e.forEach((e,t)=>{let r=L("img");r.alt=e.alt?.trim()||`Attached image ${t+1}`,r.loading="lazy",r.decoding="async",r.referrerPolicy="no-referrer",r.style.display="block",r.style.width="100%",r.style.maxWidth="320px",r.style.maxHeight="320px",r.style.height="auto",r.style.objectFit="contain",r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let a=!1;o+=1,r.addEventListener("error",()=>{a||(a=!0,o=Math.max(0,o-1),r.remove(),0===o&&s())}),r.addEventListener("load",()=>{a=!0}),(e=>{let t=e.toLowerCase();return!(t.startsWith("data:image/svg+xml")||!/^(?:https?|blob):/i.test(e)&&!t.startsWith("data:image/")&&e.includes(":"))})(e.image)?(r.src=e.image,n.appendChild(r)):(a=!0,o=Math.max(0,o-1),r.remove())}),0===o?(s(),null):n}catch{return r?.(),null}})(b,!w&&!!v,()=>{w&&E&&(E.style.display="")});e?g.appendChild(e):w&&E&&(E.style.display="")}let P=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"audio"===e.type&&"string"==typeof e.audio&&e.audio.trim().length>0):[])(e);if(P.length>0){let e=(e=>{if(0===e.length)return null;try{let t=L("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(e=>{if(!Mi(e.audio))return;let n=L("audio");n.controls=!0,n.preload="metadata",n.src=e.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth="320px",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(P);e&&g.appendChild(e)}let B=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"video"===e.type&&"string"==typeof e.video&&e.video.trim().length>0):[])(e);if(B.length>0){let e=(e=>{if(0===e.length)return null;try{let t=L("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(e=>{if(!Mi(e.video))return;let n=L("video");n.controls=!0,n.preload="metadata",n.src=e.video,n.style.display="block",n.style.width="100%",n.style.maxWidth="320px",n.style.maxHeight="320px",n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(B);e&&g.appendChild(e)}let N=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"file"===e.type&&"string"==typeof e.data&&e.data.trim().length>0):[])(e);if(N.length>0){let e=(e=>{if(0===e.length)return null;try{let t=L("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(e=>{if(!Mi(e.data))return;let n=L("a");n.href=e.data,n.download=e.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=e.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(N);e&&g.appendChild(e)}let R=e.contentSegments?.length?null:Ii(e.contextMentions);if(R&&g.appendChild(R),g.appendChild(M),p&&"below"===h&&e.createdAt){let t=Li(e,d);t.classList.add("persona-mt-1"),g.appendChild(t)}let H="assistant"===e.role?((e,t)=>{if(!e)return null;let r=(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}})(e);if(null===r)return null;let n=t?.[e];return(void 0===n?r:n)||null})(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&"assistant"===e.role){let e=!(!I||!I.trim()),t="skeleton"===x.placeholder,r=t&&"line"===x.buffer&&e;if(e)r&&g.appendChild(Es());else if(t)g.appendChild(Es());else{let e=Ei("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);e&&g.appendChild(e)}}H&&e.stopReason&&!e.streaming&&(v||(M.style.display="none"),g.appendChild(((e,t)=>{let r=L("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r})(e.stopReason,H)));let $="assistant"===e.role&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&!1!==n?.enabled,W=a?.actionEligibility,D="user"===e.role&&!e.streaming&&!1!==n?.enabled&&(!0===n?.showEdit&&!0===W?.canEdit||!0===n?.showQuote&&!0===W?.canQuote||Ri(n,"user").length>0);if(($||D)&&n){let t=Hi(e,D?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,0,W);g.appendChild(t)}if(!c||"system"===e.role)return g;let F=L("div","persona-message-with-avatar persona-flex persona-gap-2 "+("user"===e.role?"persona-flex-row-reverse":"")),O=((e,t)=>{let r=L("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"),n="user"===t?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let e=L("img");e.src=n,e.alt="user"===t?"User":"Assistant",e.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(e)}else r.textContent=n,r.classList.add("user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent="user"===t?"U":"A",r.classList.add("user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r})(l,e.role);return"right"===u||"left"===u&&"user"===e.role?F.append(g,O):F.append(O,g),F},Wi=(e,t,r)=>{t.hidden=!r,t.style.display=r?"":"none",e.classList.toggle("persona-gap-6",r),e.classList.toggle("persona-gap-3",!r)},Di=(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,((e,t)=>{if(e.replaceChildren(),t)if("function"==typeof t){let r=null;try{r=t()}catch(e){console.warn("[persona] welcome.icon renderer threw",e)}if(!r)return void(e.hidden=!0);e.appendChild(r),e.hidden=!1}else{if("lucide"===t.type){let r=K(t.name,40);if(!r)return void(e.hidden=!0);e.appendChild(r)}else"image"===t.type?e.appendChild(P("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(P("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1}else e.hidden=!0})(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"),"inline"===t.iconPlacement?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")},Fi="data-persona-welcome-overlay",Oi="persona-welcome-overlay-active",zi=new WeakMap,qi=(e,t,r)=>{r.setAttribute("data-persona-welcome-plugin",""),t.appendChild(r),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(Fi,""),e.classList.contains(Oi)||(zi.set(e,e.scrollTop),e.classList.add(Oi),e.scrollTop=0)},ji=(e,t,r)=>{r&&r!==t&&r.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(Fi),e.classList.contains(Oi)&&(e.classList.remove(Oi),e.scrollTop=zi.get(e)??e.scrollTop,zi.delete(e))},_i=(e,t,r)=>{if(e.replaceChildren(),!t)return void(e.hidden=!0);let n=r?.layout?.messages?.layout??"bubble",o=P("div",{className:Pi("assistant",n).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:"flat"===n?{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(P("div",{className:"persona-flex"},o)),e.hidden=!1},Vi=()=>typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Ui=(e,t)=>{if(Vi()||"function"!=typeof e.animate||!e.isConnected)return t(null),null;let r=e.getBoundingClientRect(),n=e.parentElement,o=0,a=0,s=0;if(n){let t=getComputedStyle(n);o=parseFloat(t.rowGap)||0;let i=e.previousElementSibling,l=e.nextElementSibling,d=n.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-n.scrollTop;a=Math.max(0,i?r.top-i.getBoundingClientRect().bottom-o:r.top-d),s=Math.max(0,l?l.getBoundingClientRect().top-r.bottom-o:0)}let i=e.style.overflow;e.style.overflow="hidden";let l=getComputedStyle(e),d=parseFloat(l.paddingTop)||0,c=parseFloat(l.paddingBottom)||0,p=e.animate([{opacity:"1",transform:"none",height:`${r.height}px`,minHeight:"0px",paddingTop:`${d}px`,paddingBottom:`${c}px`,marginTop:`${a}px`,marginBottom:`${s}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:-o+"px"}],{duration:180,easing:"ease-out",fill:"forwards"}),u=!1,h=()=>{u||(u=!0,e.style.overflow=i,t(p))};return p.finished.then(h).catch(h),p},Gi=(e,t,r,n=260)=>{if(t<=1||Vi()||"function"!=typeof e.animate||!e.isConnected)return null;let o="drop"===r?-t:t;return e.animate([{transform:`translateY(${o}px)`},{transform:"none"}],{duration:n,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})},Ki=new WeakSet,Ji=(e,t)=>!!e&&void 0!==e[t],Qi=(e,t=!0===e?.launcher?.fullHeight&&!e.launcher.sidebarMode&&"docked"!==e.launcher.mountMode)=>{let r=e?.welcome,n=e?.copy,o=!0===e?.future?.v5Defaults,a=r?.layout??(o?"centered":"top"),s=Ji(r,"variant")?r.variant:!1===n?.showWelcomeCard?"none":"card",i="hero"!==s||o||void 0!==r?.layout?Ji(r,"dismiss")?r.dismiss:o||"hero"===s?"on-first-message":"never":"on-first-message",l=[];Ji(r,"title")&&Ji(n,"welcomeTitle")&&l.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Ji(r,"subtitle")&&Ji(n,"welcomeSubtitle")&&l.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Ji(r,"variant")&&Ji(n,"showWelcomeCard")&&l.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),"hero"===s&&Ji(r,"message")&&l.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!o&&void 0===r?.layout&&"hero"===s&&Ji(r,"dismiss")&&"on-first-message"!==r.dismiss&&l.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let d=r?.anchor??("centered"===a&&t?"center":"bottom"),c=null!==Va(r?.anchorComposerTop);return Ji(r,"anchorComposerTop")&&!c&&l.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),"center"!==d&&(Ji(r,"anchorComposerTop")||Ji(r,"composerGap"))&&l.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),((e,t)=>{e&&!0===e.debug&&t.length&&(Ki.has(e)||(Ki.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))})(e,l),{title:Ji(r,"title")?r.title:n?.welcomeTitle??(o?"What can I help with?":"Hello 👋"),kicker:r?.kicker??"",subtitle:Ji(r,"subtitle")?r.subtitle:n?.welcomeSubtitle??(o?"":"I can answer questions and help you get things done here."),icon:r?.icon,align:"start"===r?.align||"center"===r?.align?r.align:"centered"===a?"center":void 0,iconPlacement:r?.icon&&"function"!=typeof r.icon&&"inline"===r.icon.placement?"inline":"above",variant:s,dismiss:i,message:"hero"===s?void 0:r?.message,layout:a,anchor:d,anchorComposerTop:c?r.anchorComposerTop:"44%",composerGap:r?.composerGap?.trim()||"24px"}},Xi=(e,t)=>"none"!==e.variant&&("never"===e.dismiss||!(t??[]).some(e=>"user"===e.role)),Yi="var(--persona-components-panel-height)",Zi=e=>{let t=f(e),r=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,n=e?.launcher?.heightOffset??0;return{width:r??"var(--persona-components-panel-width)",maxWidth:r??"var(--persona-components-panel-maxWidth)",height:0===n?`max(200px, ${Yi})`:`max(200px, calc(${Yi} - ${n}px))`,maxHeight:"var(--persona-components-panel-maxHeight)"}},el="16px",tl="10px",rl="14px",nl=e=>{let t=P("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Qs(e)}});return t.hidden=!0,t},ol=(e,t)=>{let r=((e,t,r={})=>{let n=P("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});n.hidden=!0;let o=L("p","persona-welcome-kicker");o.hidden=!0;let a=L("h2","persona-welcome-title"),s=L("p","persona-welcome-subtitle"),i=P("div",{className:"persona-welcome-head-text"},o,a),l=P("div",{className:"persona-welcome-title-row"},n,i);return{host:P("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:r.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},l,s,t),iconHolder:n,kicker:o,title:a,subtitle:s,starterSuggestions:t}})(0,nl("starter"),{flatShadow:Gs(e)}),n=Qi(e);Di(r,n),Wi(t,r.host,Xi(n,e?.initialMessages));let o=(()=>{let e=P("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e})();return _i(o,n.message,e),{welcome:r,greetingHost:o}},al=(e,t)=>{let r=L("button");r.type="button",r.innerHTML='\n <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>\n <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />\n <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">\n <span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-launcher" data-role="launcher-title"></span>\n <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>\n </span>\n <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>\n ',r.addEventListener("click",t);let n=e=>{let t=e.launcher??{},n=Gs(e),o="circle"===oa(e);o?(r.dataset.personaLauncherVariant="circle",r.setAttribute("aria-label",t.title??"Open chat")):(r.removeAttribute("data-persona-launcher-variant"),r.removeAttribute("aria-label"));let a=r.querySelector("[data-role='launcher-title']");if(a){let e=t.title??"Chat Assistant";a.textContent=e,a.setAttribute("title",e)}let s=r.querySelector("[data-role='launcher-subtitle']");if(s){let e=t.subtitle??"Here to help you get answers fast";s.textContent=e,s.setAttribute("title",e)}let i=r.querySelector(".persona-flex-col");i&&(t.textHidden||n||o?i.style.display="none":i.style.display="");let l=r.querySelector("[data-role='launcher-icon']");if(l)if(t.agentIconHidden)l.style.display="none";else{let e=t.agentIconSize??"40px";if(l.style.height=e,l.style.width=e,t.agentIconBackgroundColor?(l.style.backgroundColor=t.agentIconBackgroundColor,l.classList.remove("persona-bg-persona-primary")):(l.style.backgroundColor="",l.classList.add("persona-bg-persona-primary")),l.innerHTML="",t.agentIconName){let r=parseFloat(e)||24,n=K(t.agentIconName,.6*r,"var(--persona-text-inverse, #ffffff)",1.5);n?(l.appendChild(n),l.style.display=""):(l.textContent=t.agentIconText??"💬",l.style.display="")}else t.iconUrl?l.style.display="none":(l.textContent=t.agentIconText??"💬",l.style.display="")}let d=r.querySelector("[data-role='launcher-image']");if(d){let e=t.agentIconSize??"40px";d.style.height=e,d.style.width=e,!t.iconUrl||t.agentIconName||t.agentIconHidden?d.style.display="none":(d.src=t.iconUrl,d.style.display="block")}let c=r.querySelector("[data-role='launcher-call-to-action-icon']");if(c){let e=t.callToActionIconSize??"32px";c.style.height=e,c.style.width=e,t.callToActionIconBackgroundColor?(c.style.backgroundColor=t.callToActionIconBackgroundColor,c.classList.remove("persona-bg-persona-primary")):(c.style.backgroundColor="",c.classList.add("persona-bg-persona-primary")),t.callToActionIconColor?(c.style.color=t.callToActionIconColor,c.classList.remove("persona-text-persona-call-to-action")):(c.style.color="",c.classList.add("persona-text-persona-call-to-action"));let r=0;if(t.callToActionIconPadding?(c.style.boxSizing="border-box",c.style.padding=t.callToActionIconPadding,r=2*(parseFloat(t.callToActionIconPadding)||0)):(c.style.boxSizing="",c.style.padding=""),t.callToActionIconHidden||o)c.style.display="none";else if(c.style.display=n?"none":"",c.innerHTML="",t.callToActionIconName){let n=Math.max((parseFloat(e)||24)-r,8),o=K(t.callToActionIconName,n,"currentColor",1.5);o?c.appendChild(o):c.textContent=t.callToActionIconText??"↗"}else c.textContent=t.callToActionIconText??"↗"}let p=t.position&&ti[t.position]?ti[t.position]:ti["bottom-right"];r.className=n?"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 ${p}`,n||(r.style.zIndex=String(t.zIndex??1e5)),r.style.border=t.border??"1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",r.style.boxShadow=void 0===t.shadow?"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,n?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=t.collapsedMaxWidth??"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")};return e&&n(e),{element:r,update:n,destroy:()=>{r.removeEventListener("click",t),r.remove()}}},sl=new Set,il=e=>{let t=e?.persistState;return`${("object"==typeof t?t?.keyPrefix:void 0)??"persona-"}teaser-dismissed`},ll=(e,t)=>{let r=L("div","persona-launcher-surface");r.setAttribute("data-persona-launcher-surface","true");let n=e??{},o=null,a=null,s=null,i=null,l=null,d=!1,c=!1,p=!1,u=!1,h=()=>"once"===(o?.frequency??"once")&&!1!==n.persistState,m=()=>{null!==l&&(clearTimeout(l),l=null)},g=e=>{m(),p=!0,a&&d&&(d=!1,a.hidden=!0),((e,t)=>{if(sl.add(e),t)try{window.localStorage.setItem(e,"1")}catch{}})(il(n),e&&h())},f=e=>{o&&!p&&g("user"===e&&d)},y=()=>{l=null,a&&!p&&!u&&(c=!0,d=!0,a.hidden=!1,!(typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||"function"!=typeof a.animate)&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},b=()=>{g(h()),t()},v=e=>{e.stopPropagation(),g(h())},w=al(e,()=>{f("user"),t()}),x=()=>{m(),i?.removeEventListener("click",b),s?.removeEventListener("click",v),a?.remove(),a=null,i=null,s=null,d=!1},C=()=>{let e=n.launcher?.position??"bottom-right",t=ti[e]??ti["bottom-right"];a?(r.className=B("persona-launcher-surface",t),r.setAttribute("data-teaser",e),r.style.zIndex=String(n.launcher?.zIndex??1e5),w.element.style.position="static"):(r.className="persona-launcher-surface",r.removeAttribute("data-teaser"),r.style.zIndex="",w.element.style.position="")},S=e=>{let t=(e=>{let t=e?.launcher?.teaser;return t&&t.text&&!1!==e?.launcher?.enabled&&!Gs(e??{})?t:null})(e);o=t,t?(a||(i=P("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),i.addEventListener("click",b),s=P("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"×"}),s.addEventListener("click",v),a=P("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},i,s),r.insertBefore(a,w.element)),i.textContent=t.text,s.hidden=!1===t.dismissible,s.setAttribute("aria-label",t.dismissLabel??"Dismiss message"),o&&a&&(p||c||u||((e,t)=>{if(sl.has(e))return!0;if(!t)return!1;try{return"1"===window.localStorage.getItem(e)}catch{return!1}})(il(n),h())||(m(),l=setTimeout(y,Math.max(0,o.delayMs??0))))):x()};return r.appendChild(w.element),e&&(S(e),C()),{element:r,launcher:w,get teaser(){return a?{element:a,show:y,dismiss:g}:null},setPanelOpen:(e,t="user")=>{u=e,e&&f(t)},update:e=>{n=e,w.update(e),S(e),C()},destroy:()=>{x(),w.destroy(),r.remove()}}},dl=({config:e,showClose:t})=>{let{wrapper:r,panel:n,pillRoot:o}=(e=>{let t=e?.launcher?.enabled??!0,r=Gs(e);if(Ks(e)){let t=e?.launcher?.composerBar??{},r=L("div","persona-widget-wrapper persona-fixed persona-transition");r.setAttribute("data-persona-composer-bar",""),r.dataset.state="collapsed",r.dataset.expandedSize=t.expandedSize??"anchored",r.style.zIndex=String(e?.launcher?.zIndex??1e5);let n=L("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");n.style.width="100%",r.appendChild(n);let o=L("div","persona-widget-pill-root");return o.setAttribute("data-persona-composer-bar",""),o.dataset.state="collapsed",o.dataset.expandedSize=t.expandedSize??"anchored",o.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:r,panel:n,pillRoot:o}}if(r){let e=L("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),t=L("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=L("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),r=L("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),n=f(e),o=n.launcherWidth||n.legacyLauncherWidth||void 0!==e?.theme?.components?.panel?.width?Zi(e).width:"100%";return t.style.width=o,r.style.width="100%",t.appendChild(r),{wrapper:t,panel:r}}let n=e?.launcher??{},o=n.position&&ti[n.position]?ti[n.position]:ti["bottom-right"],a=L("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let s=L("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=Zi(e);return s.style.width=i.width,s.style.maxWidth=i.maxWidth,a.appendChild(s),{wrapper:a,panel:s}})(e),a=((e,t=!0)=>{if(Ks(e))return((e,t)=>{let r=L("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:o}=si(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:el,iconSize:tl});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let a=null,s=null;if(e?.launcher?.clearChat?.enabled??1){let t=ii(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:el,iconSize:rl});a=t.button,s=t.wrapper,s.style.position="absolute",s.style.top="8px",s.style.right="32px",s.style.zIndex="10"}let i=P("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=P("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:d,greetingHost:c}=ol(e,l),{host:p,title:u,subtitle:h}=d,m=d.starterSuggestions,g=L("div","persona-widget-messages persona-flex persona-flex-col");g.style.gap="var(--persona-components-message-gap, 12px)";let f=nl("followUp"),y=ja(e,!0);y&&(g.style.maxWidth=y,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),l.append(p,c,g,f);let b=P("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"}}),v=ki({config:e}),{root:w,textNode:x}=Si();return r.append(i,o,l,b),s&&r.appendChild(s),{container:r,body:l,messagesWrapper:g,starterSuggestions:m,transcriptSuggestions:f,composerOverlay:b,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,welcomeHost:p,welcomeIconHolder:d.iconHolder,greetingHost:c,introKicker:d.kicker,introTitle:u,introSubtitle:h,closeButton:n,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:s,iconHolder:L("span"),headerTitle:L("span"),headerSubtitle:L("span"),header:i,footer:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions,setSendButtonMode:v.setSendButtonMode,peekBanner:w,peekTextNode:x}})(e,t);let r=P("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"}}),n=e?.layout?.header,o=!1!==e?.layout?.showHeader,a=n?xi(e,n,{showClose:t}):pi({config:e,showClose:t}),s=P("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"}});s.style.setProperty("scrollbar-gutter","stable");let{welcome:i,greetingHost:l}=ol(e,s),{host:d,title:c,subtitle:p}=i,u=i.starterSuggestions,h=L("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let m=nl("followUp"),g=ja(e,!1);g&&(h.style.maxWidth=g,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),s.append(d,l,h,m);let f=Ci({config:e}),y=!1!==e?.layout?.showFooter;o||(a.header.style.display="none"),ui(r,a,e),r.append(s);let b=P("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 y||(f.footer.style.display="none"),r.append(f.footer),r.append(b),{container:r,body:s,messagesWrapper:h,starterSuggestions:u,transcriptSuggestions:m,composerOverlay:b,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,welcomeHost:d,welcomeIconHolder:i.iconHolder,greetingHost:l,introKicker:i.kicker,introTitle:c,introSubtitle:p,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:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}})(e,t),s={wrapper:r,panel:n,pillRoot:o},i={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},l={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={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:s,panelElements:a,transcript:i,header:l,composer:d,replaceHeader:e=>(l.element.replaceWith(e.header),l.element=e.header,l.iconHolder=e.iconHolder,l.headerTitle=e.headerTitle,l.headerSubtitle=e.headerSubtitle,l.closeButton=e.closeButton,l.closeButtonWrapper=e.closeButtonWrapper,l.clearChatButton=e.clearChatButton,l.clearChatButtonWrapper=e.clearChatButtonWrapper,e),replaceComposer:e=>{d.footer.replaceWith(e),d.footer=e}}},cl=({config:e,plugins:t,onToggle:r})=>{let n=t.find(e=>e.renderLauncher);if(n?.renderLauncher){let t=n.renderLauncher({config:e,defaultRenderer:()=>al(e,r).element,onToggle:r});if(t)return{instance:null,element:t}}let o=ll(e,r);return{instance:o,element:o.element}},pl=(e,t,r)=>{let n=r;for(let r of t){let t=L("span","persona-tool-char");t.style.setProperty("--char-index",String(n)),t.textContent=" "===r?" ":r,e.appendChild(t),n++}return n},ul=(e,t,r)=>{re(e,t,{stateSet:r,previewKind:"reasoning",iconColor:"currentColor"})},hl=(e,t,r=new Set)=>{t=ne(t,"reasoning");let n=e.reasoning,o=Q("persona-reasoning-bubble",e.id);if(!n)return se(o,e,t,"reasoning");let a=t?.features?.reasoningDisplay??{},s=a.expandable??x.expandable,i=s&&r.has(e.id),l="complete"!==n.status,d=((e,t)=>{let r=e.reasoning?.chunks.join("").trim()??"";return r?r.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join("\n"):""})(e,a.previewMaxLines??x.previewMaxLines),c=X({expandable:s,expanded:i,bubbleType:"reasoning"}),p=L("div","persona-flex persona-flex-col persona-text-left"),u=L("span","persona-text-xs persona-text-persona-primary"),h="row"===oe(t,"reasoning"),m=h&&!l?`Thought for ${ae(n.durationMs??(void 0!==n.completedAt&&void 0!==n.startedAt?n.completedAt-n.startedAt:void 0))}`:"Thinking...",g=t?.reasoning??{},f=String(n.startedAt??Date.now()),y=()=>{let e=L("span","");return e.setAttribute("data-tool-elapsed",f),e.textContent=sr(n),e},b=g.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:m,previewText:d,isActive:l,config:t??{},elapsed:sr(n),createElapsedElement:y});"string"==typeof b&&b.trim()?(u.textContent=b,p.appendChild(u)):b instanceof HTMLElement?p.appendChild(b):(u.textContent=m,p.appendChild(u));let v=L("span","persona-text-xs persona-text-persona-primary");v.textContent=(e=>"complete"===e.status?(e=>{let t=e.completedAt??Date.now(),r=e.startedAt??t,n=(void 0===e.durationMs?Math.max(0,t-r):e.durationMs)/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`})(e):"pending"===e.status?"Waiting":"")(n),h||p.appendChild(v);let w=a.loadingAnimation??x.loadingAnimation,C=g.activeTextTemplate,S=g.completeTextTemplate,k=l?C:S,A=b instanceof HTMLElement,M=(e,t)=>{u.textContent="";let r=lr(e,""),o=0;for(let e of r){let r=e.styles.length>0?(()=>{let t=L("span",e.styles.map(e=>`persona-tool-text-${e}`).join(" "));return u.appendChild(t),t})():u;if(e.isDuration&&l)r.appendChild(y());else{let a=e.isDuration?sr(n):e.text;t?o=pl(r,a,o):r.appendChild(document.createTextNode(a))}}};if(!A&&k)if(v.style.display="none",u.style.display="",l&&"none"!==w){let e=g.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),"pulse"===w?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`),M(k,!1)):(u.classList.add(`persona-tool-loading-${w}`),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===w&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),M(k,!0))}else M(k,!1);else if(!A&&l&&"none"!==w){u.style.display="";let e=g.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),"pulse"===w)u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`);else{u.classList.add(`persona-tool-loading-${w}`),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===w&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let t=u.textContent||m;u.textContent="",pl(u,t,0)}"complete"===n.status&&!h&&(u.style.display="none")}else A||("complete"!==n.status||h?u.style.display="":u.style.display="none");if(a.iconName&&!A){let e=L("span","persona-reasoning-header-icon"),t=K(a.iconName,16,"currentColor",2);t&&(e.appendChild(t),c.appendChild(e))}let I="currentColor",T=Z(c,p,{expandable:s,expanded:i,iconColor:I,metaGap:!1}),E=ee({bubble:o,previewKind:"reasoning",expanded:i,isActive:l,previewText:d,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:d,isActive:l,config:t??{}})});if(!s)return o.append(c,E),se(o,e,t,"reasoning");let P=L("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");P.style.display=i?"":"none";let B=n.chunks.join(""),N=L("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return N.textContent=B||("complete"===n.status?"No additional context was shared.":"Waiting for details…"),P.appendChild(N),te({expanded:i,header:c,toggleIcon:T,content:P,collapsedPreview:E,iconColor:I}),o.append(c,E,P),se(o,e,t,"reasoning")},ml=e=>{if(null==e)return!0;if("string"==typeof e){if(!e.trim())return!0;try{return ml(JSON.parse(e))}catch{return!1}}return"object"==typeof e&&0===Object.keys(e).length},gl=e=>{if("object"==typeof e&&e)return!0;if("string"!=typeof e)return!1;try{let t=JSON.parse(e);return"object"==typeof t&&!!t}catch{return!1}},fl=new WeakMap;let yl=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),bl=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},vl=(e,t)=>{let r=e.toolCall,n=t?.features?.toolCallDisplay,o=n?.collapsedMode??w.collapsedMode,a=!1===r?.success?r.error||"Tool failed":((e,t)=>{let r=e.toolCall;if(!r)return"";let n=(r.chunks??[]).join("").trim();if(n)return n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(-t).join("\n");let o=nr(r.args).trim();return o?o.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join("\n"):""})(e,n?.previewMaxLines??w.previewMaxLines),s=r?"row"===oe(t,"tool")?`${"complete"===r.status?"Used":"Using"} ${r.name?.trim()||"tool"}`:(e=>"complete"===e.status?(e=>{let t=("number"==typeof e.duration?e.duration:"number"==typeof e.durationMs?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`})(e):"Using tool...")(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i="complete"!==r.status,l=t?.toolCall??{},d=s;return"tool-name"===o?d=r.name?.trim()||s:"tool-preview"===o&&a&&(d=a),i&&l.activeTextTemplate?d=ir(r,l.activeTextTemplate,d):!i&&l.completeTextTemplate&&(d=ir(r,l.completeTextTemplate,d)),!1===r.success?d+=" · Failed":r.superseded&&(d+=" · Approved, ran again below"),{summary:d,previewText:a,isActive:i}},wl=(e,t,r,n)=>{re(e,t,{stateSet:r,previewKind:"tool",iconColor:yl(n?.toolCall??{},t.classList.contains("persona-activity-row"))})},xl=(e,t,r=new Set)=>{t=ne(t,"tool");let n=e.toolCall,o=t?.toolCall??{},a=Q("persona-tool-bubble",e.id);if(o.backgroundColor&&(a.style.backgroundColor=o.backgroundColor),o.borderColor&&(a.style.borderColor=o.borderColor),o.borderWidth&&(a.style.borderWidth=o.borderWidth),o.borderRadius&&(a.style.borderRadius=o.borderRadius),a.style.boxShadow=void 0===o.shadow?"var(--persona-tool-bubble-shadow)":""===o.shadow.trim()?"none":o.shadow,!n)return se(a,e,t,"tool");let s=t?.features?.toolCallDisplay??{},i=s.expandable??w.expandable,l=i&&r.has(e.id),{summary:d,previewText:c,isActive:p}=vl(e,t),u=X({expandable:i,expanded:l,bubbleType:"tool"});o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let h=L("div","persona-flex persona-flex-col persona-text-left"),m=L("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let g=String(n.startedAt??Date.now()),f=()=>{let e=L("span","");return e.setAttribute("data-tool-elapsed",g),e.textContent=ar(n),e},y=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:s.collapsedMode??w.collapsedMode,isActive:p,config:t??{},elapsed:ar(n),createElapsedElement:f});"string"==typeof y&&y.trim()?(m.textContent=y,h.appendChild(m)):y instanceof HTMLElement?h.appendChild(y):(m.textContent=d,h.appendChild(m));let b=s.loadingAnimation??w.loadingAnimation,v=o.activeTextTemplate,x=o.completeTextTemplate,C=p?v:x,S=(e,t)=>{m.textContent="";let r=n.name?.trim()||"tool",o=lr(e,r),a=0;for(let e of o){let r=e.styles.length>0?(()=>{let t=L("span",e.styles.map(e=>`persona-tool-text-${e}`).join(" "));return m.appendChild(t),t})():m;if(e.isDuration&&p)r.appendChild(f());else{let o=e.isDuration?ar(n):e.text;t?a=pl(r,o,a):r.appendChild(document.createTextNode(o))}}};if(!(y instanceof HTMLElement))if(p&&"none"!==b){let e=o.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),"pulse"===b)m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${e}ms`),C&&S(C,!1);else if(m.classList.add(`persona-tool-loading-${b}`),m.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===b&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),C)S(C,!0);else{let e=m.textContent||d;m.textContent="",pl(m,e,0)}}else C&&S(C,!1);let k=yl(o,"row"===oe(t,"tool")),A=Z(u,h,{expandable:i,expanded:l,iconColor:k,metaGap:!0}),M=ee({bubble:a,previewKind:"tool",expanded:l,isActive:p,previewText:c,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:c,isActive:p,config:t??{}})});if(!i)return a.append(u,M),se(a,e,t,"tool");let I=L("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(I.style.display=l?"":"none",o.contentBackgroundColor&&(I.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(I.style.color=o.contentTextColor),o.contentPaddingX&&(I.style.paddingLeft=o.contentPaddingX,I.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(I.style.paddingTop=o.contentPaddingY,I.style.paddingBottom=o.contentPaddingY),!0===t.future?.v5Defaults)!function(e,t,r){let n=t.toolCall;if(!n)return;let o=r.toolCall??{},a=(t,r)=>{let n=P("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":t.toLowerCase()},style:{backgroundColor:o.codeBlockBackgroundColor,borderColor:o.codeBlockBorderColor,borderWidth:o.codeBlockBorderColor?"1px":void 0}}),a=P("div",{className:"persona-tool-detail-label",text:t,style:{color:o.labelTextColor}}),s=nr(r),i=P("pre",{className:"persona-tool-detail-value"+(gl(r)?" persona-tool-detail-code":""),text:s,attrs:s.length>420||s.split("\n").length>7?{tabindex:"0","aria-label":`${t} content`}:{},style:{color:o.codeBlockTextColor??o.contentTextColor}}),l=P("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${t.toLowerCase()}`,title:`Copy ${t.toLowerCase()}`}}),d=K("copy",14,"currentColor",1.7);d&&l.appendChild(d),n.append(a,i,l),e.appendChild(n)};ml(n.args)||a("Request",n.args);let s="complete"===n.status&&void 0!==n.result?n.result:n.chunks?.join("");void 0!==s&&("string"!=typeof s||s.trim())&&a("Response",s),!1===n.success&&e.appendChild(P("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}(I,e,t);else{if(n.name){let e=L("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?e.style.color=o.contentTextColor:o.headerTextColor&&(e.style.color=o.headerTextColor),e.textContent=n.name,I.appendChild(e)}if(void 0!==n.args){let e=L("div","persona-space-y-1"),t=L("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(t.style.color=o.labelTextColor),t.textContent="Arguments";let r=L("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");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",bl(r,o),r.textContent=nr(n.args),e.append(t,r),I.appendChild(e)}if(n.chunks&&n.chunks.length){let e=L("div","persona-space-y-1"),t=L("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(t.style.color=o.labelTextColor),t.textContent="Activity";let r=L("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");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",bl(r,o),r.textContent=n.chunks.join(""),e.append(t,r),I.appendChild(e)}if(!1===n.success&&I.appendChild(P("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),"complete"===n.status&&void 0!==n.result){let e=L("div","persona-space-y-1"),t=L("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(t.style.color=o.labelTextColor),t.textContent="Result";let r=L("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");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",bl(r,o),r.textContent=nr(n.result),e.append(t,r),I.appendChild(e)}if("complete"===n.status&&"number"==typeof n.duration){let e=L("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(e.style.color=o.contentTextColor),e.textContent=`Duration: ${n.duration}ms`,I.appendChild(e)}}return te({expanded:l,header:u,toggleIcon:A,content:I,collapsedPreview:M,iconColor:k}),a.append(u,M,I),se(a,e,t,"tool")},{setLoader:Cl,load:Sl,provide:kl,getSync:Al}=N({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),Ml=Cl,Il=Sl,Tl=Al,{setLoader:El,load:Ll}=N({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),Pl=El,Bl=Ll,Nl=new class{constructor(){this.components=new Map,this.#e=new Map}#e;register(e,t,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t),r?this.#e.set(e,r):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)})}},Rl=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:Hl,load:$l,provide:Wl,getSync:Dl}=N({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),Fl=null,Ol=new Set,zl=e=>{if(Fl)return Fl;Fl=e,e.initArtifactsUi({componentRegistry:Nl});for(let t of Rl)Nl.has(t)||Nl.register(t,"PersonaArtifactCard"===t?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=ve();t?e.__provideMarkdownParsers(t):be(()=>{let t=ve();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>W());let r=[...Ol];Ol.clear();for(let e of r)try{e()}catch{}return e},ql=Hl,jl=()=>$l().then(zl),_l=()=>{if(Fl)return Fl;let e=Dl();return e?zl(e):null},Vl=e=>Fl?()=>{}:(Ol.add(e),()=>{Ol.delete(e)});function Ul(e){return!0===e?.features?.artifacts?.enabled}function Gl(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"),!Ul(t))return;let r=t.features?.artifacts?.layout,n=r?.paneBorder?.trim(),o=r?.paneBorderLeft?.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}let Kl=["panel","seamless","detached"];function Jl(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Kl.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Ql(e){return!(!e||!Ul(e))&&"detached"===Jl(e)}function Xl(e,t){if(!Ul(t))return 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"),function(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")}(e),void Gl(e,t);let r=t.features?.artifacts?.layout,n="detached"===Jl(t)?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",r?.splitGap??n),e.style.setProperty("--persona-artifact-pane-width",r?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",r?.paneMaxWidth??"28rem"),r?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",r.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),r?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=r?.paneBackground?.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let a=r?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=[[r?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[r?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[r?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[r?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[t,r]of s){let n=t?.trim();n?e.style.setProperty(r,n):e.style.removeProperty(r)}Gl(e,t)}function Yl(e,t){for(let t of Kl)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"),!Ul(t))return;let r=t.features?.artifacts?.layout,n=Jl(t);e.classList.add(`persona-artifact-appearance-${n}`);let o=r?.paneBorderRadius?.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=r?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=r?.chatShadow?.trim();s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}let Zl=new Set(["__proto__","prototype","constructor"]),ed=new Set(["collapsed","card","panel","inline"]),td=new Set(["markdown","component"]),rd=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,nd=e=>"object"==typeof e&&!!e&&!Array.isArray(e),od=e=>!Zl.has(e),ad=e=>"string"==typeof e&&ed.has(e),sd=e=>Object.keys(e).length>0;function id(e,t,r,n){e.push({path:t,code:r,message:n})}let ld="Ignored an unsupported value.",dd={kind:"mode",message:ld},cd={kind:"string",message:"Expected a CSS length string."},pd={kind:"boolean"},ud={kind:"object",message:"Expected a preference object.",children:{showToolCalls:pd,showReasoning:pd,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:ld},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:ld},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:ld},expandable:pd,grouped:pd}},reasoningDisplay:{kind:"object",children:{expandable:pd,activePreview:pd}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:dd,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:dd,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:td,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:td}}},filePreview:{kind:"object",children:{enabled:pd}},layout:{kind:"object",children:{paneWidth:cd,paneMaxWidth:cd,paneMinWidth:cd,expandedPanelWidth:cd,resizableMinWidth:cd,resizableMaxWidth:cd,expandLauncherPanelWhenOpen:pd,resizable:pd}}}}}};function hd(e,t,r,n){if(void 0!==e)switch(t.kind){case"boolean":return"boolean"==typeof e?e:id(n,r,"invalid_type","Expected a boolean.");case"string":return"string"==typeof e?e:id(n,r,"invalid_type",t.message);case"enum":return"string"==typeof e&&t.values.has(e)?e:id(n,r,"invalid_value",t.message);case"mode":return ad(e)?Xr(e):id(n,r,"invalid_value",t.message);case"modeMap":{if(!nd(e))return id(n,r,"invalid_type","Expected an object.");let o="mediaType"===t.keys?void 0:t.keys,a={};for(let[t,s]of Object.entries(e)){let e=o?t:Yr(t);od(t)&&(o?o.has(t):rd.test(e))?ad(s)?a[e]=Xr(s):id(n,`${r}.${t}`,"invalid_value","Expected collapsed, panel, or inline."):id(n,`${r}.${t}`,o?"unknown_key":"invalid_value",o?"Ignored an unsupported selector.":'Expected a MIME type such as "text/html" or a wildcard such as "image/*".')}return sd(a)?a:void 0}case"object":{if(t.bareMode&&ad(e))return Xr(e);if(!nd(e))return id(n,r,"invalid_type",t.message??"Expected an object.");let o=Object.keys(t.children),a=e=>r?`${r}.${e}`:e;for(let t of Object.keys(e))(!od(t)||!o.includes(t))&&id(n,a(t),"unknown_key","Ignored because this key is not part of the persisted preference schema.");let s={};for(let r of o){let o=t.children[r],i=hd(e[r],o,a(r),n);if(o.deprecated&&void 0!==e[r]&&id(n,a(r),"deprecated_key",o.deprecated),void 0===i)continue;let l=o.alias??r,d=s[l];s[l]=nd(d)&&nd(i)?{...d,...i}:i}return sd(s)?s:void 0}}}function md(e){let t=[];return{preferences:(null===e?void 0:hd(e,ud,"",t))??{},issues:t}}function gd(e){if(Array.isArray(e))return e.map(gd);if(!nd(e))return e;let t={};for(let[r,n]of Object.entries(e))od(r)&&void 0!==n&&(t[r]=gd(n));return t}function fd(e,t){let r=gd(e);for(let[e,n]of Object.entries(t)){if(!od(e)||void 0===n)continue;let t=r[e];r[e]=nd(t)&&nd(n)?fd(t,n):gd(n)}return r}function yd(e,t){if(void 0===t)return void 0===e?void 0:gd(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},n=t.default??r.default,o={...r.byType,...r.byKind,...t.byType,...t.byKind},a=function(e,t){if(void 0===t)return void 0===e?void 0:gd(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},n=t.default??r.default,o={...r.byMediaType,...t.byMediaType},a={...n?{default:n}:{},...sd(o)?{byMediaType:o}:{}};return sd(a)?a:void 0}(r.files,t.files),s={...n?{default:n}:{},...sd(o)?{byKind:o}:{},...void 0===a?{}:{files:a}};return sd(s)?s:void 0}function bd(e={},t){let r=function(e){let t,r={};for(let n of e){let e=md(n).preferences;t=yd(t,e.artifacts?.display),r=fd(r,e)}let n=r;return n.artifacts&&(void 0===t?delete n.artifacts.display:n.artifacts.display=t),n}(t),n={...e};if(void 0!==r.showToolCalls&&(n.showToolCalls=r.showToolCalls),void 0!==r.showReasoning&&(n.showReasoning=r.showReasoning),r.toolCallDisplay&&(n.toolCallDisplay={...e.toolCallDisplay,...r.toolCallDisplay}),r.reasoningDisplay&&(n.reasoningDisplay={...e.reasoningDisplay,...r.reasoningDisplay}),r.artifacts){let t=e.artifacts??{},o={...t};if(void 0!==r.artifacts.display){let e=yd(t.display,r.artifacts.display);void 0!==e&&(o.display=e)}r.artifacts.filePreview&&(o.filePreview={...t.filePreview,enabled:r.artifacts.filePreview.enabled}),r.artifacts.layout&&(o.layout={...t.layout,...r.artifacts.layout}),n.artifacts=o}return n}function vd(e){let t=e.preferences;return t&&sd(t)?{...e,features:bd(e.features??{},[t])}:e}function wd(e,t){let r=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",n=/^([\d.]+)px$/i.exec(r);if(n)return Number(n[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}let{setLoader:xd,load:Cd,provide:Sd,getSync:kd}=N({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),Ad=xd,Md=Cd,Id=kd,Td=new class{#e=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||0===e.length)return t;let r=new Set(e.map(e=>e.id));return[...t.filter(e=>!r.has(e.id)),...e].sort((e,t)=>(t.priority??0)-(e.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}},Ed=e=>"object"==typeof e&&!!e&&!Array.isArray(e),Ld=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),Pd=(e,t,r)=>{if(!Ed(e)||!Ed(t)||Ld.has(r))return t;let n={...e};for(let o of Object.keys(t)){if(void 0===t[o]){delete n[o];continue}let a=r?`${r}.${o}`:o;n[o]=Pd(e[o],t[o],a)}return n};function Bd(e,t){let r=l(k),n=function(e,t,r){let n=t[s];if(n)return n;let o=new Set(c(e,r));for(let e of r){let r=d(t,e);"clear"===r&&o.delete(e),"explicit"===r&&o.add(e)}return[...o]}(e,t,r),o=p(function(e,t,r){let n={...e};for(let e of t){if(r.includes(e))continue;let t=e.split("."),o=n;for(let e of t.slice(0,-1)){let t=o[e];if(!i(t)){o=void 0;break}o[e]={...t},o=o[e]}o&&delete o[t[t.length-1]]}return n}(Pd(e,t,""),r,n),n);return y(E(o),((e,t)=>{let r=t[h];if(r)return{...r};let n=f(e);return m(t,"launcherWidth")&&(n.legacyLauncherWidth=void 0!==t.launcherWidth),m(t,"launcher")&&void 0===t.launcher?(n.launcherWidth=!1,n.sidebarWidth=!1,n.dockWidth=!1,n):(m(t.launcher,"width")&&(n.launcherWidth=void 0!==t.launcher?.width),m(t.launcher,"sidebarWidth")&&(n.sidebarWidth=void 0!==t.launcher?.sidebarWidth),m(t.launcher,"dock")&&void 0===t.launcher?.dock?n.dockWidth=!1:m(t.launcher?.dock,"width")&&(n.dockWidth=void 0!==t.launcher?.dock?.width),n)})(e,t))}let Nd=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=(e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e})(e),r=(e=>{let t=e.trim(),r=t.indexOf("{");if(-1===r)return null;let n=0;for(let e=r;e<t.length;e+=1){let o=t[e];if("{"===o&&(n+=1),"}"===o&&(--n,0===n))return t.slice(r,e+1)}return null})(t);if(!r)return null;let n=JSON.parse(r);if(!n||"object"!=typeof n||!n.action)return null;let{action:o,...a}=n;return{type:String(o),payload:a,raw:n}}catch{return null}},Rd=e=>"string"==typeof e?e:null==e?"":String(e),Hd={message:e=>{if("message"===e.type)return{handled:!0,displayText:Rd(e.payload.text)}},messageAndClick:(e,t)=>{if("message_and_click"!==e.type)return;let r=e.payload,n=Rd(r.element);if(n&&t.document?.querySelector){let e=t.document.querySelector(n);e?setTimeout(()=>{e.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:Rd(r.text)}}},$d=e=>Array.isArray(e)?e.map(e=>String(e)):[],Wd=e=>{let t=new Set($d(e.getSessionMetadata().processedActionMessageIds));return{process:r=>{if(r.streaming||"assistant"!==r.message.role||!r.text||t.has(r.message.id))return null;let n="string"==typeof r.raw&&r.raw||"string"==typeof r.message.rawContent&&r.message.rawContent||"string"==typeof r.text&&r.text||null;!n&&"string"==typeof r.text&&r.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 o=n?e.parsers.reduce((e,t)=>e||t?.({text:n,message:r.message})||null,null):null;if(!o)return null;t.add(r.message.id),(()=>{let r=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:r}))})();let a={action:o,message:r.message};e.emit("action:detected",a);for(let t of e.handlers)if(t)try{let n=t(o,{message:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{e.emit("action:resubmit",a)}});if(!n)continue;if(n.handled){let e=!1!==n.persistMessage;return{text:void 0===n.displayText?"":n.displayText,persist:e,resubmit:n.resubmit}}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",e)}return{text:"",persist:!0}},syncFromMetadata:()=>{t=new Set($d(e.getSessionMetadata().processedActionMessageIds))}}},Dd=e=>e.map(e=>({...e,streaming:!1})),Fd=e=>e.map(e=>({...e,status:"complete"})),Od=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?(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}})(r.getItem(e)):null},save:r=>{let n=t();if(n)try{let t={...r,messages:r.messages?Dd(r.messages):void 0,artifacts:r.artifacts?Fd(r.artifacts):void 0};n.setItem(e,JSON.stringify(t))}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",e)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}},zd=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let r=await t.digest("SHA-256",(new TextEncoder).encode(e));return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{}return(e=>{let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")})(e)},qd=(e,t,r)=>{let n="",o="",a="",s=!1,i=!1,l=0,d=null,c=null,p=new Set,u=()=>{if(r||s)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return s=!0,null}},h=()=>{let e=u();if(!e)return d;try{return e.getItem(n)}catch{return s=!0,d}},m=(e,t)=>{if(i||e===d)return;let r=d;d=e,l+=1;let n={previousToken:r,token:e,source:t,revision:l};for(let e of p)e(n)},g=e=>{i||(null===e.key||e.key===n)&&m(null===e.key?null:e.newValue??null,"external")},f=(async()=>{let s=await(async(e,t)=>{let r=await zd(e);return{storageKey:`${t}visitor:${r}`,leaseKey:`${t}visitor-init-lock:${r}`,lockName:`persona-visitor-init:${await zd(`${e}\0${t}`)}`}})(e,t);n=s.storageKey,o=s.leaseKey,a=s.lockName,d=h(),!r&&typeof window<"u"&&window.addEventListener("storage",g)})(),y=e=>new Promise(t=>setTimeout(t,e)),b=()=>{let e=u();if(!e)return null;try{let t=e.getItem(o);if(!t)return null;let r=JSON.parse(t);return"number"==typeof r?.expiresAt&&"string"==typeof r?.ownerNonce?r:null}catch{return null}},v=e=>{let t=u();if(t)try{b()?.ownerNonce===e&&t.removeItem(o)}catch{}},w=new Set,x=e=>i?Promise.reject(Error("Visitor store destroyed before its first init could start")):e(),C=e=>new Promise(t=>{let r=setTimeout(n,e);function n(){clearTimeout(r),w.delete(n),window.removeEventListener("storage",a),t()}function a(e){(null===e.key||e.key===o)&&n()}w.add(n),window.addEventListener("storage",a)});return{ready:f,get:async()=>(await f,m(h(),"external"),d),async set(e){await f;let t=u();if(t)try{t.setItem(n,e)}catch{s=!0}m(e,"local")},async clear(){await f;let e=u();if(e)try{e.removeItem(n)}catch{s=!0}m(null,"local")},revision:()=>l,subscribe:e=>(p.add(e),()=>{p.delete(e)}),async withFirstInitLock(e){await f;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):u()?(async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,r=Date.now()+15e3;for(;!i&&Date.now()<r;){let r=u();if(!r)break;let n=Date.now(),a=b();if(a&&a.expiresAt>n&&a.ownerNonce!==t)await C(Math.min(a.expiresAt-n,500));else{try{r.setItem(o,JSON.stringify({ownerNonce:t,expiresAt:n+1e4}))}catch{s=!0;break}if(await y(20+40*Math.random()),b()?.ownerNonce!==t)await C(500);else{c=t;try{return await x(e)}finally{c=null,v(t)}}}}return x(e)})(e):x(e)},matches:(n,o,a)=>n===e&&o===t&&a===r,destroy(){i=!0,p.clear(),typeof window<"u"&&window.removeEventListener("storage",g),c&&v(c);for(let e of[...w])e()}}},{setLoader:jd,load:_d}=N({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),Vd=jd,Ud=_d,{setLoader:Gd,load:Kd,provide:Jd,getSync:Qd}=N({fallbackImport:()=>import("./history-shell")}),Xd=Gd,Yd=Kd,Zd=Qd;function ec(){return null}function tc(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=t)return e;try{let t=function(e,t){if(!function(e){if(!e||"object"!=typeof e||!("component"in e))return!1;let t=e.component;return"string"==typeof t&&t.length>0}(e))return null;let r=e.props&&"object"==typeof e.props&&null!==e.props?e.props:{};return{component:e.component,props:r,raw:t}}((0,yt.parse)(r,yt.STR|yt.OBJ),r);t&&(e=t)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function rc(e,t){let{config:r,message:n,onPropsUpdate:o}=t,a=Nl.get(e.component);if(!a){if(Rl.includes(e.component)){jl().catch(()=>{});let e=L("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 s={message:n,config:r,updateProps:e=>{o&&o(e)}};try{return a(e.props,s)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function nc(e){if("string"==typeof e.rawContent&&e.rawContent.length>0)return e.rawContent;if("string"==typeof e.content){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function oc(e){let t=nc(e);if(!t)return!1;try{let e=JSON.parse(t);return"object"==typeof e&&!!e&&"component"in e&&"string"==typeof e.component}catch{return!1}}function ac(e){let t=nc(e);if(!t)return null;try{let e=JSON.parse(t);if("object"==typeof e&&e&&"component"in e&&"string"==typeof e.component){let r=e;return{component:r.component,props:r.props&&"object"==typeof r.props&&null!==r.props?r.props:{},raw:t}}}catch{}return null}let sc=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ic(e){let{onSubmit:t,onDismiss:r,title:n="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:l=!0,ratingLabels:d=sc}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let p=null,u=document.createElement("div");u.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let m=document.createElement("h3");m.className="persona-feedback-title",m.textContent=n,h.appendChild(m);let g=document.createElement("p");g.className="persona-feedback-subtitle",g.textContent=o,h.appendChild(g),u.appendChild(h);let f=document.createElement("div");f.className="persona-feedback-rating persona-feedback-rating-csat",f.setAttribute("role","radiogroup"),f.setAttribute("aria-label","Satisfaction rating from 1 to 5");let y=[];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":""}: ${d[e-1]}`),t.title=d[e-1],t.dataset.rating=String(e),t.innerHTML='\n <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <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>\n </svg>\n ',t.addEventListener("click",()=>{p=e,y.forEach((t,r)=>{let n=r<e;t.classList.toggle("selected",n),t.setAttribute("aria-checked",r===e-1?"true":"false")})}),y.push(t),f.appendChild(t)}u.appendChild(f);let b=null;if(l){let e=document.createElement("div");e.className="persona-feedback-comment-container",b=document.createElement("textarea"),b.className="persona-feedback-comment",b.placeholder=a,b.rows=3,b.setAttribute("aria-label","Additional comments"),e.appendChild(b),u.appendChild(e)}let v=document.createElement("div");v.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{r?.(),c.remove()});let x=document.createElement("button");return x.type="button",x.className="persona-feedback-btn persona-feedback-btn-submit",x.textContent=s,x.addEventListener("click",async()=>{if(null===p)f.classList.add("persona-feedback-shake"),setTimeout(()=>f.classList.remove("persona-feedback-shake"),500);else{x.disabled=!0,x.textContent="Submitting...";try{let e=b?.value.trim()||void 0;await t(p,e),c.remove()}catch(e){x.disabled=!1,x.textContent=s,console.error("[CSAT Feedback] Failed to submit:",e)}}}),v.appendChild(w),v.appendChild(x),u.appendChild(v),c.appendChild(u),c}function lc(e){let{onSubmit:t,onDismiss:r,title:n="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:l=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let u=null,h=document.createElement("div");h.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let g=document.createElement("h3");g.className="persona-feedback-title",g.textContent=n,m.appendChild(g);let f=document.createElement("p");f.className="persona-feedback-subtitle",f.textContent=o,m.appendChild(f),h.appendChild(m);let y=document.createElement("div");y.className="persona-feedback-rating persona-feedback-rating-nps",y.setAttribute("role","radiogroup"),y.setAttribute("aria-label","Likelihood rating from 0 to 10");let b=document.createElement("div");b.className="persona-feedback-labels";let v=document.createElement("span");v.className="persona-feedback-label-low",v.textContent=d;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=c,b.appendChild(v),b.appendChild(w);let x=document.createElement("div");x.className="persona-feedback-numbers";let C=[];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",()=>{u=e,C.forEach((t,r)=>{t.classList.toggle("selected",r===e),t.setAttribute("aria-checked",r===e?"true":"false")})}),C.push(t),x.appendChild(t)}y.appendChild(b),y.appendChild(x),h.appendChild(y);let S=null;if(l){let e=document.createElement("div");e.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=a,S.rows=3,S.setAttribute("aria-label","Additional comments"),e.appendChild(S),h.appendChild(e)}let k=document.createElement("div");k.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=i,A.addEventListener("click",()=>{r?.(),p.remove()});let M=document.createElement("button");return M.type="button",M.className="persona-feedback-btn persona-feedback-btn-submit",M.textContent=s,M.addEventListener("click",async()=>{if(null===u)x.classList.add("persona-feedback-shake"),setTimeout(()=>x.classList.remove("persona-feedback-shake"),500);else{M.disabled=!0,M.textContent="Submitting...";try{let e=S?.value.trim()||void 0;await t(u,e),p.remove()}catch(e){M.disabled=!1,M.textContent=s,console.error("[NPS Feedback] Failed to submit:",e)}}}),k.appendChild(A),k.appendChild(M),h.appendChild(k),p.appendChild(h),p}let dc="persona-chat-history",cc="data-persona-composer-reason",pc="data-persona-composer-notice",uc={"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 hc(e){if(!e)return[];let t=[],r=Array.from(e.items??[]);for(let e of r){if("file"!==e.kind||!e.type.startsWith("image/"))continue;let r=e.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let n=uc[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${n}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let r of Array.from(e.files??[]))r.type.startsWith("image/")&&t.push(r);return t}function mc(e){if(!e)return!1;let t=e.types;return!!t&&("function"==typeof t.contains?t.contains("Files"):Array.from(t).includes("Files"))}let gc=e=>e&&"object"==typeof e?{...e}:{},fc=e=>e.map(e=>({...e,streaming:!1})),yc=(e,t,r)=>{let n=e?.markdown?xe(e.markdown):null,o=Pe(e?.sanitize);e?.postprocessMessage&&o&&void 0===e?.sanitize&&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,s=a=>{let s=a.text??"",i=a.message.rawContent??null;if(t){let e=t.process({text:s,raw:i??s,message:a.message,streaming:a.streaming});null!==e&&(s=e.text,e.persist||(a.message.__skipPersist=!0),e.resubmit&&!a.streaming&&r&&r())}let l,d=null!==ve();if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:s,raw:i??a.text??""});l=o?o(t):t}else if(n){let e=a.streaming?(e=>{if(!e||!e.includes("|"))return e;let t=e.split("\n"),r=!1;for(let e=0;e<t.length-1;e++){let n=t[e],o=t[e+1];if(!Ne(n)||Be.test(n)||!Be.test(o))continue;let a=Re(n).length;if(a<1)continue;let s=$e(a);t[e+1]!==s&&(t[e+1]=s,r=!0);let i=e+2;for(;i<t.length;i++){let e=t[i];if(""===e.trim()||!Ne(e))break;let n=He(We(Re(e),a));t[i]!==n&&(t[i]=n,r=!0)}e=i-1}return r?t.join("\n"):e})(s):s,t=n(e);l=o&&d?o(t):t}else l=ke(s);return l};return e=>{try{return s(e)}catch(t){return a||(a=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",t)),ke(e.text??"")}}};function bc(e){let t=L("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),void 0!==e?.backdropBlur&&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 r=K(e?.iconName??"upload",e?.iconSize??"48px",e?.iconColor??"rgba(59, 130, 246, 0.6)",e?.iconStrokeWidth??.5);if(r&&t.appendChild(r),e?.label){let r=L("span","persona-drop-overlay-label");r.textContent=e.label,t.appendChild(r)}return t}let vc=(e,t)=>{let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];r[e]=t?{...t,...n}:n}return r},wc=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:vc(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),xc=(e,t,o)=>{if(null==e)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 s=E(t),i=new Set,l=new Set,d=function(e){let t=new Set,r=new Set,n=new Set,o=new Map,a=e=>{clearTimeout(o.get(e)),o.delete(e)};return{observe(a,s,i,l={}){let d="tool"===s?a.toolCall:a.reasoning;if(d&&!r.has(a.id)&&(!t.has(a.id)&&"complete"!==d.status&&d.chunks?.some(Boolean)&&(t.add(a.id),!1!==l.autoExpand&&i.add(a.id)),t.has(a.id)&&"complete"===d.status&&!n.has(a.id))){if(n.add(a.id),!1===l.autoCollapseDelay)return;o.set(a.id,setTimeout(()=>{o.delete(a.id),i.delete(a.id),e(a.id,s)},l.autoCollapseDelay??1e3))}},manual(e){r.add(e),a(e)},prune(e){for(let o of new Set([...t,...r,...n]))e.has(o)||(a(o),t.delete(o),r.delete(o),n.delete(o))},clear(){for(let e of o.keys())a(e);t.clear(),r.clear(),n.clear()}}}((e,t)=>{Ha.delete(e);let r=Array.from(lt.querySelectorAll("[data-message-id]")).find(t=>t.dataset.messageId===e);r&&("tool"===t?wl(e,r,i,s):ul(e,r,l))}),c=new Map,p=()=>{qn({delayMs:s.tooltip?.delayMs??200,skipDelayMs:s.tooltip?.skipDelayMs??300})};p();let u=s.features;s=vd(s);let h=Td.getForInstance(s.plugins),m=es(e),g=[],y=!1,b=(e=>{let t=new Map,r=!1,n=()=>{if(r||!1===e()?.persistState)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return r=!0,null}};return o=>{let a=t=>((e,t,r)=>`${(e=>{let t=e?.persistState;return("object"==typeof t?t?.keyPrefix:void 0)??"persona-"})(e)}plugin:${t}:${r}`)(e(),o,t);return{get:e=>{let o=a(e),s=n();if(s)try{return s.getItem(o)}catch{r=!0}return t.get(o)??null},set:(e,o)=>{let s=a(e),i=n();if(i)try{return void i.setItem(s,o)}catch{r=!0}t.set(s,o)},remove:e=>{let o=a(e);t.delete(o);let s=n();if(s)try{s.removeItem(o)}catch{r=!0}}}}})(()=>s),v=null,w=null,x=null,C=!1,S=null,k=e=>{v=e,e.initApprovalUi({webMcpToolTitle:Ye});let t=e.createBuiltInApprovalPlugin(c);w=t.plugin,x=t.teardown},A=()=>{if(v)return v;let e=Tl();return e?(k(e),e):(Il().then(e=>{C||v||(k(e),S?.())}).catch(()=>{}),null)},M=!1,I=!1,T=null,P=(e,t,r,n)=>{if(!e.querySelector("[data-tv-form]"))return;let o=Id();o?o.enhanceWithForms(e,t,r,n):Md().then(()=>{M||I||!T||(I=!0,T())}).catch(()=>{})};s.components&&Nl.registerAll(s.components);let B,N,R=(()=>{let e=new Map,t=(t,r)=>{e.get(t)?.delete(r)};return{on:(r,n)=>(e.has(r)||e.set(r,new Set),e.get(r).add(n),()=>t(r,n)),off:t,emit:(t,r)=>{e.get(t)?.forEach(e=>{try{e(r)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",e)}})}}})(),H=!1===s.persistState?null:s.storageAdapter??Od(),$=!!s.clientToken&&"function"!=typeof s.reconnectStream,W={},D=null,F=new Promise(e=>{B=e}),O=()=>{},z=new Promise(e=>{O=e}),q=!1,j=e=>{if(s.onStateLoaded)try{let t=s.onStateLoaded(e);if(t&&"object"==typeof t&&"state"in t){let{state:e,open:r}=t;return r&&(q=!0),e}return t}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}return e};if(H?.load)try{let e=H.load();if(e&&"function"==typeof e.then)D=e.then(e=>j(e??{messages:[],metadata:{}}));else{let t=j(e??{messages:[],metadata:{}});t.metadata&&(W=gc(t.metadata)),t.messages?.length&&(s={...s,initialMessages:t.messages}),t.artifacts?.length&&(s={...s,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),N=t.draft}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",e)}else if(s.onStateLoaded)try{let e=j({messages:[],metadata:{}});e.messages?.length&&(s={...s,initialMessages:e.messages})}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}D||B();let _=()=>W,U=e=>{W=e({...W})??{},si()},G=s.actionParsers&&s.actionParsers.length?s.actionParsers:[Nd],J=s.actionHandlers&&s.actionHandlers.length?s.actionHandlers:[Hd.message,Hd.messageAndClick],Q=Wd({parsers:G,handlers:J,getSessionMetadata:_,updateSessionMetadata:U,emit:R.emit,documentRef:typeof document<"u"?document:null});Q.syncFromMetadata();let X=s.launcher?.enabled??!0,Y=s.launcher?.autoExpand??!1,Z=s.autoFocusInput??!1,ee=Y,te=X,re=s.layout?.header?.layout,ne=!1,se=()=>Ks(s),pe=()=>X||se(),ue=!se()&&(!X||Y),he=!1,me=null,ge=()=>{he=!0,me&&clearTimeout(me),me=setTimeout(()=>{he&&=(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),!1)},1e4)},fe=yc(s,Q,ge),we=s.features?.showReasoning??!0,xe=s.features?.showToolCalls??!0,Ce=s.features?.showEventStreamToggle??!1,Se=s.features?.scrollToBottom??{},Ae=s.features?.scrollBehavior??{},Me=()=>("object"==typeof s.persistState?s.persistState?.keyPrefix:void 0)??"persona-",Ie=`${Me()}event-stream`,Te=null,Ee=s.features?.eventStream?.maxEvents??2e3,Le=null,Pe=null,Be=null,Ne=!1,Re=null,He=!1,$e=null,We=0,De=(e,t)=>{Le?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},Fe=(e,t)=>{Pe?.processEvent(e,t),Le?De(e,t):Be&&(Be.length>=Ee&&Be.shift(),Be.push({type:e,payload:t}))},Oe=()=>{!Le&&Ce&&(Be??=[],Bl().then(e=>{if(Ne||Le||!Ce)return;Te=new e.EventStreamStore(Ie),Le=new e.EventStreamBuffer(Ee,Te),Pe??=new e.ThroughputTracker,Te.open().then(()=>Le?.restore()).catch(e=>{s.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",e)});let t=Be??[];Be=null;for(let e of t)Pe?.processEvent(e.type,e.payload),De(e.type,e.payload)}).catch(()=>{}))};Ce&&Oe();let qe=!1,je=null,_e=()=>{},Ve=()=>{},Ue=()=>{},Ke=()=>{},Je=()=>{},Qe=e=>{R.emit("message:copy",e),va?.isClientTokenMode()&&va.submitMessageFeedback(e.id,"copy").catch(e=>{s.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",e)}),s.messageActions?.onCopy?.(e)},Xe=e=>{R.emit("message:feedback",e),va?.isClientTokenMode()&&va.submitMessageFeedback(e.messageId,e.type).catch(e=>{s.debug&&console.error("[AgentWidget] Failed to submit feedback:",e)}),s.messageActions?.onFeedback?.(e)};s.statusIndicator;let Ze=(e,t=s.statusIndicator??{})=>"idle"===e?t.idleText??Tr.idle:"connecting"===e?t.connectingText??Tr.connecting:"connected"===e?t.connectedText??Tr.connected:"error"===e?t.errorText??Tr.error:"paused"===e?t.pausedText??Tr.paused:"resuming"===e?t.resumingText??Tr.resuming:Tr[e];function et(e,t,r,n){if(!se()&&("transient"===r.mode||e.classList.contains("persona-mb-2"))&&(de(e,mt,r),le(e,r,n)),!e.hasAttribute(cc)&&!e.hasAttribute(pc))if("idle"===n&&r.idleLink){e.textContent="";let n=document.createElement("a");n.href=r.idleLink,n.target="_blank",n.rel="noopener noreferrer",n.textContent=t,n.style.color="inherit",n.style.textDecoration="none",e.appendChild(n)}else e.textContent=t}let tt=dl({config:s,showClose:pe()}),{wrapper:rt,panel:nt,pillRoot:ot}=tt.shell,at=tt.panelElements,{container:st,body:it,messagesWrapper:lt,starterSuggestions:dt,transcriptSuggestions:ct,suggestions:pt,textarea:ut,sendButton:ht,composerForm:mt,statusText:gt,welcomeHost:ft,welcomeIconHolder:yt,greetingHost:bt,introKicker:vt,introTitle:wt,introSubtitle:xt,closeButton:Ct,iconHolder:St,headerTitle:kt,headerSubtitle:At,header:Mt,footer:Tt,actionsRow:Lt}=at,Pt=at.leftActions,Bt=at.rightActions,Nt=at.sendButtonWrapper,Rt=at.setSendButtonMode,Ht=at.micButton,$t=at.micButtonWrapper,Wt=at.attachmentButton,Dt=at.attachmentButtonWrapper,Ft=at.attachmentInput,qt=at.attachmentPreviewsContainer;st.classList.add("persona-relative"),it.classList.add("persona-relative");let jt=()=>Se.label??"",_t=()=>Ae.mode??"anchor-top",Ut=()=>"follow"===_t()||"anchor-top"===_t()&&fs,Kt=()=>Ae.anchorTopOffset??16,Qt=()=>!0===Ae.pauseOnInteraction,Xt=()=>!1!==Ae.showActivityWhilePinned,Yt=()=>!0===Ae.announce,Zt=()=>Ae.scrollbar??"on-scroll",er=L("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");er.type="button",er.style.display="none",er.setAttribute("data-persona-scroll-to-bottom","true");let tr=L("span","persona-flex persona-items-center"),rr=L("span",""),nr=L("span","");nr.setAttribute("data-persona-scroll-to-bottom-count",""),nr.style.display="none",er.append(tr,rr,nr),st.appendChild(er);let ar=L("div","persona-stream-anchor-spacer");ar.setAttribute("aria-hidden","true"),ar.setAttribute("data-persona-anchor-spacer",""),ar.style.flexShrink="0",ar.style.pointerEvents="none",ar.style.height="0px",ar.style.display="none",it.appendChild(ar);let sr=L("div","persona-sr-only");sr.setAttribute("aria-live","polite"),sr.setAttribute("aria-atomic","true"),sr.setAttribute("role","status"),sr.setAttribute("data-persona-live-region",""),Object.assign(sr.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"}),st.appendChild(sr);let ir=null,lr=null,dr=e=>{Yt()&&e&&(lr=e,null===ir&&(ir=setTimeout(()=>{ir=null,lr&&Yt()&&(sr.textContent=lr),lr=null},400)))},cr=()=>{let t=e.ownerDocument.defaultView??window;return(s.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(s.launcher?.mobileBreakpoint??640)&&(X||Gs(s))||!0===s.launcher?.fullHeight&&!s.launcher.sidebarMode&&!Gs(s)},pr=()=>Qi(s,cr()),ur="empty",hr=0,mr=()=>hr||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,gr=()=>{let e="none"===Tt.style.display?0:Tt.offsetHeight;er.style.bottom=`${e+mr()+12}px`};gr();let fr=()=>{an||(Tt.style.marginBottom=hr>0?`${hr}px`:"")},yr=()=>{let t=_a(s,se()),r=pr();e.setAttribute("data-persona-welcome-fullscreen",String(cr())),e.setAttribute("data-persona-welcome-layout",r.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",s.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom");let n="none"===Tt.style.display?0:Tt.offsetHeight,o="center"===r.anchor&&"empty"===ur?Va(r.anchorComposerTop)??Va("44%"):null,a=null!==o&&"centered"===r.layout&&void 0===s.welcome?.anchor&&void 0===s.welcome?.anchorComposerTop,i=a?getComputedStyle(it):null,l=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,d=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,c=Math.max(0,(parseFloat(i?.paddingBottom??"")||0)-("overlay"===t?l+d:0)),p=a?it.getBoundingClientRect().top-st.getBoundingClientRect().top:0,u=!a||ft.hidden?0:(ft.querySelector("[data-persona-welcome-plugin]")??ft).offsetHeight,h=null===o||se()?0:a?Math.max(0,Math.round((st.clientHeight-p-u-c-n)/2)):(e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight))({columnHeight:st.clientHeight,footerHeight:n,fraction:o});e.style.setProperty("--persona-composer-overlay-height",`${n}px`),e.style.setProperty("--persona-composer-lift",`${"overlay"===t?h:0}px`),hr="block"===t?h:0,fr(),gr()},br=()=>{let e=!!jt();er.setAttribute("aria-label",jt()||"Jump to latest"),er.title=jt(),er.setAttribute("data-persona-scroll-to-bottom-has-label",e?"true":"false"),tr.innerHTML="";let t=K(Se.iconName??"arrow-down","14px","currentColor",2);t?(tr.appendChild(t),tr.style.display=""):tr.style.display="none",rr.textContent=jt(),rr.style.display=e?"":"none"};br();let vr=null,wr=null,Cr=Rn();Cr.subscribe(e=>{try{st.dispatchEvent(new CustomEvent("persona:composer:state",{detail:e,bubbles:!0,composed:!0}))}catch{}});let kr=()=>{Cr.setText(ut?.value??"")},Ar=()=>{Cr.setMentionRefs(wr?.getMentionRefs()??[])},Mr=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}),Ir=e=>{let t=Object.freeze(e.map(Mr));Cr.setAttachments(t);try{s.attachments?.onChange?.(t)}catch(e){console.error("[AgentWidget] attachments.onChange failed:",e)}Fl()};Cr.setSelectedModelId(s.composer?.selectedModelId);let Lr=()=>s.composer?.modes??[],Pr=()=>function(e,t){return e?.length?e.filter(e=>!Oo(e.groupId,t)&&!function(e,t){return!!e&&"hidden"===t?.find(t=>t.id===e)?.chipVisibility}(e.groupId,t)):[]}(Lr(),s.composer?.modeGroups);{let e=zo(s.composer?.defaultActiveModeIds??[],Lr());e.length&&Cr.setActiveModeIds(e)}function Br(e){if(Cr.getState().selectedModelId!==e){Cr.setSelectedModelId(e),Hr?.repaint();try{s.composer?.onModelChange?.(e)}catch(e){console.error("[AgentWidget] composer.onModelChange failed:",e)}}}function Nr(e){Cr.setActiveModeIds(e),Dr?.render(e,Pr()),Fr.forEach(e=>e.repaint()),bn?.resolve(),bd(),Mn()}function Rr(e){Nr(function(e,t,r,n){let o=r.find(e=>e.id===t);if(!o)return[...e];let a=e.includes(t),s=new Set(e);if(a)s.delete(t);else{if("single"===((e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null)(o,n)){let e=r.filter(e=>e.groupId===o.groupId).map(e=>e.id);s=new Set([...s].filter(t=>!e.includes(t)))}s.add(t)}return r.filter(e=>s.has(e.id)).map(e=>e.id)}(Cr.getState().activeModeIds,e,Lr(),s.composer?.modeGroups))}let Hr=null,Wr=null,Dr=null,Fr=new Map,Or=null;function zr(e){Cr.setQuote(e),Or?.render(Cr.getState().quote),Mn(),hi()}let _r=!1;function Vr(){let e=s.composer?.streamingSubmitBehavior??"block";return"interrupt"===e?s.clientToken?"interrupt":(!_r&&!0===s.debug&&(_r=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block"):e}let Ur=null;function Gr(e){Cr.setPendingSubmission(e),Ur?.render(Cr.getState().pendingSubmission),Mn()}let Kr=()=>{let e=[],t=Cr.getState().activeModeIds,r=new Set;if(Lr().forEach((n,o)=>{if(Oo(n.groupId,s.composer?.modeGroups)){let t=n.groupId;if(r.has(t))return;r.add(t);let a=(e=>{let t=Fr.get(e);if(t)return t;let r=qo({groupId:e,getGroup:()=>s.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>Lr().filter(t=>t.groupId===e),getActiveIds:()=>Cr.getState().activeModeIds,onSelect:e=>Rr(e)});return Fr.set(e,r),r})(t);a.action.order=Do(o),a.action.label=s.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(a.action)}else e.push({id:Wo(n.id),kind:"button",placement:"start",order:Do(o),presentation:n.presentation??"auto",label:n.label,shortLabel:n.shortLabel,iconName:n.iconName,pressed:t.includes(n.id),onSelect:()=>Rr(n.id)})}),s.composer?.models?.length&&!h.some(e=>e.renderComposer)){let t=s.composer?.modelPicker?.presentation??"native";(!Hr||Wr!==t)&&(Wr=t,Hr=Bo({getModels:()=>s.composer?.models??[],getSelectedModelId:()=>Cr.getState().selectedModelId,onSelect:e=>Br(e),presentation:t,getSuffix:()=>s.composer?.modelPicker?.suffix})),e.push(Hr.action)}return e},Jr=null,Qr=h.find(e=>e.renderHeader);if(Qr?.renderHeader){let e=Qr.renderHeader({config:s,defaultRenderer:()=>{let e=pi({config:s,showClose:pe()});return ui(st,e,s),e.header},onClose:()=>Rl(!1,"user")});e&&Mt&&(Mt.replaceWith(e),Mt=e,tt.header.element=e)}let Xr=()=>{Re&&(it.style.display="none",Tt.parentNode?.insertBefore(Re.element,Tt),Re.update())},Yr=()=>{if(!Le)return void Oe();if(He=!0,Re?Xr():Bl().then(e=>{!Re&&He&&Le&&(Re=e.createEventStreamView({buffer:Le,getFullHistory:()=>Le.getAllFromStore(),onClose:()=>Zr(),config:s,plugins:h,getThroughput:()=>Pe?.getMetric()??{status:"idle"},renderIconByName:K}),Xr())}).catch(()=>{Zr()}),tn){tn.style.boxShadow=`inset 0 0 0 1.5px ${li.actionIconColor}`;let e=s.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&tn.classList.add(e))}let e=()=>{if(!He)return;let t=Date.now();t-We>=200&&(Re?.update(),We=t),$e=requestAnimationFrame(e)};We=0,$e=requestAnimationFrame(e),Ei(),R.emit("eventStream:opened",{timestamp:Date.now()})},Zr=()=>{if(He){if(He=!1,Re&&Re.element.remove(),it.style.display="",tn){tn.style.boxShadow="";let e=s.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&tn.classList.remove(e))}null!==$e&&(cancelAnimationFrame($e),$e=null),Ei(),R.emit("eventStream:closed",{timestamp:Date.now()})}},tn=null;if(Ce){let e=s.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:"");tn=L("button",t),tn.style.width="28px",tn.style.height="28px",tn.style.color=li.actionIconColor,tn.type="button",tn.setAttribute("aria-label","Event Stream"),tn.title="Event Stream";let o=n(r.Activity,"18px","currentColor",1.5);o&&tn.appendChild(o);let a=at.clearChatButtonWrapper,i=at.closeButtonWrapper,l=a||i;l&&l.parentNode===Mt?Mt.insertBefore(tn,l):Mt.appendChild(tn),tn.addEventListener("click",()=>{He?Zr():Yr()})}let rn=e=>{let t=s.attachments;if(!t?.enabled)return;let r=e.querySelector("[data-persona-composer-attachment-previews]")??e.querySelector(".persona-attachment-previews");if(!r){r=L("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let t=e.querySelector("[data-persona-composer-form]");t?.parentNode?t.parentNode.insertBefore(r,t):e.insertBefore(r,e.firstChild)}if(!(e.querySelector("[data-persona-composer-attachment-input]")??e.querySelector('input[type="file"]'))){let r=L("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Sr).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label",t.buttonTooltipText??"Attach files"),e.appendChild(r)}},an=!1,sn=e=>{let t=h.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let r=s.composer,n=!!y&&va.isStreaming();return t.renderComposer({config:s,defaultRenderer:e,requestRender:()=>lu(),storage:b(t.id),onSubmit:e=>{va&&!va.isStreaming()&&Xc(e.trim(),{consumeDraft:!1})},streaming:n,disabled:n,openAttachmentPicker:()=>{$l()||Ft?.click()},models:r?.models,selectedModelId:Cr.getState().selectedModelId??r?.selectedModelId,onModelChange:e=>Br(e),onVoiceToggle:!0===s.voiceRecognition?.enabled?()=>{Jr?.()}:void 0})},ln=sn(()=>Ci({config:s}).footer);ln&&(tt.replaceComposer(ln),Tt=tt.composer.footer,an=!0);let dn=null;function cn(){let e=ut;if(!e)return;let t=s.composer?.inputAttributes,r=t?.ariaLabel||e instanceof HTMLTextAreaElement?null:e.getAttribute("aria-label");to(e,t),r&&e.setAttribute("aria-label",r),eo(e,{submitKey:s.composer?.submitKey,insertNewlineOnTouchEnter:s.composer?.insertNewlineOnTouchEnter,coarsePointer:Xn(e)}),Qn(e,Jn(s.composer?.maxLines,se()?5:3))}let pn=e=>{dn=Wn(e,{debug:!0===s.debug}),dn&&(e=>{mt=e.form,ut=e.input,Nt=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(ht=e.sendButton),e.micButton&&(Ht=e.micButton,$t=e.micButton.parentElement),e.found.status&&(gt=e.found.status),e.found.suggestions&&(pt=e.found.suggestions),e.attachmentButton&&(Wt=e.attachmentButton,Dt=e.attachmentButton.parentElement),Ft=e.attachmentInput??null,qt=e.attachmentPreviews??null,e.found.actionsRow&&(Lt=e.found.actionsRow),Pt=e.found.actionsStart,Bt=e.found.actionsEnd})(dn),cn()};rn(Tt),pn(Tt),kr();let un=ja(s,se());un&&(lt.style.maxWidth=un,lt.style.marginLeft="auto",lt.style.marginRight="auto",lt.style.width="100%",bt.style.maxWidth=un,bt.style.marginLeft="auto",bt.style.marginRight="auto",bt.style.width="100%",dt.style.maxWidth=un,ct.style.maxWidth=un,ct.style.marginLeft="auto",ct.style.marginRight="auto",ct.style.width="100%");let hn=()=>{let e=ja(s,se());if(e&&!se())for(let t of[mt,pt,qt,gt])t&&(t.style.maxWidth=e,t.style.marginLeft="auto",t.style.marginRight="auto",t.style.width="100%")};hn();let fn=()=>{s.attachments?.enabled&&Ft&&qt&&(vr?vr.remountPreviews(qt):(vr=Bn.fromConfig(s.attachments,Ir),vr.setPreviewsContainer(qt)),dn?.addListener(Ft,"change",e=>{let t=e.target;vr?.handleFileSelect(t.files),t.value=""}),st.querySelector(".persona-attachment-drop-overlay")||st.appendChild(bc(s.attachments.dropOverlay)))};fn();let yn=()=>{if(!s.contextMentions?.enabled||!ut)return;let e=jr();if(!e){let e=ut;return void qr().then(()=>{!wr&&ut===e&&e.isConnected&&(yn(),bn?.resolve())},()=>{})}let t=dn?.header??null,r=t?Ho(t):void 0;if(wr=e.createContextMentionOrchestrator({deps:{loadContextMentions:Yo,loadContextMentionsInline:ra,renderLucideIcon:K,createMentionButton:na},config:s,textarea:ut,anchor:mt??ut,getMessages:()=>va.getMessages(),liveRegionHost:st,chipRow:r}),wr&&!r){let e=ut;e.parentElement?.insertBefore(wr.contextRow,e)}};yn();let bn=null,vn={getState:()=>Cr.getState(),getValue:()=>ut?.value??"",setValue:e=>{ut&&(ut.value=e,ut.dispatchEvent(new Event("input",{bubbles:!0})),kr())},submit:()=>{!function(e){e&&("function"==typeof e.requestSubmit?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}(dn?.form??null)},openAttachmentPicker:()=>{$l()||Ft?.click()},toggleVoice:()=>{Jr?.()},requestRender:()=>bn?.resolve()},wn=()=>{let e=[];return(wr?.affordanceButtons??[]).forEach((t,r)=>{e.push({id:`core:mention-${r}`,placement:"start",order:100+r,element:t,managed:!0})}),Dt&&e.push({id:"core:attachment",placement:"start",order:200,element:Dt}),$t&&e.push({id:"core:mic",placement:"end",order:800,element:$t}),Nt&&e.push({id:"core:send",placement:"end",order:vo,element:Nt}),e},xn=()=>{bn?.destroy(),bn=Eo({getBindings:()=>dn,collect:()=>({builtIns:wn(),configActions:[...Kr(),...s.composer?.actions??[]],plugins:h,contributionContext:{config:s,getState:()=>Cr.getState(),requestRender:()=>bn?.resolve()},debug:!0===s.debug}),actionContext:vn,getState:()=>Cr.getState(),getOverflow:()=>s.composer?.actionOverflow,reportError:(e,t)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),bn.resolve()};xn();let Cn=()=>{if(Dr?.destroy(),Dr=null,!Pr().length)return;let e=dn?.header;e&&(Dr=$o({row:Ho(e),onRemove:e=>Rr(e),initialIds:Cr.getState().activeModeIds}),Dr.render(Cr.getState().activeModeIds,Pr()))};Cn();let Sn=()=>{Or?.destroy(),Or=null,Ur?.destroy(),Ur=null;let e=dn?.header;e&&(Or=jo({onDismiss:()=>zr(void 0)}),e.appendChild(Or.element),Or.render(Cr.getState().quote),"defer-one"===Vr()&&(Ur=_o({onEdit:()=>function(){let e=Cr.getState().pendingSubmission;e&&(Gr(void 0),ut&&(ut.value=e.text,ut.dispatchEvent(new Event("input",{bubbles:!0})),kr()),e.options.selectedModelId&&(Cr.setSelectedModelId(e.options.selectedModelId),Hr?.repaint()),e.options.activeModeIds?.length&&Nr(e.options.activeModeIds),e.options.quote&&zr(e.options.quote),ut?.focus())}(),onRemove:()=>Gr(void 0)}),e.appendChild(Ur.element),Ur.render(Cr.getState().pendingSubmission)))};Sn();let kn=function(){let e=!1;return{observe:(t,r)=>r?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}(),An=()=>{let e=dn?.header?.querySelector(No);if(e)return e.childElementCount>0;let t=Cr.getState();return t.mentionRefs.length>0||zo(t.activeModeIds,Pr()).length>0};function Mn(){let e=Cr.getState(),t=kn.observe(function(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let r=t.getComputedStyle(e),n=Number.parseFloat(r.lineHeight),o=Number.parseFloat(r.fontSize),a=Number.isFinite(n)&&n>0?n:Number.isFinite(o)&&o>0?1.4*o:0;if(!a)return!1;let s=(Number.parseFloat(r.paddingTop)||0)+(Number.parseFloat(r.paddingBottom)||0);return e.scrollHeight-s>1.5*a}(ut),e.text);Tt.toggleAttribute("data-persona-composer-compact",function(e){return!e.wrapped&&!e.text.includes("\n")&&!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}({text:e.text,wrapped:t,hasAttachments:e.attachments.length>0,hasChips:An(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission}))}function Tn(){"single-row"!==s.composer?.layout||se()?Tt.removeAttribute("data-persona-composer-layout"):Tt.setAttribute("data-persona-composer-layout","single-row")}Tn(),Cr.subscribe(()=>{bn?.sync(),Fl(),Ol(),Mn(),hi()}),Ol();let En=!1;(()=>{let e=s.layout?.slots??{};(e=>{if(En||!0!==s.debug)return;let t=["messages","composer"].filter(t=>e[t]);t.length&&(En=!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.`))})(e);let t=e=>{switch(e){case"body-top":return it.querySelector("[data-persona-intro-card]");case"messages":return lt;case"footer-top":return pt;case"composer":return mt;case"footer-bottom":return gt;default:return null}},r=(e,t)=>{switch(e){case"header-left":case"header-center":case"header-right":if("header-left"===e)Mt.insertBefore(t,Mt.firstChild);else if("header-right"===e)Mt.appendChild(t);else{let e=Mt.querySelector(".persona-flex-col");e?e.parentNode?.insertBefore(t,e.nextSibling):Mt.appendChild(t)}break;case"body-top":{let e=it.querySelector("[data-persona-intro-card]");e?e.replaceWith(t):it.insertBefore(t,it.firstChild);break}case"body-bottom":it.appendChild(t);break;case"footer-top":pt.replaceWith(t);break;case"footer-bottom":gt.replaceWith(t)}};for(let[n,o]of Object.entries(e))if(o)try{let e=o({config:s,defaultContent:()=>t(n)});e&&r(n,e)}catch(e){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${n}":`,e)}})(),lt.addEventListener("click",e=>{let t=e.target;if(!(t instanceof Element))return;let r=t.closest("button[data-persona-copy-tool-detail]");r&&(e.preventDefault(),e.stopPropagation(),async function(e){let t=e.closest("[data-persona-tool-detail]"),r=t?.querySelector("pre");if(!r)return;let n=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(fl.get(e));try{await navigator.clipboard.writeText(r.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let t=K("check",14,"currentColor",2);t&&e.replaceChildren(t)}catch{e.setAttribute("aria-label","Copy failed — try again"),e.title="Copy failed — try again"}fl.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",n),e.title=n;let t=K("copy",14,"currentColor",1.7);t&&e.replaceChildren(t),fl.delete(e)},1800))}(r))});let Ln=e=>{let t=e.target.closest('button[data-expand-header="true"]');if(!t)return;let r=t.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!r)return;let n=r.getAttribute("data-message-id");if(!n)return;ks(),Li();let o=t.getAttribute("data-bubble-type");if(r.classList.contains("persona-activity-row")){d.manual(n);let e=r.parentElement?.closest("[data-persona-tool-group]");e?.dataset.messageId&&d.manual(e.dataset.messageId)}if("reasoning"===o)l.has(n)?l.delete(n):l.add(n),ul(n,r,l);else if("tool"===o)i.has(n)?i.delete(n):i.add(n),wl(n,r,i,s);else if("approval"===o&&v){let e="expanded"===((!1===s.approval?void 0:s.approval)?.detailsDisplay??"collapsed"),t=c.get(n)??e;c.set(n,!t),v.updateApprovalDetailsUI(n,r,s,c)}Ha.delete(n)};lt.addEventListener("pointerdown",e=>{e.target.closest('button[data-expand-header="true"]')&&(e.preventDefault(),Ln(e))}),lt.addEventListener("click",e=>{0===e.detail&&e.target.closest(".persona-activity-row")&&Ln(e)}),lt.addEventListener("keydown",e=>{let t=e.target;("Enter"===e.key||" "===e.key)&&t.closest('button[data-expand-header="true"]')&&(e.preventDefault(),Ln(e))}),lt.addEventListener("copy",e=>{let{clipboardData:t}=e;if(!t)return;let r=lt.getRootNode(),n="function"==typeof r.getSelection?r.getSelection():window.getSelection();if(!n||n.isCollapsed)return;let o=n.toString(),a=(e=>e.replace(/^\n+/,"").replace(/\s+$/,""))(o);a&&a!==o&&(t.setData("text/plain",a),e.preventDefault())});let Pn=new Map,Nn=null,Hn="idle",$n={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading…"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Dn=()=>{lt.querySelectorAll('[data-action="read-aloud"]').forEach(e=>{let t=e.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;((e,t)=>{let{icon:r,label:n}=$n[t];e.setAttribute("aria-label",n),e.title=n,e.setAttribute("aria-pressed","idle"===t?"false":"true"),e.classList.toggle("persona-message-action-active","idle"!==t),e.classList.toggle("persona-message-action-loading","loading"===t);let o=K(r,14,"currentColor",2);o&&(e.innerHTML="",e.appendChild(o))})(e,t&&t===Nn?Hn:"idle")})};lt.addEventListener("click",e=>{let t=e.target.closest(".persona-message-action-btn[data-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let o=t.closest("[data-actions-for]");if(!o)return;let a=o.getAttribute("data-actions-for");if(!a)return;let i=t.getAttribute("data-action");if("copy"===i){let e=va.getMessages().find(e=>e.id===a);if(e&&Qe){let o=e.content||"";navigator.clipboard.writeText(o).then(()=>{t.classList.add("persona-message-action-success");let e=n(r.Check,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e)),setTimeout(()=>{t.classList.remove("persona-message-action-success");let e=n(r.Copy,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e))},2e3)}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",e)}),Qe(e)}}else if("read-aloud"===i)va.toggleReadAloud(a);else if("upvote"===i||"downvote"===i){let e="upvote"===i?"thumbs-up":"thumbs-down";if((Pn.get(a)??null)===i){Pn.delete(a),t.classList.remove("persona-message-action-active");let r=K(e,14,"currentColor",2);r&&(t.innerHTML="",t.appendChild(r))}else{let r="upvote"===i?"downvote":"upvote",n=o.querySelector(`[data-action="${r}"]`);if(n){n.classList.remove("persona-message-action-active");let e=K("upvote"===r?"thumbs-up":"thumbs-down",14,"currentColor",2);e&&(n.innerHTML="",n.appendChild(e))}Pn.set(a,i),t.classList.add("persona-message-action-active");let s=K(e,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 l=va.getMessages().find(e=>e.id===a);l&&Xe&&Xe({type:i,messageId:l.id,message:l})}}else if("regenerate"===i)Fn?.regenerate(a);else if("edit"===i)Fn?.edit(a);else if("quote"===i)Fn?.quote(a);else if(i?.startsWith("custom:")){let e=i.slice(7),r=s.messageActions?.custom?.find(t=>t.id===e),n=va.getMessages().find(e=>e.id===a);if(!r||!n)return;try{r.onSelect(n)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let Fn=null;lt.addEventListener("click",e=>{let t=e.target.closest("button[data-approval-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.closest(".persona-approval-bubble");if(!r)return;let n=r.getAttribute("data-message-id");if(!n)return;let o=t.getAttribute("data-approval-action");if(!o)return;let a="approve"===o?"approved":"denied",s=va.getMessages().find(e=>e.id===n);if(!s?.approval)return;let i=r.querySelector("[data-approval-buttons]");i&&i.querySelectorAll("button").forEach(e=>{e.disabled=!0,e.style.opacity="0.5",e.style.cursor="not-allowed"}),"webmcp"===s.approval.toolType?va.resolveWebMcpApproval(n,a):va.resolveApproval(s.approval,a)});let On=null,zn=!1,jn=null,_n=()=>{},Vn="none",Un=null,Kn={artifacts:[],selectedId:null},Yn=!1,ao=!1,so=!1,lo=!1,po=()=>lo||Kn.artifacts.some(e=>"panel"===en(s.features?.artifacts,e)),uo=()=>Kn.artifacts.length>0&&!Yn&&po(),ho={current:null},mo=(e,t)=>{let r=va.getArtifactById(t),n=r?.markdown,o=r?.title||"artifact",a=r?.file,s=r?.artifactType??"markdown";if(!n){let t=(e.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]"))?.getAttribute("data-message-id");if(t){let e=va.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);n=t?.props?.markdown,o=t?.props?.title||o,t?.props?.file&&"object"==typeof t.props.file&&(a=t.props.file),!r&&"string"==typeof t?.props?.artifactType&&(s=t.props.artifactType)}catch{}}}return{markdown:n,title:o,file:a,artifactType:s}};lt.addEventListener("click",e=>{let t=e.target.closest("[data-download-artifact]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-download-artifact");if(!r||!0===s.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:r}))return;let{markdown:n,title:o,file:a}=mo(t,r);if(!n)return;let i=_l();i&&i.triggerArtifactDownload(i.downloadInfoFor({title:o,markdown:n,file:a}))}),lt.addEventListener("click",e=>{let t=e.target.closest("[data-artifact-custom-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-artifact-custom-action");if(!r)return;let n=t.closest("[data-artifact-inline]"),o=n?null:t.closest("[data-open-artifact]"),a=n?n.getAttribute("data-artifact-inline"):o?.getAttribute("data-open-artifact")??null,i=(n?s.features?.artifacts?.inlineActions:s.features?.artifacts?.cardActions)?.find(e=>e.id===r);if(!i)return;let{markdown:l,title:d,file:c,artifactType:p}=mo(t,a??""),u={artifactId:a,title:d,artifactType:p,markdown:l,file:c};try{Promise.resolve(i.onClick(u)).catch(()=>{})}catch{}}),lt.addEventListener("click",e=>{let t=e.target.closest("[data-copy-artifact]");if(!t)return;e.preventDefault(),e.stopPropagation();let o=t.getAttribute("data-copy-artifact");if(!o)return;let a=va.getArtifactById(o),s=_l();if(!s)return;let i="";if(a)i=s.artifactCopyText(a);else{let{markdown:e,file:r,artifactType:n}=mo(t,o);"markdown"===n&&(i=s.artifactCopyText({id:o,artifactType:"markdown",status:"complete",markdown:e??"",...r?{file:r}:{}}))}i&&navigator.clipboard.writeText(i).then(()=>{let e=n(r.Check,16,"currentColor",2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=n(r.Copy,16,"currentColor",2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),lt.addEventListener("click",e=>{let t=e.target.closest("[data-expand-artifact-inline]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-expand-artifact-inline");r&&!0!==s.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:r})&&(Yn=!1,lo=!0,ao=!0,so=!0,va.selectArtifact(r),Xo())}),lt.addEventListener("click",e=>{let t=e.target;if(t.closest("[data-download-artifact]")||t.closest("[data-artifact-custom-action]"))return;let r=t.closest("[data-open-artifact]");if(!r)return;let n=r.getAttribute("data-open-artifact");n&&!0!==s.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:n})&&(e.preventDefault(),e.stopPropagation(),Yn=!1,lo=!0,va.selectArtifact(n),Xo())}),lt.addEventListener("keydown",e=>{if("Enter"!==e.key&&" "!==e.key)return;let t=e.target;(t.hasAttribute("data-open-artifact")||t.hasAttribute("data-expand-artifact-inline"))&&(e.preventDefault(),t.click())});let go=at.composerOverlay,fo=e=>{qr().catch(()=>{}),Ot(e,s,go)},yo=null,bo={mount:e,overlay:go,sessionRef:ho,config:()=>s},wo=!1,xo=e=>t=>{let r=t.target,n=r?.closest?.("[data-persona-ask-sheet-for]");if(!n||!("click"===e?r?.closest("[data-ask-user-action]"):"Enter"===t.key&&r?.matches?.('[data-ask-free-text-input="true"]')))return;let o=r=>{yo??=r.createAskUserSheetHandlers(bo),yo[e](t)},a=jr();a?o(a):wo||(wo=!0,qr().then(e=>{wo=!1,n.isConnected&&o(e)},()=>{wo=!1}))};go.addEventListener("click",xo("click")),go.addEventListener("keydown",xo("keydown"));let Co=e=>{if(!/^[1-9]$/.test(e.key)||e.metaKey||e.ctrlKey||e.altKey)return;let t=e.target;if("INPUT"===t?.tagName||"TEXTAREA"===t?.tagName||t?.isContentEditable)return;let r=go.querySelector("[data-persona-ask-sheet-for]");if(!r||"rows"!==r.getAttribute("data-ask-layout")||"true"===r.getAttribute("data-multi-select"))return;let n=Number(e.key),o=r.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[n-1];o&&(e.preventDefault(),o.click())};document.addEventListener("keydown",Co);let So=null,ko=null,Ao=null,Mo=null,Io=()=>{},To=!1,Lo="",Po="";function Ro(){Mo?.(),Mo=null}let Fo=()=>{if(!So||!ko)return;let t=e.classList.contains("persona-artifact-welded-split"),r=e.ownerDocument.defaultView??window,n=r.innerWidth<=640;if(!t||e.classList.contains("persona-artifact-narrow-host")||n)return ko.style.removeProperty("position"),ko.style.removeProperty("left"),ko.style.removeProperty("top"),ko.style.removeProperty("bottom"),ko.style.removeProperty("width"),void ko.style.removeProperty("z-index");let o=So.firstElementChild;if(!o||o===ko)return;ko.style.position="absolute",ko.style.top="0",ko.style.bottom="0",ko.style.width="10px",ko.style.zIndex="5";let a=wd(So,r),s=o.offsetWidth+a/2-5;ko.style.left=`${Math.max(0,s)}px`},Go=()=>{},Jo=()=>{let t=e.ownerDocument.defaultView??window,r=s.launcher?.mobileFullscreen??!0,n=s.launcher?.mobileBreakpoint??640;return!(!r||t.innerWidth>n)&&(X||Gs(s))},Qo=()=>!Ul(s)||!uo()||e.classList.contains("persona-artifact-narrow-host")||Jo()||(e.ownerDocument.defaultView??window).innerWidth<641?"none":Ql(s)?"detached":"welded",Xo=()=>{if(!On||!Ul(s))return;Xl(e,s),Yl(e,s),Go();let t=s.features?.artifacts?.layout?.narrowHostMaxWidth??520,r=nt.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",r>0&&r<=t);let n=uo();On.setVisible(n),On.update(Kn),Yn?(On.setMobileOpen(!1),On.element.classList.add("persona-hidden"),On.backdrop?.classList.add("persona-hidden"),ao=!1,so=!1):Kn.artifacts.length>0&&po()?(On.element.classList.remove("persona-hidden"),On.setMobileOpen(!0)):(On.setMobileOpen(!1),On.element.classList.add("persona-hidden"),On.backdrop?.classList.add("persona-hidden"),ao=!1,so=!1);let o=!0===s.features?.artifacts?.layout?.showExpandToggle;if(On.setExpandToggleVisible(o),On.setCopyButtonVisible(!0===s.features?.artifacts?.layout?.showCopyButton),On.setRefreshButtonVisible("function"==typeof s.features?.artifacts?.layout?.onDocumentToolbarRefresh),On.setCustomActions(s.features?.artifacts?.toolbarActions??[]),On.setTabFade(s.features?.artifacts?.layout?.tabFade),On.setRenderTabBar(s.features?.artifacts?.renderTabBar),!o&&!so&&(ao=!1),ao!==To){let e=On.element;ao?(Lo=e.style.width,Po=e.style.maxWidth,e.style.removeProperty("width"),e.style.removeProperty("max-width")):(Lo&&(e.style.width=Lo),Po&&(e.style.maxWidth=Po),Lo="",Po=""),To=ao}e.classList.toggle("persona-artifact-expanded",ao),On.setExpanded(ao);let a=Qo();a!==Vn&&(Vn=a,_n()),Io()};if(Ul(s)){nt.style.position="relative";let t=L("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),r=L("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");t.appendChild(st),So=r,r.appendChild(t),nt.appendChild(r);let n=e=>{zn||On||(On=e.createArtifactPane(s,{onSelect:e=>ho.current?.selectArtifact(e),onDismiss:()=>{Yn=!0,Xo()},onToggleExpand:()=>{let e=!ao,t=Kn.selectedId??Kn.artifacts[Kn.artifacts.length-1]?.id??null;!0!==s.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:t,expanded:e})&&(ao=e,e||(so=!1),Xo())}}),On.element.classList.add("persona-hidden"),r.appendChild(On.element),On.backdrop&&nt.appendChild(On.backdrop),Io(),Xo())},o=_l();o?n(o):(Vl(()=>{let e=_l();e&&n(e)}),jl().catch(()=>{})),Io=()=>{if(So&&On)if(!0!==s.features?.artifacts?.layout?.resizable)Ao?.(),Ao=null,Ro(),ko&&=(ko.remove(),null),On.element.style.removeProperty("width"),On.element.style.removeProperty("maxWidth");else{if(!ko){let t=L("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 r=e.ownerDocument,n=r.defaultView??window,o=o=>{if(!On||0!==o.button||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||n.innerWidth<=640)return;o.preventDefault(),Ro();let a=o.clientX,i=On.element.getBoundingClientRect().width,l=s.features?.artifacts?.layout,d=r=>{let o=So.getBoundingClientRect().width,s=e.classList.contains("persona-artifact-welded-split"),d=wd(So,n),c=s?0:t.getBoundingClientRect().width||6,p=function(e,t,r,n,o,a,s=200){let i=function(e){if(!e?.trim())return 200;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):200}(o),l=function(e,t,r,n){let o=e-n-2*t-r;return Math.max(0,o)}(t,r,n,s);l=Math.max(i,l);let d=function(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}(a);return null!==d&&(l=Math.min(l,d)),function(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}(e,i,l)}(i-(r.clientX-a),o,d,c,l?.resizableMinWidth,l?.resizableMaxWidth,(()=>{let e=sc?.railShell?sc.railHost:null,t=e?.isConnected?e:null,r=t?t.getBoundingClientRect().width:0;return r<=0?200:r+360})());On.element.style.width=`${p}px`,On.element.style.maxWidth="none",Fo()},c=()=>{r.removeEventListener("pointermove",d),r.removeEventListener("pointerup",c),r.removeEventListener("pointercancel",c),Mo=null;try{t.releasePointerCapture(o.pointerId)}catch{}};Mo=c,r.addEventListener("pointermove",d),r.addEventListener("pointerup",c),r.addEventListener("pointercancel",c);try{t.setPointerCapture(o.pointerId)}catch{}};t.addEventListener("pointerdown",o),ko=t,So.insertBefore(t,On.element),Ao=()=>{t.removeEventListener("pointerdown",o)}}if(ko){let e=uo();ko.classList.toggle("persona-hidden",!e),Fo()}}},Go=()=>{if(!X||!On||s.launcher?.sidebarMode||Gs(s)&&"emerge"===Js(s).reveal)return;let t=e.ownerDocument.defaultView??window,r=s.launcher?.mobileFullscreen??!0,n=s.launcher?.mobileBreakpoint??640;if(r&&t.innerWidth<=n||!function(e,t){return!(!t||!Ul(e))&&!1!==e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen}(s,X))return;let o=Zi(s).width,a=s.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";uo()?(nt.style.width=a,nt.style.maxWidth=a):(nt.style.width=o,nt.style.maxWidth=o)},typeof ResizeObserver<"u"&&(jn=new ResizeObserver(()=>{Xo()}),jn.observe(nt))}else nt.appendChild(st);se()&&ot&&(at.peekBanner&&ot.appendChild(at.peekBanner),ot.appendChild(Tt)),e.appendChild(rt),ot&&e.appendChild(ot);let Zo=()=>{let t=Jo()||se()&&"fullscreen"===s.launcher?.composerBar?.expandedSize||!0===s.launcher?.fullHeight&&!s.launcher?.sidebarMode&&!Gs(s);if(lt.style.gap=t?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",lt.style.setProperty("--persona-transcript-gap",lt.style.gap),se()){nt.style.width="100%",nt.style.maxWidth="100%";let e=s.launcher?.composerBar??{},t="expanded"===rt.dataset.state,r=e.expandedSize??"anchored";if(!t||"fullscreen"===r)return st.style.background="",st.style.border="",st.style.borderRadius="",st.style.overflow="",void(st.style.boxShadow="");let n=s.theme?.components?.panel,o=Oa(s),a=(e,t)=>null==e||""===e?t:Ca(o,e)??e;return st.style.background="var(--persona-surface, #ffffff)",st.style.border=a(n?.border,"1px solid var(--persona-border)"),st.style.borderRadius=a(n?.borderRadius,"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))"),st.style.boxShadow=a(n?.shadow,"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))"),void(st.style.overflow="hidden")}let r=Gs(s),n=s.launcher?.sidebarMode??!1,o=r||n||(s.launcher?.fullHeight??!1),i=!1===s.launcher?.enabled,l=!0===s.launcher?.detachedPanel,d=s.theme?.components?.panel,c=s.darkTheme?.components?.panel,p="dark"===Fa(s)?a(d??{},c??{}):d,u=Oa(s),h=(e,t)=>null==e||""===e?t:Ca(u,e)??e,m=e.ownerDocument.defaultView??window,g=s.launcher?.mobileFullscreen??!0,y=s.launcher?.mobileBreakpoint??640,b=m.innerWidth<=y,v=g&&b&&X,w=r&&g&&b,x=s.launcher?.position??"bottom-left",C="bottom-left"===x||"top-left"===x,S=s.launcher?.zIndex??1e5,k=(e,t,r)=>`var(--persona-components-panel-modes-${e}-${t}, ${r})`,A=p?.modes?.floating,M=h(A?.border??p?.border,k("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),I=h(A?.shadow??p?.shadow,k("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),T=h(A?.borderRadius??p?.borderRadius,k("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),E=l&&!v&&!w,L=v||w?"mobile":E?"floating":r?"docked":n?"sidebar":i?"inline":"floating",P=p?.modes?.[L];E?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let B=E?M:n||v?"none":M,N=E?I:v?"none":n?C?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":i?"none":I;r&&!v&&!E&&(N="none",B="none");let R=E?T:n||v?"0":T,H=h(P?.border??p?.border,k(L,"border",B)),$=h(P?.shadow??p?.shadow,k(L,"shadow",N)),W=h(P?.borderRadius??p?.borderRadius,k(L,"borderRadius",R)),D=Qo(),F="detached"===D,O="welded"===D;e.classList.toggle("persona-artifact-detached-split",F),e.classList.toggle("persona-artifact-welded-split",O);let z="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)))))",q="flush"==("flush"===s.features?.artifacts?.layout?.chatSurface?"flush":"card")&&Ul(s)&&Ql(s)&&i&&!r;e.classList.toggle("persona-artifact-chat-flush",q);let j=F||q?"none":$,_=F?M:O?"none":H,V=F?T:W;q&&(_="none",V="0");let U=null!=P?.borderRadius&&""!==P.borderRadius||null!=p?.borderRadius&&""!==p.borderRadius,G=q&&!U?"0":W,K=it.scrollTop;e.style.cssText="",rt.style.cssText="",nt.style.cssText="",st.style.cssText="",it.style.cssText="",an||(Tt.style.cssText=""),He&&(it.style.display="none"),(o||i)&&(e.style.minWidth="0");let J=()=>{K<=0||(it.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(it.scrollTop===K)return;let e=it.scrollHeight-it.clientHeight;e<=0||(it.scrollTop=Math.min(K,e))})};if(v)return rt.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"),rt.style.cssText=`\n position: fixed !important;\n inset: 0 !important;\n width: 100% !important;\n height: 100% !important;\n max-height: 100% !important;\n margin: 0 !important;\n padding: 0 !important;\n display: flex !important;\n flex-direction: column !important;\n z-index: ${S} !important;\n background-color: var(--persona-surface, #ffffff) !important;\n `,nt.style.cssText="\n position: relative !important;\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n max-width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n margin: 0 !important;\n padding: 0 !important;\n box-shadow: none !important;\n border-radius: 0 !important;\n ",st.style.cssText="\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n max-height: 100% !important;\n overflow: hidden !important;\n border-radius: 0 !important;\n border: none !important;\n ",it.style.flex="1 1 0%",it.style.minHeight="0",it.style.overflowY="auto",Tt.style.flexShrink="0",fr(),ne=!0,void J();let Q=Zi(s);if(n||r){if(r)if("emerge"!==Js(s).reveal||l)nt.style.width="100%",nt.style.maxWidth="100%";else{let e=Js(s).width;nt.style.width=e,nt.style.maxWidth=e}}else i&&o?(nt.style.width="100%",nt.style.maxWidth="100%"):(nt.style.width=Q.width,nt.style.maxWidth=Q.maxWidth);if(Go(),nt.style.boxShadow=j,nt.style.borderRadius=G,F?nt.style.border="none":O&&(nt.style.border=H),st.style.border=_,st.style.borderRadius=V,st.style.boxShadow=F&&!q?z:"",q&&(st.style.background="transparent",it.style.background="transparent",Tt.style.background="transparent",Tt.style.borderTop="none"),O){let e=s.features?.artifacts?.layout;Un=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||W}else Un=null;let Y=null!=P?.border||null!=p?.border;if(r&&!v&&!E&&!F&&!O&&!Y&&(st.style.border="none","right"===Js(s).side?st.style.borderLeft="1px solid var(--persona-border)":st.style.borderRight="1px solid var(--persona-border)"),r&&!v&&O&&!Y&&("right"===Js(s).side?nt.style.borderLeft="1px solid var(--persona-border)":nt.style.borderRight="1px solid var(--persona-border)"),o&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",i&&(e.style.width="100%"),rt.style.display="flex",rt.style.flexDirection="column",rt.style.flex="1 1 0%",rt.style.minHeight="0",rt.style.maxHeight="100%",rt.style.height="100%",i&&(rt.style.overflow="hidden"),nt.style.display="flex",nt.style.flexDirection="column",nt.style.flex="1 1 0%",nt.style.minHeight="0",nt.style.maxHeight="100%",nt.style.height="100%",F||(nt.style.overflow="hidden"),st.style.display="flex",st.style.flexDirection="column",st.style.flex="1 1 0%",st.style.minHeight="0",st.style.maxHeight="100%",st.style.overflow="hidden",it.style.flex="1 1 0%",it.style.minHeight="0",it.style.overflowY="auto",Tt.style.flexShrink="0"),i&&(E||F||q)&&!r&&(q||(rt.style.padding="var(--persona-panel-inset)"),rt.style.background="var(--persona-panel-canvas-bg)"),rt.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"),!n&&!i&&!r&&(ti[x]??ti["bottom-right"]).split(" ").forEach(e=>rt.classList.add(e)),n){let e=f(s).sidebarWidth?s.launcher?.sidebarWidth??"420px":Ca(Oa(s),"components.panel.width")??"420px";rt.style.cssText=l?`\n position: fixed !important;\n top: var(--persona-panel-inset) !important;\n bottom: var(--persona-panel-inset) !important;\n width: ${e} !important;\n height: calc(100vh - (2 * var(--persona-panel-inset))) !important;\n max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;\n margin: 0 !important;\n padding: 0 !important;\n display: flex !important;\n flex-direction: column !important;\n z-index: ${S} !important;\n ${C?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}\n `:`\n position: fixed !important;\n top: 0 !important;\n bottom: 0 !important;\n width: ${e} !important;\n height: 100vh !important;\n max-height: 100vh !important;\n margin: 0 !important;\n padding: 0 !important;\n display: flex !important;\n flex-direction: column !important;\n z-index: ${S} !important;\n ${C?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}\n `,nt.style.cssText=`\n position: relative !important;\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n max-width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n margin: 0 !important;\n padding: 0 !important;\n box-shadow: ${j} !important;\n border-radius: ${G} !important;\n ${F?"border: none !important;":O?`border: ${H} !important;`:""}\n `,nt.style.setProperty("width","100%","important"),nt.style.setProperty("max-width","100%","important"),st.style.cssText=`\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n max-height: 100% !important;\n overflow: hidden !important;\n border-radius: ${V} !important;\n border: ${_} !important;\n ${F&&!q?`box-shadow: ${z} !important;`:""}\n ${q?"background: transparent !important;":""}\n `,an||(Tt.style.cssText=`\n flex-shrink: 0 !important;\n border-top: none !important;\n padding: 8px 16px 12px 16px !important;\n ${q?"background: transparent !important;":""}\n `)}if(!i&&!r){let e=n?"":"padding-top: 1.25em !important;",t=n?"":`z-index: ${s.launcher?.zIndex??1e5} !important;`;rt.style.cssText+="max-height: -moz-available !important; max-height: stretch !important;"+e+t}fr(),J()},ea=()=>{e.style.setProperty("--persona-content-max-width",ja(s,se()))},ta=!1;function oa(){s.layout?.topFade&&it.scrollTop>1?it.setAttribute("data-persona-top-fade","true"):it.removeAttribute("data-persona-top-fade")}let aa=()=>{oa();let t=_a(s,se());se()&&s.composer?.placement&&!0===s.debug&&!ta&&(ta=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let r=pr();e.setAttribute("data-persona-composer-placement",t),e.setAttribute("data-persona-conversation-state",ur),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",r.composerGap??"24px"),yr()},sa=()=>{if(se())return;let t=Gs(s),r=s.launcher?.sidebarMode??!1;if(t||r||s.launcher?.fullHeight||!X)return;let n=e.ownerDocument.defaultView??window,o=s.launcher?.mobileFullscreen??!0,a=s.launcher?.mobileBreakpoint??640;if(o&&n.innerWidth<=a)return;let i=Zi(s);nt.style.height=i.height,nt.style.maxHeight=i.maxHeight};Zo(),za(e,s),Xl(e,s),Yl(e,s),ea(),aa(),_n=()=>{Zo(),sa(),za(e,s),Xl(e,s),Yl(e,s),ea(),aa(),Un?e.style.setProperty("--persona-artifact-welded-outer-radius",Un):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Ve(),_e()};let ia=[];ia.push(()=>{zn=!0}),ia.push(()=>{g.forEach(e=>e()),m.destroy()}),ia.push(()=>{document.removeEventListener("keydown",Co)}),ia.push(()=>{null!==ir&&clearTimeout(ir)});let la=null,da=null;ia.push(()=>{la?.(),la=null,da?.(),da=null}),jn&&ia.push(()=>{jn?.disconnect(),jn=null}),ia.push(()=>{Ao?.(),Ao=null,Ro(),ko&&=(ko.remove(),null),On?.element.style.removeProperty("width"),On?.element.style.removeProperty("maxWidth"),On?.destroy()}),Ce&&ia.push(()=>{Ne=!0,Be=null,null!==$e&&(cancelAnimationFrame($e),$e=null),Re?.destroy(),Re=null,Le?.destroy(),Le=null,Te=null});let ca=null,pa=()=>{ca&&=(ca(),null),"auto"===s.colorScheme&&(ca=qa(()=>{za(e,s)}))};pa(),ia.push(()=>{ca&&=(ca(),null)}),ia.push(()=>{C=!0,x?.()}),ia.push(()=>{M=!0});let ua=!1;ia.push(()=>{ua=!0});let ha=(t,r)=>{let n=vs(t,r);return n||!ys.includes(t)?n:(Ws().then(n=>{if(ua)return;bs(n.wipe),bs(n.glyphCycle);let o=vs(t,r);o&&Ns(o,e)}).catch(()=>{}),null)},ma=s.features?.streamAnimation;if(ma?.type&&"none"!==ma.type){let t=ha(ma.type,ma.plugins);t&&Ns(t,e),ia.push(()=>Bs(e))}let ga=ei(pt),fa=ei(dt),ya=ei(ct),ba=[ga,fa,ya];ia.push(()=>{ba.forEach(e=>e.destroy())});let va,wa=null,xa=null,Sa=!1,ka=0,Aa=null,Ma=e=>e.reduce((e,t)=>"user"===t.role?e+1:e,0),Ia=e=>{for(let t=e.length-1;t>=0;t--)if(Vt(e[t]))return e[t].id??null;return null},Ta=!1,Ea=!1,La=!1,Pa=(e,t)=>{Ea||!0!==s.debug||t.enabled&&!t.expose&&(Sa||La&&(va.isStreaming()||e.some(Vt)||(Ea=!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."))))},Ba=e=>{if(!va)return;let t=e??va.getMessages(),r=e=>{e.render([],va,ut,t)},n=e=>{ba.forEach(t=>{t!==e&&r(t)})};xa&&(Ma(t)>ka||Ia(t)!==Aa)&&(xa=null);let o=Jt(s);Pa(t,o);let a=o.enabled?Gt(t):null,i=xa??a,l=xa?"host":"agent";if(i){let e=s.suggestions?.followUps,r=e?.placement??(e?"auto":"composer"),o="after-message"===("auto"===r?se()?"composer":"after-message":r)?ya:ga;return n(o),void o.render(i,va,ut,t,s.suggestionChipsConfig,{source:l,surface:"followUp",variant:e?.variant??"chip",behavior:e?.behavior??"send",overflow:e?.overflow??"wrap",maxItems:e?.maxItems??4,config:s,plugins:h,submitPrompt:Qc})}if(t.some(e=>"user"===e.role))return void ba.forEach(r);let d=!0===s.future?.v5Defaults,c=cr(),p=s.suggestions?.starters??(d?{}:void 0);if(p){let e=Xi(pr(),t),o=p.placement??"auto",a="auto"===o?e?"welcome":"composer":o;if("welcome"===a&&!e)return Ta||!0!==s.debug||(Ta=!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".')),void ba.forEach(r);let i="welcome"===a?fa:ga;n(i),i.render(p.items??s.suggestionChips,va,ut,t,s.suggestionChipsConfig,{surface:"starter",variant:p.variant??(d&&!c?"chip":"card"),behavior:p.behavior??"send",overflow:p.overflow??"wrap",maxItems:p.maxItems??(d&&!c?3:4),config:s,plugins:h,submitPrompt:Qc})}else n(ga),ga.render(s.suggestionChips,va,ut,t,s.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:s,plugins:h,submitPrompt:Qc})},Na=()=>{xa&&(xa=null,Ba())},Ra=!1,Ha=new Map,$a=new Map,Wa=new Map,Da=new Map,Ua=null,Ga=null;function Ka(){if(!Ua)return;let e=Ua;Ua=null,Ga?.destroy(),Ga=null,Ha.delete(e),st.querySelector(`#wrapper-${e}`)?.removeAttribute("data-preserve-runtime"),va&&gl(lt,va.getMessages(),fe)}let Ja=0,Qa=null!==ve(),Xa=function(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>!!t&&(t=!1,!0),resume:()=>!t&&(t=!0,!0)}}(),Ya=0,Za=null,ts=!1,ls=!1,ds=0,cs=null,ps=null,us=!1,hs=!1,gs=null,fs=!0,xs=!1,Cs=null,Ss=!1,ks=()=>{Ss=!0,Ps()},As=null,Ms=null,Ls=()=>{e.setAttribute("data-persona-scrollbar",Zt()),"on-scroll"!==Zt()&&(null!==Ms&&clearTimeout(Ms),Ms=null,it.removeAttribute("data-persona-scrollbar-visible"))},Ps=()=>{"on-scroll"===Zt()&&(it.setAttribute("data-persona-scrollbar-visible",""),null!==Ms&&clearTimeout(Ms),Ms=setTimeout(()=>{Ms=null,ss(it,24)&&it.removeAttribute("data-persona-scrollbar-visible")},1e3))};Ls(),ia.push(()=>{null!==Ms&&clearTimeout(Ms)});let Rs=new Map,Hs=!1,$s=null,Fs={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Mn();let Os=s.voiceRecognition?.autoResume??!1,qs=()=>va.isVoiceActive()||va.isBargeInActive(),js=!1,_s=e=>{R.emit("voice:state",{active:Fs.active,source:e,timestamp:Date.now()})},Vs=()=>{U(e=>({...e,voiceState:{active:Fs.active,timestamp:Date.now(),manuallyDeactivated:Fs.manuallyDeactivated}}))},Us=e=>{js=!e.persisted,Fs.active&&Vs()};typeof window<"u"&&(window.addEventListener("pagehide",Us),ia.push(()=>window.removeEventListener("pagehide",Us)));let Qs=()=>va?fc(va.getMessages()).filter(e=>!e.__skipPersist):[],Ys=null,ri=(e,t)=>{typeof console<"u"&&console.error(e,t)},ni=(e,t)=>{let r=()=>{try{let r=e();return r&&"function"==typeof r.then?Promise.resolve(r).catch(e=>{ri(t,e)}):null}catch(e){return ri(t,e),null}},n=Ys?Ys.then(()=>r()??void 0):r();if(!n)return;let o=n.finally(()=>{Ys===o&&(Ys=null)});Ys=o};function si(e){if(!H?.save)return;let t=e?fc(e):va?Qs():[],r=$&&va?.getResumableHandle();r&&(W={...W,durableResume:{executionId:r.executionId,after:r.lastEventId}});let n={messages:t,metadata:W,artifacts:Kn.artifacts,selectedArtifactId:Kn.selectedId,...ii?{draft:ii}:{}};ni(()=>H.save(n),"[AgentWidget] Failed to persist state:")}let ii,di=()=>!(!H?.save||!1===s.persistState||"object"==typeof s.persistState&&!1===s.persistState.persist?.draft),ci=function(e){let t=e.delay??500,r=null,n=!1,o=()=>{null!==r&&(clearTimeout(r),r=null)};return{schedule:()=>{n||(o(),r=setTimeout(()=>{r=null,e.write()},t))},flush:()=>{n||null===r||(o(),e.write())},cancel:o,destroy:()=>{n=!0,o()}}}({write:()=>{if(!di())return;let e=Cr.getState(),t=function(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}}:{}}}({text:e.text,mentionRefs:e.mentionRefs,contentSegments:zc(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(ii)&&(ii=t,si())}});function hi(){di()&&ci.schedule()}function mi(){ci.flush()}function gi(e){if(!di())return;let t=function(e,t){if(!e||"string"!=typeof e.text)return;let r=new Set(t.mentionSourceIds),n=(e.mentionRefs??[]).filter(e=>r.has(e.sourceId)),o=n.length===(e.mentionRefs?.length??0)&&n.length>0,a=new Set(t.modes.map(e=>e.id)),s=(e.activeModeIds??[]).filter(e=>a.has(e)),i=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...o?{mentionRefs:n}:{},...o&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...i?{selectedModelId:i}:{},...s.length?{activeModeIds:s}:{},...e.quote?.text?{quote:e.quote}:{}}}(e,{mentionSourceIds:(s.contextMentions?.sources??[]).map(e=>e.id),modelIds:(s.composer?.models??[]).map(e=>e.id),modes:s.composer?.modes??[]});t&&(ii=e,ut&&!ut.value&&(ut.value=t.text,ut.dispatchEvent(new Event("input",{bubbles:!0})),kr()),t.selectedModelId&&(Cr.setSelectedModelId(t.selectedModelId),Hr?.repaint()),Nr(t.activeModeIds??[]),t.quote&&zr(t.quote),ci.cancel())}function fi(){ci.cancel(),ii&&(ii=void 0,di()&&si())}let yi=null,bi=()=>rt.querySelector("#persona-scroll-container")||it,vi=()=>{null!==yi&&(cancelAnimationFrame(yi),yi=null),ts=!1},wi=()=>{null!==Za&&(cancelAnimationFrame(Za),Za=null),ls=!1,vi()},Si=()=>{let e=jt()||"Jump to latest",t=Ra&&Mi()&&("anchor-top"!==_t()||Xt());er.toggleAttribute("data-persona-scroll-to-bottom-streaming",t),ds>0?(nr.textContent=String(ds),nr.style.display="",er.setAttribute("aria-label",`${e} (${ds} new)`)):(nr.textContent="",nr.style.display="none",er.setAttribute("aria-label",t?`${e} (response streaming below)`:e))},Ai=()=>{0!==ds&&(ds=0,Si())},Mi=()=>Ut()?!Xa.isFollowing():!(()=>{let e=cs?.spacerHeight??0;return e<=0?ss(it,24):Ji(e)-it.scrollTop-it.clientHeight<=24})(),Ii=()=>!!va&&va.getMessages().length>0,Ei=()=>{if(!1===Se.enabled||He||qe&&"panel"===je)return er.parentNode&&er.remove(),void(er.style.display="none");er.parentNode!==st&&st.appendChild(er),gr();let e=as(it)>0&&Mi()&&Ii();e?Si():Ai(),er.style.display=e?"":"none"},Li=()=>{Xa.pause()&&(wi(),Ei())},Bi=()=>{Xa.resume(),Ai(),Ei()},Ni=(e=!1)=>{Ut()&&Ii()&&Xa.isFollowing()&&(e||Ra)&&(null!==Za&&(cancelAnimationFrame(Za),Za=null),ls=!0,Za=requestAnimationFrame(()=>{Za=null,ls=!1,Xa.isFollowing()&&Hi(bi(),e?220:140)}))},Ri=(e,t,r,n=()=>!0)=>{let o=e.scrollTop,a=t(),s=a-o;if(vi(),Math.abs(s)<1)return ts=!0,e.scrollTop=a,Ya=e.scrollTop,void(ts=!1);let i=performance.now();ts=!0;let l=d=>{if(!n())return void vi();let c=t();c!==a&&(a=c,s=a-o);let p=d-i,u=Math.min(p/r,1),h=(e=>1-(1-e)**3)(u);e.scrollTop=o+s*h,Ya=e.scrollTop,u<1?yi=requestAnimationFrame(l):(e.scrollTop=a,Ya=e.scrollTop,yi=null,ts=!1)};yi=requestAnimationFrame(l)},Hi=(e,t=500)=>{let r=as(e)-e.scrollTop;Math.abs(r)<1?Ya=e.scrollTop:Math.abs(r)>=80?(vi(),ts=!0,e.scrollTop=as(e),Ya=e.scrollTop,ts=!1):Ri(e,()=>as(e),t,()=>Xa.isFollowing())},Fi=()=>{if(!Ii())return void Ei();let e=bi();ts=!0,e.scrollTop=as(e),Ya=e.scrollTop,ts=!1,Ei()},Oi=e=>{let t=0,r=e;for(;r&&r!==it;)t+=r.offsetTop,r=r.offsetParent;return t},zi=()=>function(e,t){return!(!e||e.isCollapsed)&&(t.contains(e.anchorNode)||t.contains(e.focusNode))}((()=>{let e=it.getRootNode();return("function"==typeof e.getSelection?e.getSelection():null)??it.ownerDocument.getSelection()})(),it),Vi=()=>{if("last-user-turn"!==(Ae.restorePosition??"bottom"))return!1;let e=va?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>"user"===e.role);if(!t)return!1;let r=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(t.id):t.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=it.querySelector(`[data-message-id="${r}"]`);if(!n)return!1;let o=Math.min(Math.max(0,Oi(n)-Kt()),as(it));return ts=!0,it.scrollTop=o,Ya=it.scrollTop,ts=!1,"follow"===_t()&&!ss(it,24)&&Xa.pause(),Ei(),!0},Ki=e=>{let t=Math.max(0,Math.round(e));ar.style.height=`${t}px`,ar.style.display=t>0?"":"none",cs&&(cs.spacerHeight=Math.max(0,e))},Ji=e=>{let t=parseFloat(getComputedStyle(it).paddingBottom)||0,r=0;for(let e of Array.from(it.children)){if(e===ar||0===e.offsetHeight)continue;let t=Oi(e)+e.offsetHeight;t>r&&(r=t)}let n=it.scrollHeight-e;return r>0?Math.min(r+t,n):n},Yi=()=>{null!==ps&&(cancelAnimationFrame(ps),ps=null),vi(),cs=null,ar.style.height="0px",ar.style.display="none"},el=e=>typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),nl=e=>it.querySelector(`[data-message-id="${el(e)}"]`),ol=e=>{null!==ps&&cancelAnimationFrame(ps),ps=requestAnimationFrame(()=>{ps=null;let t=el(e),r=it.querySelector(`[data-message-id="${t}"]`);if(!r)return;let n=Oi(r),o=Ji(cs?.spacerHeight??0),{targetScrollTop:a,spacerHeight:s}=is({anchorOffsetTop:n,topOffset:Kt(),viewportHeight:it.clientHeight,contentHeight:o,slack:24});cs={initialSpacerHeight:s,contentHeightAtAnchor:o,spacerHeight:s},Ki(s),Ri(it,()=>r.isConnected?Math.max(0,Oi(r)-Kt()):a,220)})},al=()=>{if("anchor-top"!==_t()||!cs||!Cs)return;let e=nl(Cs);if(!e)return;vi();let t=cs.spacerHeight,r=Ji(t),{targetScrollTop:n,spacerHeight:o}=is({anchorOffsetTop:Oi(e),topOffset:Kt(),viewportHeight:it.clientHeight,contentHeight:r,slack:24});cs={initialSpacerHeight:o,contentHeightAtAnchor:r,spacerHeight:o},Ki(o),ts=!0,it.scrollTop=n,Ya=it.scrollTop,ts=!1,Ei()},sl=e=>{if(null===gs)return!0;let t=nl(gs),r=nl(e);if(!t||!r)return!0;let n=Oi(r)-Oi(t);return Kt()+n>it.clientHeight-96},il=(e,t)=>{let r="user"===t?"user":"assistant",n=s.layout?.messages?.[r],o=n?.width??"content",a=n?.maxWidth??("full"===o?`var(--persona-message-${r}-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-${o}`),e.classList.toggle("persona-justify-end","user"===t),e.setAttribute("data-message-role",t),e.setAttribute("data-message-width",o),a?e.style.setProperty("--persona-message-row-max-width",a):e.style.removeProperty("--persona-message-row-max-width")},ll=(e,t)=>{let r=document.createElement("div");return r.className="persona-flex",r.id=`wrapper-${e}`,r.setAttribute("data-wrapper-id",e),il(r,t),r},pl=!1,ml=()=>{pl||(pl=!0,Ge().catch(()=>{}),ye().catch(()=>{pl=!1}))},gl=(e,t,r)=>{t.length>0&&ml(),((e,t,r)=>{let n=new Set;for(let e of t){let t="tool"===e.variant?"tool":"reasoning"===e.variant?"reasoning":null;if(!t||"row"!==oe(s,t))continue;let r="tool"===t?s.features?.toolCallDisplay:s.features?.reasoningDisplay;!1!==r?.expandable&&(n.add(e.id),d.observe(e,t,"tool"===t?i:l,r))}let o=document.createElement("div"),a=(()=>{let e=h.find(e=>e.renderLoadingIndicator);return e?.renderLoadingIndicator?e.renderLoadingIndicator:s.loadingIndicator?.render?s.loadingIndicator.render:void 0})(),p=new Set,u=new Map,m=new Set,g=h.some(e=>e.renderAskUserQuestion),f=[],y=[],b=!1!==s.enableComponentStreaming,v=!1!==s.approval,x=[],C=s.messageActions,S=!0===C?.showRegenerate&&!1!==C.enabled&&!0!==ho.current?.isStreaming()?function(e){for(let t=e.length-1;t>=0;--t){let r=e[t];if("user"===r.role||r.streaming)return null;if("assistant"===r.role&&!r.variant)return nn(e,r.id)?r.id:null}return null}(t):null,k=!0===C?.showEdit&&!1!==C.enabled,M=!0===C?.showQuote&&!1!==C.enabled,I=null,T=s.features?.reasoningDisplay?.completedVisibility,E=e=>"removed"===T||"removed-when-short"===T&&((e,t)=>{let r=t?.durationMs??15e3,n=t?.chars??1200;return"number"==typeof e.durationMs?e.durationMs<r:(e.chunks??[]).join("").length<n})(e,s.features?.reasoningDisplay?.shortThinkThreshold),L="removed"===s.features?.toolCallDisplay?.completedVisibility,B=e=>"reasoning"===e.variant&&"complete"===e.reasoning?.status?E(e.reasoning):L&&"tool"===e.variant&&"complete"===e.toolCall?.status;if(t.forEach(t=>{if(B(t))return;if(p.add(t.id),u.set(t.id,t.role),Ua===t.id&&Ga){let e=ll(t.id,t.role);return e.setAttribute("data-persona-message-edit-stub","true"),e.setAttribute("data-preserve-runtime","true"),o.appendChild(e),void(I={messageId:t.id,element:Ga.element})}let n=g&&It(t),d=v&&"approval"===t.variant&&!!t.approval,C=!n&&"assistant"===t.role&&!t.variant&&b&&oc(t);!d&&Da.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),Da.delete(t.id)),!C&&Wa.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),Wa.delete(t.id));let T=It(t)?`:${t.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:"",E={canRegenerate:S===t.id,canEdit:k&&on(t),canQuote:M&&!t.variant&&(t.content?.trim().length??0)>0},L=`${E.canRegenerate?"r":""}${E.canEdit?"e":""}${E.canQuote?"q":""}`,N=function(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)??"","string"==typeof e.toolCall?.args?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")}(t,Ja)+T+`:${L}`,R=n||d||C?null:function(e,t,r){let n=e.get(t);return n&&n.fingerprint===r?n.wrapper:null}(Ha,t.id,N);if(R)return o.appendChild(R.cloneNode(!0)),void(It(t)&&t.toolCall?.id&&!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),fo(t)));let H=null,$=h.find(e=>!!("reasoning"===t.variant&&e.renderReasoning||"tool"===t.variant&&e.renderToolCall||!t.variant&&e.renderMessage)),W=s.layout?.messages;if(It(t)&&!0===t.agentMetadata?.askUserQuestionAnswered)return $a.delete(t.id),void e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime");if(Vt(t)&&Jt(s).enabled)return;if(It(t)&&!1!==s.features?.askUserQuestion?.enabled){let e=h.find(e=>"function"==typeof e.renderAskUserQuestion);if(e&&ho.current){let r=$a.get(t.id),n=r!==N,a=null;if(n){let{payload:r,complete:n}=Et(t),o=t.id,i=()=>ho.current?.getMessages().find(e=>e.id===o);a=e.renderAskUserQuestion({message:t,payload:r,complete:n,resolve:e=>{let t=i();t&&ho.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=i();e?.agentMetadata?.awaitingLocalTool&&(ho.current?.markAskUserQuestionResolved(e),ho.current?.resolveAskUserQuestion(e,"(dismissed)"))},config:s})}if(n&&null===a&&null==r)return void(!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),fo(t)));let i=ll(t.id,t.role);return i.setAttribute("data-ask-plugin-stub","true"),i.setAttribute("data-preserve-runtime","true"),o.appendChild(i),void f.push({messageId:t.id,fingerprint:N,bubble:a})}return void(!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),fo(t)))}if(d){let r=A();if(!r)return void o.appendChild(ll(t.id,t.role));let n=h.find(e=>"function"==typeof e.renderApproval)??w,a=Da.get(t.id)!==N,i=null;if(a&&n?.renderApproval){let e=t.id,o=(t,r)=>{let n=ho.current?.getMessages().find(t=>t.id===e);n?.approval&&("webmcp"===n.approval.toolType?ho.current?.resolveWebMcpApproval(n.id,t):ho.current?.resolveApproval(n.approval,t,r))};i=n.renderApproval({message:t,defaultRenderer:()=>r.createApprovalBubble(t,s,c),config:s,approve:e=>o("approved",e),deny:e=>o("denied",e)})}if(!a||null!==i){let e=ll(t.id,t.role);return e.setAttribute("data-approval-plugin-stub","true"),e.setAttribute("data-preserve-runtime","true"),o.appendChild(e),void x.push({messageId:t.id,fingerprint:N,bubble:i})}e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),Da.delete(t.id),H=r.createApprovalBubble(t,s,c)}else if($)if("reasoning"===t.variant&&t.reasoning&&$.renderReasoning){if(!we)return;H=$.renderReasoning({message:t,defaultRenderer:()=>hl(t,s,l),config:s})}else if("tool"===t.variant&&t.toolCall&&$.renderToolCall){if(!xe)return;H=$.renderToolCall({message:t,defaultRenderer:()=>xl(t,s,i),config:s})}else $.renderMessage&&(H=$.renderMessage({message:t,defaultRenderer:()=>{let e=$i(t,r,W,s.messageActions,0,{loadingIndicatorRenderer:a,widgetConfig:s,actionEligibility:E});return"user"!==t.role&&P(e,t,s,va),e},config:s}));if(!H&&C){let n=ac(t);if(n){let a=Wa.get(t.id),i=a!==N,l=!1!==s.wrapComponentDirectiveInBubble&&!1!==Nl.getOptions(n.component)?.bubbleChrome,d=null;if(i){let o=rc(n,{config:s,message:t,transform:r});if(o&&"PersonaArtifactInline"===n.component){let r=o.hasAttribute("data-artifact-inline")?o:o.querySelector("[data-artifact-inline]"),n=r?.getAttribute("data-artifact-inline")??"",a=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(n):n,s=n?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${a}"]`)??null:null;r&&s&&s!==r&&_l()?.hasLiveInlineArtifactBlock(s)&&(r===o?o=s:r.replaceWith(s))}if(o)if(l){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 n=document.createElement("div");n.className="persona-mb-3 persona-text-sm persona-leading-relaxed",n.innerHTML=r({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(n)}e.appendChild(o),d=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 n=document.createElement("div");n.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",n.innerHTML=r({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(n)}e.appendChild(o),d=e}}if(d||null!=a){let e=ll(t.id,t.role);return e.setAttribute("data-component-directive-stub","true"),e.setAttribute("data-preserve-runtime","true"),o.appendChild(e),void y.push({messageId:t.id,fingerprint:N,bubble:d})}}}if(!H)if("reasoning"===t.variant&&t.reasoning){if(!we)return;H=hl(t,s,l)}else if("tool"===t.variant&&t.toolCall){if(!xe)return;H=xl(t,s,i)}else if("approval"===t.variant&&t.approval){if(!1===s.approval)return;let e=A();if(!e)return;H=e.createApprovalBubble(t,s,c)}else{let e=s.layout?.messages;H=e?.renderUserMessage&&"user"===t.role?e.renderUserMessage({message:t,config:s,streaming:!!t.streaming}):e?.renderAssistantMessage&&"assistant"===t.role?e.renderAssistantMessage({message:t,config:s,streaming:!!t.streaming}):$i(t,r,e,s.messageActions,0,{loadingIndicatorRenderer:a,widgetConfig:s,actionEligibility:E}),"user"!==t.role&&H&&P(H,t,s,va)}let D=ll(t.id,t.role);D.appendChild(H),function(e,t,r,n){e.set(t,{fingerprint:r,wrapper:n})}(Ha,t.id,N,D),o.appendChild(D)}),at.composerOverlay&&at.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(e=>{let t=e.getAttribute("data-persona-ask-sheet-for");t&&!m.has(t)&&zt(at.composerOverlay,t)}),s.features?.toolCallDisplay?.grouped){let e=[],r=[],a="summary"===s.features.toolCallDisplay.groupedMode;t.forEach(t=>{if("tool"===t.variant&&t.toolCall&&xe){if(L&&"complete"===t.toolCall.status)return;r.push(t)}else("reasoning"!==t.variant||we&&("complete"!==t.reasoning?.status||!E(t.reasoning)))&&((r.length>1||a&&r.length>0)&&e.push(r),r=[])}),(r.length>1||a&&r.length>0)&&e.push(r),e.forEach(e=>{let t=e.map(e=>Array.from(o.children).find(t=>t instanceof HTMLElement&&t.getAttribute("data-wrapper-id")===e.id)).filter(e=>!!e);if(t.length<(a?1:2))return;let r=ll(`tool-group-${e[0].id}`,"assistant");if(r.setAttribute("data-persona-tool-group-row","true"),"collapsible"===s.features?.toolCallDisplay?.groupedMode){let o=`tool-group-${e[0].id}`,a=e.some(e=>"complete"!==e.toolCall?.status),l={...e[0],id:o,toolCall:{id:o,name:`${e.length} tools`,status:a?"running":"complete",chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>!1===e.toolCall?.success)}};n.add(o),d.observe(l,"tool",i,s.features.toolCallDisplay);let c=`${a?"Using":"Used"} ${e.length} tools`,p=s.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:c,config:s}),u=ie(l,s,i.has(o),p??c);return u.bubble.classList.add("persona-tool-group"),u.body.dataset.personaToolGroupStack="true",t[0].before(r),r.appendChild(u.bubble),void t.forEach((e,t)=>{e.style.setProperty("--persona-message-row-max-width","100%"),e.style.setProperty("--persona-activity-stagger",40*t+"ms"),e.classList.add("persona-activity-group-child"),u.body.appendChild(e)})}let l=document.createElement("div");l.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",l.setAttribute("data-persona-tool-group","true");let c=document.createElement("div");c.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",c.id=`tool-group-summary-${e[0].id}`;let p=`Called ${e.length} ${1===e.length?"tool":"tools"}`,u=s.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:p,config:s});((e,t)=>null!=t&&("string"==typeof t?(e.textContent=t,!0):(e.appendChild(t),!0)))(c,u)||(c.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"),l.appendChild(c),a||l.appendChild(h),r.appendChild(l),t[0].before(r),t.forEach((e,r)=>{if(a)return void e.remove();e.style.setProperty("--persona-message-row-max-width","100%");let n=document.createElement("div");n.className="persona-tool-group-item persona-relative",n.setAttribute("data-persona-tool-group-item","true"),r<t.length-1&&n.setAttribute("data-persona-tool-group-connector","true"),n.appendChild(e),h.appendChild(n)})})}d.prune(n),function(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}(Ha,p);let N=e=>"tool"===e.variant&&!xe||"reasoning"===e.variant&&!we||B(e),R=t.some(e=>"assistant"===e.role&&e.streaming&&!N(e)),H=t.length-1;for(;H>=0&&N(t[H]);)H--;let $=H>=0?t[H]:void 0,W=H<t.length-1,D="assistant"===$?.role&&!$.streaming&&"approval"!==$.variant&&!W;if(Ra&&t.some(e=>"user"===e.role)&&!R&&!D){let e={config:s,streaming:!0,location:"standalone",defaultRenderer:Ti},t=h.find(e=>e.renderLoadingIndicator),r=null;if(t?.renderLoadingIndicator&&(r=t.renderLoadingIndicator(e)),null===r&&s.loadingIndicator?.render&&(r=s.loadingIndicator.render(e)),null===r&&(r=Ti()),r){let e=document.createElement("div"),t=!1!==s.loadingIndicator?.showBubble,n=s.layout?.messages?.layout??"bubble";e.className=t?Pi("assistant",n).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))","flat"!==n&&(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(r);let a=ll("typing-indicator","assistant");a.appendChild(e),o.appendChild(a)}}if(!Ra&&t.length>0){let e=t[t.length-1],r={config:s,lastMessage:e,messageCount:t.length},n=h.find(e=>e.renderIdleIndicator),a=null;if(n?.renderIdleIndicator&&(a=n.renderIdleIndicator(r)),null===a&&s.loadingIndicator?.renderIdle&&(a=s.loadingIndicator.renderIdle(r)),a){let e=document.createElement("div");e.className=!1===s.loadingIndicator?.showBubble?["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=ll("idle-indicator","assistant");t.appendChild(e),o.appendChild(t)}}if(function(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)})}(o),rs(e,o),ze(e),I){let{messageId:t,element:r}=I,n=e.querySelector(`#wrapper-${t}`);n&&r.parentElement!==n&&(il(n,u.get(t)??"user"),n.replaceChildren(r))}if(f.length>0)for(let{messageId:t,fingerprint:r,bubble:n}of f){let o=e.querySelector(`#wrapper-${t}`);o&&(il(o,u.get(t)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),$a.set(t,r)))}if($a.size>0)for(let e of $a.keys())p.has(e)||$a.delete(e);if(y.length>0)for(let{messageId:t,fingerprint:r,bubble:n}of y){let o=e.querySelector(`#wrapper-${t}`);o&&(il(o,u.get(t)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),Wa.set(t,r)))}if(Wa.size>0)for(let e of Wa.keys())p.has(e)||Wa.delete(e);if(x.length>0)for(let{messageId:t,fingerprint:r,bubble:n}of x){let o=e.querySelector(`#wrapper-${t}`);o&&(il(o,u.get(t)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),Da.set(t,r)))}if(Da.size>0)for(let e of Da.keys())p.has(e)||Da.delete(e)})(e,t,r),Dn()},yl=null,bl=()=>{if(yl)return;let t=e=>{let t=e.composedPath();t.includes(rt)||ot&&t.includes(ot)||Rl(!1,"user")};yl=t,(e.ownerDocument??document).addEventListener("pointerdown",t,!0)},vl=()=>{yl&&=((e.ownerDocument??document).removeEventListener("pointerdown",yl,!0),null)};ia.push(()=>vl());let Cl=null,Sl=()=>{if(Cl)return;let t=e=>{"Escape"===e.key&&(e.isComposing||Rl(!1,"user"))};Cl=t,(e.ownerDocument??document).addEventListener("keydown",t,!0)},kl=()=>{Cl&&=((e.ownerDocument??document).removeEventListener("keydown",Cl,!0),null)};ia.push(()=>kl());let Al=!1,Ml=new Set,El=()=>s.launcher?.composerBar?.peek?.streamAnimation||s.features?.streamAnimation,Ll=()=>{if(!se())return;let t=at.peekBanner,r=at.peekTextNode;if(!t||!r)return;if(ue)return void t.classList.remove("persona-pill-peek--visible");let n,o=va?.getMessages()??[];for(let e=o.length-1;e>=0;e--){let t=o[e];if("assistant"===t.role&&t.content){n=t;break}}if(!n)return void t.classList.remove("persona-pill-peek--visible");let a=n.content,s=!!n.streaming,i=El(),l=ms(i),d="none"===l.type?null:ha(l.type,i?.plugins),c=!0===d?.isAnimating?.(n),p=null!==d&&(s||c);p&&d&&!Ml.has(d.name)&&(Ns(d,e),Ml.add(d.name));let u=p&&d?.containerClass?d.containerClass:null,h=r.dataset.personaPeekStreamClass??null;h&&h!==u&&(r.classList.remove(h),delete r.dataset.personaPeekStreamClass),u&&h!==u&&(r.classList.add(u),r.dataset.personaPeekStreamClass=u),p?(r.style.setProperty("--persona-stream-step",`${l.speed}ms`),r.style.setProperty("--persona-stream-duration",`${l.duration}ms`)):(r.style.removeProperty("--persona-stream-step"),r.style.removeProperty("--persona-stream-duration"));let m=p?ws(a,l.buffer,d,n,s):a;if(!p||"skeleton"!==l.placeholder||!s||m&&m.trim()){let e=Math.max(0,m.length-100),o=m.length>100?m.slice(-100):m,a=ke(o);if(p&&d){let s=a;("char"===d.wrap||"word"===d.wrap)&&(s=Is(a,d.wrap,`peek-${n.id}`,{skipTags:d.skipTags,startIndex:e}));let i=document.createElement("div");if(i.innerHTML=s,d.useCaret&&o.length>0){let e=Ts(),t=i.querySelectorAll(".persona-stream-char, .persona-stream-word"),r=t[t.length-1];r?.parentNode?r.parentNode.insertBefore(e,r.nextSibling):i.appendChild(e)}rs(r,i),d.onAfterRender?.({container:r,bubble:t,messageId:n.id,message:n,speed:l.speed,duration:l.duration})}else{let e=m.length>100?`…${o}`:o;r.textContent!==e&&(r.textContent=e)}}else{let e=document.createElement("div"),t=Es();t.classList.add("persona-pill-peek__skeleton"),e.appendChild(t),rs(r,e)}let g=Ra||Al;t.classList.toggle("persona-pill-peek--visible",g)};if(se()){let e=at.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),Rl(!0,"user")};e.addEventListener("pointerdown",t),ia.push(()=>{e.removeEventListener("pointerdown",t)})}let t=()=>{Al||(Al=!0,Ll())},r=()=>{Al&&(Al=!1,Ll())};nt.addEventListener("pointerenter",t),nt.addEventListener("pointerleave",r),ia.push(()=>{nt.removeEventListener("pointerenter",t),nt.removeEventListener("pointerleave",r)}),ot&&(ot.addEventListener("pointerenter",t),ot.addEventListener("pointerleave",r),ia.push(()=>{ot.removeEventListener("pointerenter",t),ot.removeEventListener("pointerleave",r)}))}let Pl=()=>{if(ue&&ml(),!pe())return;if(se()){let e=(s.launcher?.composerBar??{}).expandedSize??"anchored",t=ue?"expanded":"collapsed";return rt.dataset.state=t,rt.dataset.expandedSize=e,ot&&(ot.dataset.state=t,ot.dataset.expandedSize=e),rt.style.removeProperty("display"),rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),nt.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),(e=>{let t=s.launcher?.composerBar??{},r=t.expandedSize??"anchored",n=t.bottomOffset??"16px",o=t.collapsedMaxWidth,a=t.expandedMaxWidth??"880px",i=t.expandedTopOffset??"5vh",l=t.modalMaxWidth??"880px",d=t.modalMaxHeight??"min(90vh, 800px)",c="calc(100vw - 32px)",p=rt.style;if(p.left="",p.right="",p.top="",p.bottom="",p.transform="",p.width="",p.maxWidth="",p.height="",p.maxHeight="",ot){let e=ot.style;e.bottom=n,e.width=o??""}e&&"fullscreen"!==r&&("modal"===r?(p.top="50%",p.left="50%",p.transform="translate(-50%, -50%)",p.bottom="auto",p.right="auto",p.width=l,p.maxWidth=c,p.maxHeight=d,p.height=d):(p.left="50%",p.transform="translateX(-50%)",p.bottom=`calc(${n} + var(--persona-pill-area-height, 80px))`,p.top=i,p.width=a,p.maxWidth=c))})(ue),st.style.display=ue?"flex":"none",_n(),ue?(bl(),Sl()):(vl(),kl()),void Ll()}let t=Gs(s),r=e.ownerDocument.defaultView??window,n=s.launcher?.mobileBreakpoint??640,o=s.launcher?.mobileFullscreen??!0,a=r.innerWidth<=n,i=o&&a&&X,l=Js(s).reveal;ue?(rt.style.removeProperty("display"),rt.style.display=t?"flex":"",rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),nt.classList.remove("persona-scale-95","persona-opacity-0"),nt.classList.add("persona-scale-100","persona-opacity-100"),zp?(zp.setPanelOpen(!0),zp.element.style.display="none"):qp&&(qp.style.display="none")):(t?!t||"overlay"!==l&&"push"!==l||i?(rt.style.setProperty("display","none","important"),rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),nt.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(rt.style.removeProperty("display"),rt.style.display="flex",rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),nt.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(rt.style.display="",rt.classList.add("persona-pointer-events-none","persona-opacity-0"),nt.classList.remove("persona-scale-100","persona-opacity-100"),nt.classList.add("persona-scale-95","persona-opacity-0")),zp?(zp.setPanelOpen(!1),zp.element.style.display=t?"none":""):qp&&(qp.style.display=t?"none":""))},Rl=(t,r="user")=>{if(!pe()||ue===t)return;let n=ue;ue=t,Pl();let o=(()=>{let t=s.launcher?.sidebarMode??!1,r=e.ownerDocument.defaultView??window,n=s.launcher?.mobileFullscreen??!0,o=s.launcher?.mobileBreakpoint??640,a=r.innerWidth<=o,i=Gs(s)&&n&&a,l=se()&&"fullscreen"===(s.launcher?.composerBar?.expandedSize??"fullscreen");return t||n&&a&&X||i||l})();if(ue&&o){if(!la){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&(la=Ds(r,s.launcher?.zIndex??1e5))}da||=zs(e.ownerDocument)}else ue||(la?.(),la=null,da?.(),da=null);ue&&(Up(),Vi()||("follow"===_t()?Ni(!0):Fi()));let a={open:ue,source:r,timestamp:Date.now()};ue&&!n?R.emit("widget:opened",a):!ue&&n&&R.emit("widget:closed",a),R.emit("widget:state",{open:ue,launcherEnabled:X,voiceActive:Fs.active,streaming:va.isStreaming()})},Hl={inputDisabled:!1,sendDisabled:!1},$l=()=>Hl.inputDisabled,Wl=()=>ce(s.voiceRecognition?.provider)&&!!va&&(va.isBargeInActive()||["listening","processing","speaking"].includes(va.getVoiceStatus())),Dl=()=>Hl.inputDisabled||Hl.sendDisabled;function Fl(){if(!ht)return;if("streaming"===Cr.getState().phase)return void(ht.disabled=!1);let e=!!vr&&!vr.isReady();ht.disabled=Dl()||e}function Ol(){if(!Nt)return;let e=Cr.getState(),t="when-text"===s.sendButton?.visibility&&"streaming"!==e.phase&&0===e.text.trim().length&&0===e.attachments.length;Nt.toggleAttribute("data-persona-send-hidden",t)}function zl(){let e=ro(s.composer?.inputDisabled),t=ro(s.composer?.sendDisabled);Hl={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},Cr.setInputDisabled(e.disabled),Cr.setSendDisabled(t.disabled);let r="streaming"===Cr.getState().phase,n=e.disabled,o=r||n;ut&&(ut instanceof HTMLTextAreaElement?ut.disabled=n:ut.setAttribute("contenteditable",n?"false":"true"),ut.setAttribute("aria-disabled",n?"true":"false")),Wt&&(Wt.disabled=n),Ft&&(Ft.disabled=n);for(let e of wr?.affordanceButtons??[])e.querySelectorAll("button").forEach(e=>{e.disabled=n});Ht&&(Ht.disabled=n||r&&!Wl()),ba.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute("data-disabled",o),e instanceof HTMLButtonElement||e.setAttribute("aria-disabled",o?"true":"false")}),e.buttons.forEach(e=>{e.disabled=o})}),ud.forEach(e=>{e.toggleAttribute("data-disabled",o),e instanceof HTMLButtonElement?e.disabled=o:e.setAttribute("aria-disabled",o?"true":"false"),e.querySelectorAll("button").forEach(e=>{e.disabled=o})}),Tt.dataset.personaComposerStreaming=r?"true":"false",Tt.dataset.personaComposerInputDisabled=n?"true":"false",Tt.dataset.personaComposerSendDisabled=Dl()?"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=r)}),Fl(),function(){let e=(Hl.inputDisabled?Hl.inputReason:void 0)??(Hl.sendDisabled?Hl.sendReason:void 0);if(se()){let t=mt??Tt;e?t.setAttribute("title",e):t.removeAttribute("title"),Tt.toggleAttribute(cc,!!e)}else if(e)gt.setAttribute("role","status"),gt.setAttribute("aria-live","polite"),gt.setAttribute(cc,""),gt.removeAttribute(pc),gt.textContent=e,le(gt,s.statusIndicator??{},"idle");else if(gt.hasAttribute(cc)&&(gt.removeAttribute("role"),gt.removeAttribute("aria-live"),gt.removeAttribute(cc),y)){let e=va.getStatus();et(gt,Ze(e),s.statusIndicator??{},e)}}()}let ql=e=>{Cr.setStreaming(e),Rt(e?"stop":"send"),zl()},Gl=()=>{Fs.active||ut&&ut.focus()};R.on("widget:opened",()=>{s.autoFocusInput&&setTimeout(()=>Gl(),200)});let Kl=null,Jl=!1,Zl=!ft.hidden,ed=null,td=!D,rd=null;ia.push(()=>{rd?.cancel(),rd=null});let nd,od,ad=t=>{let r=(e=>(e??[]).some(e=>"user"===e.role)?"active":"empty")(t);if(r===ur)return;ur=r,e.setAttribute("data-persona-conversation-state",r);let n=mr();yr(),td&&(rd?.cancel(),rd=Gi(Tt,"active"===r?n:mr(),"active"===r?"drop":"rise","centered"===pr().layout?320:260)),al()},sd=null,id=null,ld=null,dd=!1,cd=e=>{let t=pr(),r=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??"bottom"}|${t.align??""}|${t.iconPlacement}|${t.kicker??""}|${t.title}|${t.subtitle}`;(r!==sd||t.icon!==nd)&&(sd=r,nd=t.icon,Di({host:ft,iconHolder:yt,kicker:vt,title:wt,subtitle:xt,starterSuggestions:dt},t));let n=void 0===t.message?null:`${s.layout?.messages?.layout??"bubble"}|${t.message}`;n!==id&&(id=n,_i(bt,t.message,s));let o=e??(va?va.getMessages():s.initialMessages);ad(o);let a=Jl,i=!a&&Xi(t,o),l=i!==Zl;if(Zl=i,ld)return ed?.cancel(),ed=null,a!==dd&&(dd=a,a?ji(it,ft,null):qi(it,ft,ld)),void Wi(it,ft,!a);if(l&&!i&&!a&&"on-first-message"===t.dismiss&&td)return void(ed=Ui(ft,e=>{ed===e&&(ed=null),!Zl&&!ld&&(Wi(it,ft,!1),al()),e?.cancel()}));if(ed){if(!i&&!a)return;ed.cancel(),ed=null}let d=!ft.hidden;Wi(it,ft,i),!i&&d&&al()},pd=[],ud=[],hd=!1,md=null,gd=()=>{ud.length=0;let e=pd.splice(0,pd.length);for(let t of e)try{t()}catch(e){console.warn("[persona] renderWelcome cleanup threw",e)}};ia.push(gd);let fd=(e,t)=>{let r=Xs(e,t);if(!r)return!0===s.debug&&console.warn("[persona] renderStarter received a suggestion with no label"),L("span");let n=s.suggestions?.starters,o=Zs({item:{...r,behavior:r.behavior??n?.behavior??"send"},index:t,surface:"starter",source:"config",variant:n?.variant??"card",streaming:!!y&&va.isStreaming(),config:s,plugins:h,chipsConfig:s.suggestionChipsConfig,session:va,getTextarea:()=>ut,eventTarget:ft,submitPrompt:Qc});return ud.push(o),o},yd=()=>{if(hd)return;hd=!0;let e=pr();md=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`,od=e.icon;try{gd(),ji(it,ft,ld),ld=null,dd=!1;let t=va?va.getMessages():s.initialMessages,r=Xi(e,t),n=0,o=null;for(let t of h)if(t.renderWelcome&&(o=t.renderWelcome({config:e,variant:e.variant,visible:r,defaultRenderer:()=>ft,sendMessage:e=>{if(!va||va.isStreaming())return;let t=e.trim();t&&va.sendMessage(t)},requestRender:()=>yd(),renderStarter:e=>fd(e,n++),storage:b(t.id),onCleanup:e=>{pd.push(e)}}),o))break;o&&o!==ft&&(ld=o,qi(it,ft,o))}finally{hd=!1}cd()},bd=()=>{cd(),an||(ut.placeholder=function(e,t){if(t?.length&&0!==e.length)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}(Cr.getState().activeModeIds,s.composer?.modes)??s.copy?.inputPlaceholder??"How can I help...",!s.sendButton?.useIcon&&!va?.isStreaming()&&(ht.textContent=s.copy?.sendButtonLabel??"Send")),ut.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ut.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},xd=!!s.setStoredConversationId,Cd=e=>U(t=>{let r={...t};return delete r[e],r}),Sd=e=>{let t=W[e];return"string"==typeof t?t:null},kd=()=>{let e=W.durableResume;if(!e||"object"!=typeof e)return null;let t=e;return"string"==typeof t.executionId&&t.executionId.length>0&&"string"==typeof t.after&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};s.clientToken&&(s={...s,getStoredSessionId:()=>Sd("sessionId"),setStoredSessionId:e=>{U(t=>({...t,sessionId:e}))},clearStoredSessionId:s.clearStoredSessionId??(()=>Cd("sessionId")),getStoredConversationId:s.getStoredConversationId??(()=>Sd("conversationId")),setStoredConversationId:s.setStoredConversationId??(e=>{U(t=>({...t,conversationId:e}))}),clearStoredConversationId:s.clearStoredConversationId??(()=>Cd("conversationId"))});let Ad=()=>s.clientToken??null,Ed=e=>qd(e,Me(),!1===s.persistState),Ld=Ad(),Pd=Ld?Ed(Ld):null,Rd={...Pd?{visitorStore:Pd}:{},historyBootstrapReady:!0!==s.features?.history?.enabled||Zd()?F:Promise.all([F,z]).then(()=>{}),getStoredMessageCursor:()=>Sd("historyMessageCursor"),setStoredMessageCursor:e=>{null===e?Cd("historyMessageCursor"):U(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:()=>{let e=W.pendingDisplayProjections;if(!e||"object"!=typeof e)return null;let t=e;return"string"==typeof t.conversationId&&Array.isArray(t.messageIds)?{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>"string"==typeof e)}:null},setPendingDisplayProjections:e=>{e?U(t=>({...t,pendingDisplayProjections:e})):Cd("pendingDisplayProjections")},getStoredResumableHandle:kd,setStoredResumableHandle:e=>{e?U(t=>({...t,durableResume:e})):Cd("durableResume")},shouldResumeDurableConversation:()=>$&&null!==kd(),...xd?{}:{getStoredConversationRevision:()=>Sd("conversationRevision"),setStoredConversationRevision:e=>{null===e?Cd("conversationRevision"):U(t=>({...t,conversationRevision:e}))}}};if($){let t=s.onExecutionState,r=e.ownerDocument.defaultView,n=!1,o=()=>n=!0,a=()=>n=!1;r?.addEventListener("pagehide",o),r?.addEventListener("pageshow",a),ia.push(()=>{r?.removeEventListener("pagehide",o),r?.removeEventListener("pageshow",a)}),s={...s,reconnectStream:s.reconnectStream??(e=>va.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!n)&&Rd.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let $d=()=>{let e=Ad();if(e&&Pd?.matches(e,Me(),!1===s.persistState)||!e&&!Pd)return;Pd?.destroy(),Pd=e?Ed(e):null;let t={...Rd};Pd?t.visitorStore=Pd:delete t.visitorStore,Rd=t,va.setHistoryInternals(Rd)},Dd=null,Fd=(e,t)=>{if(Object.is(e,t))return!0;if(null===e||null===t||"object"!=typeof e||"object"!=typeof t)return!1;if(Array.isArray(e)||Array.isArray(t))return!(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)&&e.every((e,r)=>Fd(e,t[r]));let r=e,n=t,o=Object.keys(r),a=Object.keys(n);return o.length===a.length&&o.every(e=>Object.prototype.hasOwnProperty.call(n,e)&&Fd(r[e],n[e]))},zd=e=>{let{content:t,rawContent:r,llmContent:n,...o}=e;return o},jd=e=>!("assistant"!==e.role||!0!==e.streaming||e.variant||e.toolCall||e.tools||e.approval||e.reasoning||e.contentParts||e.stopReason||oc(e)),_d=null,Vd=null,Gd=null,Kd=null,Jd=null,Qd=e=>{let t,r;_d=e,Vd=null;for(let n=e.length-1;n>=0;--n){let o=e[n];if(!t&&"user"===o.role&&(t=o),!r&&"assistant"===o.role&&(r=o),!Vd&&jd(o)&&(Vd={index:n,id:o.id}),t&&r&&Vd)break}gl(lt,e,fe),_l()?.updateInlineArtifactBlocks(lt,Kn.artifacts,{suppressTransition:Ra}),Dd??=setInterval(()=>{let e=lt.querySelectorAll("[data-tool-elapsed]");if(0===e.length)return clearInterval(Dd),void(Dd=null);let t=Date.now();e.forEach(e=>{let r=Number(e.getAttribute("data-tool-elapsed"));r&&(e.textContent=e.closest(".persona-activity-row")?ae(t-r):or(t-r))})},100),cd(e),Ba(e),Ni(!Ra),(e=>{let t=new Map;e.forEach(e=>{let r=Rs.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!r&&"assistant"===e.role&&(R.emit("assistant:message",e),!hs&&("anchor-top"!==_t()||Xt())&&Mi()&&(ds+=1,Si(),Ei(),dr(1===ds?"1 new message below.":`${ds} new messages below.`))),"assistant"===e.role&&r?.streaming&&!1===e.streaming&&R.emit("assistant:complete",e),"approval"===e.variant&&e.approval&&(r?"pending"!==e.approval.status&&R.emit("approval:resolved",{approval:e.approval,decision:e.approval.status}):R.emit("approval:requested",{approval:e.approval,message:e}))}),Rs.clear(),t.forEach((e,t)=>{Rs.set(t,e)})})(e),0===e.length&&(Yi(),fs=!0,xs=!1,Cs=null,Ss=!1),!us||hs?(us=!0,gs=t?.id??null,As=r?.id??null):t&&t.id!==gs?(gs=t.id,(e=>{let t=_t();"follow"===t?(Bi(),Ni(!0)):"anchor-top"===t&&(fs=!1,xs=!0,Ss=!1,Cs=e,ol(e))})(t.id)):r&&r.id!==As&&"anchor-top"===_t()&&(xs?fs=!1:(fs=!0,Yi(),Bi(),Ni(!0))),r&&(As=r.id),(e=>{if("anchor-top"!==_t()||!xs||Ss||zi())return;let t=null===gs;for(let r of e)if(t){if(os(r)){if(r.id===Cs||!sl(r.id))return;return Cs=r.id,void ol(r.id)}}else r.id===gs&&(t=!0)})(e);let n=Fs.lastUserMessageId;t&&t.id!==n&&(Fs.lastUserMessageId=t.id,R.emit("user:message",t)),Fs.lastUserMessageWasVoice=!!t?.viaVoice,(e=>{if(!$)return si(e);Jd=e,queueMicrotask(()=>{Jd===e&&(Jd=null,si(e))})})(e),Ll()},Xd=()=>{null!==Kd&&(cancelAnimationFrame(Kd),Kd=null);let e=Gd;Gd=null,e&&Qd(e)},tc=()=>{null!==Kd&&cancelAnimationFrame(Kd),Kd=null,Gd=null};va=new In(s,{onMessagesChanged(e){(e=>{let t=Gd??_d;Ra&&t&&Vd&&((e,t,r)=>{if(e.length!==t.length)return!1;let n=e[r.index],o=t[r.index];return!(!n||!o||n.id!==r.id||o.id!==r.id)&&(!Object.is(n.content,o.content)||!Object.is(n.rawContent,o.rawContent)||!Object.is(n.llmContent,o.llmContent))&&jd(n)&&jd(o)&&Fd(zd(n),zd(o))})(t,e,Vd)?(Gd=e,null===Kd&&(Kd=requestAnimationFrame(()=>{Kd=null;let e=Gd;Gd=null,e&&Qd(e)}))):0===e.length?(tc(),Qd(e)):(Xd(),Qd(e))})(e)},onStatusChanged(e){let t=s.statusIndicator??{};et(gt,(e=>"idle"===e?t.idleText??Tr.idle:"connecting"===e?t.connectingText??Tr.connecting:"connected"===e?t.connectedText??Tr.connected:"error"===e?t.errorText??Tr.error:"paused"===e?t.pausedText??Tr.paused:"resuming"===e?t.resumingText??Tr.resuming:Tr[e])(e),t,e),Je()},onStreamingChanged(e){e||(0===va?.getMessages().length?tc():Xd()),Ra=e,ql(e),Je(),va&&gl(lt,va.getMessages(),fe),e||(Ni(!0),(()=>{if(!cs||cs.spacerHeight<=0)return;let e=Ji(cs.spacerHeight),t=Math.max(0,Math.round(it.scrollTop)+it.clientHeight-e+24);t<cs.spacerHeight&&(Ki(t),Ei())})(),La=!0,va&&Pa(va.getMessages(),Jt(s))),Ei(),dr(e?"Responding…":"Response complete."),Ll()},onVoiceStatusChanged(e){if(R.emit("voice:status",{status:e,timestamp:Date.now()}),"disconnected"!==e&&!ce(s.voiceRecognition?.provider))return;let t=va.getVoiceNotice();switch(t&&Uc(t,1e4),e){case"listening":if(!Hs){let e=va.getVoiceDisclosure();e&&(Hs=!0,se()?($s=ut.placeholder,ut.placeholder=e,dr(e)):Uc(e,1e4))}Mp(),Sp();break;case"processing":Mp(),kp();break;case"speaking":Mp(),Ap();break;default:"idle"===e&&va.isBargeInActive()?(Mp(),Sp(),Ht?.setAttribute("aria-label","End voice session")):(Fs.active=!1,Hs=!1,null!==$s&&(ut.placeholder=$s,$s=null),Mp(),_s("system"),js||Vs())}},onArtifactsState(e){Kn=e,0===e.artifacts.length&&(lo=!1),_l()?.updateInlineArtifactBlocks(lt,e.artifacts,{suppressTransition:Ra}),Xo(),si()},onHistoryStateChanged(e){Ue(e)},onHistoryNotice(e){Ke(e)},onReconnect(e){let{executionId:t,lastEventId:r}=e.handle;"paused"===e.phase?R.emit("stream:paused",{executionId:t,after:r}):"resuming"===e.phase?R.emit("stream:resuming",{executionId:t,after:r,attempt:e.attempt??1}):R.emit("stream:resumed",{executionId:t,after:r})}},Rd),ho.current=va,ia.push(()=>va.cancel()),ia.push(()=>{va.destroy(),Pd?.destroy(),Pd=null});let nc=null;if(va.onReadAloudChange((e,t)=>{Nn=e,Hn=t,Dn();let r=e??nc;e&&(nc=e);let n=r?va.getMessages().find(e=>e.id===r)??null:null;R.emit("message:read-aloud",{messageId:r,message:n,state:t,timestamp:Date.now()}),"idle"===t&&(nc=null)}),y=!0,us=!0,!0===s.voiceRecognition?.enabled&&ce(s.voiceRecognition.provider))try{va.setupVoice()}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",e)}let sc=null,uc=null,vc=!1,xc=va.getHistoryState(),Cc=()=>!0===s.features?.history?.enabled,Sc=e=>{e&&(sr.textContent="",sr.textContent=e)},kc=()=>{g.forEach(e=>e()),g=[];let t=sc,r=t?.railCollapseShortcut();t&&r&&g.push(m.register({id:"history-rail-collapse",combo:r.combo,scope:"page"===s.features?.history?.rail?.collapseShortcutScope?"page":"widget",when:()=>qe&&"rail"===je&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of s.layout?.header?.trailingActions??[])t.shortcut&&g.push(m.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let r=e.querySelector(`[data-persona-header-action="${t.id}"]`);r?r.click():s.layout?.header?.onAction?.(t.id)}}));for(let e of h)for(let t of e.shortcuts??[])g.push(m.register({...t,id:`${e.id}:${t.id}`}))};kc();let Ac=null,Mc=!1,Ic=()=>{if(!kt)return;let e="conversation"===s.layout?.header?.titleSource,t=e&&Ac?.trim()||null;kt.textContent=t??s.launcher?.title??"Chat Assistant";let r=kt.closest(".persona-combo-btn");if(!r)return;let n=!e||null!==va.getActiveConversationId();r.setAttribute("data-persona-menu-locked",n?"false":"true"),r.setAttribute("aria-haspopup",n?"true":"false"),n||r.setAttribute("aria-expanded","false"),r.style.cursor=n?"pointer":"default";let o=r.querySelector("svg");o&&(o.style.display=n?"":"none")};Ic(),st.addEventListener("persona:title-menu-builtin",e=>{let t=e.detail?.actionId,r=va.getActiveConversationId();r&&("delete"===t?Pc(e=>e.requestDeleteConversation(r)):"star"===t&&va.canUpdateConversations()&&Pc(e=>e.updateHistoryConversation(r,{starred:!Mc})).catch(()=>{}))}),Ue=e=>{xc=e,sc?.historySurface?.view.setNewConversationRequired("new_conversation_required"===e.recovery),ql(e.sendBlocked||Ra),sc?.syncEarlierMessagesPill()},Ke=e=>{("history_continuity_reset"===e.code||"conversation_deleted_recovered"===e.code)&&(Ha.clear(),Yi(),Bi()),Sc(e.message),sc?.historySurface?.view.refresh()};let Tc={get actionManager(){return Q},get activeConversationTitle(){return Ac},announceHistory:Sc,get applyRailChrome(){return Ve},set applyRailChrome(e){Ve=e},get artifactSplitRoot(){return So},get body(){return it},get config(){return s},get container(){return st},get conversationOpenPendingEl(){return Kl},set conversationOpenPendingEl(e){Kl=e},get conversationOpenTakeover(){return Jl},set conversationOpenTakeover(e){Jl=e},currentKeyPrefix:Me,destroyCallbacks:ia,eventBus:R,get footer(){return Tt},get header(){return Mt},get historyChromeSync(){return Je},set historyChromeSync(e){Je=e},historyFeatureEnabled:Cc,get historyInternals(){return Rd},set historyInternals(e){Rd=e},get historyPresentation(){return je},set historyPresentation(e){je=e},get historySessionState(){return xc},get historyVisible(){return qe},set historyVisible(e){qe=e},get isStreaming(){return Ra},jumpToBottomInstant:Fi,get lastAppliedMessages(){return _d},set lastAppliedMessages(e){_d=e},get launcherEnabled(){return X},get launcherSurfaceInstance(){return zp},maybeFocusInput:Gl,messageCache:Ha,get messagesWrapper(){return lt},mount:e,get open(){return ue},panel:nt,panelElements:at,get persistentMetadata(){return W},set persistentMetadata(e){W=e},plugins:h,get reapplyHistoryHostChrome(){return _e},set reapplyHistoryHostChrome(e){_e=e},repinAnchoredMessage:al,resetAnchorState:Yi,restoreScrollPosition:Vi,resumeAutoScroll:Bi,runStorageMutation:ni,get session(){return va},setActiveConversationSummary:e=>{Mc=!0===e?.starred,(e=>{e!==Ac&&(Ac=e,Ic())})(e&&e.title.trim()||null),Ic()},storageAdapter:H,get suppressScrollSend(){return hs},set suppressScrollSend(e){hs=e},syncScrollToBottomButton:Ei,updateWelcome:cd,getHistoryProviderFactory:ec,historyErrors:{HistoryClientError:Er,HistoryProviderError:$r},isDockedMountMode:Gs,renderLucideIcon:K,loadHistoryView:Ud,createHeaderIconButton:ai,attachTooltip:Gn},Ec=e=>(!sc&&!vc&&(sc=e.createHistoryShell(Tc),sc.railCollapseShortcut()&&kc()),sc),Lc=()=>{if(sc)return Promise.resolve(sc);let e=Zd();return e?Promise.resolve(Ec(e)):(uc??=Yd().then(Ec,e=>{throw uc=null,e}),uc)},Pc=e=>{let t=Zd(),r=sc??(t?Ec(t):null);return r?e(r):Lc().then(t=>{if(!t)throw Error("[AgentWidget] The widget was destroyed");return e(t)})},Bc=()=>{sc?.syncHistoryPresentation()};ia.push(()=>{vc=!0}),Cc()&&Lc().catch(()=>{}).finally(O),s.clientToken&&(!0===s.features?.history?.enabled||"mount"===s.sessionInit)&&va.initClientSession().then(()=>{let e=sc;if(e?.historyAvailable())return va.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{sc?.syncEarlierMessagesPill()}).catch(e=>{s.debug&&console.warn("[AgentWidget] Pre-init client session failed:",e)});let Nc=()=>va.warmClientSession(),Rc=e=>{let t=s.sessionInit??"input",r=dn?.input??ut,n=e.target;r&&("input"===e.type?("input"===t||"focus"===t)&&n===r&&e.inputType&&r.value.trim():"focus"===t&&("keyup"===e.type?n===r&&"Tab"===e.key:(dn?.form??mt)?.contains(n)))&&Nc()},Hc=["input","pointerdown","keyup"];Hc.forEach(t=>e.addEventListener(t,Rc));let $c,Wc,Dc=()=>{let e=Wc;Wc=void 0;try{"function"==typeof e&&e()}catch{}},Fc=()=>{let t=s.clientToken&&"function"==typeof s.sessionInit?s.sessionInit:void 0;if(t!==$c){Dc(),$c=t;try{Wc=t?.({warm:Nc,mount:e})}catch{}}};Fc(),ia.push(()=>{Hc.forEach(t=>e.removeEventListener(t,Rc)),Dc()}),(Ce||s.onSSEEvent)&&va.setSSEEventCallback((e,t)=>{s.onSSEEvent?.(e,t),Fe(e,t)});let Oc=()=>{let e=s.resume??($?Rd.getStoredResumableHandle?.():null);e&&"function"==typeof s.reconnectStream&&va.resumeFromHandle(e)};D?D.then(e=>{if(e){if(e.metadata&&(W=gc(e.metadata),Q.syncFromMetadata()),e.messages?.length){hs=!0;try{va.hydrateMessages(e.messages)}finally{hs=!1}ml()}e.artifacts?.length&&va.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),gi(e.draft)}}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",e)}).finally(()=>{td=!0,B(),Oc()}):(gi(N),Oc());let zc=()=>{let e=ut.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>"mention"===e.kind)?e.contentSegments:void 0},qc=!1,jc=null,_c=()=>{ut.value="",ut.style.height="auto",kr(),tp()},Vc=null;function Uc(e,t=4e3){dr(e),!se()&&gt&&(gt.hasAttribute(cc)||(gt.setAttribute(pc,""),gt.setAttribute("role","status"),gt.setAttribute("aria-live","polite"),gt.textContent=e,le(gt,s.statusIndicator??{},"idle"),Vc&&clearTimeout(Vc),Vc=setTimeout(()=>{if(Vc=null,gt?.hasAttribute(pc)&&(gt.removeAttribute(pc),gt.removeAttribute("role"),gt.removeAttribute("aria-live"),y)){let e=va.getStatus();et(gt,Ze(e),s.statusIndicator??{},e)}},t)))}let Gc=(e={})=>{let t=(e.overrideText??ut?.value??"").trim();return e.resolveInlineCommand&&t?(wr?.takeInlineCommand(t)??Promise.resolve(null)).then(r=>Kc(e,t,r)):Kc(e,t,null)},Kc=(e,t,r)=>{if("action"===r?.kind)return _c(),wr?.clear(),void Ar();let n="server"===r?.kind?r.mentions:null,o="prompt"===r?.kind?r.sendText:t,a=e.pending?.contentParts;if(!function(e){return!(!0===e.inputDisabled||!0===e.sendDisabled||e.hasAttachments&&!e.attachmentsReady)&&(!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions)}({text:o,hasAttachments:(vr?.hasAttachments()??!1)||(a?.length??0)>0,attachmentsReady:vr?.isReady()??!0,hasMentions:wr?.hasMentions()??!1,hasServerMentions:!!n,inputDisabled:$l(),sendDisabled:Dl()}))return;let i=va.isStreaming()?Vr():"block";if("defer-one"===i&&!e.pending)return Cr.getState().pendingSubmission?void Uc("One message is already queued. Edit or remove it first."):void function(e){let t=Cr.getState(),r=vr?.hasAttachments()??!1,n=r?[...vr.getContentParts()]:[];r&&e.sendText&&n.push(xr(e.sendText)),Gr(Uo({text:e.sendText,contentParts:n.length?n:void 0,mentionRefs:[...wr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:zc(),options:{...t.selectedModelId&&{selectedModelId:t.selectedModelId},...t.activeModeIds.length>0&&{activeModeIds:[...t.activeModeIds]},...t.quote&&{quote:{...t.quote}}},viaVoice:e.intent.viaVoice})),!1!==e.intent.consumeDraft&&_c(),r&&vr.clearAttachments(),wr?.clear(),Ar(),t.quote&&zr(void 0),fi(),kn.release(),Mn(),dr("Message queued. It sends when the response finishes.")}({intent:e,sendText:o,serverMentions:n});let l={text:o,mentionRefs:[...wr?.getMentionRefs()??[],...n?.refs??[]],contentSegments:"prompt"===r?.kind?void 0:zc(),options:{...Cr.getState().selectedModelId&&{selectedModelId:Cr.getState().selectedModelId},...Cr.getState().activeModeIds.length>0&&{activeModeIds:[...Cr.getState().activeModeIds]},...Cr.getState().quote&&{quote:{...Cr.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(l.options={...e.pending.options},l.contentSegments=e.pending.contentSegments,l.mentionRefs=[...e.pending.mentionRefs],l.viaVoice=e.pending.viaVoice);let d=()=>{if(a?.length)return[...a];if(!vr?.hasAttachments())return;let e=[...vr.getContentParts()];return l.text&&e.push(xr(l.text)),e};l.contentParts=d();let c=()=>{Ka(),se()&&(ue||(s.launcher?.composerBar?.expandOnSubmit??1)&&Rl(!0,"auto"));let t=wr?.collectForSubmit()??null,r=((e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[r,n]=await Promise.allSettled([e.finalize(),t.finalize()]),o=[];return"fulfilled"===r.status?o.push(r.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",r.reason),"fulfilled"===n.status?o.push(n.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",n.reason),wc(o)}}:e:t)(t,n),o=d();!1!==e.consumeDraft&&_c();let a={selectedModelId:l.options.selectedModelId,activeModeIds:l.options.activeModeIds},c="interrupt"===i;c&&va.cancel(),va.sendMessage(l.text,{contentParts:o,mentions:r??void 0,contentSegments:l.contentSegments,viaVoice:l.viaVoice,composerOptions:a,...l.options.quote&&{quote:l.options.quote},...c&&{interrupt:!0}}),vr?.hasAttachments()&&vr.clearAttachments(),t&&wr?.clear(),Ar();let p=Cr.getState().activeModeIds,u=function(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&"once"!==(t.persistence??"sticky")).map(e=>e.id):[]}(p,s.composer?.modes);u.length!==p.length&&Nr(u),Cr.getState().quote&&zr(void 0),fi(),kn.release(),Mn()},p=s.composer?.onBeforeSend;if(!p)return void c();let u=new AbortController;jc=u;let h=e=>{jc=null,"error"===e.status?(e=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",e)})(e.error):"proceed"===e.status&&c()},m=Ko(p,l,u.signal);if(m instanceof Promise)return Cr.setPreparing(!0),m.then(h).finally(()=>Cr.setPreparing(!1));h(m)};Fn={regenerate:function(e){if(va.isStreaming())return;let t=nn(va.getMessages(),e);t&&(Ka(),va.resubmitFrom(t,{reason:"retry"})&&al())},edit:function(e){if(!0!==s.messageActions?.showEdit)return;let t=va.getMessages().find(t=>t.id===e);t&&on(t)&&Ua!==e&&(Ka(),Ua=e,Ga=Vo({messageId:e,initialText:t.content,onSave:t=>function(e,t){let r=Ga;Ua=null,Ga=null,r?.destroy(),Ha.delete(e),va.resubmitFrom(e,{reason:"edit",replacement:{text:t,mentionRefs:[],options:{}}})?al():gl(lt,va.getMessages(),fe)}(e,t),onCancel:()=>Ka()}),Ha.delete(e),gl(lt,va.getMessages(),fe),Ga.focus())},quote:e=>{let t=va.getMessages().find(t=>t.id===e)?.content?.trim();t&&(zr({text:t,messageId:e}),ut?.focus())}};let Jc=async e=>{if(!qc){qc=!0;try{await Gc({resolveInlineCommand:!0,...e})}finally{qc=!1}}};function Qc(e){Dl()||(_c(),Xc(e,{consumeDraft:!1}))}let Xc=(e,t)=>{if(qc)return;qc=!0;let r=()=>{qc=!1};try{let n=Gc({...t,overrideText:e});n instanceof Promise?n.finally(r):r()}catch(e){throw r(),e}},Yc=e=>{e.preventDefault(),va.isStreaming()?(va.cancel(),Pe?.reset(),Re?.update()):qc||Jc()},Zc={...ns},ep=!1,tp=()=>{Zc={...ns}},rp=e=>{"Escape"!==e.key||e.isComposing||e.composedPath().includes(st)&&(jc?(jc.abort(),jc=null,e.preventDefault(),e.stopImmediatePropagation()):va.isStreaming()&&(va.cancel(),Pe?.reset(),Re?.update(),tp(),e.preventDefault(),e.stopImmediatePropagation()))},np=null,op=!1,ap=null,sp=null,ip=()=>"review"===s.voiceRecognition?.completionBehavior;function lp(e){Ht?.setAttribute("data-state",e),"recording"===e?function(){if(null!==pp)return;if("function"!=typeof requestAnimationFrame)return void gp(y?va.getVoiceLevel()??cp:cp);let e=()=>{pp=requestAnimationFrame(e);let t=y?va.getVoiceLevel():null;null===t?gp(cp):(hp+=.3*(t-hp),gp(hp))};pp=requestAnimationFrame(e)}():yp()}let dp="--persona-voice-level",cp=.5,pp=null,up=-1,hp=0,mp=()=>{let e=[],t=$t??Ht?.parentElement??null;return t&&e.push(t),Tt&&e.push(Tt),e},gp=e=>{let t=Math.round(100*Math.max(0,Math.min(1,e)))/100;if(t!==up){up=t;for(let e of mp())e.style.setProperty(dp,String(t))}},fp=()=>{up=-1,hp=0;for(let e of mp())e.style.removeProperty(dp)};function yp(){null!==pp&&(cancelAnimationFrame(pp),pp=null),fp()}let bp=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,vp=(e="user")=>{if(op||va.isStreaming())return;let t=bp();if(!t)return;np=new t;let r=s.voiceRecognition??{},n=r.pauseDuration??2e3;np.continuous=r.provider?.browser?.continuous??!0,np.interimResults=!0,np.lang=r.provider?.browser?.language??"en-US";let o=ut.value;np.onresult=e=>{let t="",r="";for(let n=0;n<e.results.length;n++){let o=e.results[n],a=o[0].transcript;o.isFinal?t+=a+" ":r=a}let a=o+t+r;ut.value=a,kr(),ap&&clearTimeout(ap),(t||r)&&(ap=window.setTimeout(()=>{if(ut.value.trim()&&np&&op){if(wp(),ip())return;Jc({viaVoice:!0})}},n))},np.onerror=e=>{"no-speech"!==e.error&&wp()},np.onend=()=>{if(op){let e=ut.value.trim();!ip()&&e&&e!==o.trim()&&Jc({viaVoice:!0}),wp()}};try{if(np.start(),op=!0,Fs.active=!0,"system"!==e&&(Fs.manuallyDeactivated=!1),_s(e),Vs(),Mn(),Ht){let e=s.voiceRecognition??{};sp={backgroundColor:Ht.style.backgroundColor,color:Ht.style.color,borderColor:Ht.style.borderColor,iconName:e.iconName??"mic",iconSize:parseFloat(e.iconSize??"")||24};let t=e.recordingBackgroundColor,r=e.recordingIconColor,n=e.recordingBorderColor;if(Ht.classList.add("persona-voice-recording"),lp("recording"),Ht.style.backgroundColor=t??"var(--persona-voice-recording-bg, #ef4444)",Ht.style.color=r??"var(--persona-voice-recording-indicator, #ffffff)",r){let e=Ht.querySelector("svg");e&&e.setAttribute("stroke",r)}n&&(Ht.style.borderColor=n),Ht.setAttribute("aria-label","Stop voice recognition")}}catch{wp("system")}},wp=(e="user")=>{if(op){if(op=!1,ap&&=(clearTimeout(ap),null),np){try{np.stop()}catch{}np=null}if(Fs.active=!1,_s(e),Vs(),Mn(),Ht){if(Ht.classList.remove("persona-voice-recording"),lp("idle"),sp){Ht.style.backgroundColor=sp.backgroundColor,Ht.style.color=sp.color,Ht.style.borderColor=sp.borderColor;let e=Ht.querySelector("svg");e&&e.setAttribute("stroke",sp.color||"currentColor"),sp=null}Ht.setAttribute("aria-label","Start voice recognition")}}},xp=null,Cp=e=>{let t=t=>{xp??=t.createMicStateStyles({mic:()=>Ht,config:()=>s,session:()=>va,get original(){return sp},set original(e){sp=e},setMicState:lp,renderIcon:K,iconFallbackPx:24}),e(xp)},r=gn();r?t(r):mn().then(t,()=>{})},Sp=()=>Cp(e=>e.recording()),kp=()=>Cp(e=>e.processing()),Ap=()=>Cp(e=>e.speaking()),Mp=()=>Cp(e=>e.reset()),Ip=()=>{if(!$l())if(ce(s.voiceRecognition?.provider)){let e=va.getVoiceStatus(),t=va.getVoiceInterruptionMode();if("none"===t&&("processing"===e||"speaking"===e))return;if("cancel"===t&&("processing"===e||"speaking"===e))return void va.stopVoicePlayback();if(va.isBargeInActive())return va.stopVoicePlayback(),void va.deactivateBargeIn().then(()=>{Fs.active=!1,Fs.manuallyDeactivated=!0,Vs(),_s("user"),Mp()});va.toggleVoice().then(()=>{Fs.active=qs(),Fs.manuallyDeactivated=!Fs.active,Vs(),_s("user"),Fs.active?Sp():Mp()})}else if(op){let e=ut.value.trim();Fs.manuallyDeactivated=!0,Vs(),wp("user"),e&&!ip()&&Jc()}else Fs.manuallyDeactivated=!1,Vs(),vp("user")};Jr=Ip;let Tp=()=>va.prewarmVoice(),Ep=()=>{let e=s.voiceRecognition;return!0===e?.enabled&&(e.prewarm??(!!s.clientToken&&"hover"))},Lp=e=>{"hover"===Ep()&&Ht?.contains(e.target)&&Tp()},Pp=["pointerover","pointerdown","focusin"];Pp.forEach(t=>e.addEventListener(t,Lp));let Bp,Np,Rp=null,Hp=()=>{let e=Np;Np=void 0;try{"function"==typeof e&&e()}catch{}},$p=()=>{let t=Ep(),r="function"==typeof t&&Ht?t:void 0,n=r?Ht:null;if((r!==Bp||n!==Rp)&&(Hp(),Bp=r,Rp=n,r&&n))try{Np=r({warm:Tp,micButton:n,mount:e})}catch{}};$p(),ia.push(()=>{Pp.forEach(t=>e.removeEventListener(t,Lp)),Hp()}),Ht&&ia.push(()=>{ce(s.voiceRecognition?.provider)?(va.isVoiceActive()&&va.toggleVoice(),Mp()):wp("system")});let Wp=R.on("assistant:complete",()=>{Cr.getState().pendingSubmission&&setTimeout(()=>{va.isStreaming()||function(){let e=Cr.getState().pendingSubmission;e&&(Gr(void 0),Xc(e.text,{consumeDraft:!1,pending:e}))}()},0)});ia.push(Wp);let Dp=R.on("assistant:complete",()=>{Os&&(Fs.active||Fs.manuallyDeactivated||("assistant"!==Os||Fs.lastUserMessageWasVoice)&&setTimeout(()=>{!Fs.active&&!Fs.manuallyDeactivated&&(ce(s.voiceRecognition?.provider)?va.toggleVoice().then(()=>{Fs.active=va.isVoiceActive(),_s("auto"),va.isVoiceActive()&&Sp()}):vp("auto"))},600))});ia.push(Dp);let Fp=R.on("action:resubmit",()=>{setTimeout(()=>{va&&!va.isStreaming()&&va.continueConversation()},100)});ia.push(Fp);let Op=()=>{Rl(!ue,"user")},zp=null,qp=null;if(X&&!se()){let{instance:e,element:t}=cl({config:s,plugins:h,onToggle:Op});zp=e,e||(qp=t)}zp?e.appendChild(zp.element):qp&&e.appendChild(qp),Pl(),Ba(),bd(),yd(),ql(va.isStreaming()),Vi()||("follow"===_t()?Ni(!0):Fi()),(()=>{if(!1===s.voiceRecognition?.enabled)return;let e=gc(W.voiceState),t=!!e.active,r=Number(e.timestamp??0);Fs.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-r<3e4&&setTimeout(()=>{Fs.active||(Fs.manuallyDeactivated=!1,ce(s.voiceRecognition?.provider)?va.toggleVoice().then(()=>{Fs.active=qs(),_s("restore"),Fs.active?Sp():(Vs(),Uc("Tap the mic to resume your voice call",1e4))}):vp("restore"))},ce(s.voiceRecognition?.provider)?0:1e3)})(),Z&&(!X||se()?setTimeout(()=>Gl(),0):ue&&setTimeout(()=>Gl(),200));let jp=null,_p=()=>{jp&&(jp.disconnect(),jp.observe(Tt),jp.observe(st),jp.observe(ft))},Vp=cr(),Up=()=>{if(se())return gr(),void Pl();let t=Gs(s),r=s.launcher?.sidebarMode??!1,n=e.ownerDocument.defaultView??window,o=s.launcher?.mobileFullscreen??!0,a=s.launcher?.mobileBreakpoint??640,i=n.innerWidth<=a,l=o&&i&&X;try{if(l)return _n(),void(Vn=Qo());let e=!1;ne&&(ne=!1,_n(),e=!0);let n=Qo();if(!e&&n!==Vn&&(_n(),e=!0),Vn=n,e&&Io(),!X&&!t)return nt.style.height="",void(nt.style.width="");if(!r&&!t){let e=Zi(s);nt.style.width=e.width,nt.style.maxWidth=e.maxWidth}Go(),sa()}finally{gr(),yr();let t=cr();if(t!==Vp&&(Vp=t,cd(),Ba()),Pl(),ue&&X){let t=(e.ownerDocument.defaultView??window).innerWidth<=(s.launcher?.mobileBreakpoint??640),r=s.launcher?.sidebarMode??!1,n=s.launcher?.mobileFullscreen??!0,o=Gs(s)&&n&&t,a=r||n&&t&&X||o;if(a&&!da){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&!la&&(la=Ds(r,s.launcher?.zIndex??1e5)),da=zs(e.ownerDocument)}else a||(la?.(),la=null,da?.(),da=null)}}};Up();let Gp=e.ownerDocument.defaultView??window;if(Gp.addEventListener("resize",Up),ia.push(()=>Gp.removeEventListener("resize",Up)),typeof ResizeObserver<"u"){jp=new ResizeObserver(()=>{yr()}),_p(),ia.push(()=>{jp?.disconnect(),jp=null});let e=new ResizeObserver(()=>{Bc()});e.observe(st),ia.push(()=>e.disconnect())}Gp.addEventListener("resize",Bc),ia.push(()=>Gp.removeEventListener("resize",Bc)),Ya=it.scrollTop;let Kp=as(it),Jp=()=>{oa();let e=it.scrollTop,t=as(it),r=t<Kp;if(Kp=t,!Ut())return Ya=e,void Ei();let{action:n,nextLastScrollTop:o}=function(e){let{following:t,currentScrollTop:r,lastScrollTop:n,nearBottom:o,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:l=!0,resumeRequiresDownwardScroll:d=!1}=e,c=r-n;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:r}:!t&&o&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:r}:t&&i&&c<0||t&&l&&!o?{action:"pause",delta:c,nextLastScrollTop:r}:{action:"none",delta:c,nextLastScrollTop:r}}({following:Xa.isFollowing(),currentScrollTop:e,lastScrollTop:Ya,nearBottom:ss(it,24),userScrollThreshold:4,isAutoScrolling:ts||ls||r,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});Ya=o,"resume"===n?zi()||Bi():"pause"===n&&Li()};if(it.addEventListener("scroll",Jp,{passive:!0}),ia.push(()=>it.removeEventListener("scroll",Jp)),typeof ResizeObserver<"u"){let e=new ResizeObserver(()=>{(()=>{if(Ut()){if(!Xa.isFollowing()||ss(it,1))return;Ni(!Ra)}else{if(cs&&cs.initialSpacerHeight>0){let e=it.scrollHeight-cs.spacerHeight,t=function(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}({initialSpacerHeight:cs.initialSpacerHeight,contentHeightAtAnchor:cs.contentHeightAtAnchor,currentContentHeight:e});t!==cs.spacerHeight&&Ki(t)}Ei()}})(),ze(lt)});e.observe(lt),e.observe(it),ia.push(()=>e.disconnect())}let Qp=()=>{Ut()&&Xa.isFollowing()&&zi()&&Li()},Xp=it.ownerDocument;Xp.addEventListener("selectionchange",Qp),ia.push(()=>{Xp.removeEventListener("selectionchange",Qp)});let Yp=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Zp=e=>{Yp.has(e.key)&&(ks(),Qt()&&Ut()&&Xa.isFollowing()&&Li())},eu=e=>{e.target?.closest("a, button, [tabindex], input, textarea, select")&&(ks(),Qt()&&Ut()&&Xa.isFollowing()&&Li())};it.addEventListener("keydown",Zp),it.addEventListener("focusin",eu),ia.push(()=>{it.removeEventListener("keydown",Zp),it.removeEventListener("focusin",eu)});let tu=e=>{if(0!==e.deltaY&&ks(),!Ut())return;let t=function(e){let{following:t,deltaY:r,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=e;return t&&r<0?"pause":!t&&o&&r>0&&n?"resume":"none"}({following:Xa.isFollowing(),deltaY:e.deltaY,nearBottom:ss(it,24),resumeWhenNearBottom:!0});"pause"===t?Li():"resume"===t&&!zi()&&Bi()};it.addEventListener("wheel",tu,{passive:!0}),it.addEventListener("touchmove",ks,{passive:!0}),it.addEventListener("pointerdown",ks,{passive:!0}),ia.push(()=>{it.removeEventListener("touchmove",ks),it.removeEventListener("pointerdown",ks)}),ia.push(()=>it.removeEventListener("wheel",tu)),er.addEventListener("click",()=>{Yi(),it.scrollTop=it.scrollHeight,Ya=it.scrollTop,Bi(),Ni(!0),Ei()}),ia.push(()=>er.remove()),ia.push(()=>{wi(),Yi()});let ru=()=>{Ct&&(wa&&=(Ct.removeEventListener("click",wa),null),pe()?(Ct.style.display="",wa=()=>{Rl(!1,"user")},Ct.addEventListener("click",wa)):Ct.style.display="none")};ru(),(()=>{let{clearChatButton:e}=at;e&&e.addEventListener("click",()=>{let e=sc;if(e?.historyAvailable())return void e.startNewConversation({focusComposer:!0}).catch(e=>{s.debug&&console.warn("[AgentWidget] New conversation failed:",e)});va.clearMessages(),s.layout?.topFade&&(it.scrollTop=0),it.removeAttribute("data-persona-top-fade"),Ha.clear(),Bi(),zt(at.composerOverlay);try{localStorage.removeItem(dc),s.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${dc}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(s.clearChatHistoryStorageKey&&s.clearChatHistoryStorageKey!==dc)try{localStorage.removeItem(s.clearChatHistoryStorageKey),s.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${s.clearChatHistoryStorageKey}`)}catch(e){console.error("[AgentWidget] Failed to clear custom localStorage:",e)}let t=new CustomEvent("persona:clear-chat",{detail:{timestamp:(new Date).toISOString()}});window.dispatchEvent(t),H?.clear&&ni(()=>H.clear(),"[AgentWidget] Failed to clear storage adapter:"),W={},Q.syncFromMetadata(),vr?.clearAttachments(),fi(),Gr(void 0),zr(void 0),Ka(),Le?.clear(),Pe?.reset(),Re?.update()})})();let nu=[["keydown",e=>{if(ut&&!$l()&&(e.isComposing||!wr?.handleKeydown(e))){if(!(!1===s.features?.composerHistory||"ArrowUp"!==e.key&&"ArrowDown"!==e.key||e.shiftKey||e.metaKey||e.ctrlKey||e.altKey||e.isComposing)){let t=0===ut.selectionStart&&0===ut.selectionEnd,r=function(e){let{direction:t,history:r,currentValue:n,atStart:o,state:a}=e,s=-1!==a.index;if(0===r.length)return{handled:!1,state:a};if("up"===t){if(!s&&!o)return{handled:!1,state:a};if(!s){let e=r.length-1;return{handled:!0,value:r[e],state:{index:e,draft:n}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:r[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let e=a.index+1;return{handled:!0,value:r[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}({direction:"ArrowUp"===e.key?"up":"down",history:va.getMessages().filter(e=>"user"===e.role).map(e=>e.content??"").filter(e=>e.length>0),currentValue:ut.value,atStart:t,state:Zc});if(Zc=r.state,r.handled)return e.preventDefault(),void(void 0!==r.value&&(e=>{if(!ut)return;ep=!0,ut.value=e,ut.dispatchEvent(new Event("input",{bubbles:!0})),ep=!1;let t=ut.value.length;ut.setSelectionRange(t,t)})(r.value))}if(Zn(e,{submitKey:s.composer?.submitKey,insertNewlineOnTouchEnter:s.composer?.insertNewlineOnTouchEnter,coarsePointer:Xn(ut)}))if(va.isStreaming()){if(e.preventDefault(),"block"===Vr()||qc||Dl())return;tp(),Jc()}else qc||Dl()?e.preventDefault():(tp(),e.preventDefault(),ht.click())}}],["input",e=>{ep||(e.isComposing||wr?.handleInput(e.inputType??void 0),tp())}],["input",kr],["input",Ar],["keyup",Ar],["paste",async e=>{if(!0!==s.attachments?.enabled||!vr||$l())return;let t=hc(e.clipboardData);0!==t.length&&(e.preventDefault(),await vr.handleFiles(t))}],["focus",()=>wr?.prefetch()]],ou=e=>{if(e)for(let[t,r]of nu)dn?.addListener(e,t,r)},au=()=>{dn&&(dn.addListener(dn.form,"submit",Yc),dn.addListener(dn.footer,"click",Ar),ou(ut),Ht&&dn.addListener(Ht,"click",Ip),$p())};au();let su=()=>{wr?.onComposerSwap((e,t)=>{(e=>{if(e)for(let[t,r]of nu)dn?.removeListener(e,t,r)})(t),ut=e,dn&&(dn.input=e),ou(e),cn(),zl(),kr()})};su();let iu=!1;function lu(){if(!iu){iu=!0;try{let e=ut?.value??"",t=Tt.ownerDocument??document,r=!!ut&&t.activeElement===ut;yp(),dn?.destroy(),dn=null,wr?.destroy(),wr=null;let n=null,o=()=>(n=se()?ki({config:s}):Ci({config:s}),n.footer),a=sn(o)??o();tt.replaceComposer(a),Tt=tt.composer.footer;let i=null!==n&&a===n.footer;an=!i,Rt=i?n.setSendButtonMode:()=>{},rn(Tt),pn(Tt),hn(),fn(),yn(),su(),xn(),Cn(),Sn(),au();let l=ba.indexOf(ga);if(ga.destroy(),ga=ei(pt),l>=0&&(ba[l]=ga),ut&&(ut.value=e),kr(),Ar(),bd(),Ba(),ql(va.isStreaming()),"transient"===s.statusIndicator?.mode&&!se()){let e=va.getStatus();et(gt,Ze(e),s.statusIndicator,e)}Fs.active&&lp("recording"),_n(),_p(),gr(),Mn(),Ol(),r&&ut?.focus()}finally{iu=!1}}}let du=e.ownerDocument??document;du.addEventListener("keydown",rp,!0);let cu=()=>{mi()},pu=()=>{"hidden"===du.visibilityState&&mi()};typeof window<"u"&&(window.addEventListener("pagehide",cu),du.addEventListener("visibilitychange",pu),ia.push(()=>{window.removeEventListener("pagehide",cu),du.removeEventListener("visibilitychange",pu)}));let uu="persona-attachment-drop-active",hu=0,mu=()=>{hu=0,st.classList.remove(uu)},gu=()=>!0===s.attachments?.enabled&&null!==vr&&!$l(),fu=e=>{mc(e.dataTransfer)&&gu()&&(hu++,1===hu&&st.classList.add(uu))},yu=e=>{mc(e.dataTransfer)&&gu()&&(hu--,hu<=0&&mu())},bu=e=>{mc(e.dataTransfer)&&gu()&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},vu=e=>{if(!mc(e.dataTransfer)||!gu())return;e.preventDefault(),e.stopPropagation(),mu();let t=Array.from(e.dataTransfer.files??[]);0!==t.length&&vr.handleFiles(t)};st.addEventListener("dragenter",fu,!0),st.addEventListener("dragleave",yu,!0),e.addEventListener("dragover",bu,!0),e.addEventListener("drop",vu,!0);let wu=e.ownerDocument,xu=e=>{gu()&&e.preventDefault()},Cu=e=>{gu()&&e.preventDefault()};wu.addEventListener("dragover",xu),wu.addEventListener("drop",Cu),ia.push(()=>{dn?.destroy(),dn=null,yp(),bn?.destroy(),bn=null,Dr?.destroy(),Dr=null,Or?.destroy(),Or=null,Ur?.destroy(),Ur=null,Hr=null,Wr=null,mi(),ci.destroy(),Vc&&clearTimeout(Vc),Ka(),jc?.abort(),jc=null,vr?.destroy(),vr=null,Cr.destroy(),du.removeEventListener("keydown",rp,!0),wr?.destroy()}),ia.push(()=>{st.removeEventListener("dragenter",fu,!0),st.removeEventListener("dragleave",yu,!0),e.removeEventListener("dragover",bu,!0),e.removeEventListener("drop",vu,!0),wu.removeEventListener("dragover",xu),wu.removeEventListener("drop",Cu),mu()}),ia.push(()=>{va.cancel()}),zp?ia.push(()=>{zp?.destroy()}):qp&&ia.push(()=>{qp?.remove()});let Su={update(t){let o=!0===s.future?.v5Defaults,a=s.toolCall,i=s.messageActions,l=s.layout?.messages,d=s.colorScheme,c=s.loadingIndicator,m=s.iterationDisplay,g=s.features?.showReasoning,f=s.features?.showToolCalls,y=s.features?.toolCallDisplay,b=s.features?.reasoningDisplay,v=s.features?.streamAnimation?.type,w=!0===s.features?.history?.enabled,x=s.features?.history?.provider,C=s.getIdentityProof,S=s.clientToken,k=s.contextMentions;s=Bd({...s,features:u},t),u=s.features,s=vd(s),p(),Zo(),za(e,s),Xl(e,s),Yl(e,s),Ve(),Xo(),s.colorScheme!==d&&pa();let A=Td.getForInstance(s.plugins);h.length=0,h.push(...A),kc(),X=s.launcher?.enabled??!0,Y=s.launcher?.autoExpand??!1,we=s.features?.showReasoning??!0,xe=s.features?.showToolCalls??!0,Se=s.features?.scrollToBottom??{};let M=_t();Ae=s.features?.scrollBehavior??{},M!==_t()&&(Yi(),Bi()),Ls(),br(),Ei();let I=Ce;if(Ce=s.features?.showEventStreamToggle??!1,Ce&&!I){if(Le||(Oe(),va.setSSEEventCallback((e,t)=>{s.onSSEEvent?.(e,t),Fe(e,t)})),!tn&&Mt){let e=s.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:"");tn=L("button",t),tn.style.width="28px",tn.style.height="28px",tn.style.color=li.actionIconColor,tn.type="button",tn.setAttribute("aria-label","Event Stream"),tn.title="Event Stream";let o=n(r.Activity,"18px","currentColor",1.5);o&&tn.appendChild(o);let a=at.clearChatButtonWrapper,i=at.closeButtonWrapper,l=a||i;l&&l.parentNode===Mt?Mt.insertBefore(tn,l):Mt.appendChild(tn),tn.addEventListener("click",()=>{He?Zr():Yr()})}}else!Ce&&I&&(Zr(),tn&&=(tn.remove(),null),Le?.clear(),Te?.destroy(),Le=null,Te=null,Pe?.reset(),Pe=null,Be=null);if(!1===s.launcher?.enabled&&zp&&(zp.destroy(),zp=null),!1===s.launcher?.enabled&&qp&&(qp.remove(),qp=null),!1!==s.launcher?.enabled&&!zp&&!qp){let{instance:t,element:r}=cl({config:s,plugins:h,onToggle:Op});zp=t,t||(qp=r),e.appendChild(r)}zp&&zp.update(s),Ic(),At&&void 0!==s.launcher?.subtitle&&(At.textContent=s.launcher.subtitle);let T=s.layout?.header;if(T?.layout!==re&&Mt){let e=T?xi(s,T,{showClose:pe(),onClose:()=>Rl(!1,"user")}):pi({config:s,showClose:pe(),onClose:()=>Rl(!1,"user")});tt.replaceHeader(e),Mt=tt.header.element,St=tt.header.iconHolder,kt=tt.header.headerTitle,At=tt.header.headerSubtitle,Ct=tt.header.closeButton,re=T?.layout,Ic()}else if(T){if(St&&(St.style.display=!1===T.showIcon?"none":""),kt&&(kt.style.display=!1===T.showTitle?"none":""),At&&(At.style.display=!1===T.showSubtitle?"none":""),Ct){let e=pe()&&!1!==T.showCloseButton;Ct.style.display=e?"":"none"}if(at.clearChatButtonWrapper){let e=T.showClearChat;if(void 0!==e){at.clearChatButtonWrapper.style.display=e?"":"none";let{closeButtonWrapper:t}=at;t&&!t.classList.contains("persona-absolute")&&(e?t.classList.remove("persona-ml-auto"):t.classList.add("persona-ml-auto"))}}}let E=!1!==s.layout?.showHeader;Mt&&(Mt.style.display=E?"":"none");let P=!1!==s.layout?.showFooter;Tt&&(Tt.style.display=P?"":"none"),gr(),Ei(),X===te?Y!==ee&&Rl(Y,"auto"):X?Rl(Y,"auto"):(ue=!0,Pl()),ee=Y,te=X,Up(),ru();let B=JSON.stringify(s.toolCall)!==JSON.stringify(a),N=JSON.stringify(s.messageActions)!==JSON.stringify(i),H=JSON.stringify(s.layout?.messages)!==JSON.stringify(l),$=s.loadingIndicator?.render!==c?.render||s.loadingIndicator?.renderIdle!==c?.renderIdle||s.loadingIndicator?.showBubble!==c?.showBubble,W=s.iterationDisplay!==m,D=(s.features?.showReasoning??!0)!==(g??!0)||(s.features?.showToolCalls??!0)!==(f??!0)||JSON.stringify(s.features?.toolCallDisplay)!==JSON.stringify(y)||JSON.stringify(s.features?.reasoningDisplay)!==JSON.stringify(b);(!0===s.future?.v5Defaults!==o||B||N||H||$||W||D)&&va&&(Ja++,gl(lt,va.getMessages(),fe));let F=s.features?.streamAnimation?.type;if(F!==v&&F&&"none"!==F){let t=ha(F,s.features?.streamAnimation?.plugins);t&&Ns(t,e)}let O=s.launcher??{},z=O.headerIconHidden??!1,q=s.layout?.header?.showIcon,j=z||!1===q,V=O.headerIconName,G=O.headerIconSize??"40px";if(St){let e=Mt,t=e?.querySelector(".persona-flex-col");if(j)St.style.display="none",e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(St.style.display="",St.style.height=G,St.style.width=G,e&&t&&(e.contains(St)?St.nextSibling!==t&&(St.remove(),e.insertBefore(St,t)):e.insertBefore(St,t)),V){let e=parseFloat(G)||24,t=K(V,.6*e,"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))`,St.replaceChildren(t)):St.textContent=O.agentIconText??"💬"}else if(O.iconUrl){let e=St.querySelector("img");if(e)e.src=O.iconUrl,e.style.height=G,e.style.width=G;else{let e=document.createElement("img");e.src=O.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=G,e.style.width=G,St.replaceChildren(e)}}else{let e=St.querySelector("svg"),t=St.querySelector("img");(e||t)&&St.replaceChildren(),St.textContent=O.agentIconText??"💬"}let r=St.querySelector("img");r&&(r.style.height=G,r.style.width=G)}}let J=s.layout?.header?.showTitle,Z=s.layout?.header?.showSubtitle;if(kt&&(kt.style.display=!1===J?"none":""),At&&(At.style.display=!1===Z?"none":""),Ct){let e=pe()&&!1!==s.layout?.header?.showCloseButton;if(Ct.style.display=e?"":"none",!se()){let e=O.closeButtonSize??"";Ct.style.height=e,Ct.style.width=e,Ct.style.minWidth=e,Ct.style.minHeight=e}let t=O.closeButtonPlacement??"inline",{closeButtonWrapper:r}=at,n="top-right"===t,o=r?.classList.contains("persona-absolute");if(r&&n!==o)if(r.remove(),n){r.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let e=sc?.railColumn??st;e.style.position="relative",e.appendChild(r)}else{let e=O.clearChat?.placement??"inline";r.className=(O.clearChat?.enabled??1)&&"inline"===e?"":"persona-ml-auto",Mt&&Mt.appendChild(r)}if(Ct.style.color=O.closeButtonColor||li.actionIconColor,O.closeButtonBackgroundColor?(Ct.style.backgroundColor=O.closeButtonBackgroundColor,Ct.classList.remove("hover:persona-bg-gray-100")):(Ct.style.backgroundColor="",Ct.classList.add("hover:persona-bg-gray-100")),O.closeButtonBorderWidth||O.closeButtonBorderColor){let e=O.closeButtonBorderWidth||"0px",t=O.closeButtonBorderColor||"transparent";Ct.style.border=`${e} solid ${t}`,Ct.classList.remove("persona-border-none")}else Ct.style.border="",Ct.classList.add("persona-border-none");O.closeButtonBorderRadius?(Ct.style.borderRadius=O.closeButtonBorderRadius,Ct.classList.remove("persona-rounded-full")):(Ct.style.borderRadius="",Ct.classList.add("persona-rounded-full")),O.closeButtonPaddingX?(Ct.style.paddingLeft=O.closeButtonPaddingX,Ct.style.paddingRight=O.closeButtonPaddingX):(Ct.style.paddingLeft="",Ct.style.paddingRight=""),O.closeButtonPaddingY?(Ct.style.paddingTop=O.closeButtonPaddingY,Ct.style.paddingBottom=O.closeButtonPaddingY):(Ct.style.paddingTop="",Ct.style.paddingBottom=""),oi(Ct,O.closeButtonIconName??"x",{iconSize:se()?tl:void 0,iconText:O.closeButtonIconText??"×"});let a=O.closeButtonTooltipText??"Close chat",i=O.closeButtonShowTooltip??!0;Ct.setAttribute("aria-label",a),r&&Gn({anchor:Ct,trigger:r,text:()=>Ct?.getAttribute("aria-label")??a,enabled:i})}let{clearChatButton:ne,clearChatButtonWrapper:oe}=at;if(ne){let e=O.clearChat??{},t=e.enabled??!0,r=s.layout?.header?.showClearChat,n=void 0===r?t:r,o=e.placement??"inline";if(oe){oe.style.display=n?"":"none";let{closeButtonWrapper:e}=at;!se()&&e&&!e.classList.contains("persona-absolute")&&(n?e.classList.remove("persona-ml-auto"):e.classList.add("persona-ml-auto"));let t="top-right"===o,r=oe.classList.contains("persona-absolute");if(!se()&&t!==r&&n){if(oe.remove(),t){oe.className="persona-absolute persona-top-4 persona-z-50",oe.style.right="48px";let e=sc?.railColumn??st;e.style.position="relative",e.appendChild(oe)}else{oe.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",oe.style.right="";let e=at.closeButtonWrapper;Mt&&e&&e.parentElement===Mt?Mt.insertBefore(oe,e):Mt&&Mt.appendChild(oe)}let e=at.closeButtonWrapper;e&&!e.classList.contains("persona-absolute")&&(t?e.classList.add("persona-ml-auto"):e.classList.remove("persona-ml-auto"))}}if(n){if(!se()){let t=e.size??"";ne.style.height=t,ne.style.width=t,ne.style.minWidth=t,ne.style.minHeight=t}let t=e.iconColor??"";if(ne.style.color=t||li.actionIconColor,oi(ne,e.iconName??"refresh-cw",{iconSize:se()?rl:void 0}),e.backgroundColor?(ne.style.backgroundColor=e.backgroundColor,ne.classList.remove("hover:persona-bg-gray-100")):(ne.style.backgroundColor="",ne.classList.add("hover:persona-bg-gray-100")),e.borderWidth||e.borderColor){let t=e.borderWidth||"0px",r=e.borderColor||"transparent";ne.style.border=`${t} solid ${r}`,ne.classList.remove("persona-border-none")}else ne.style.border="",ne.classList.add("persona-border-none");e.borderRadius?(ne.style.borderRadius=e.borderRadius,ne.classList.remove("persona-rounded-full")):(ne.style.borderRadius="",ne.classList.add("persona-rounded-full")),e.paddingX?(ne.style.paddingLeft=e.paddingX,ne.style.paddingRight=e.paddingX):(ne.style.paddingLeft="",ne.style.paddingRight=""),e.paddingY?(ne.style.paddingTop=e.paddingY,ne.style.paddingBottom=e.paddingY):(ne.style.paddingTop="",ne.style.paddingBottom="");let r=e.tooltipText??"Clear chat",n=e.showTooltip??!0;ne.setAttribute("aria-label",r),oe&&Gn({anchor:ne,trigger:oe,text:()=>ne?.getAttribute("aria-label")??r,enabled:n})}}let ae=s.actionParsers&&s.actionParsers.length?s.actionParsers:[Nd],ie=s.actionHandlers&&s.actionHandlers.length?s.actionHandlers:[Hd.message,Hd.messageAndClick];Q=Wd({parsers:ae,handlers:ie,getSessionMetadata:_,updateSessionMetadata:U,emit:R.emit,documentRef:typeof document<"u"?document:null}),fe=yc(s,Q,ge),$d(),va.updateConfig(s),Fc(),(!0===s.features?.history?.enabled!==w||s.features?.history?.provider!==x||s.getIdentityProof!==C||s.clientToken!==S)&&(sc?.closeHistory({restoreFocus:!1}),sc?.installHistoryProvider()),sc?.syncHistoryChromeImpl(),Bc(),Cc()&&!sc&&Lc().catch(()=>{}),gl(lt,va.getMessages(),fe),Ba(),bd(),(()=>{let e=pr();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`!==md||e.icon!==od)&&yd()})(),ql(va.isStreaming()),k!==s.contextMentions&&lu();let he=!0===s.voiceRecognition?.enabled,me=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),ye=ce(s.voiceRecognition?.provider);if(he&&(me||ye))if(Ht&&$t){let e=s.voiceRecognition??{},t=s.sendButton??{},r=e.iconName??"mic",n=e.iconSize,o=parseFloat(n??"")||24;Ht.classList.add(no),Ht.classList.toggle(oo,!n),Ht.style.width=n??"",Ht.style.height=n??"",Ht.style.minWidth=n??"",Ht.style.minHeight=n??"";let a=e.iconColor??t.textColor;Ht.innerHTML="";let i=K(r,o,a||"currentColor",1.5);i?Ht.appendChild(i):Ht.textContent="🎤";let l=e.backgroundColor??t.backgroundColor;Ht.style.backgroundColor=l||"",Ht.style.color=a||"var(--persona-text, #111827)",e.borderWidth?(Ht.style.borderWidth=e.borderWidth,Ht.style.borderStyle="solid"):(Ht.style.borderWidth="",Ht.style.borderStyle=""),e.borderColor?Ht.style.borderColor=e.borderColor:Ht.style.borderColor="",e.paddingX?(Ht.style.paddingLeft=e.paddingX,Ht.style.paddingRight=e.paddingX):(Ht.style.paddingLeft="",Ht.style.paddingRight=""),e.paddingY?(Ht.style.paddingTop=e.paddingY,Ht.style.paddingBottom=e.paddingY):(Ht.style.paddingTop="",Ht.style.paddingBottom="");let d=e.tooltipText??"Start voice recognition",c=e.showTooltip??!1;Ht.setAttribute("aria-label",d),$t&&Gn({anchor:Ht,trigger:$t,text:()=>Ht?.getAttribute("aria-label")??d,enabled:c}),$t.style.display="",Ht.disabled=$l()||va.isStreaming()&&!Wl()}else{let e=co(s);if(e){Ht=e.button,$t=e.wrapper;let t=Nt&&Nt.parentElement===Bt?Nt:null;Bt?Bt.insertBefore($t,t):mt?.appendChild($t),dn&&(dn.micButton=Ht),dn?.addListener(Ht,"click",Ip),Ht.disabled=$l()||va.isStreaming()&&!Wl()}}else Ht&&$t&&($t.style.display="none",ce(s.voiceRecognition?.provider)?va.isVoiceActive()&&va.toggleVoice():op&&wp());if($p(),!0===s.attachments?.enabled){if(Dt&&Wt){Dt.style.display="";let e=s.attachments??{};Ft&&(Ft.accept=(e.allowedTypes??Sr).join(","),Ft.multiple=(e.maxFiles??4)>1),vr&&vr.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}else{let e=s.attachments??{};qt||(qt=L("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),qt.style.display="none",(ut.parentElement??mt).insertBefore(qt,ut)),Ft||(Ft=document.createElement("input"),Ft.type="file",Ft.accept=(e.allowedTypes??Sr).join(","),Ft.multiple=(e.maxFiles??4)>1,Ft.style.display="none",Ft.setAttribute("aria-label","Attach files"),(ut.parentElement??mt).insertBefore(Ft,ut)),Dt=L("div","persona-send-button-wrapper"),Wt=L("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${no} ${oo}`),Wt.type="button",Wt.setAttribute("aria-label",e.buttonTooltipText??"Attach file");let t=e.buttonIconName??"paperclip";Wt.style.fontSize="18px",Wt.style.lineHeight="1";let r=K(t,24,"currentColor",1.5);r?Wt.appendChild(r):Wt.textContent="📎",Wt.addEventListener("click",e=>{e.preventDefault(),Ft?.click()}),Dt.appendChild(Wt);let n=e.buttonTooltipText??"Attach file";Gn({anchor:Wt,trigger:Dt,text:()=>Wt?.getAttribute("aria-label")??n}),Pt?Pt.append(Dt):mt.appendChild(Dt),dn&&(dn.attachmentButton=Wt,dn.attachmentInput=Ft??void 0,dn.attachmentPreviews=qt??void 0),!vr&&Ft&&qt&&(vr=Bn.fromConfig(e,Ir),vr.setPreviewsContainer(qt),dn?.addListener(Ft,"change",async()=>{vr&&Ft?.files&&(await vr.handleFileSelect(Ft.files),Ft.value="")}))}if(st.querySelector(".persona-attachment-drop-overlay")?.remove(),st.appendChild(bc(s.attachments?.dropOverlay)),Wt){let e=s.attachments??{},t=e.buttonTooltipText??"Attach file";Wt.setAttribute("aria-label",t),Wt.textContent="";let r=K(e.buttonIconName??"paperclip",24,"currentColor",1.5);r?Wt.appendChild(r):Wt.textContent="📎",Dt&&Gn({anchor:Wt,trigger:Dt,text:()=>Wt?.getAttribute("aria-label")??t})}}else Dt&&(Dt.style.display="none"),vr&&vr.clearAttachments(),st.querySelector(".persona-attachment-drop-overlay")?.remove();let be=s.sendButton??{},ve=be.useIcon??!1,ke=be.iconText??"↑",Me=be.iconName,Ie=be.tooltipText??"Send message",Ee=be.showTooltip??!1,Ne=be.size,Re=parseFloat(Ne??"")||40,$e=be.backgroundColor,We=be.textColor;if(ve){if(ht.style.width=Ne??"",ht.style.height=Ne??"",ht.style.minWidth=Ne??"",ht.style.minHeight=Ne??"",ht.style.fontSize="18px",ht.style.lineHeight="1",ht.style.color=We||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!va.isStreaming())if(ht.innerHTML="",Me){let e=parseFloat(be.iconSize??"")||Math.round(.5*Re),t=We?.trim()||"currentColor",r=be.iconStrokeWidth??2,n=K(Me,e,t,r),o=K(be.stopIconName??"square",e,t,r);n&&o?ht.appendChild(io(n,o)):n?ht.appendChild(n):ht.textContent=ke}else ht.textContent=ke;ht.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${no}`,$e?(ht.style.backgroundColor=$e,ht.classList.remove("persona-bg-persona-primary")):(ht.style.backgroundColor="",ht.classList.add("persona-bg-persona-primary"))}else ht.textContent=s.copy?.sendButtonLabel??"Send",ht.style.width="",ht.style.height="",ht.style.minWidth="",ht.style.minHeight="",ht.style.fontSize="",ht.style.lineHeight="",ht.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",$e?(ht.style.backgroundColor=$e,ht.classList.remove("persona-bg-persona-accent")):ht.classList.add("persona-bg-persona-accent"),We?ht.style.color=We:ht.classList.add("persona-text-white");be.borderWidth?(ht.style.borderWidth=be.borderWidth,ht.style.borderStyle="solid"):(ht.style.borderWidth="",ht.style.borderStyle=""),be.borderColor?ht.style.borderColor=be.borderColor:ht.style.borderColor="",be.paddingX?(ht.style.paddingLeft=be.paddingX,ht.style.paddingRight=be.paddingX):(ht.style.paddingLeft="",ht.style.paddingRight=""),be.paddingY?(ht.style.paddingTop=be.paddingY,ht.style.paddingBottom=be.paddingY):(ht.style.paddingTop="",ht.style.paddingBottom=""),va.isStreaming()||ht.setAttribute("aria-label",Ie),Ol(),Nt&&Gn({anchor:ht,trigger:Nt,text:()=>ht.getAttribute("aria-label")??Ie,enabled:Ee}),Tn(),aa();let De=zo(Cr.getState().activeModeIds,s.composer?.modes);Cr.setActiveModeIds(De),Pr().length>0!=!!Dr&&Cn(),Dr?.render(De,Pr());for(let e of[...Fr.keys()])Oo(e,s.composer?.modeGroups)||Fr.delete(e);Fr.forEach(e=>e.repaint()),Hr?.repaint(),bn?.resolve();let ze=ja(s,se());if(ea(),ze){lt.style.maxWidth=ze,lt.style.marginLeft="auto",lt.style.marginRight="auto",lt.style.width="100%",bt.style.maxWidth=ze,bt.style.marginLeft="auto",bt.style.marginRight="auto",bt.style.width="100%";for(let e of[mt,pt,qt,gt])e&&(e.style.maxWidth=ze,e.style.marginLeft="auto",e.style.marginRight="auto",e.style.width="100%")}else{lt.style.maxWidth="",lt.style.marginLeft="",lt.style.marginRight="",lt.style.width="",bt.style.maxWidth="",bt.style.marginLeft="",bt.style.marginRight="",bt.style.width="";for(let e of[mt,pt,qt,gt])e&&(e.style.maxWidth="",e.style.marginLeft="",e.style.marginRight="",e.style.width="")}let qe=s.statusIndicator??{};if(de(gt,mt,qe),le(gt,qe,va?.getStatus()??"idle"),va){let e=va.getStatus();et(gt,(e=>"idle"===e?qe.idleText??Tr.idle:"connecting"===e?qe.connectingText??Tr.connecting:"connected"===e?qe.connectedText??Tr.connected:"error"===e?qe.errorText??Tr.error:"paused"===e?qe.pausedText??Tr.paused:"resuming"===e?qe.resumingText??Tr.resuming:Tr[e])(e),qe,e)}gt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let je="left"===qe.align?"persona-text-left":"center"===qe.align?"persona-text-center":"persona-text-right";gt.classList.add(je),cn(),zl(),Mn(),_e()},open(){pe()&&Rl(!0,"api")},close(){pe()&&Rl(!1,"api")},toggle(){pe()&&Rl(!ue,"api")},reconnect(){va.reconnectNow()},clearChat(){Yn=!1,d.clear(),i.clear(),l.clear(),c.clear(),va.clearMessages(),s.layout?.topFade&&(it.scrollTop=0),it.removeAttribute("data-persona-top-fade"),Ha.clear(),Bi();try{localStorage.removeItem(dc),s.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${dc}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(s.clearChatHistoryStorageKey&&s.clearChatHistoryStorageKey!==dc)try{localStorage.removeItem(s.clearChatHistoryStorageKey),s.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${s.clearChatHistoryStorageKey}`)}catch(e){console.error("[AgentWidget] Failed to clear custom localStorage:",e)}let e=new CustomEvent("persona:clear-chat",{detail:{timestamp:(new Date).toISOString()}});window.dispatchEvent(e),H?.clear&&ni(()=>H.clear(),"[AgentWidget] Failed to clear storage adapter:"),W={},Q.syncFromMetadata(),vr?.clearAttachments(),fi(),Gr(void 0),zr(void 0),Ka(),Le?.clear(),Pe?.reset(),Re?.update()},setMessage:e=>!(!ut||va.isStreaming()||$l()||(!ue&&pe()&&Rl(!0,"system"),ut.value=e,ut.dispatchEvent(new Event("input",{bubbles:!0})),0)),submitMessage(e){if(va.isStreaming()||Dl())return!1;let t=e?.trim()||ut.value.trim();return!!t&&(!ue&&pe()&&Rl(!0,"system"),ut.value="",ut.style.height="auto",kr(),Xc(t,{consumeDraft:!1}),!0)},getComposerState:()=>Cr.getState(),setQuote(e){let t=e?.text?.trim();t&&zr({...e,text:t})},clearQuote(){zr(void 0)},startVoiceRecognition:()=>!va.isStreaming()&&(ce(s.voiceRecognition?.provider)?(va.isVoiceActive()||va.isBargeInActive()||(!ue&&pe()&&Rl(!0,"system"),Fs.manuallyDeactivated=!1,Vs(),va.toggleVoice().then(()=>{Fs.active=qs(),Vs(),_s("user"),Fs.active&&Sp()})),!0):!!op||!!bp()&&(!ue&&pe()&&Rl(!0,"system"),Fs.manuallyDeactivated=!1,Vs(),vp("user"),!0)),stopVoiceRecognition:()=>ce(s.voiceRecognition?.provider)?!(!va.isVoiceActive()&&!va.isBargeInActive()||((va.isBargeInActive()?va.deactivateBargeIn():va.toggleVoice()).then(()=>{Fs.active=!1,Fs.manuallyDeactivated=!0,Vs(),_s("user"),Mp()}),0)):!!op&&(Fs.manuallyDeactivated=!0,Vs(),wp("user"),!0),injectMessage:e=>(!ue&&pe()&&Rl(!0,"system"),va.injectMessage(e)),injectAssistantMessage(e){!ue&&pe()&&Rl(!0,"system");let t=va.injectAssistantMessage(e);return he&&(he=!1,me&&=(clearTimeout(me),null),setTimeout(()=>{va&&!va.isStreaming()&&va.continueConversation()},100)),t},injectUserMessage:e=>(!ue&&pe()&&Rl(!0,"system"),va.injectUserMessage(e)),injectSystemMessage:e=>(!ue&&pe()&&Rl(!0,"system"),va.injectSystemMessage(e)),injectMessageBatch:e=>(!ue&&pe()&&Rl(!0,"system"),va.injectMessageBatch(e)),injectComponentDirective:e=>(!ue&&pe()&&Rl(!0,"system"),va.injectComponentDirective(e)),injectTestMessage(e){!ue&&pe()&&Rl(!0,"system"),va.injectTestEvent(e)},connectStream:async(e,t)=>va.connectStream(e,t),__pushEventStreamEvent(e){Ce&&(Oe(),Fe(e.type,e.payload))},showEventStream(){Ce&&Yr()},hideEventStream(){He&&Zr()},isEventStreamVisible:()=>He,listConversations:e=>va.listConversations(e),getActiveConversationId:()=>va.getActiveConversationId(),openConversation:(e,t)=>Pc(r=>r.openHistoryConversation(e,{focusComposer:!0===t?.focus})),startNewConversation:e=>Pc(t=>t.startNewConversation({focusComposer:!0===e?.focus})),warmSession(){Nc()},deleteConversation:e=>Pc(t=>t.deleteHistoryConversation(e)),renameConversation:(e,t)=>Pc(r=>r.updateHistoryConversation(e,{title:t})),setConversationStarred:(e,t)=>Pc(r=>r.updateHistoryConversation(e,{starred:t})),clearConversationHistory:e=>Pc(t=>t.clearConversationHistory(e)),resetHistoryIdentity:()=>Pc(e=>e.resetHistoryIdentity()),async getVisitorToken(){let e=Pd;if(!e)return null;let t=await e.get();return e===Pd?t:null},getHistoryIdentityStatus(){let e=sc?.historyProvider;return e?e.getIdentityStatus():Cc()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory:e=>Cc()?Pc(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...void 0===e?.focus?{}:{focus:e.focus}})):Promise.resolve(),hideHistory(e){sc?.closeHistory(void 0===e?.restoreFocus?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible:()=>qe,showArtifacts(){Ul(s)&&(Yn=!1,lo=!0,Xo(),On?.setMobileOpen(!0))},hideArtifacts(){Ul(s)&&(Yn=!0,Xo())},upsertArtifact:e=>Ul(s)?("panel"===en(s.features?.artifacts,{artifactType:e.artifactType,..."markdown"===e.artifactType&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})&&(Yn=!1,lo=!0),va.upsertArtifact(e)):null,selectArtifact(e){Ul(s)&&va.selectArtifact(e)},clearArtifacts(){Ul(s)&&va.clearArtifacts()},getArtifacts:()=>va?.getArtifacts()??[],getSelectedArtifactId:()=>va?.getSelectedArtifactId()??null,focusInput:()=>!(X&&!ue&&!se()||!ut||(ut.focus(),0)),async resolveApproval(e,t,r){let n=va.getMessages().find(t=>"approval"===t.variant&&t.approval?.id===e);if(!n?.approval)throw Error(`Approval not found: ${e}`);if("webmcp"!==n.approval.toolType)return va.resolveApproval(n.approval,t,r);va.resolveWebMcpApproval(n.id,t)},setFollowUpSuggestions(e){(e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length)return void Na();let r=va?va.getMessages():[];xa=t,Sa=!0,ka=Ma(r),Aa=Ia(r),Ba(r)})(e)},clearFollowUpSuggestions(){Na()},getMessages:()=>va.getMessages(),getStatus:()=>va.getStatus(),getPersistentMetadata:()=>({...W}),updatePersistentMetadata(e){U(e)},on:(e,t)=>R.on(e,t),off(e,t){R.off(e,t)},isOpen:()=>pe()&&ue,isVoiceActive:()=>Fs.active,toggleReadAloud(e){va.toggleReadAloud(e)},stopReadAloud(){va.stopSpeaking()},getReadAloudState:e=>va.getReadAloudState(e),onReadAloudChange:e=>va.onReadAloudChange(e),getState:()=>({open:pe()&&ue,launcherEnabled:X,voiceActive:Fs.active,streaming:va.isStreaming()}),showCSATFeedback(e){!ue&&pe()&&Rl(!0,"system");let t=lt.querySelector(".persona-feedback-container");t&&t.remove();let r=ic({onSubmit:async(t,r)=>{va.isClientTokenMode()&&await va.submitCSATFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e});lt.appendChild(r),r.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(e){!ue&&pe()&&Rl(!0,"system");let t=lt.querySelector(".persona-feedback-container");t&&t.remove();let r=lc({onSubmit:async(t,r)=>{va.isClientTokenMode()&&await va.submitNPSFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e});lt.appendChild(r),r.scrollIntoView({behavior:"smooth",block:"end"})},submitCSATFeedback:async(e,t)=>va.submitCSATFeedback(e,t),submitNPSFeedback:async(e,t)=>va.submitNPSFeedback(e,t),destroy(){Xd(),null!=Dd&&(clearInterval(Dd),Dd=null),d.clear(),i.clear(),l.clear(),c.clear(),ia.forEach(e=>e()),rt.remove(),ot?.remove(),zp?.destroy(),qp?.remove(),wa&&Ct.removeEventListener("click",wa)}};if((o?.debugTools||s.debug)&&typeof window<"u"){let e=window.AgentWidgetBrowser,t={controller:Su,getMessages:Su.getMessages,getStatus:Su.getStatus,getMetadata:Su.getPersistentMetadata,updateMetadata:Su.updatePersistentMetadata,clearHistory:()=>Su.clearChat(),setVoiceActive:e=>e?Su.startVoiceRecognition():Su.stopVoiceRecognition()};window.AgentWidgetBrowser=t,ia.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),r=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Su.focusInput()};if(window.addEventListener("persona:focusInput",r),ia.push(()=>{window.removeEventListener("persona:focusInput",r)}),Ce){let e=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Su.showEventStream()},r=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Su.hideEventStream()};window.addEventListener("persona:showEventStream",e),window.addEventListener("persona:hideEventStream",r),ia.push(()=>{window.removeEventListener("persona:showEventStream",e),window.removeEventListener("persona:hideEventStream",r)})}let n=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Su.showHistory()},o=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Su.hideHistory()};window.addEventListener("persona:showHistory",n),window.addEventListener("persona:hideHistory",o),ia.push(()=>{window.removeEventListener("persona:showHistory",n),window.removeEventListener("persona:hideHistory",o)});let a=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Su.showArtifacts()},s=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Su.hideArtifacts()},i=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==t||r?.artifact&&Su.upsertArtifact(r.artifact)},l=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==t||"string"==typeof r?.id&&Su.selectArtifact(r.id)},d=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Su.clearArtifacts()};window.addEventListener("persona:showArtifacts",a),window.addEventListener("persona:hideArtifacts",s),window.addEventListener("persona:upsertArtifact",i),window.addEventListener("persona:selectArtifact",l),window.addEventListener("persona:clearArtifacts",d),ia.push(()=>{window.removeEventListener("persona:showArtifacts",a),window.removeEventListener("persona:hideArtifacts",s),window.removeEventListener("persona:upsertArtifact",i),window.removeEventListener("persona:selectArtifact",l),window.removeEventListener("persona:clearArtifacts",d)})}let ku=function(e){return e?!0===e?{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}(s.persistState);if(ku&&pe()){let t=function(e){try{let t="local"===e?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}(ku.storage),r=`${ku.keyPrefix}widget-open`,n=`${ku.keyPrefix}widget-voice`,o=`${ku.keyPrefix}widget-voice-mode`;if(t){let a=ku.persist?.openState&&"true"===t.getItem(r),s=ku.persist?.voiceState&&"true"===t.getItem(n),i=ku.persist?.voiceState&&"true"===t.getItem(o);if(a&&(zp?.setPanelOpen(!0,"auto"),setTimeout(()=>{Su.open(),setTimeout(()=>{if(s||i)Su.startVoiceRecognition();else if(ku.persist?.focusInput){let t=e.querySelector("textarea");t&&t.focus()}},100)},0)),ku.persist?.openState&&(R.on("widget:opened",()=>{t.setItem(r,"true")}),R.on("widget:closed",()=>{t.setItem(r,"false")})),ku.persist?.voiceState&&(R.on("voice:state",e=>{t.setItem(n,e.active?"true":"false")}),R.on("user:message",e=>{t.setItem(o,e.viaVoice?"true":"false")})),ku.clearOnChatClear){let e=()=>{t.removeItem(r),t.removeItem(n),t.removeItem(o)},a=()=>e();window.addEventListener("persona:clear-chat",a),ia.push(()=>{window.removeEventListener("persona:clear-chat",a)})}}}if(q&&pe()&&(zp?.setPanelOpen(!0,"auto"),setTimeout(()=>{Su.open()},0)),Ll(),!Qa){let e=be(()=>{va&&(Ja++,Ha.clear(),gl(lt,va.getMessages(),fe))});ia.push(e)}S=()=>{va&&(Ja++,Ha.clear(),gl(lt,va.getMessages(),fe))},va.getMessages().length>0&&ml(),T=()=>{va&&(Ja++,Ha.clear(),gl(lt,va.getMessages(),fe))};let Au=V(()=>{va&&(Ja++,Ha.clear(),gl(lt,va.getMessages(),fe))});ia.push(Au);let Mu=Vl(()=>{va&&(Ja++,Ha.clear(),gl(lt,va.getMessages(),fe),_l()?.updateInlineArtifactBlocks(lt,Kn.artifacts,{suppressTransition:!0}),Xo())});return ia.push(Mu),Su},Cc=(e,t)=>{let r=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(r);return o?Math.max(0,t*parseFloat(o[1])/100):420},Sc=(e,t)=>{let r=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=r?"":"100%",e.style.display=r?"":"flex",e.style.flexDirection=r?"":"column",e.style.flex=r?"":"1 1 auto",e.style.minHeight=r?"":"0",e.style.minWidth=r?"":"0"},kc=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=""},Ac=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",kc(e)},Mc=e=>{e.style.transition=""},Ic=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=""},Tc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ec=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Lc=(e,t,r,n)=>{t?(e.style.boxSizing="border-box",e.style.padding=r,e.style.background=n):(e.style.padding="",e.style.background="",e.style.boxSizing="")},Pc=(e,t)=>Gs(t)?((e,t)=>{let{ownerDocument:r}=e,n=e.parentElement;if(!n)throw Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if("BODY"===o||"HTML"===o)throw Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),l=r.createElement("div"),d=r.createElement("aside"),c=r.createElement("div"),p=!(t?.launcher?.enabled??1)||(t?.launcher?.autoExpand??!1);i.dataset.personaDockRole="push-track",l.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),n.insertBefore(s,e),l.appendChild(e);let u=null,h=()=>{u?.disconnect(),u=null},m=null,g=()=>{m=!0===t?.launcher?.detachedPanel?(e=>{let t=Oa(e),r=t.components?.panel,n=(e,r)=>null==e||""===e?r:Ca(t,e)??e;return{inset:n(r?.inset,sa),canvasBackground:n(r?.canvasBackground,ia)}})(t):null};g();let f=()=>{((e,t,r,n,o,a,s,i)=>{let l=Js(a),d="push"===l.reveal,c=null!=i,p=i?.inset??"",u=i?.canvasBackground??"";((e,t,r,n,o)=>{o?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,n),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(n))})(e,t,r,n,d),((e,t,r,n,o,a)=>{let s=a?t:e;"left"===o?s.firstElementChild!==n&&s.replaceChildren(n,r):s.lastElementChild!==n&&s.replaceChildren(r,n)})(e,t,r,n,l.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=l.side,e.dataset.personaDockOpen=s?"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",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let h=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,g=a?.launcher?.mobileBreakpoint??640,f=null!=h&&h.innerWidth<=g;if(m&&f&&s)e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ic(t),Mc(n),Ac(n),Tc(r),Ec(o,n),Lc(n,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String(a?.launcher?.zIndex??1e5),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(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",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");else if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Ac(n),((e,t)=>{!1===t?e.style.maxHeight="":(e.style.maxHeight="100vh",e.style.maxHeight=t)})(n,l.maxHeight),Lc(n,c&&s,p,u),"overlay"===l.reveal){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ic(t),Mc(n),Tc(r),Ec(o,n);let a=l.animate?"transform 180ms ease":"none",i="right"===l.side?"translateX(100%)":"translateX(-100%)",d=s?"translateX(0)":i;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=l.width,n.style.maxWidth=l.width,n.style.minWidth=l.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=a,n.style.transform=d,n.style.pointerEvents=s?"auto":"none",n.style.zIndex="2","right"===l.side?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if("push"===l.reveal){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Mc(n),kc(n),Ec(o,n);let a=Cc(l.width,e.clientWidth),i=Math.max(0,e.clientWidth),d=l.animate?"margin-left 180ms ease":"none",c="right"===l.side?s?-a:0:s?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=`${i+a}px`,t.style.transition=d,t.style.marginLeft=`${c}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${i}px`,r.style.maxWidth=`${i}px`,r.style.minWidth=`${i}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=l.width,n.style.minWidth=l.width,n.style.maxWidth=l.width,n.style.position="relative",n.style.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Ic(t),kc(n),Tc(r),Ec(o,n);let a="emerge"===l.reveal;a?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let i=s?l.width:"0px",d=l.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease"+(c?", padding 180ms ease":""):"none",u=!s;if(n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${i}`,n.style.width=i,n.style.maxWidth=i,n.style.minWidth=i,n.style.minHeight="0",((e,t)=>{!1===t?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")})(n,l.maxHeight),n.style.overflow=a||u?"hidden":"visible",n.style.transition=d,a){n.style.alignItems="right"===l.side?"flex-start":"flex-end";let t=c?`calc(${Cc(l.width,e.clientWidth)}px - (2 * ${p}))`:l.width;o.style.width=t,o.style.minWidth=t,o.style.maxWidth=t,o.style.boxSizing="border-box"}}})(s,i,l,d,c,t,p,m)},y=null,b=()=>{y?.(),y=null,!0===t?.launcher?.detachedPanel&&"auto"===t?.colorScheme&&(y=qa(()=>{g(),f()}))},v=!1,w=()=>{f(),h(),"push"===Js(t).reveal&&typeof ResizeObserver<"u"&&(u=new ResizeObserver(()=>{f()}),u.observe(s)),p&&!v&&"true"!==s.dataset.personaDockMobileFullscreen&&(v=!0,((e,t)=>{let r=e.parentElement;if(!r)return;let n=e.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(n);let o=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),o&&!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."+(!1===t.maxHeight?" 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.")})(s,Js(t)))},x=s.ownerDocument.defaultView,C=()=>{w()};return x?.addEventListener("resize",C),"push"===Js(t).reveal?(i.appendChild(l),i.appendChild(d),s.appendChild(i)):(s.appendChild(l),s.appendChild(d)),w(),b(),{mode:"docked",host:c,shell:s,syncWidgetState(e){let t=!e.launcherEnabled||e.open;p!==t&&(p=t,w())},updateConfig(e){t=e,!1===(t?.launcher?.enabled??!0)&&(p=!0),g(),w(),b()},destroy(){x?.removeEventListener("resize",C),y?.(),y=null,h(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),s.remove()}}})(e,t):((e,t)=>{let r=e.ownerDocument.createElement("div");return Sc(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(e){Sc(r,e)},destroy(){r.remove()}}})(e,t),Bc=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let r=t.head.querySelector("link[data-persona]");if(!r)return;let n=r.cloneNode(!0);e.insertBefore(n,e.firstChild)},Nc=[],Rc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Hc=new Set(["button","a","input","select","textarea","details","summary"]),$c=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Wc=/\b(product|card|item|listing|result)\b/i,Dc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i;function Fc(e){let t="string"==typeof e.className?e.className:"";if(Wc.test(t)||e.id&&Wc.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&Wc.test(r.value))return!0}return!1}function Oc(e){return Dc.test((e.textContent??"").trim())}function zc(e){let t=e.querySelectorAll("a[href]");for(let e=0;e<t.length;e++){let r=t[e].getAttribute("href")??"";if(r&&"#"!==r&&!r.toLowerCase().startsWith("javascript:"))return!0}return!1}function qc(e){let t=e.match(Dc);return t?t[0]:null}function jc(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 r=e.querySelector("h1, h2, h3, h4, h5, h6");return r?.textContent?.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function _c(e){return Fc(e)&&Oc(e)&&(zc(e)||function(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}(e))?5200:0}function Vc(e){return!Fc(e)||Oc(e)||!zc(e)||(e.textContent??"").trim().length<20||!e.querySelector("h1, h2, h3, h4, h5, h6, .title")&&!e.querySelector(".snippet, .description, p")?0:2800}let Uc=[{id:"commerce-card",scoreElement:e=>_c(e),shouldSuppressDescendant(e,t,r){if(t===e||!e.contains(t))return!1;if("static"===r.interactivity){let e=r.text.trim();return!!(0===e.length||Dc.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(0===_c(e))return null;let{title:r,href:n}=jc(e),o=qc((e.textContent??"").trim())??qc(t.text)??"",a=function(e){let t=[],r=e=>{let r=e.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(e=>r(e.textContent??"")),e.querySelectorAll('[role="button"]').forEach(e=>r(e.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(e=>{r(e.value??"")}),t.slice(0,6)}(e);return[n&&r?`[${r}](${n})${o?`: ${o}`:""}`:r?`${r}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join("\n")}},{id:"result-card",scoreElement:e=>Vc(e),formatSummary(e,t){if(0===Vc(e))return null;let{title:r,href:n}=jc(e);return[n&&r?`[${r}](${n})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join("\n")}}];function Gc(e){return typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}let Kc=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Jc(e){let t=e.tagName.toLowerCase(),r=e.getAttribute("role");return"a"===t&&e.hasAttribute("href")?"navigable":"input"===t||"select"===t||"textarea"===t||"textbox"===r||"combobox"===r||"listbox"===r||"spinbutton"===r?"input":"button"===t||"button"===r||Hc.has(t)||r&&$c.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||"true"===e.getAttribute("contenteditable")?"clickable":"static"}function Qc(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility)return!1}catch{}return"none"!==e.style.display&&"hidden"!==e.style.visibility}function Xc(e){let t={},r=e.id;r&&(t.id=r);let n=e.getAttribute("href");n&&(t.href=n);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let i=e.getAttribute("name");i&&(t.name=i);let l=e.getAttribute("role");l&&(t.role=l);for(let r=0;r<e.attributes.length;r++){let n=e.attributes[r];n.name.startsWith("data-")&&(t[n.name]=n.value)}return t}function Yc(e){let t=e.tagName.toLowerCase();if(e.id){let t=`#${Gc(e.id)}`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}for(let r of Kc){let n=e.getAttribute(r);if(n){let o=`${t}[${r}="${Gc(n)}"]`;try{if(1===e.ownerDocument.querySelectorAll(o).length)return o}catch{}}}let r=Array.from(e.classList).filter(e=>e&&!e.startsWith("persona-")).slice(0,3);if(r.length>0){let n=`${t}.${r.map(e=>Gc(e)).join(".")}`;try{if(1===e.ownerDocument.querySelectorAll(n).length)return n}catch{}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0){let t=`${n}:nth-of-type(${r+1})`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}}}let n=e.parentElement;if(n){let r=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function Zc(e,t){let r=e.tagName.toLowerCase(),n=(e.textContent??"").trim().substring(0,t);return{selector:Yc(e),tagName:r,text:n,role:e.getAttribute("role"),interactivity:Jc(e),attributes:Xc(e)}}function ep(e,t,r,n){let o=function(e){return"static"===e?100:3e3}(t.interactivity),a=null;for(let s of r){let r=s.scoreElement(e,t,n);r>0&&(o+=r,s.formatSummary&&!a&&(a=s))}return{score:o,formattingRule:a}}function tp(e,t){for(let r of e)if(t.el!==r.el&&r.formattingRule?.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}let rp={components:{panel:{borderRadius:"0",shadow:"none"}}},np={id:"shop",label:"Shopping Assistant",config:{theme:{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"}}},launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"🛍️",position:"bottom-right",width:v},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"]}},op={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:rp}},ap={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:rp}},sp={shop:np,minimal:op,fullscreen:ap},ip=typeof document<"u"?document.currentScript?.src??null:null,lp=(e,t=`host ${e} alongside it`)=>()=>{let r=ip?.replace(/index\.global\.js($|\?)/,`${e}$1`);return r&&r!==ip?import(r):Promise.reject(Error(`Could not derive the ${e} URL from the widget script URL (${ip??"unavailable"}). Self-hosted deployments that rename index.global.js should ${t}.`))};return(e=>{Ze=e})(lp("webmcp-polyfill.js","install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp")),fe(lp("markdown-parsers.js")),Ue(lp("client-stream.js")),br(lp("client-history.js")),zr(lp("ui-extras.js")),Kr(lp("session-actions.js")),Xd(lp("history-shell.js")),(e=>{yn=e})(lp("runtype-tts.js","host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly")),Xo(lp("context-mentions.js")),ta(lp("context-mentions-inline.js")),Vd(lp("history-view.js")),$s(lp("animations-extra.js","host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin")),Ml(lp("approval-ui.js")),hn(lp("voice-runtime.js")),pt(lp("voice-client-tools.js")),ql(lp("artifacts-ui.js")),Ad(lp("forms-ui.js")),$(lp("icons-extra.js","host icons-extra.js alongside it, or register the icons they use via registerIcons()")),it(lp("webmcp-runtime.js")),xn(lp("session-reconnect.js")),Pl(lp("event-stream-view.js")),e.ASK_USER_QUESTION_CLIENT_TOOL=Xt,e.ASK_USER_QUESTION_PARAMETERS_SCHEMA=Qt,e.ASK_USER_QUESTION_TOOL_NAME=bt,e.AgentWidgetClient=Hr,e.AgentWidgetSession=In,e.AttachmentManager=Bn,e.BrowserSpeechEngine=sn,e.DEFAULT_COMPONENTS=wa,e.DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH="440px",e.DEFAULT_FLOATING_LAUNCHER_WIDTH=v,e.DEFAULT_PALETTE=ma,e.DEFAULT_SEMANTIC=ya,e.DEFAULT_WIDGET_CONFIG=I,e.HistoryProviderError=$r,e.PRESETS=sp,e.PRESET_FULLSCREEN=ap,e.PRESET_MINIMAL=op,e.PRESET_SHOP=np,e.ReadAloudController=ln,e.SUGGEST_REPLIES_CLIENT_TOOL=_t,e.SUGGEST_REPLIES_PARAMETERS_SCHEMA=jt,e.SUGGEST_REPLIES_TOOL_NAME=qt,e.THEME_ZONES={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"},e.VERSION=mr,e.WEBMCP_TOOL_PREFIX=Je,e.applyFeaturePreferences=bd,e.applyThemeVariables=za,e.attachHeaderToContainer=ui,e.buildComposer=Ci,e.buildDefaultHeader=yi,e.buildHeader=pi,e.buildHeaderWithLayout=xi,e.buildMinimalHeader=bi,e.builtInClientToolsForDispatch=Yt,e.canonicalArtifactDisplayMode=Xr,e.collectEnrichedPageContext=function(e={}){let t=function(e){let t=e.options??{},r=t.maxElements??e.maxElements??80,n=t.excludeSelector??e.excludeSelector??".persona-host",o=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,s=t.root??e.root,i=t.mode??"structured",l=t.maxCandidates??Math.max(500,10*r),d=e.rules??Uc;return"simple"===i&&e.rules&&e.rules.length>0?(typeof console<"u"&&"function"==typeof console.warn&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.'),d=[]):"simple"===i&&(d=[]),{mode:i,maxElements:r,maxCandidates:l,excludeSelector:n,maxTextLength:o,visibleOnly:a,root:s,rules:d}}(e),r=t.root??document.body;return r?"simple"===t.mode?function(e,t){let r=[],n=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=o.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let t=a,s=t.tagName.toLowerCase();if(Rc.has(s)){a=o.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){a=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Qc(t)){a=o.nextNode();continue}let i=Zc(t,e.maxTextLength),l=i.text.length>0,d=Object.keys(i.attributes).length>0&&!Object.keys(i.attributes).every(e=>"role"===e);if(!l&&!d){a=o.nextNode();continue}n.has(i.selector)||(n.add(i.selector),r.push(i))}a=o.nextNode()}let s=[],i=[];for(let e of r)"static"===e.interactivity?i.push(e):s.push(e);return[...s,...i].slice(0,e.maxElements)}(t,r):function(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,o=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let t=i,l=t.tagName.toLowerCase();if(Rc.has(l)){i=s.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Qc(t)){i=s.nextNode();continue}let d=Zc(t,e.maxTextLength),c=d.text.length>0,p=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(e=>"role"===e);if(!c&&!p||n.has(d.selector)){i=s.nextNode();continue}n.add(d.selector);let{score:u,formattingRule:h}=ep(t,d,e.rules,r);o.push({el:t,domIndex:a,enriched:d,score:u,formattingRule:h}),a+=1}i=s.nextNode()}o.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),n=+("static"===t.enriched.interactivity);return r===n?t.score===e.score?e.domIndex-t.domIndex:t.score-e.score:r-n});let l=[];for(let t of o){if(l.length>=e.maxElements)break;tp(l,t)||l.push(t)}return l.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),n=+("static"===t.enriched.interactivity);return r===n?1===r&&t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex:r-n}),l.map(e=>{let t;if(e.formattingRule?.formatSummary){let n=e.formattingRule.formatSummary(e.el,e.enriched,r);n&&(t=n)}let n={...e.enriched};return t&&(n.formattedSummary=t),n})}(t,r):[]},e.componentRegistry=Nl,e.createActionManager=Wd,e.createAgentExperience=xc,e.createAskUserQuestionBubble=(e,t)=>{let r=L("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let n=Tt(t);Pt(r,n);let o=L("span","persona-ask-stub-label"),{complete:a}=Et(e);return o.textContent=a?"Awaiting your response…":"Preparing options…",r.appendChild(o),r},e.createBubbleWithLayout=(e,t,r,n,o,a)=>{let s=r??{};return"user"===e.role&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):"assistant"===e.role&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):$i(e,t,r,n,0,a)},e.createCSATFeedback=ic,e.createComboButton=fi,e.createComponentMiddleware=function(){let e=tc();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}},e.createComponentStreamParser=tc,e.createDefaultSanitizer=Le,e.createDirectivePostprocessor=e=>{let t=xe(e);return e=>{let r=[],n=Ie(e,r),o=t(n);return r.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n=`<div class="persona-form-directive" data-tv-form="${Ae(t)}"></div>`;o=o.replace(r,n)}),o}},e.createDropdownMenu=hi,e.createFlexibleJsonStreamParser=e=>{let t=null,r=0,n=e||(e=>{if(!e||"object"!=typeof e)return null;let t=e=>"string"==typeof e?rr(e):null;if(e.component&&"string"==typeof e.component)return"string"==typeof e.text?rr(e.text):"";if("init"===e.type&&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 o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(e.length<=r)return null===t?null:{text:t,raw:e};try{let r=(0,yt.parse)(e,yt.STR|yt.OBJ),o=n(r);null!==o&&(t=o)}catch{}return r=e.length,{text:t||"",raw:e}},close:()=>{}}},e.createIconButton=mi,e.createImagePart=function(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}},e.createJsonStreamParser=ur,e.createLabelButton=gi,e.createLocalStorageAdapter=Od,e.createMarkdownProcessor=we,e.createMarkdownProcessorFromConfig=xe,e.createMessageActions=Hi,e.createNPSFeedback=lc,e.createPlainTextParser=cr,e.createRegexJsonParser=pr,e.createSplitButton=function(e){let{label:t,icon:r,iconSize:n,iconOnly:o,menuItems:a,onSelect:s,onPrimary:i,position:l="bottom-left",portal:d,chevronLabel:c="More options",chevronIconSize:p,className:u,primaryClassName:h,chevronClassName:m}=e,g=L("div","persona-split-btn"+(u?" "+u:"")),f={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:i},y=o&&r?mi({...f,icon:r,size:n??14}):gi({...f,icon:r,iconSize:n??14}),b=mi({icon:"chevron-down",label:c,size:p??14,className:"persona-split-btn-chevron"+(m?" "+m:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});g.append(y,b);let v=null,w=()=>{if(v)return v;let e=("function"==typeof d?d():d)??void 0;return v=hi({items:a,onSelect:s,anchor:g,position:l,portal:e,onOpenChange:e=>{b.setAttribute("aria-expanded",e?"true":"false")}}),e||g.appendChild(v.element),v};return g.isConnected?w():requestAnimationFrame(()=>{v||w()}),b.addEventListener("click",e=>{e.stopPropagation(),w().toggle()}),{element:g,primaryButton:y,chevronButton:b,openMenu:()=>w().show(),closeMenu:()=>v?.hide(),toggleMenu:()=>w().toggle(),destroy:()=>{v?.destroy(),g.remove()}}},e.createStandardBubble=$i,e.createTextPart=xr,e.createTheme=Ia,e.createThemeObserver=qa,e.createToggleGroup=function(e){let{items:t,selectedId:r,onSelect:n,className:o}=e,a=L("div","persona-toggle-group"+(o?" "+o:""));a.setAttribute("role","group");let s=r,i=[];function l(){for(let e of i)e.btn.setAttribute("aria-pressed",e.id===s?"true":"false")}for(let e of t){let t;e.icon?t=mi({icon:e.icon,label:e.label,className:e.className,onClick:()=>{s=e.id,l(),n(e.id)}}):(t=L("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",()=>{s=e.id,l(),n(e.id)})),t.setAttribute("aria-pressed",e.id===s?"true":"false"),i.push({id:e.id,btn:t}),a.appendChild(t)}return{element:a,setSelected:function(e){s=e,l()}}},e.createTypingIndicator=Ti,e.createWidgetHostLayout=Pc,e.createXmlParser=hr,e.defaultActionHandlers=Hd,e.defaultJsonActionParser=Nd,e.defaultParseRules=Uc,e.detectColorScheme=Da,e.directivePostprocessor=e=>{let t=[],r=Ie(e,t),n=Se(r);return t.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=`<div class="persona-form-directive" data-tv-form="${Ae(t)}"></div>`;n=n.replace(r,o)}),n},e.ensureAskUserQuestionSheet=Ot,e.escapeHtml=ke,e.extractComponentDirectiveFromMessage=ac,e.fileToImagePart=async function(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},n.onerror=()=>r(Error("Failed to read file")),n.readAsDataURL(e)})},e.formatEnrichedContext=function(e,t={}){if(0===e.length)return"No page elements found.";let r=t.mode??"structured",n=[];if("structured"===r){let t=e.map(e=>e.formattedSummary).filter(e=>!!e&&e.length>0);t.length>0&&n.push(`Structured summaries:\n${t.map(e=>`- ${e.split("\n").join("\n ")}`).join("\n")}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let t of e)"structured"===r&&t.formattedSummary||o[t.interactivity].push(t);if(o.clickable.length>0){let e=o.clickable.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}" (clickable)`);n.push(`Interactive elements:\n${e.join("\n")}`)}if(o.navigable.length>0){let e=o.navigable.map(e=>`- ${e.selector}${e.attributes.href?`[href="${e.attributes.href}"]`:""}: "${e.text.substring(0,100)}" (navigable)`);n.push(`Navigation links:\n${e.join("\n")}`)}if(o.input.length>0){let e=o.input.map(e=>`- ${e.selector}${e.attributes.type?`[type="${e.attributes.type}"]`:""}: "${e.text.substring(0,100)}" (input)`);n.push(`Form inputs:\n${e.join("\n")}`)}if(o.static.length>0){let e=o.static.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}"`);n.push(`Content:\n${e.join("\n")}`)}return n.join("\n\n")},e.generateAssistantMessageId=gt,e.generateMessageId=function(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`},e.generateStableSelector=Yc,e.generateUserMessageId=mt,e.getActiveTheme=Oa,e.getAgentWidgetHandles=()=>[...Nc],e.getColorScheme=Fa,e.getDisplayText=function(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("")},e.getHeaderLayout=wi,e.getImageParts=function(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)},e.getPreset=function(e){return sp[e]},e.hasComponentDirective=oc,e.hasImages=wr,e.headerLayouts=vi,e.initAgentWidget=e=>{let t,r=(e=>{if(typeof window>"u"||typeof document>"u")throw Error("Chat widget can only be mounted in a browser environment");if("string"==typeof e){let t=document.querySelector(e);if(!t)throw Error(`Chat widget target "${e}" was not found`);return t}return e})(e.target),n=!0===e.useShadowDom,o=r.ownerDocument,a=e.config,s=Pc(r,a),i=[],l=(e,t)=>{let a=!(t?.launcher?.enabled??1)||Gs(t),s=o.createElement("div");if(s.setAttribute("data-persona-root","true"),a&&(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0",s.style.minWidth="0"),n){let t=e.attachShadow({mode:"open"});t.appendChild(s),Bc(t,o)}else e.appendChild(s),Bc(e,o);return r.id&&s.setAttribute("data-persona-instance",r.id),s},d=()=>{s.syncWidgetState(t.getState())},c=()=>{let r=l(s.host,a);t=xc(r,a,{debugTools:e.debugTools}),i.forEach(e=>e()),i=[t.on("widget:opened",d),t.on("widget:closed",d)],d()},p=()=>{i.forEach(e=>e()),i=[],t.destroy()};c(),e.onChatReady?.();let u=e=>{p(),s.destroy(),s=Pc(r,e),a=e,c()},h=new Proxy({update(e){let r=Bd(a??{},e),n=Gs(a),o=Gs(r),i=Ks(a),l=Ks(r);n!==o||i!==l?u(r):(a=r,s.updateConfig(a),t.update(e),d())},destroy(){p(),s.destroy();let t=Nc.indexOf(h);-1!==t&&Nc.splice(t,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},{get(e,r,n){if("host"===r)return s.host;if(r in e)return Reflect.get(e,r,n);let o=t[r];return"function"==typeof o?o.bind(t):o}});return Nc.push(h),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=h),h},e.isAskUserQuestionMessage=It,e.isComponentDirectiveType=function(e){return"object"==typeof e&&!!e&&"component"in e&&"string"==typeof e.component&&"props"in e&&"object"==typeof e.props},e.isDockedMountMode=Gs,e.isHistoryProviderError=function(e){return e instanceof $r},e.isSuggestRepliesMessage=Vt,e.isWebMcpToolName=nt,e.isWelcomeVisible=Xi,e.latestAgentSuggestions=Gt,e.listRegisteredStreamAnimations=()=>Array.from(fs.keys()),e.loadMarkdownParsers=ye,e.markdownPostprocessor=Se,e.mergeWithDefaults=E,e.normalizeContent=function(e){return"string"==typeof e?[{type:"text",text:e}]:e},e.normalizeMediaType=Yr,e.onMarkdownParsersReady=be,e.parseAskUserQuestionPayload=Et,e.parseSuggestRepliesPayload=Ut,e.parseWidgetPreferenceSlice=md,e.pickBestVoice=an,e.pluginRegistry=Td,e.registerIcons=e=>{for(let[t,r]of Object.entries(e))O.set(t,r);U()>0&&!q&&_(!1)},e.registerStreamAnimationPlugin=bs,e.removeAskUserQuestionSheet=zt,e.renderComponentDirective=rc,e.renderLoadingIndicatorWithFallback=Ei,e.renderLucideIcon=K,e.resolveArtifactDisplay=Zr,e.resolveArtifactDisplayMode=en,e.resolveConfigPreferences=vd,e.resolveDockConfig=Js,e.resolveSanitizer=Pe,e.resolveTokens=Sa,e.resolveWelcomeConfig=Qi,e.stripWebMcpPrefix=rt,e.themeToCssVariables=Pa,e.unregisterStreamAnimationPlugin=e=>{gs.some(t=>t.name===e)||fs.delete(e)},e.validateImageFile=function(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10485760){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}},e.validateTheme=ka,e}({});
9
9
  //# sourceMappingURL=index.global.js.map