@runtypelabs/persona 4.29.1 → 4.29.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/approval-ui.d.cts +1 -1
- package/dist/approval-ui.d.ts +1 -1
- package/dist/artifacts-ui.d.cts +2 -2
- package/dist/artifacts-ui.d.ts +2 -2
- package/dist/{chunk-DGlFKA0r.js → chunk-B2HCRERn.js} +1 -1
- package/dist/{chunk-BcLIgi1h.js → chunk-Car1mORT.js} +1 -1
- package/dist/chunk-DrpuvY5W.js +1 -0
- package/dist/client-history.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/{composer-input-B0P4OtNi.d.cts → composer-input-C3Xh1Qzj.d.cts} +1 -1
- package/dist/{composer-input-B0P4OtNi.d.ts → composer-input-C3Xh1Qzj.d.ts} +1 -1
- package/dist/{context-mention-manager-DmLI_RM6.d.cts → context-mention-manager-BsEiGObk.d.cts} +1 -1
- package/dist/{context-mention-manager-DmLI_RM6.d.ts → context-mention-manager-BsEiGObk.d.ts} +1 -1
- package/dist/context-mentions-inline.d.cts +2 -2
- package/dist/context-mentions-inline.d.ts +2 -2
- package/dist/context-mentions.d.cts +3 -3
- package/dist/context-mentions.d.ts +3 -3
- package/dist/{defaults-DVo1wbZs.d.cts → defaults-DN-L67ak.d.cts} +1 -1
- package/dist/{defaults-DVo1wbZs.d.ts → defaults-DN-L67ak.d.ts} +1 -1
- package/dist/event-stream-view.d.cts +1 -1
- package/dist/event-stream-view.d.ts +1 -1
- package/dist/{fallback-speech-engine-BMnlmKnY.d.cts → fallback-speech-engine-Cph8FTux.d.cts} +1 -1
- package/dist/{fallback-speech-engine-BMnlmKnY.d.ts → fallback-speech-engine-Cph8FTux.d.ts} +1 -1
- package/dist/forms-ui.d.cts +2 -2
- package/dist/forms-ui.d.ts +2 -2
- package/dist/history-view.d.cts +1 -1
- package/dist/history-view.d.ts +1 -1
- package/dist/index.cjs +51 -51
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +37 -37
- package/dist/index.js.map +1 -1
- package/dist/{markdown-parsers-loader-CeovcyYf.d.cts → markdown-parsers-loader-C4Xze-Jw.d.cts} +1 -1
- package/dist/{markdown-parsers-loader-CeovcyYf.d.ts → markdown-parsers-loader-C4Xze-Jw.d.ts} +1 -1
- package/dist/{preview-Bkb4UrQC.d.cts → preview-m9QlqsZi.d.cts} +2 -2
- package/dist/{preview-Bkb4UrQC.d.ts → preview-m9QlqsZi.d.ts} +2 -2
- package/dist/{session-iLyKipoM.d.cts → session-BtvvmWnw.d.cts} +6 -6
- package/dist/{session-iLyKipoM.d.ts → session-BtvvmWnw.d.ts} +6 -6
- package/dist/session-reconnect.d.cts +2 -2
- package/dist/session-reconnect.d.ts +2 -2
- package/dist/smart-dom-reader.d.cts +1 -1
- package/dist/smart-dom-reader.d.ts +1 -1
- package/dist/theme-editor-preview.cjs +54 -54
- package/dist/theme-editor-preview.d.cts +1 -1
- package/dist/theme-editor-preview.d.ts +1 -1
- package/dist/theme-editor-preview.js +35 -35
- package/dist/theme-editor.d.cts +2 -2
- package/dist/theme-editor.d.ts +2 -2
- package/dist/theme-reference.d.cts +2 -2
- package/dist/theme-reference.d.ts +2 -2
- package/dist/{types-BuDirJkQ.d.cts → types-DL-oBHE1.d.cts} +6 -0
- package/dist/{types-BuDirJkQ.d.ts → types-DL-oBHE1.d.ts} +6 -0
- package/dist/voice-client-tools.d.cts +1 -1
- package/dist/voice-client-tools.d.ts +1 -1
- package/dist/voice-runtime.cjs +1 -1
- package/dist/voice-runtime.d.cts +2 -2
- package/dist/voice-runtime.d.ts +2 -2
- package/dist/voice-runtime.js +1 -1
- package/dist/voice-worklet-player.d.cts +2 -2
- package/dist/voice-worklet-player.d.ts +2 -2
- package/dist/{webmcp-runtime-entry-CXLjRt1k.d.cts → webmcp-runtime-entry-T6SU_TlL.d.cts} +1 -1
- package/dist/{webmcp-runtime-entry-CXLjRt1k.d.ts → webmcp-runtime-entry-T6SU_TlL.d.ts} +1 -1
- package/dist/webmcp-runtime.d.cts +1 -1
- package/dist/webmcp-runtime.d.ts +1 -1
- package/package.json +1 -1
- package/src/generated/runtype-openapi-contract.ts +6 -0
- package/src/session.test.ts +23 -0
- package/src/session.ts +35 -17
- package/src/ui.scroll.test.ts +7 -2
- package/src/ui.stream-replay.test.ts +86 -0
- package/src/ui.streaming-coalescing.test.ts +183 -0
- package/src/ui.ts +120 -106
- package/src/ui.typing-indicator.test.ts +21 -0
- package/src/utils/message-fingerprint.test.ts +9 -0
- package/src/utils/message-fingerprint.ts +18 -5
- package/src/utils/morph.ts +10 -0
- package/dist/chunk-Csks3Qw1.js +0 -1
package/dist/index.global.js
CHANGED
|
@@ -4,5 +4,5 @@ var AgentWidget=function(e){var t=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),
|
|
|
4
4
|
*
|
|
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
|
-
*/var m=t(e=>{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 g=(e,t=24,r="currentColor",o=2)=>{if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.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 o=document.createElementNS("http://www.w3.org/2000/svg",t);Object.entries(r).forEach(([e,t])=>{"stroke"!==e&&o.setAttribute(e,String(t))}),n.appendChild(o)}),n},f=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function y(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[e,o]of Object.entries(t)){let t=r[e];r[e]=f(t)&&f(o)?y(t,o):o}return r}let b=Symbol("persona.defaultsProvenance"),v=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function w(e,t=""){return Object.entries(e).flatMap(([e,r])=>{let o=t?`${t}.${e}`:e;return v(r)?w(r,o):[o]})}function x(e,t){for(let r of t.split(".")){if(!v(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?.[b]??t.filter(t=>"explicit"===x(e,t))}function S(e,t){return Object.defineProperty(e,b,{value:t,enumerable:!0,configurable:!0}),e}function k(e,t,r){return S(e,C(t,w(r)))}let A=Symbol("persona.panelAliasProvenance"),M=(e,t)=>null!=e&&Object.prototype.hasOwnProperty.call(e,t),I=(e,t)=>M(e,t)&&void 0!==e[t],T=e=>{let t=e?.[A];return t?{...t}:(e=>({launcherWidth:I(e?.launcher,"width"),legacyLauncherWidth:I(e,"launcherWidth"),sidebarWidth:I(e?.launcher,"sidebarWidth"),dockWidth:I(e?.launcher?.dock,"width")}))(e)},E=(e,t)=>(Object.defineProperty(e,A,{value:t,enumerable:!0,configurable:!0}),e),L=(e,t)=>E(e,T(t)),P="min(440px, calc(100vw - 24px))",B={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},R={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},N={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:P,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:B,reasoningDisplay:R,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},$={},H={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 W(e){return!0===e?.future?.v5Defaults?"v5":"v4"}function D(e){let t="v5"===W(e)?H:$;return y(N,t)}let F=D();function O(e,t){if(e||t)return e?t?y(e,t):e:t}function z(e){let t=D(e);return e?k(L({...t,...e,theme:O(t.theme,e.theme),darkTheme:O(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,o=e.features?.artifacts,n=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===o?void 0:{...r,...o,layout:{...r?.layout,...o?.layout}},g=void 0===n&&void 0===a?void 0:{...n,...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,H):k(L(t),void 0,H)}let q=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},j=(e,t={},...r)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),void 0!==t.text&&(o.textContent=t.text),t.attrs)for(let[e,r]of Object.entries(t.attrs))o.setAttribute(e,r);if(t.style){let e=o.style,r=t.style;for(let t of Object.keys(r)){let o=r[t];null!=o&&(e[t]=o)}}let n=r.filter(e=>null!=e);return n.length>0&&o.append(...n),o},_=(...e)=>e.filter(Boolean).join(" "),U=e=>{let{fallbackImport:t,resetOnSetLoader:r=!1}=e,o=null,n=null,a=null;return{setLoader:e=>{o=e,r&&(n=null,a=null)},load:()=>n?Promise.resolve(n):a||(a=(o??t)().then(e=>(n=e,e)).catch(e=>{throw a=null,e}),a),provide:e=>{n=e},getSync:()=>n}},{setLoader:V,load:K}=U({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),G=V,J=K,X={activity:m.Activity,"arrow-down":m.ArrowDown,"arrow-up":m.ArrowUp,"arrow-up-right":m.ArrowUpRight,bot:m.Bot,"chevron-down":m.ChevronDown,"chevron-up":m.ChevronUp,"chevron-right":m.ChevronRight,"chevron-left":m.ChevronLeft,check:m.Check,clipboard:m.Clipboard,"clipboard-copy":m.ClipboardCopy,"code-xml":m.CodeXml,copy:m.Copy,file:m.File,"file-code":m.FileCode,"file-spreadsheet":m.FileSpreadsheet,"file-text":m.FileText,"image-plus":m.ImagePlus,loader:m.Loader,"loader-circle":m.LoaderCircle,mic:m.Mic,paperclip:m.Paperclip,quote:m.Quote,"refresh-cw":m.RefreshCw,search:m.Search,send:m.Send,"shield-alert":m.ShieldAlert,"shield-check":m.ShieldCheck,"shield-x":m.ShieldX,square:m.Square,"thumbs-down":m.ThumbsDown,"thumbs-up":m.ThumbsUp,upload:m.Upload,"volume-2":m.Volume2,x:m.X,"at-sign":m.AtSign,"arrow-left":m.ArrowLeft,"arrow-right":m.ArrowRight,"external-link":m.ExternalLink,ellipsis:m.Ellipsis,"ellipsis-vertical":m.EllipsisVertical,menu:m.Menu,"panel-left":m.PanelLeft,plus:m.Plus,minus:m.Minus,pencil:m.Pencil,trash:m.Trash,"trash-2":m.Trash2,download:m.Download,maximize:m.Maximize,minimize:m.Minimize,"message-square":m.MessageSquare,star:m.Star,eye:m.Eye,history:m.History},Q="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("."),Y=new Map(Object.entries(X)),Z=new Set,ee=!1,te=new Set,re=e=>{let t=[...te];e&&te.clear();for(let e of t)try{e()}catch{}},oe=e=>ee?()=>{}:(te.add(e),()=>{te.delete(e)}),ne=()=>{let e=0;for(let t of[...Z]){let r=Y.get(t.name);if(!r)continue;Z.delete(t),e++;let o=g(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},ae=!1,se=(e,t=24,r="currentColor",o=2)=>{let n=Y.get(e);if(n)return g(n,t,r,o);if(Q.includes(e)){ae&&=!1;let n=((e,t,r)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o})(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}),J().then(e=>{if(!ee){for(let[t,r]of Object.entries(e.EXTRA_LUCIDE_ICONS))Y.has(t)||Y.set(t,r);ee=!0,ne(),re(!0)}}).catch(e=>{ae=!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},ie=["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"],le=(e,t)=>{let r=q("div",["persona-message-bubble",e,...ie].join(" "));return r.id=`bubble-${t}`,r.setAttribute("data-message-id",t),r},de=e=>{let t=q("button",e.expandable?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},ce=(e,t,r)=>{e.innerHTML="";let o=g(t?m.ChevronUp:m.ChevronDown,16,r,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},pe=(e,t,r)=>{if(!r.expandable)return e.append(t),null;let o=q("div","persona-flex persona-items-center");ce(o,r.expanded,r.iconColor);let n=q("div",r.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return n.append(o),e.append(t,n),o},ue=e=>{let t=q("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let 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},he=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&ce(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"},me=(e,t,r)=>{let o=r.stateSet.has(e),n=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),s=t.querySelector(`[data-persona-collapsed-preview="${r.previewKind}"]`);if(!n||!a)return;n.setAttribute("aria-expanded",o?"true":"false");let i=n.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");i&&ce(i,o,r.iconColor),a.style.display=o?"":"none",s&&(s.style.display=o?"none":s.textContent||s.childNodes.length?"":"none")};function ge(e,t){let r="tool"===t?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[r]:{..."tool"===t?B:R,...!0===e?.future?.v5Defaults?H.features?.[r]:{},...e?.features?.[r]}}}}function fe(e,t){let r="tool"===t?"toolCallDisplay":"reasoningDisplay";return e?.features?.[r]?.variant??(e?.future?.v5Defaults?"row":"card")}function ye(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 be(e,t,r,o){if("row"!==fe(r,o))return e;e.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,e.dataset.activityKind=o,"tool"===o&&void 0===r.toolCall?.shadow&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let n=e.querySelector(":scope > button");if(!n)return e;n.className="persona-activity-header";let a="tool"===o?t.toolCall:t.reasoning,s="complete"!==a?.status,i=t.approval?.status??t.toolCall?.approvalStatus,l=t.toolCall?.interrupted?"interrupted":"denied"===i?"denied":"pending"===i?"awaiting-approval":!1===t.toolCall?.success?"error":s?"pending"===a?.status?"pending":"running":"done";e.dataset.activityState=l;let d=q("span","persona-activity-icon");d.dataset.activityIcon=l;let c="reasoning"===o?r.features?.reasoningDisplay?.iconName:void 0,p=c?se(c,16,"currentColor",2):"pending"===l?g(m.Circle,16,"currentColor",2):"awaiting-approval"===l?g(m.Clock,16,"currentColor",2):se({pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x",interrupted:"x","awaiting-approval":"clock"}[l],16,"currentColor",2);p&&d.appendChild(p),n.querySelector(".persona-reasoning-header-icon")?.remove();let u="tool"===o?"toolCallDisplay":"reasoningDisplay",h=r.features?.[u]?.iconVisibility??(r.future?.v5Defaults?"active":"always");if(("always"===h||"active"===h&&"done"!==l)&&n.prepend(d),"tool"===o&&a){let e=q("span","persona-activity-duration");s&&a.startedAt&&e.setAttribute("data-tool-elapsed",String(a.startedAt));let r=("tool"===o?t.toolCall?.duration:void 0)??a.durationMs??(void 0!==a.completedAt&&void 0!==a.startedAt?a.completedAt-a.startedAt:void 0);e.textContent=void 0===r?"":ye(r),n.appendChild(e)}n.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),n.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}`,n.setAttribute("aria-controls",f.id)),e}function ve(e,t,r,o){let n=q("div","");n.id=`bubble-${e.id}`,n.dataset.messageId=e.id;let a=q("button","");a.type="button",a.dataset.expandHeader="true",a.dataset.bubbleType="tool",a.setAttribute("aria-expanded",String(r));let s=q("div","");"string"==typeof o?s.textContent=o:s.appendChild(o),pe(a,s,{expandable:!0,expanded:r,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let i=q("div","persona-border-t");return i.id=`activity-details-${e.id}`,i.style.display=r?"":"none",a.setAttribute("aria-controls",i.id),n.append(a,i),be(n,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),n.dataset.personaToolGroup="true","shimmer"===t.features?.toolCallDisplay?.loadingAnimation&&(n.dataset.activityGroupShimmer="true"),{bubble:n,body:i}}let we=(e,t,r)=>{let o="transient"===t.mode,n=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)||o&&n&&!1!==t.visible?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},xe=(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:Se,load:ke,provide:Ae,getSync:Me}=U({fallbackImport:()=>import("./markdown-parsers-entry")}),Ie=new Set,Te=Se,Ee=()=>{let e=Me();return e?Promise.resolve(e):ke().then(e=>((()=>{let e=[...Ie];Ie.clear();for(let t of e)try{t()}catch{}})(),e))},Le=e=>Me()?()=>{}:(Ie.add(e),()=>{Ie.delete(e)}),Pe=Me,Be=e=>{let t=null;return r=>{let o=Pe();if(!o)return He(r);if(!t){let{Marked:r}=o,n=e?.markedOptions;t=new r({gfm:n?.gfm??!0,breaks:n?.breaks??!0,pedantic:n?.pedantic,silent:n?.silent});let a=(e=>{if(!e)return;let t={},r=e;if(r.heading){let e=r.heading;t.heading=(t,r,o)=>e({type:"heading",raw:o,depth:r,text:t,tokens:[]})}if(r.code){let e=r.code;t.code=(t,r,o)=>e({type:"code",raw:"",text:t,lang:r,escaped:o})}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,o)=>e({type:"link",raw:"",href:t,title:r??null,text:o,tokens:[]})}if(r.image){let e=r.image;t.image=(t,r,o)=>e({type:"image",raw:"",href:t,title:r??null,text:o})}if(r.list){let e=r.list;t.list=(t,r,o)=>e({type:"list",raw:"",ordered:r,start:o,loose:!1,items:[],itemsHtml:t})}if(r.listitem){let e=r.listitem;t.listitem=(t,r,o)=>e({type:"list_item",raw:"",task:r,checked:o,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)}},Re=e=>e?Be({markedOptions:e.options,renderer:e.renderer}):Be(),Ne=Be(),$e=e=>Ne(e),He=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),We=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),De=e=>`%%FORM_PLACEHOLDER_${e}%%`,Fe=(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=De(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 o=De(t.length);return t.push({token:o,type:r}),o}),r},Oe={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(".")},ze=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,qe=()=>{let e=null;return t=>{let r=Pe();if(!r)return He(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:")&&!ze.test(e)&&(t.attrValue="",t.keepAttr=!1)}})}return e.sanitize(t,Oe)}},je=e=>!1===e?null:"function"==typeof e?e:qe(),_e=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Ue=e=>e.includes("|"),Ve=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())},Ke=e=>`| ${e.join(" | ")} |`,Ge=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Je=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Xe="var(--persona-md-table-scroll-fade, 24px)",Qe=new WeakSet;function Ye(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,o=t-r;e.style.setProperty("--persona-fade-l",r<=1?"0px":Xe),e.style.setProperty("--persona-fade-r",o<=1?"0px":Xe)}function Ze(e){Qe.has(e)||(Qe.add(e),e.addEventListener("scroll",e=>{let t=e.target;t?.classList?.contains("persona-table-scroll")&&Ye(t)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Ye)}let{setLoader:et,load:tt,provide:rt,getSync:ot}=U({fallbackImport:()=>import("./client-stream")}),nt=et,at=tt,st=ot,{setLoader:it,load:lt}=U({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),dt=it,ct=lt,{setLoader:pt,load:ut}=U({fallbackImport:()=>import("@runtypelabs/persona/voice-client-tools")}),ht=pt,mt=ut;function gt(e){return e.startsWith("agent_")?{kind:"agentId",agentId:e}:e.startsWith("flow_")?{kind:"flowId",flowId:e}:null}function ft(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function yt(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}var bt=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}),vt=t(e=>{var t=e&&e.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var o in e)"default"!==o&&!Object.prototype.hasOwnProperty.call(r,o)&&t(r,e,o)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let o=bt();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return o.Allow}}),r(bt(),e);var n=class extends Error{};e.PartialJSON=n;var a=class extends Error{};function s(e,t=o.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 n(`${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)||o.Allow.NULL&t&&r-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||o.Allow.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||o.Allow.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||o.Allow.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||o.Allow._INFINITY&t&&1<r-s&&r-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):"NaN"===e.substring(s,s+3)||o.Allow.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):h()),c=()=>{let n=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(n,++s-Number(a)))}catch(e){l(String(e))}else if(o.Allow.STR&t)try{return JSON.parse(e.substring(n,s-Number(a))+'"')}catch{return JSON.parse(e.substring(n,e.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},p=()=>{s++,m();let n={};try{for(;"}"!==e[s];){if(m(),s>=r&&o.Allow.OBJ&t)return n;let a=c();m(),s++;try{n[a]=d()}catch(e){if(o.Allow.OBJ&t)return n;throw e}m(),","===e[s]&&s++}}catch{if(o.Allow.OBJ&t)return n;i("Expected '}' at end of object")}return s++,n},u=()=>{s++;let r=[];try{for(;"]"!==e[s];)r.push(d()),m(),","===e[s]&&s++}catch{if(o.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(o.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}l(String(r))}}let n=s;for("-"===e[s]&&s++;e[s]&&-1===",]}".indexOf(e[s]);)s++;s==r&&!(o.Allow.NUM&t)&&i("Unterminated number literal");try{return JSON.parse(e.substring(n,s))}catch{"-"===e.substring(n,s)&&i("Not sure what '-' is");try{return JSON.parse(e.substring(n,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 wt="ask_user_question",xt="data-persona-ask-sheet-for",Ct="Type your own answer here",St="Send",kt="data-ask-question-count",At="data-ask-answers",Mt="data-ask-grouped",It=!1,Tt=e=>e.replace(/["\\]/g,"\\$&"),Et=e=>"tool"===e.variant&&!!e.toolCall&&"ask_user_question"===e.toolCall.name,Lt=e=>e?.features?.askUserQuestion??{},Pt=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 o=t.chunks;if(!o||0===o.length)return{payload:null,complete:r};try{let e=o.join(""),t=(0,vt.parse)(e,vt.STR|vt.OBJ|vt.ARR);if(t&&"object"==typeof t)return{payload:t,complete:r}}catch{}return{payload:null,complete:r}},Bt=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!It&&(It=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},Rt=(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))},Nt=(e,t,r)=>{if("rows"!==e)return null;let o=q("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let e=q("span","persona-ask-row-check");o.appendChild(e)}else{let e=q("span","persona-ask-row-badge");e.textContent=String(r+1),o.appendChild(e)}return o},$t=e=>{let t=q("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},Ht=(e,t)=>{let r=q("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 o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=e.freeTextPlaceholder??Ct,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),"rows"!==t){let t=q("button","persona-ask-free-text-submit persona-pointer-events-auto");t.type="button",t.textContent=e.submitLabel??St,t.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(t)}return r},Wt=e=>{let t=e.getAttribute(At);if(!t)return{};try{let e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch{return{}}},Dt=e=>{let t=Number(e.getAttribute("data-ask-current-index")??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Ft=e=>{let t=Number(e.getAttribute("data-ask-question-count")??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ot=e=>"true"===e.getAttribute(Mt),zt=(e,t,r)=>{let o=Lt(r),n=(e=>"pills"===e.getAttribute("data-ask-layout")?"pills":"rows")(e),{payload:a,complete:s}=Pt(t),i=Ot(e),l=Dt(e),d=Ft(e),c=i?((e,t)=>Bt(e)[t]??null)(a,l):(e=>Bt(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,o)=>{let n=q("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");n.setAttribute("role","group"),n.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++)n.appendChild($t(o));return n}if(s.forEach((e,t)=>{n.appendChild(((e,t,r,o)=>{let n=q("button","rows"===r?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(n.type="button",n.setAttribute("role",o?"checkbox":"button"),n.setAttribute("aria-pressed","false"),n.setAttribute("data-ask-user-action","pick"),n.setAttribute("data-option-index",String(t)),n.setAttribute("data-option-label",e.label),"rows"===r){let a=q("span","persona-ask-row-content"),s=q("span","persona-ask-row-label");if(s.textContent=e.label,a.appendChild(s),e.description){let t=q("span","persona-ask-row-description");t.textContent=e.description,a.appendChild(t)}n.appendChild(a);let i=Nt(r,o,t);i&&n.appendChild(i)}else n.textContent=e.label,e.description&&(n.title=e.description);return n})(e,t,o,a))}),!1!==e?.allowFreeText){let e="rows"===o?"Other":"Other…";if("rows"===o){let r=q("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=q("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??Ct,l.setAttribute("data-ask-free-text-input","true"),l.setAttribute("aria-label",t.freeTextLabel??e),i.appendChild(l),r.appendChild(i);let d=Nt(o,a,s.length);d&&r.appendChild(d),n.appendChild(r)}else{let r=q("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,n.appendChild(r)}}return n})(c,o,s,n);g.replaceWith(e)}if("rows"!==n){let t=e.querySelector('[data-ask-free-text-row="true"]');t&&t.replaceWith(Ht(o,n))}let f=e.querySelector('[data-ask-multi-actions="true"]');i||!p||f?(!p||i)&&f&&f.remove():e.appendChild((e=>{let t=q("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=q("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=e.submitLabel??St,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t})(o)),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 o=q("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=q("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=r.backLabel??"Back",n.setAttribute("data-ask-user-action","back"),n.disabled=0===e,o.appendChild(n);let a=q("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=q("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=q("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),o.appendChild(a),o})(l,d,o);y?y.replaceWith(t):e.appendChild(t)}else y&&y.remove();(e=>{let t=Wt(e)[Dt(e)],r=new Set;"string"==typeof t?r.add(t):Array.isArray(t)&&t.forEach(e=>r.add(e));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(e=>{let t=e.getAttribute("data-option-label")??"",o=r.has(t);e.setAttribute("aria-pressed",o?"true":"false"),e.classList.toggle("persona-ask-pill-selected",o)});let n=new Set(Array.from(o).map(e=>e.getAttribute("data-option-label")??"")),a=e.querySelector('[data-ask-free-text-input="true"]');a&&("string"==typeof t&&t.length>0&&!n.has(t)?(a.value=t,a.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):a.value="")})(e),(e=>{if(!Ot(e))return;let t=Wt(e)[Dt(e)],r="string"==typeof t&&t.length>0||Array.isArray(t)&&t.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!r);let n=e.querySelector('[data-ask-user-action="submit-multi"]');n&&(n.disabled=0===Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).length)})(e)},qt=(e,t,r)=>{if(!r||!Et(e)||!1===Lt(t).enabled)return;let o=e.toolCall.id;r.querySelectorAll(`[${xt}]`).forEach(e=>{e.getAttribute(xt)!==o&&e.remove()});let n=r.querySelector(`[${xt}="${Tt(o)}"]`);if(n)return void((e,t,r)=>{let{payload:o}=Pt(t),n=Math.max(1,Bt(o).length);n>Ft(e)&&(e.setAttribute(kt,String(n)),n>1&&!Ot(e)&&e.setAttribute(Mt,"true")),zt(e,t,r)})(n,e,t);let{payload:a}=Pt(e),s=((e,t,r)=>{let o=Lt(t),n=(e=>"pills"===e.layout?"pills":"rows")(o),a=e.toolCall.id,s=Bt(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 o={};return t.forEach((e,t)=>{let n="string"==typeof e?.question?e.question:"";if(n&&Object.prototype.hasOwnProperty.call(r,n)){let e=r[n];("string"==typeof e||Array.isArray(e))&&(o[t]=e)}}),o})(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=q("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(xt,a),p.setAttribute("data-tool-call-id",a),p.setAttribute("data-message-id",e.id),p.setAttribute(kt,String(i)),p.setAttribute("data-ask-current-index",String(c)),p.setAttribute(Mt,l?"true":"false"),p.setAttribute("data-ask-layout",n),((e,t)=>{e.setAttribute(At,JSON.stringify(t))})(p,d),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),void 0!==o.slideInMs&&p.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Rt(p,o);let u=q("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=q("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",u.appendChild(h);let m=q("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",u.appendChild(m),p.appendChild(u);let g=q("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");return g.setAttribute("data-ask-pill-list","true"),g.setAttribute("role","group"),p.appendChild(g),"rows"!==n&&p.appendChild(Ht(o,n)),zt(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p})(e,t,a);r.appendChild(s)},jt=(e,t)=>{if(!e)return;let r=t?`[${xt}="${Tt(t)}"]`:`[${xt}]`;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)})},_t="suggest_replies",Ut={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},Vt={name:_t,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:Ut,origin:"sdk",annotations:{readOnlyHint:!0}},Kt=e=>"tool"===e.variant&&"suggest_replies"===e.toolCall?.name,Gt=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 o=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 o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Jt=e=>{for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role)return null;if(!Kt(r))continue;let o=Gt(r.toolCall?.args);return o.length>0?o:null}return null},Xt=new Set,Qt=e=>{let t=e?.suggestions?.followUps,r=e?.features?.suggestReplies,o=e=>{let o=t?.[e],n=r?.[e];void 0!==o&&void 0!==n&&o!==n&&((e,t,r)=>{let o=`${e}:${t}:${r}`;Xt.has(o)||(Xt.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))})(e,n,o)};e&&(o("enabled"),o("expose"));let n=t?.enabled??r?.enabled??!0;return{enabled:n,expose:!!n&&(t?.expose??r?.expose??!1)}},Yt={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},Zt={name:wt,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:Yt,origin:"sdk",annotations:{readOnlyHint:!0}},er=e=>{let t=[],r=e?.features?.askUserQuestion;return!0===r?.expose&&!1!==r.enabled&&t.push(Zt),Qt(e).expose&&t.push(Vt),t},tr=e=>"object"==typeof e&&!!e&&!Array.isArray(e),rr=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:tr(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:r,result:t.result}}:null},or=(e,t)=>{let r,o=[],n=[],a=[],s="",i=()=>{0!==n.length&&(o.push({role:"assistant",content:"",createdAt:s,toolCalls:n},{role:"tool",content:"",createdAt:s,toolResults:a}),n=[],a=[])};for(let l of e){let e=rr(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;n.length>0&&(void 0===t||t!==r)&&i(),0===n.length&&(s=l.createdAt,r=t),n.some(t=>t.toolCallId===e.call.toolCallId)||(n.push(e.call),a.push(e.result));continue}let d=t(l);d&&(i(),o.push(d))}return i(),o},nr=e=>e.replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ar=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)}},sr=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ir=e=>{if(e.interrupted&&void 0===e.duration&&void 0===e.durationMs&&(void 0===e.startedAt||void 0===e.completedAt))return"";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 sr(t)},lr=e=>{let t=void 0===e.durationMs?Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())):e.durationMs;return sr(t)},dr=(e,t,r)=>{if(!t)return r;let o=e.name?.trim()||"tool",n=ir(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},cr=(e,t)=>{let r,o=e.replace(/\{toolName\}/g,t),n=[],a=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0;for(;null!==(r=a.exec(o));)r.index>s&&pr(n,o.slice(s,r.index),[]),void 0===r[1]?void 0===r[2]?void 0!==r[3]&&pr(n,r[3],["dim"]):pr(n,r[2],["italic"]):pr(n,r[1],["bold"]),s=r.index+r[0].length;return s<o.length&&pr(n,o.slice(s),[]),n},pr=(e,t,r)=>{let o=t.split("{duration}");for(let t=0;t<o.length;t++)o[t]&&e.push({text:o[t],styles:r}),t<o.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},ur=()=>({processChunk:()=>null,getExtractedText:()=>null,__isPlainTextParser:!0}),hr=()=>{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 o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let n=(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!==n&&(e=n),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)}},mr=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return null!==e||""===e?{text:e||"",raw:r}:null;try{let t=(0,vt.parse)(r,vt.STR|vt.OBJ);t&&"object"==typeof t&&(t.component&&"string"==typeof t.component?e="string"==typeof t.text?nr(t.text):"":"init"===t.type&&t.form?e="":"string"==typeof t.text&&(e=nr(t.text)))}catch{}return t=r.length,null===e?null:{text:e,raw:r}},close:()=>{}}},gr=()=>{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}},fr="4.29.1",{setLoader:yr,load:br,provide:vr}=U({fallbackImport:()=>import("./client-history")}),wr=yr,xr=br;function Cr(e){return"string"!=typeof e&&e.some(e=>"image"===e.type)}function Sr(e){return{type:"text",text:e}}let kr=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ar=[...kr,"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 Mr(e){return function(e){return kr.includes(e)||e.startsWith("image/")}(e.type)}function Ir(e,t=Ar,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 Tr(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 Er(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(),o=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let n=e.sequence??0,a=t.sequence??0;return n===a?e.id.localeCompare(t.id):n-a})}let Lr=e=>!0===e.localOnly||"assistant"===e.role&&"string"==typeof e.id&&e.id.startsWith("reconnect-failed-"),Pr={idle:"Online",connecting:"Connecting…",connected:"Streaming…",error:"Offline",paused:"Connection lost…",resuming:"Reconnecting…"};var Br=class extends Error{constructor(e,t,r){super(t),this.name="HistoryClientError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};let Rr=e=>"reason"in e?e.reason:void 0,Nr=(e,t)=>e instanceof Br&&e.code===t,$r=e=>!e.voiceCaption&&!Lr(e)&&!!(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),Hr=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),Wr=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});var Dr=class{#e;#t;#r;#o;#n;#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":fr,...e.headers},this.debug=!!e.debug,this.#r=e.streamParser??function(e){switch(e){case"json":return mr;case"regex-json":return hr;case"xml":return gr;default:return ur}}(e.parserType),this.#o=e.contextProviders??[],this.#n=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 ct().then(t=>{let r=new t.WebMcpBridge(e,{recordToolDisplayTitles:n,getToolDisplayTitle:a,loadPolyfill:p});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 mt()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await((await e())?.snapshotForDispatch())??[];return{tools:t,fingerprint:i(t)}},onChange:t=>{let r=null,o=!1;return e().then(e=>{e&&!o&&(r=e.watchToolChanges(t))}),()=>{o=!0,r?.()}},execute:async(t,r,o)=>{let n=await e();return n?n.executeVoiceToolCall(t,r,o):{status:"failed",error:{message:"WebMCP runtime failed to load."}}}};return t}executeWebMcpToolCall(e,t,r){return!0===this.config.webmcp?.enabled?this.#k().then(o=>o?o.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:o}=this.config;if(!r)return{agentId:e,flowId:t};let n=function(e,t){let r=e.trim();if(!r)throw Error("[Persona] `target` is empty.");let o=r.indexOf(":");if(o>0){let e=r.slice(0,o),n=r.slice(o+1);if("runtype"===e){let e=gt(n);if(e)return e;throw Error(`[Persona] target "runtype:${n}" 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(n).payload}}let n=gt(r);if(n)return n;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,o);return"agentId"===n.kind?{agentId:n.agentId}:"flowId"===n.kind?{flowId:n.flowId}:{targetPayload:n.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 o=t.conversationId,n=await this.readVisitorToken();if(!0!==t.durableRecovery?.enabled||!o||!n)throw new Br("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.#M()}/v1/client/conversations/${encodeURIComponent(o)}/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":fr,"X-Visitor-Token":n},signal:e.signal});if(401!==i.status||r){if(!i.ok)throw await(await xr()).historyErrorFor(this.#T(),i,!0);return i}{r=!0;let e=await xr();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.#R()}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)}}#R(){return this.isClientTokenMode()?!0!==this.config.features?.history?.enabled||this.#h?{state:"unavailable",reason:"history_disabled"}:this.#N():{state:"unavailable",reason:"ineligible_mode"}}#N(){let e=this.#f;return"browser_only"===e?.state?e:this.#$()}#$(){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&&Rr(t)===Rr(e);if(this.#f=e,!r){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#y])t(e)}}async#H(e){let t=this.#L()&&!e.omitVisitorFields,r=!e.omitVisitorFields,o=null;(t||r)&&(await this.historyInternals.historyBootstrapReady,o=await this.readVisitorToken());let n=this.#A(),a=n.agentId??n.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)&&o?{visitorToken:o}:{},...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":fr},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 Br("history_disabled","Visitor history is disabled for this surface");return this.#H({...e,omitVisitorFields:!0})}throw 403===l.status&&"durable_recovery_disabled"===r.error?new Br("history_disabled","Durable recovery is disabled for this surface"):(t||e.durableResume)&&401===l.status&&"visitor_required"===r.error?new Br("visitor_required","Visitor credential no longer resolves"):s&&404===l.status?new Br("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.#H({conversationId:e,durableResume:t});return t&&!0!==r.durableRecovery?.enabled&&this.historyInternals.setStoredResumableHandle?.(null),this.#D(r,e,!1)}catch(r){if(!Nr(r,"not_found")&&!Nr(r,"visitor_required")&&!Nr(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,o=await this.#H({storedSessionId:r}),n=await this.#O(o);return this.#D(n,e,t)}async#z(e){let t=this.config.getStoredSessionId?.()||null,r=this.config.getStoredConversationId?.()||null,o=await this.#H({storedSessionId:t,identityProof:e}),n=this.#D(o,r,!1);return this.clientSession=n,this.#c=null,this.#p=!1,this.resetClientToolsFingerprint(),n}async#O(e){if(!e.visitor?.token||this.#g||!this.#L()&&!0!==e.durableRecovery?.enabled)return e;this.#g=!0;try{return await this.#H({storedSessionId:e.sessionId})}catch{return e}finally{this.#g=!1}}#D(e,t,r){let o=e.conversationId;return o&&t&&(r||o!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:o}),this.config.setStoredSessionId?.(e.sessionId),o&&(this.config.setStoredConversationId?.(o),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 Br("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 Br("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let o=await this.#H({conversationId:e,identityProof:r});return this.#q(o)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.#H({});return this.#q(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#L()&&this.#B(this.#$())}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":fr},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,o,n=this.config.getIdentityProof;if(!t.trim()||!n)throw Error("Chat identity requires identityProvider and getIdentityProof.");try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,r)=>{o=()=>r(e.reason),e.addEventListener("abort",o,{once:!0}),e.aborted&&o()})]):await t}catch{throw e?.throwIfAborted(),Error("The identity proof provider failed.")}finally{o&&e?.removeEventListener("abort",o)}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,o,n)=>e.#V(t,r,o,n),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#C;#T(){let e=this;return this.#C??={HistoryClientError:Br,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.#N(),derivedBrowserOnly:()=>e.#$(),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 xr()).listConversations(this.#T(),e)}async getConversation(e,t){return(await xr()).getConversation(this.#T(),e,t)}async finalizeDisplayProjections(e,t){return(await xr()).finalizeDisplayProjections(this.#T(),e,t)}async deleteConversation(e,t){return(await xr()).deleteConversation(this.#T(),e,t)}async deleteAllConversations(e){return(await xr()).deleteAllConversations(this.#T(),e)}async resetVisitor(){return(await xr()).resetVisitor(this.#T())}async dispatch(e,t){return e.signal?.throwIfAborted(),at().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#G(e,t):this.#J(e,t)}async#K(e,t){let r=`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`;this.#d=r;let o=()=>this.#d===r,n=e=>{o()&&t(e)};t({type:"status",status:"connecting"});try{let t=()=>{if(e.signal?.throwIfAborted(),!o())throw new DOMException("Turn superseded","AbortError")},a=this.clientSession??await this.initSession();t();let s=async()=>{t();let r=a,o=!0===r.durableRecovery?.enabled;if(o&&(!r.conversationId||!await this.readVisitorToken()))throw Error("Renewing this conversation requires its visitor credential.");t();let n=await this.#H({...o||this.#L()?{conversationId:r.conversationId,durableResume:o}:{storedSessionId:r.sessionId},signal:e.signal});if(t(),r.conversationId&&n.conversationId!==r.conversationId||o&&!0!==n.durableRecovery?.enabled)throw Error("Session renewal did not preserve this conversation.");a=this.#D(n,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.#X(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($r).map(e=>{let t=d?Tr(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,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},p=async()=>{t();let r=!0===a.durableRecovery?.enabled?await this.readVisitorToken():null;return t(),this.#V(a.sessionId,i.clientTools,async o=>{t();let n=await this.#_(e.signal);t();let s={...c,sessionId:a.sessionId,...o,...n&&{identityProof:n}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...s,...n&&{identityProof:{provider:n.provider,token:"[REDACTED]"}}}),fetch(this.#I("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr,...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 Br("invalid_identity_proof","The identity proof was rejected");throw n({type:"error",error:e}),e}if(401===h.status){this.clearClientSession(),this.config.onSessionExpired?.();let e=Error("Session expired. Please refresh to continue.");throw n({type:"error",error:e}),e}if(429===h.status){let t=Error(e.hint||"Message limit reached for this session.");throw n({type:"error",error:t}),t}if(410===h.status&&"conversation_deleted"===e.error){let e=new Br("conversation_deleted","This conversation was deleted");throw n({type:"error",error:e}),e}let t=Error(e.error||"Failed to send message");throw n({type:"error",error:t}),t}if(!h.body){let e=Error("No response body received");throw n({type:"error",error:e}),e}m(),n({type:"status",status:"connected"});try{await this.#Q(h.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof Br)&&!t.message.includes("Session expired")&&!t.message.includes("Message limit")&&n({type:"error",error:t}),t}}async#J(e,t){t({type:"status",status:"connecting"});let r=await this.#X(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let o,n={...this.#t};if(this.#i)try{let e=await this.#i();n={...n,...e}}catch(e){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",e)}if(this.#a)try{o=await this.#a(this.#e,{method:"POST",headers:n,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 o=await fetch(this.#e,{method:"POST",headers:n,body:JSON.stringify(r),signal:e.signal});if(!o.ok||!o.body){let e=Error(`Chat backend request failed: ${o.status} ${o.statusText}`);throw t({type:"error",error:e}),e}t({type:"status",status:"connected"});try{await this.#Q(o.body,t)}finally{t({type:"status",status:"idle"})}}async#G(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 o,n={...this.#t};if(this.#i)try{let e=await this.#i();n={...n,...e}}catch(e){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",e)}if(this.#a)try{o=await this.#a(this.#e,{method:"POST",headers:n,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 o=await fetch(this.#e,{method:"POST",headers:n,body:JSON.stringify(r),signal:e.signal});if(!o.ok||!o.body){let e=Error(`Agent execution request failed: ${o.status} ${o.statusText}`);throw t({type:"error",error:e}),e}t({type:"status",status:"connected"});try{await this.#Q(o.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,o){t({type:"status",status:"connected"});try{await this.#Q(e,t,r,o)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t,r){return(await at()).resolveApproval(this.#U(),e,t,r)}async#V(e,t,r,o){let n,a=!!(t&&t.length>0),s=a?i(t):void 0,l=this.clientToolsFingerprintSessionId===e,d=a&&l&&this.lastSentClientToolsFingerprint===s,c=!a&&!0===o?.emptyMeansReplace&&this.#u===e,p=!1;for(let e=0;n=await r({...a&&(p||!d)&&t?{clientTools:t}:{},...c?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),409===n.status&&0===e&&a&&"client_tools_resend_required"===(await n.clone().json().catch(()=>null))?.error;e++)p=!0,this.lastSentClientToolsFingerprint=null;return{response:n,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=e,a?this.#u=e:c&&(this.#u=null)}}}async resumeFlow(e,t,r){return(await at()).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.#o.length&&await Promise.all(this.#o.map(async r=>{try{let o=await r({messages:e,config:this.config});o&&"object"==typeof o&&Object.assign(t,o)}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 o=or(Hr(e),e=>!$r(e)||"user"!==e.role&&"assistant"!==e.role&&"system"!==e.role||e.variant&&"assistant"!==e.variant?null:Wr(e)),n=this.#te(t),a={agent:this.#re(this.config.agent??{agentId:r},n),messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};n&&(a.composerOptions=n);let s=[...er(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#X(e,t){let r=or(Hr(e),e=>$r(e)?Wr(e):null),o=this.#A(),n={messages:r,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[e,t]of Object.entries(o.targetPayload))"messages"!==e&&(n[e]=t);let a=[...er(this.config),...await((await this.#k())?.snapshotForDispatch())??[]];a.length>0&&(n.clientTools=a);let s=await this.#ee(e);s&&(n.context=s);let i=this.#te(t);if(i&&(n.composerOptions=i),this.#n)try{let e=await this.#n({payload:{...n},config:this.config});if(e&&"object"==typeof e){let t=e;return void 0!==n.clientTools&&!("clientTools"in t)&&(t.clientTools=n.clientTools),t}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",e)}return n}async#Q(e,t,r,o){let{streamResponse:n}=st()??await at();return n({config:()=>this.config,createStreamParser:this.#r,parseSSEEvent:this.#s,onSSEEvent:(e,t)=>this.#l?.(e,t)},e,t,r,o)}},Fr=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:Or,load:zr,provide:qr,getSync:jr}=U({fallbackImport:()=>import("./ui-extras-entry")}),_r=Or,Ur=zr,Vr=jr,{setLoader:Kr,load:Gr,provide:Jr,getSync:Xr}=U({fallbackImport:()=>import("./session-actions")}),Qr=Kr,Yr=Gr,Zr=Xr,eo=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function to(e){return"card"===e?"collapsed":e}function ro(e){return e.split(";",1)[0].trim().toLowerCase()}function oo(e,t){let r=e?.display,o="string"==typeof r?{default:r}:r??{};if(t.file&&o.files){if("string"==typeof o.files)return{mode:to(o.files),matchedBy:{type:"files"}};let e=t.file.mimeType?ro(t.file.mimeType):void 0,r=e?function(e,t){if(!e)return;let r=Object.entries(e);for(let[e,o]of r)if(ro(e)===t)return{mode:to(o),selector:ro(e)};let o=`${t.split("/",1)[0]}/*`;for(let[e,t]of r)if(ro(e)===o)return{mode:to(t),selector:o}}(o.files.byMediaType,e):void 0;if(e&&r)return{mode:r.mode,matchedBy:{type:"mediaType",mediaType:e,selector:r.selector}};if(o.files.default)return{mode:to(o.files.default),matchedBy:{type:"files"}}}let n=o.byKind?.[t.artifactType];if(n)return{mode:to(n),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=o.byType?.[t.artifactType];if(a)return{mode:to(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:to(s),matchedBy:{type:"preferredMode"}}:o.default?{mode:to(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function no(e,t){return oo(e,t).mode}function ao(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 so(e,t=140){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-1)}…`}function io(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 lo(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 co(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 po=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 o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(n.voice=e)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):co(a));void 0!==t.rate&&(n.rate=t.rate),void 0!==t.pitch&&(n.pitch=t.pitch),n.onend=()=>r.onEnd?.(),n.onerror=e=>{let t=e.error;"canceled"===t||"interrupted"===t?r.onEnd?.():r.onError?.(Error(t||"Speech synthesis failed"))},setTimeout(()=>{o.speak(n),r.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},uo=class{#e=null;#t=null;#r="idle";#o=new Set;#n=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.#o.add(e),()=>this.#o.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.#n;this.#e?.stop(),this.#s(e,"loading");try{if(!this.#e){let e=await this.#a();if(r!==this.#n)return;if(!e)return void this.#s(null,"idle");this.#e=e}this.#e.speak(t,{onStart:()=>{r===this.#n&&this.#s(e,"playing")},onEnd:()=>{r===this.#n&&this.#s(null,"idle")},onError:()=>{r===this.#n&&this.#s(null,"idle")}})}catch{r===this.#n&&this.#s(null,"idle")}}stop(){this.#n++,this.#e?.stop(),this.#s(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#o.clear()}#s(e,t){this.#t="idle"===t?null:e,this.#r=t;for(let e of this.#o)e(this.#t,this.#r)}},ho=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:mo,load:go,getSync:fo}=U({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),yo=mo,bo=go,vo=fo;function wo(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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /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 xo=null,Co=()=>xo?xo():import("./voice/runtype-tts-entry"),{setLoader:So,load:ko}=U({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),Ao=So,Mo=ko,Io="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 To=class extends Error{constructor(e,t){super(t),this.name="SessionHistoryError",this.code=e}};function Eo(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 o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return r.message?`${o}\n\n_Details: ${r.message}_`:o}let Lo=e=>c(e)||"suggest_replies"===e;var Po=class e{#e;#t;#r;#o;#n;#a;#s;#i;#l;#d;#c;#p;#u;#h;#m;#g;#f;#y;#b;#v;#w;#S;#k;#A;#M;#I;#L;#P;#R;#N;#$;#B;#H;#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.#o=null,this.#n=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.#R=new Map,this.#N=null,this.#$=null,this.#B=!1,this.#H=null,this.#E=null,this.#W=!1,this.#F=null,this.#D=null,this.#q=null,this.#j=new ho,this.#_=Promise.resolve(),this.#x=null,this.#U=null,this.ttsSpokenMessageIds=new Set,this.readAloud=new uo(()=>this.#C()),this.#oe=null,this.#ne=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.#n=e.message.id),("approval"===e.message.variant||!0===e.message.agentMetadata?.awaitingLocalTool)&&Yr().catch(()=>{});let o=e.message.toolCall,n=!!o?.name&&(c(o.name)||"suggest_replies"===o.name&&Qt(this.config).enabled);!0===e.message.agentMetadata?.awaitingLocalTool&&n&&!0===this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool&&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=>({...h(e),sequence:e.sequence??this.#ye()})),this.messages=this.#be(this.messages),this.client=new Dr(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&&bo().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&&Co().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=po.isSupported()?new po({pickVoice:e?.pickVoice}):null;if("runtype"===e?.provider){let r=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,n=this.config.clientToken,a=!1!==e.browserFallback;if(r&&o&&n)return Co().then(({RuntypeSpeechEngine:s,FallbackSpeechEngine:i})=>{let l=new s({host:r,agentId:o,clientToken:n,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 n&&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.#_,o=++this.#m;this.#h=bo().then(async e=>{await r,o===this.#m&&this.#T(e,e.createVoiceProvider(t))}).catch(e=>{console.error("Failed to setup voice:",e)}).finally(()=>{o===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.#K(),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.#G(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()}#K(){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.#G(!0),this.#x?.settle(),this.#x=null,this.#j=new ho,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#J(e){try{await e.disconnect()}catch(e){console.error("Failed to disconnect voice:",e)}}#G(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.#$=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],o={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(o)}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.#H?.(),this.#H=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 To("history_unavailable","No conversation history provider is installed");return e}#re(e){let t=this.#te(),r=e??this.config.features?.history?.scope,o=this.config.getIdentityProof?"verified-user":"browser",n=r??(t.capabilities.scopes.includes(o)?o:t.capabilities.scopes[0]??o);if(!t.capabilities.scopes.includes(n))throw new Fr("unsupported_scope","This history scope is not supported.");return{scope:n}}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())}#X(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(()=>{})}#Q(){if(this.streaming||"paused"===this.status||"resuming"===this.status)throw new To("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.#Q();let o=this.#re(t?.scope);await this.awaitHistorySettled();let n=++this.#S,a=await r.getPage(e,{context:o});if(n!==this.#S)throw new To("superseded","A later selection won");let s=await r.prepareOpen(e,{context:o});if(n!==this.#S)throw s.discard(),new To("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.#R.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 o=this.#te(),n=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(o,e,a,n).finally(()=>{this.#L.delete(s)});return this.#L.set(s,l),l}async#Ie(e,t,r,o){let n=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:r,...n?{beforeCreatedAt:n}:{},context:o});if(this.#b&&this.#b!==t)return{messages:[],nextMessageCursor:a.nextCursor};let s=this.#Te(a.messages),i=Er(this.messages,s);this.messages=this.#be(i.map(e=>this.#Ee(e))),this.#w=a.nextCursor;for(let e of a.messages)this.#R.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#Y(),{messages:s,nextMessageCursor:a.nextCursor}}#Te(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let r=t.get(e.id);if(r){if(this.webMcpApprovalResolvers.has(r.id)||r.approval&&u(r.approval)&&r.approval.id===e.approval?.id&&"pending"!==r.approval.status&&"pending"===e.approval?.status)return r;let t=r.agentMetadata?.executionId,o=[...r.toolCall?[r.toolCall]:[],...r.tools??[]];if(t&&o.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return r}return h(e)})}async startNewConversation(e){let t=this.#te(),r=this.#re(e?.scope);await this.awaitHistorySettled();let o=++this.#S,n=await t.prepareStartNew({context:r});if(o!==this.#S)throw n.discard(),new To("superseded","A later action won");await this.#Le(n)}async#Le(e){this.#Pe(),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(),o=this.#re(t?.scope);await this.awaitHistorySettled(),await r.delete(e,{context:o}),e===this.#b&&await this.#Be(o)}async updateConversation(e,t,r){let o=this.#te();if(!o.update)throw new To("history_unavailable","This history provider cannot update conversations");let n=this.#re(r?.scope);return await this.awaitHistorySettled(),o.update(e,t,{context:n})}canUpdateConversations(){return"function"==typeof this.#ee?.update}async clearConversationHistory(e){let t=this.#te(),r=this.#re(e?.scope);await this.awaitHistorySettled();let o=await t.deleteAll({...void 0===e?.targetId?{}:{targetId:e.targetId},context:r});return await this.#Be(r),o}async resetHistoryDevice(){let e=this.#te();if(!e.resetDevice)throw new To("history_unavailable","This history provider cannot reset the device");this.#S+=1,this.#P=null;try{return await e.resetDevice()}finally{this.#Pe(),this.#b=null,this.#v=null,this.#w=null,this.#A=null,this.#M=!1,this.#Y()}}async#Be(e){this.#S+=1,this.#P=null,this.#Pe(),this.#b=null,this.#v=null,this.#w=null,this.#M=!0,this.#A=null,this.#Y(),await this.#Re(e)}async#Re(e){let t=this.#ee;if(t)try{let r=await t.prepareStartNew({context:e});await this.#Le(r)}catch{this.#M=!0,this.#A="new_conversation_required",this.#Y(),this.#X("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.#Re(this.#re()),"new_conversation_required"===this.#A))throw new To("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.#$e(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#R.clear(),this.#He(null)}#Pe(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#We(),this.#De(),this.#ne++,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.#Pe(),this.#b=e.conversationId,this.#v=null,this.#w=null,this.#A=null,this.#Y(),this.#X("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.#H?.(),this.#H=null,this.#E=e,e&&(this.#H=e.subscribe(e=>this.#Fe(e))))}#Fe(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.#Pe():(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.#X("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#Oe(){return this.#W?(this.#F||=this.#ze().finally(()=>{this.#F=null}),this.#F):Promise.resolve()}async#ze(){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 o=this.#re(e?.scope);this.#M=!0,this.#Y();let n=this.#qe(t,r,o).finally(()=>{this.#M=null!==this.#A,this.#I===n&&(this.#I=null),this.#Y()});return this.#I=n,n}async#qe(e,t,r){this.#b=t;let o=this.clientSession?.conversationRevision??this.#v??null,n=this.#B?this.#$:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#B=!1,this.#w=this.historyInternals.getStoredMessageCursor?.()??this.#w,await this.replayPendingProjections(),o&&n&&o===n)return void(this.#v=o);let a,s=await e.getPage(t,{context:r}),i=this.#Te(s.messages),l=new Set(s.messages.map(e=>e.id)),d=this.messages.some(e=>l.has(e.id)),c=s.messages[0]?.createdAt;if(d){let e=this.#o?this.#n:null;a=Er(this.messages.filter(t=>!(!l.has(t.id)&&t.id!==e)||void 0!==c&&t.createdAt<c),i).map(e=>this.#Ee(e))}else a=i.map(e=>this.#Ee(e));this.#w=s.nextCursor,this.#v=s.conversationRevision||o||null,this.#R.clear();for(let e of s.messages)this.#R.set(e.id,e.content);this.#Me(),this.messages=this.#be(a),this.callbacks.onMessagesChanged([...this.messages])}#je(){return!0===this.config.features?.history?.enabled&&this.isClientTokenMode()}#He(e){this.#N=e,this.historyInternals.setPendingDisplayProjections?.(e)}#_e(){return this.historyInternals.getPendingDisplayProjections?.()??this.#N}#Ue(e){if(this.#je())for(let t of e){let e=Tr(t);void 0!==e&&this.#R.set(t.id,e)}}#me(){if(!this.#je())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=Tr(e);void 0!==r&&this.#R.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.#Ke(e,t,!1)).finally(()=>{this.#P===r&&(this.#P=null)});this.#P=r}async#Ke(e,t,r){if(this.#b!==e)return;let o=t.filter(e=>this.#R.get(e.id)!==e.displayContent);if(0===o.length)this.#Ge(e,t);else try{let{conversationRevision:r}=await this.client.finalizeDisplayProjections(e,o);for(let e of o)this.#R.set(e.id,e.displayContent);this.#b===e&&r&&(this.#v=r),this.#Ge(e,t)}catch(n){if(!r&&this.#Je(n))return void await this.#Ke(e,o,!0);if(n instanceof Br&&("not_found"===n.code||"conversation_deleted"===n.code))return void this.#Ge(e,t);this.#X("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#Je(e){return e instanceof Br?"request_failed"===e.code:e instanceof Error}#Ge(e,t){let r=this.#_e();if(!r||r.conversationId!==e)return;let o=new Set(t.map(e=>e.id)),n=r.messageIds.filter(e=>!o.has(e));this.#He(n.length?{conversationId:e,messageIds:n}:null)}async replayPendingProjections(){if(!this.#je())return;let e=this.#_e();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#Xe(){await this.awaitHistorySettled(),await this.#Oe(),"new_conversation_required"===this.#A&&await this.#Ne()}static#Qe(e){return e instanceof Br&&"conversation_deleted"===e.code}async#Ye(t,r,o,n,a){this.#Ue(t);try{return void await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:o,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent)}catch(t){if(!e.#Qe(t))throw t;let s=await this.#Ze(n);if(!s)throw t;this.#Ue([s]),await this.client.dispatch({messages:[s],signal:r.signal,assistantMessageId:o,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent)}}async#Ze(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let r={...t};this.#S+=1,this.#P=null,this.#Pe(),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.#Le(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.#X("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.#X("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},o=function(e,t){let r=e.voiceRecognition,o=t.voiceRecognition;return!0===r?.enabled!=(!0===o?.enabled)||r?.provider?.type!==o?.provider?.type||r?.provider?.custom!==o?.provider?.custom||r?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(r?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}(this.config,r),n=function(e,t){return Io.some(r=>e[r]!==t[r])}(this.config,r);this.config=r,o&&(this.cleanupVoice(),!0===r.voiceRecognition?.enabled&&Ce(r.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(r.features?.artifacts?.display);if(!n)return this.client.updateConfig(r),void(a&&this.#et());this.#De(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.client=new Dr(this.config,this.historyInternals),a&&this.#et(),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:o,contentParts:n,id:a,createdAt:s,sequence:i,streaming:l=!1,voiceProcessing:d,voiceCaption:c,rawContent:p}=e,u={id:a??("user"===t?ft():"assistant"===t?yt():`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!==o&&{llmContent:o},...void 0!==n&&{contentParts:n},...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:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:l,streaming:d=!1,voiceProcessing:c,rawContent:p}=r,u={id:s??("user"===e?ft():"assistant"===e?yt():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:o,createdAt:i??(new Date).toISOString(),sequence:l??this.#ye(),streaming:d,...void 0!==n&&{llmContent:n},...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:o="",llmContent:n,id:a,createdAt:s,sequence:i}=e,l={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...void 0!==n&&{llmContent:n},...void 0!==a&&{id:a},...void 0!==s&&{createdAt:s},...void 0!==i&&{sequence:i}})}async#tt(e,t,r){let o;try{o=await r()}catch{return}let n=o.blocks.join("\n\n"),a=[n,t].filter(Boolean).join("\n\n"),s=Array.isArray(e.contentParts)&&e.contentParts.length>0,i=o.contentParts.length>0;if(s){let t=[];n&&t.push(Sr(n)),t.push(...o.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(i){let t=[];a&&t.push(Sr(a)),t.push(...o.contentParts),e.contentParts=t}else n&&(e.llmContent=a);Object.keys(o.context).length>0&&(e.mentionContext=o.context)}async sendMessage(e,t){let r=e.trim(),o=!!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||o))return;this.#U&&!t?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#I||this.#P||this.#M||this.#W)&&await this.#Xe(),this.stopSpeaking(),this.abortController?.abort(),this.#De(),this.#ne++,this.#We();let n=t?.voiceTurn?.userMessageId,a=n?this.messages.find(e=>e.id===n&&"user"===e.role):void 0,s=a?.id??ft(),i=yt();this.#n=null;let l=t?.contentParts&&Cr(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.#tt(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:[Sr(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=(new Date).toISOString(),u=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:p}]:[...this.messages],h=(a??this.messages.find(e=>e.id===s))?.createdAt??p,m=((e,t)=>{let r=new Set;return(Array.isArray(e)?e:[]).flatMap(e=>{if(!eo(e))return[];let{toolCallId:o,name:n}=e;if("string"!=typeof o||!o||"string"!=typeof n||!n||r.has(o))return[];r.add(o);let a=eo(e.arguments)?e.arguments:{},s=e.result??null;return[{id:`voice-tool-${o}`,role:"assistant",variant:"tool",content:"",createdAt:t,streaming:!1,toolCall:{id:o,name:n,status:"complete",args:a,result:s},agentMetadata:{clientToolAnswer:{toolCallId:o,toolName:n,args:a,result:s}}}]})})(t?.voiceTurn?.priorToolResults,h);for(let e of m)this.messages.some(t=>t.id===e.id)||(this.#Ce(e),u.push({...e,createdAt:p}));let g=m.map(({agentMetadata:e})=>{let{toolCallId:t,toolName:r,args:o,result:n}=e.clientToolAnswer;return{toolCallId:t,name:r,arguments:o,result:n}});try{await this.#Ye(u,c,i,s,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn,...g.length>0&&{voicePriorToolResults:g}})}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=Eo(e,this.config.errorMessage);if(t){let e={id:i,role:"assistant",createdAt:(new Date).toISOString(),content:t,localOnly:!0,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 o=r+1;for(;o<e.length&&"user"!==e[o].role;)o+=1;return{start:r,end:o}}(this.messages,e);if(!r)return!1;let o=this.messages[r.start],n=t.replacement,a=n?n.text:o.content,s=n?n.contentParts:o.contentParts;if(!(a?.trim()||(s?.length??0)>0||!n&&(o.llmContent?.trim()?.length??0)>0))return!1;let i=n?void 0:{...void 0!==o.llmContent&&{llmContent:o.llmContent},...void 0!==o.rawContent&&{rawContent:o.rawContent},...o.mentionContext&&{mentionContext:o.mentionContext},...o.contextMentions&&{contextMentions:o.contextMentions},...o.quote&&{quote:o.quote}},l=n?this.#rt(n.options):o.composerOptions,d=n?n.contentSegments:o.contentSegments,c=n?n.options?.quote:void 0,p=n?n.viaVoice:o.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}#rt(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.#Xe(),this.abortController?.abort(),this.#We();let e=yt();this.#n=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=Eo(t,this.config.errorMessage);if(r){let t={id:e,role:"assistant",createdAt:(new Date).toISOString(),content:r,localOnly:!0,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.#n=t.assistantMessageId);let r=t?.preserveAssistantId?t.assistantMessageId:void 0,o=!1;for(let e of this.messages)e.streaming&&e.id!==r&&(e.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.#ce(!0);let n={};try{await this.client.processStream(e,e=>{let t=this.#t;this.#t=n;try{this.handleEvent(e)}finally{this.#t=t}},t?.assistantMessageId,t?.seedContent),this.#ot(n)}catch(e){if("resuming"===this.status||this.#a)return void this.#nt(n);this.#ot(n),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;do{t="webmcp-"+ ++this.#p}while(this.messages.some(e=>e.id===`approval-${t}`||e.approval?.id===t));let r={id:t,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(t=>{this.webMcpApprovalResolvers.set(o,t),e.signal?.addEventListener("abort",()=>this.resolveWebMcpApproval(o,"timeout"),{once:!0})})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(t=>t.id===e);o?.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r("approved"===t)}#oe;#ne;#at(e){let t=this.#oe??={s:this,setStreaming:e=>this.#ce(e),appendMessage:e=>this.#Ce(e),nextSequence:()=>this.#ye(),settleApprovalPausedToolCall:e=>this.#st(e),resumeAfter:e=>this.#o?.executionId===e?this.#o.lastEventId:void 0},r=Zr();if(r)return e(r,t);let o=this.#ne;return Yr().then(r=>o===this.#ne?e(r,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,r){return this.#at((o,n)=>o.resolveApproval(n,e,t,r))}resolveAskUserQuestion(e,t){return this.#at((r,o)=>r.resolveAskUserQuestion(o,e,t))}resolveWebMcpToolCall(e){return this.#at((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 o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.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.#it(e)})}#it(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.#at((t,o)=>t.resolveWebMcpToolCallBatch(o,e,r))}#De(){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.#We(),this.#De(),this.#ne++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#ce(!1),this.#de("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#We(),this.#De(),this.#ne++,this.messages=[],this.agentExecution=null,this.#$e(),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.#$e()}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.#lt(r),r}#lt(e){let t=`artifact-ref-${e.id}`,r=ao(no(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}}),o=this.messages.find(e=>e.id===t);o?(o.rawContent=r,o.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:"",rawContent:r})}#et(){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 o=ao(no(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!==o&&(r.rawContent=o,r.streaming="streaming"===t.status,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#$e(){(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.#We(),this.#De(),this.#ne++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#be(e.map(e=>({...h(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.#n||"running"!==this.agentExecution?.status)return;let r=null===this.#o;this.#o={executionId:t,lastEventId:e,assistantMessageId:this.#n,status:"running"},this.#dt(r)}#ie(){return null!==this.#o&&"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.#o&&"function"==typeof this.config.reconnectStream&&(this.#a=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#o}),this.#ce(!0),this.#de("resuming"),this.#ct().then(e=>{this.#a&&this.#o&&e.begin()}))}#ct(){return this.#s?Promise.resolve(this.#s):(this.#i||(this.#i=Mo().then(({createReconnectController:e})=>{let t=e(this.#pt());return this.#s=t,t}),this.#i.catch(()=>{this.#i=null})),this.#i)}#pt(){let e=this;return{get config(){return e.config},getResumable:()=>e.#o,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,o)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:t=>e.#Ce(t),settleParked:t=>e.#ut(t),nextSequence:()=>e.#ye(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>Eo(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;if(this.#pe())return this.#ht(e.executionId),void(this.#o={executionId:e.executionId,lastEventId:e.after,assistantMessageId:this.#n??"",status:"running"});let t=this.#mt(e.executionId)?yt():this.#gt();t||(t=yt(),this.#Ce({id:t,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,sequence:this.#ye()})),this.#n=t,this.#ht(e.executionId),this.#o={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.#le()}#ut(e){let t=this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0;if(!t&&!this.#pe()){if(!this.#mt(e))return!1;this.#ue()}if(this.#a=!1,!t){let e=!1;for(let t of this.messages)t.streaming&&(t.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.#ce(!1),this.abortController=null}return this.#de("idle"),!0}#ht(e){this.agentExecution||={executionId:e,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}}#mt(e){return this.messages.some(t=>t.agentMetadata?.executionId===e&&[t.toolCall,...t.tools??[]].some(e=>!0===e?.interrupted))}#gt(){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}#We(){this.#a=!1,this.#s?.teardown(),this.#ue()}#ue(){this.#l&&=(clearTimeout(this.#l),null);let e=null!==this.#o;this.#o=null,e&&this.config.onExecutionState?.(null)}#dt(e){let t=this.config.onExecutionState;t&&(e?(this.#l&&=(clearTimeout(this.#l),null),t(this.#o)):this.#l||=setTimeout(()=>{this.#l=null,this.config.onExecutionState?.(this.#o)},500))}getResumableHandle(){return this.#o}#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.#ot(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 o=wo(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return co(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||"assistant"!==t.role)return;let r=wo(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o?.voice,rate:o?.rate,pitch:o?.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()}#ot(e){for(let[t,r]of[...this.#e])r===e&&(this.#e.delete(t),this.#st(t))}#nt(e){for(let[t,r]of this.#e)r===e&&this.#e.set(t,void 0)}#st(e){let t=this.messages.find(t=>t.id===e)?.approval,r=t?.toolCallId,o=r&&this.messages.find(e=>e.toolCall?.id===r),n=o&&o.toolCall;if(!n||"complete"===n.status||"pending"===t.status)return;let a={...n,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({...o,streaming:!1,toolCall:a})}#Ce(e){let t=this.#Ee(e);this.messages=this.#be([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#Ee(e),r=this.messages.findIndex(e=>e.id===t.id);-1===r?this.#Ce(t):(this.messages=this.messages.map((e,o)=>{if(o!==r||e.toolCall?.name&&c(e.toolCall.name)&&"complete"===e.toolCall.status&&t.toolCall?.id===e.toolCall.id&&"complete"!==t.toolCall.status&&("pending"===t.toolCall.status&&!t.toolCall.name||!e.toolCall.interrupted&&(void 0!==e.toolCall.result||void 0!==e.toolCall.success)&&(!t.agentMetadata?.executionId||t.agentMetadata.executionId===e.agentMetadata?.executionId)))return e;let n={...e,...t};!0===e.agentMetadata?.askUserQuestionAnswered&&t.agentMetadata&&(n.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),!0===e.agentMetadata?.suggestRepliesResolved&&t.agentMetadata&&(n.agentMetadata={...n.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&n.agentMetadata&&!n.agentMetadata.clientToolAnswer&&(n.agentMetadata={...n.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let r=e.approval,o=t.approval;n.approval={...r,...o,executionId:o.executionId||r.executionId,toolName:o.toolName||r.toolName,description:o.description||r.description,toolType:o.toolType??r.toolType,reason:o.reason??r.reason,parameters:o.parameters??r.parameters,toolCallId:o.toolCallId??r.toolCallId}}let s=t.toolCall?.name,i=t.agentMetadata?.executionId,l=t.toolCall?.id;if(s&&Lo(s)&&i&&l&&!0===t.agentMetadata?.awaitingLocalTool){let t=`${i}:${l}`,r=this.webMcpInflightKeys.has(t),o=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,s=e.agentMetadata?.executionId===i&&e.toolCall?.id===l&&void 0!==a&&Lo(a)&&"complete"===e.toolCall?.status&&!e.toolCall.interrupted;(r||o||s)&&(n.agentMetadata={...n.agentMetadata??{},awaitingLocalTool:!1},n.toolCall=e.toolCall,n.streaming=e.streaming)}return n}),this.messages=this.#be(this.messages),this.callbacks.onMessagesChanged([...this.messages]))}#Ee(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(),o=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let n=e.sequence??0,a=t.sequence??0;return n===a?e.id.localeCompare(t.id):n-a})}};let Bo={add:e=>async function(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Mr(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>r(Error("Failed to read file")),o.readAsDataURL(e)})}(e)},Ro={allowedTypes:Ar,maxFileSize:10485760,maxFiles:4};function No(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}var $o=class e{#e;#t;#r;constructor(e={}){this.attachments=[],this.#e=null,this.#t=new Map,this.#r=!1,this.config={allowedTypes:e.allowedTypes??Ro.allowedTypes,maxFileSize:e.maxFileSize??Ro.maxFileSize,maxFiles:e.maxFiles??Ro.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#o(){return"function"==typeof this.config.adapter?.add}#n(){return this.#o()?this.config.adapter:Bo}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:Ro.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=Ir(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 o={id:No(),file:r,previewUrl:Mr(r)?URL.createObjectURL(r):null,contentPart:null,status:this.#o()?"uploading":"processing",progress:this.#o()?0:void 0};this.attachments.push(o),this.#d(o),t.push(o)}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 o=await this.#n().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=o,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.#o()?"uploading":"processing",t.progress=this.#o()?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 o=this.#e?.querySelector(`[data-attachment-id="${e}"]`);o&&o.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=Mr(e.file),r=q("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let t=q("img");t.src=e.previewUrl,t.alt=e.file.name,t.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",t.style.width="48px",t.style.height="48px",t.style.objectFit="cover",t.style.borderRadius="8px",r.appendChild(t)}else{let t=q("div");t.style.width="48px",t.style.height="48px",t.style.borderRadius="8px",t.style.backgroundColor="var(--persona-container, #f3f4f6)",t.style.border="1px solid var(--persona-border, #e5e7eb)",t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="center",t.style.justifyContent="center",t.style.gap="2px",t.style.overflow="hidden";let o=function(e){return"application/pdf"===e||e.startsWith("text/")||e.includes("word")?m.FileText:e.includes("excel")||e.includes("spreadsheet")?m.FileSpreadsheet:"application/json"===e?m.FileCode:m.File}(e.file.type),n=g(o,20,"var(--persona-muted, #6b7280)",1.5);n&&t.appendChild(n);let a=q("span");a.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),a.style.fontSize="8px",a.style.fontWeight="600",a.style.color="var(--persona-muted, #6b7280)",a.style.textTransform="uppercase",a.style.lineHeight="1",t.appendChild(a),r.appendChild(t)}let o=j("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),n=q("div","persona-attachment-progress");n.appendChild(q("div","persona-attachment-progress__bar"));let a=j("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),s=se("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);s?a.appendChild(s):a.textContent="↻",a.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),o.append(n,a),r.appendChild(o);let i=q("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");i.type="button",i.setAttribute("aria-label","Remove attachment"),i.style.position="absolute",i.style.top="-4px",i.style.insetInlineEnd="-4px",i.style.width="18px",i.style.height="18px",i.style.borderRadius="50%",i.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",i.style.border="none",i.style.cursor="pointer",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.padding="0";let l=g(m.X,10,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):(i.textContent="×",i.style.color="var(--persona-text-inverse, #ffffff)",i.style.fontSize="14px",i.style.lineHeight="1"),i.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(i),this.#e.appendChild(r),this.#p(r,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 o=e.querySelector(".persona-attachment-progress__bar");if(o){let e=t.progress;o.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 Ho=(e,t)=>e.length===t.length&&e.every((e,r)=>e===t[r]);function Wo(){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,o=!1,n=!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(o=!1,n||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,!n&&!o&&(o=!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 o=t[r];return e.id===o.id&&e.name===o.name&&e.mimeType===o.mimeType&&e.size===o.size&&e.status===o.status&&e.progress===o.progress&&e.error===o.error}))(e.attachments,t)||(e.attachments=[...t],i())},setMentionRefs:t=>{Ho(e.mentionRefs,t)||(e.mentionRefs=[...t],i())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,i())},setActiveModeIds:t=>{Ho(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:()=>{o&&s()},destroy:()=>{n=!0,o=!1,t.clear()}}}let Do=(e,...t)=>{for(let r of t){let t=e.querySelector(r);if(t)return t}return null},Fo=(e,t)=>{let r=q("div",e);return r.setAttribute(t,""),r.setAttribute("data-persona-composer-synthesized",""),r.style.display="contents",r};function Oo(e,t={}){let r=Do(e,"[data-persona-composer-form]"),o=Do(e,"[data-persona-composer-input]");if(!r||!o){let e=`[Persona] composer surface is missing required element(s): ${[!r&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(r||o))throw Error(e);return typeof console<"u"&&console.warn(e),null}let n={header:Do(e,"[data-persona-composer-header]"),body:Do(e,"[data-persona-composer-body]"),actionsStart:Do(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Do(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Do(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Do(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Do(e,"[data-persona-composer-status]")},a=new Set,s=n.header;s||(a.add("header"),s=Fo("persona-widget-composer__header","data-persona-composer-header"),r.parentNode?r.parentNode.insertBefore(s,r):e.appendChild(s));let i=n.body??o.parentElement??r,l=(e,t,r,o,n)=>{if(t)return t;a.add(e);let s=Fo(r,o);return n.appendChild(s),s},d=l("actionsStart",n.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",r),c=l("actionsEnd",n.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",r),p=l("suggestions",n.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),u=l("status",n.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[];return{footer:e,form:r,input:o,header:s,body:i,actionsStart:d,actionsEnd:c,suggestions:p,status:u,attachmentInput:Do(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0,attachmentPreviews:Do(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Do(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Do(e,"[data-persona-composer-submit]")??void 0,micButton:Do(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:n,addListener:(e,t,r,o)=>{e.addEventListener(t,r,o),h.push({target:e,type:t,handler:r,options:o})},removeListener:(e,t,r,o)=>{e.removeEventListener(t,r,o),h=h.filter(o=>!((e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler)(o,{target:e,type:t,handler:r}))},destroy:()=>{for(let e of h)e.target.removeEventListener(e.type,e.handler,e.options);h=[]}}}let zo=200,qo=300,jo=0,_o=e=>Math.max(0,e);function Uo(e){void 0!==e.delayMs&&(zo=_o(e.delayMs)),void 0!==e.skipDelayMs&&(qo=_o(e.skipDelayMs))}let Vo=new WeakMap,Ko=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Go=(e,t,r)=>Math.min(Math.max(e,t),Math.max(t,r)),Jo=[...["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 Xo(e){Vo.get(e.anchor)?.destroy();let t,{anchor:r,trigger:o=r,text:n,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 n?n():n).trim(),v=()=>("function"==typeof a?a():a??"").trim(),w=()=>_o(e.delayMs??zo),x=()=>_o(e.skipDelayMs??qo),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=>{jo=e>0?Date.now()+e:0})(x())},k=()=>{if(!p)return;let e=d(),t=c(),o=r.getBoundingClientRect(),n=p.getBoundingClientRect(),a=e.documentElement.clientWidth||t.innerWidth,s=e.documentElement.clientHeight||t.innerHeight,u=a-l-n.width,h=o.left+o.width/2-n.width/2,m=Go(h,l,u),g=o.top-l,f=s-l-o.bottom,y=g>=n.height+i||g>=f?"top":"bottom",b="top"===y?o.top-i-n.height:o.bottom+i,v=s-l-n.height,w=Go(b,l,v),x=o.left+o.width/2,C=Math.max(10,n.width-10),S=Go(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 Ko(t)?t:e.ownerDocument.body})(r);if(!e||!t)return;let o=d(),n=c();p=o.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex="100001";let a=n.getComputedStyle?.(r);if(a){for(let e of Jo){let t=a.getPropertyValue(e).trim();t&&p.style.setProperty(e,t)}a.fontFamily&&(p.style.fontFamily=a.fontFamily)}u=o.createElement("span"),u.className="persona-control-tooltip__label",u.textContent=e,p.appendChild(u);let i=v();i&&(h=o.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=i,p.appendChild(h));let l=o.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()};n.addEventListener("scroll",g,!0),n.addEventListener("resize",g);let f=r.getRootNode(),w=Ko(f)?f:o.documentElement,x=typeof MutationObserver>"u"?null:new MutationObserver(()=>{r.isConnected||S()});x?.observe(w,{childList:!0,subtree:!0}),m=()=>{n.removeEventListener("scroll",g,!0),n.removeEventListener("resize",g),x?.disconnect()}},M=()=>{g||f?(e=>{y||p||(C(),e||w()<=0||Date.now()<jo?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()};o.addEventListener("mouseenter",I),o.addEventListener("mouseleave",T),r.addEventListener("focus",E),r.addEventListener("blur",L),r.addEventListener("keydown",B),r.addEventListener("click",P);let R={get isOpen(){return null!==p},show:A,hide:S,reposition:k,destroy:()=>{y||(y=!0,S(),o.removeEventListener("mouseenter",I),o.removeEventListener("mouseleave",T),r.removeEventListener("focus",E),r.removeEventListener("blur",L),r.removeEventListener("keydown",B),r.removeEventListener("click",P),Vo.delete(r))}};return Vo.set(r,R),R}function Qo(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 o=parseFloat(r);return Number.isFinite(o)&&o>0?o:20}function Yo(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function Zo(e,t){e.style.maxHeight=t*Qo(e)+"px",e.style.overflowY="auto"}function en(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 tn(e){return!0===e.insertNewlineOnTouchEnter&&!0===e.coarsePointer}function rn(e,t){if("Enter"!==e.key||e.shiftKey||e.isComposing)return!1;let r=!0===e.metaKey||!0===e.ctrlKey,o=t.submitKey??"enter";return"none"!==o&&("mod-enter"===o?r:r||!tn(t))}function on(e,t){e.setAttribute("enterkeyhint",function(e){return"enter"===(e.submitKey??"enter")?tn(e)?"enter":"send":"enter"}(t))}function nn(e,t){let r=t?.autocomplete;e.setAttribute("autocomplete","string"==typeof r&&r?r:"off");let o=(t,r)=>{void 0===r?e.removeAttribute(t):e.setAttribute(t,r)};o("autocapitalize","string"==typeof t?.autocapitalize?t.autocapitalize:void 0),o("spellcheck","boolean"==typeof t?.spellcheck?String(t.spellcheck):void 0),o("inputmode","string"==typeof t?.inputmode&&t.inputmode?t.inputmode:void 0),o("aria-label","string"==typeof t?.ariaLabel&&t.ariaLabel?t.ariaLabel:void 0)}function an(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 sn="persona-composer-control",ln="persona-composer-control--glyph",dn=(e,t,r)=>{let o=e.ownerDocument?.defaultView;if(!o)return;let n=o.getComputedStyle(e);for(let e of r){let r=n.getPropertyValue(e).trim();r?t.style.setProperty(e,r):t.style.removeProperty(e)}},cn=(e,t)=>{let r=q("textarea");r.setAttribute("data-persona-composer-input",""),r.placeholder=e?.copy?.inputPlaceholder??"How can I help...",r.dir="auto",on(r,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:en(r)}),nn(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 o=Yo(e?.composer?.maxLines,t?.defaultMaxLines??3),n=20*o+"px";return r.style.maxHeight=n,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!==n){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=o*Qo(r);return n=`${t}px`,r.style.maxHeight=n,t})());r.style.height=`${e}px`})}}},pn=(e,t,r="send")=>{let o=j("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"),o.append(e,t),o},un=e=>{let t=e?.sendButton??{},r=t.useIcon??!1,o=t.iconText??"↑",n=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=q("div","persona-send-button-wrapper"),f=j("button",{className:_("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?`persona-flex persona-items-center persona-justify-center ${sn}`:"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(n&&(y=se(n,e,s,r)),b=se(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=pn(y,b),f.appendChild(v)):y?f.appendChild(y):(f.textContent=o,b=null)}else f.textContent=l;f.setAttribute("aria-label",s),g.appendChild(f),Xo({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}},hn=e=>{let t=e?.voiceRecognition??{};if(!0!==t.enabled)return null;let r=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),o="runtype"===t.provider?.type,n="custom"===t.provider?.type;if(!(r||o||n))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=q("div","persona-send-button-wrapper"),p=j("button",{className:_("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",sn,!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=se(a,i,d||"currentColor",1.5);u?p.appendChild(u):p.textContent="🎤",c.appendChild(p);let h=t.tooltipText??"Start voice recognition";return Xo({anchor:p,trigger:c,text:()=>p.getAttribute("aria-label")??h,enabled:t.showTooltip??!1}),{button:p,wrapper:c}},mn=e=>{let t=e?.attachments??{};if(!0!==t.enabled)return null;let r=q("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 o=q("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??Ar).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let n=t.buttonIconName??"paperclip",a=q("div","persona-send-button-wrapper"),s=j("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${sn} ${ln}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),i=se(n,24,"currentColor",1.5);i?s.appendChild(i):s.textContent="📎",s.addEventListener("click",e=>{e.preventDefault(),o.click()}),a.appendChild(s);let l=t.buttonTooltipText??"Attach file";return Xo({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??l}),{button:s,wrapper:a,input:o,previewsContainer:r}},gn=e=>{let t=e?.statusIndicator??{},r="left"===t.align?"persona-text-left":"center"===t.align?"persona-text-center":"persona-text-right",o=q("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),we(o,t,"idle");let n=t.idleText??"Online";if(t.idleLink){let e=q("a");e.href=t.idleLink,e.target="_blank",e.rel="noopener noreferrer",e.textContent=n,e.style.color="inherit",e.style.textDecoration="none",o.appendChild(e)}else o.textContent=n;return o},fn=()=>j("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function yn(e){let{anchor:t,content:r,placement:o="bottom-start",offset:n=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"===o||"top-end"===o?c-n-l.height:e.bottom+n,h="bottom-end"===o||"top-end"===o?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,o=t.ownerDocument??document,n=()=>{t.isConnected?m():(g(),c?.("anchor-removed"))},a=e=>{let o="function"==typeof e.composedPath?e.composedPath():[];o.includes(r)||o.includes(t)||(g(),c?.("outside"))},s=e.setTimeout(()=>{o.addEventListener("pointerdown",a,!0)},0);e.addEventListener("scroll",n,!0),e.addEventListener("resize",n),h=()=>{e.clearTimeout(s),o.removeEventListener("pointerdown",a,!0),e.removeEventListener("scroll",n,!0),e.removeEventListener("resize",n)},d?.()};return{get isOpen(){return u},open:f,close:g,toggle:()=>u?g():f(),reposition:m,destroy:g}}let bn=["--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"],vn="data-persona-menu-focus",wn=new Set(["ArrowDown","ArrowUp","Home","End"]);function xn(e){return"menuitem"===e.getAttribute("role")?e:e.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')??e}let Cn=1e3,Sn="data-persona-composer-action",kn="data-persona-composer-disable-when-streaming";function An(e){let t=e.clientWidth;if(!t)return 0;let r=e.ownerDocument?.defaultView;if(!r?.getComputedStyle)return t;let o=r.getComputedStyle(e),n=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,t-n)}let Mn=(e,t)=>{e&&typeof console<"u"&&console.warn(t)},In=e=>"plugin"===e.source?`plugin "${e.pluginId}"`:"config"===e.source?"composer.actions":"a core built-in",Tn=(e,t,r)=>void 0===e?r:"function"==typeof e?!0===e(t):!0===e;function En(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 Ln=e=>"custom"===e.kind,Pn=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e;function Bn(e){let t=new Map,r=[],o=!1,n=()=>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(kn,!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 o=q("span","persona-composer-overflow-menu__icon");if(t.iconName){let e=se(t.iconName,16,"currentColor",1.5);e&&o.appendChild(e)}let n=q("span","persona-composer-overflow-menu__label");n.textContent=t.shortLabel??t.label,r.append(o,n)})(e,t);r.removeAttribute("role"),r.removeAttribute("tabindex"),r.removeAttribute("title");let o=n(),a=!!t.shortLabel;if(r.className=_("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",sn,ln,a&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),r.style.width=o&&!a?o:"",r.style.height=o??"",r.style.minWidth=o&&!a?o:"",r.style.minHeight=o??"",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=se(t.iconName,24,"currentColor",1.5);e&&r.appendChild(e)}if(a){let e=q("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=Xo({anchor:r,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,r)=>{let o=t.action,n=j("button",{attrs:{type:"button"}}),s=n;if("bar"===r){let e=q("div","persona-send-button-wrapper");e.appendChild(n),s=e}s.setAttribute(Sn,t.id);let i={resolved:t,element:s,button:n,owned:!0,managed:!0,busy:!1,visible:!0,mode:r},l=t=>{if(t.preventDefault(),t.stopPropagation(),i.busy||n.disabled)return;let r,o=i.resolved.action;"menu"===i.mode&&u?.close(!0);try{r=o.onSelect(e.actionContext,t)}catch(t){return void e.reportError(t,{actionId:i.resolved.id})}r&&"function"==typeof r.then&&(i.busy=!0,n.setAttribute("aria-busy","true"),r.catch(t=>{e.reportError(t,{actionId:i.resolved.id})}).finally(()=>{i.busy=!1,n.removeAttribute("aria-busy")}))};return n.addEventListener("click",l),i.detach=()=>n.removeEventListener("click",l),a(i,o),i},i=t=>{let r,o=t.action;try{r=o.render({...e.actionContext,id:t.id,action:o})}catch(o){return e.reportError(o,{actionId:t.id}),null}return r?.element?(r.element.setAttribute(Sn,t.id),r.element.toggleAttribute(kn,!0===o.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?Ln(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 o=t[r];if(!o.managed)continue;let n=null;for(let o=r+1;o<t.length;o++){let r=t[o];if(!r.managed&&r.element.parentElement===e){n=r.element;break}}n?(o.element.parentElement!==e||o.element.nextSibling!==n)&&e.insertBefore(o.element,n):e.lastChild!==o.element&&e.appendChild(o.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 o=r instanceof HTMLButtonElement||r instanceof HTMLSelectElement||r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement?r:r.querySelector("button, select, input, textarea");o&&(o.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,o=q("div","persona-send-button-wrapper"),n=j("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${sn} ${ln}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(n);let a=j("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),s=()=>{let t=e.getButtonSize?.()??"";n.style.width=t,n.style.height=t,n.style.minWidth=t,n.style.minHeight=t,n.style.lineHeight="1",n.replaceChildren();let r=se("plus",24,"currentColor",1.5);r?n.appendChild(r):n.textContent="+"},i=()=>{n.setAttribute("aria-label",t),n.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&&xn(t)===e;t.toggleAttribute(vn,r&&c)}},u=()=>l.filter(e=>e.isConnected||a.contains(e)).map(xn).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=()=>o.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(),n.setAttribute("aria-expanded","false"),v(),w(),d=-1,c=!1;for(let e of l)e.removeAttribute(vn);e&&n.focus()}},k=(e=0,t=!1)=>{if(r||C())return;c=t,dn(n,a,bn),(x||=yn({anchor:n,content:a,placement:"top-start",offset:6,onDismiss:()=>{n.setAttribute("aria-expanded","false"),v()}}),x).open(),n.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(o)||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(wn.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 n.addEventListener("click",A),n.addEventListener("keydown",M),a.addEventListener("keydown",I),{trigger:o,triggerButton:n,panel:a,setItems:e=>{for(let t of l)e.includes(t)||t.removeAttribute(vn);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(),n.removeEventListener("click",A),n.removeEventListener("keydown",M),a.removeEventListener("keydown",I),x?.destroy(),x=null,o.remove(),a.remove(),l=[]}}}({label:e.getOverflowLabel?.()??"More actions",getButtonSize:n}),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 o=e.resolved.presentation;return"overflow"===o||"auto"===o&&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 o=e;"function"==typeof o.matches&&o.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=Pn(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""})(e.element);r?(e.menuLabel||=q("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 o=e.resolved.action;if(o&&!Ln(o)){d(e),t.delete(e.resolved.id);let o=s(e.resolved,r);return t.set(e.resolved.id,o),o}if("menu"===r){let t=j("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none","data-persona-tooltip-suppressed":""}});t.appendChild(e.element),function(e){Vo.get(e)?.hide()}(Pn(e.element)),e.menuSlot=t;let r=t=>{let r=Pn(e.element);if(r.disabled)return;let o=t.target===r||r.contains(t.target);u?.close(!0),o||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(o)return;let n=e.getBindings();if(!n)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=An(e),typeof ResizeObserver<"u"&&(m=new ResizeObserver(t=>{let r=t[t.length-1]?.contentRect?.width??An(e);r!==g&&(g=r,w())}),m.observe(e)))})(n.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 o=q("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let n=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(n)&&n>0?n:Number.isFinite(r)?r:null}(e.collapseAutoActionsBelow,t);if(null===r)return!1;let o=g||An(t);return o>0&&o<r})(i,n.footer),d={start:[],end:[]},x=[];for(let e of r){let r=t.get(e.id);if(!r)continue;let o=e.action,n=!o||Tn(o.visible,a,!0)&&En(o.visibility,a);if(r.visible!==n&&(r.visible=n,!n&&r.managed&&(r.menuSlot??r.element).remove()),n){if(r=v(r,y(r,i,l)),o){let e=Tn(o.disabled,a,!1)||!0===o.disableWhenStreaming&&s;p(r,e),!Ln(o)&&void 0!==o.pressed&&r.button?.setAttribute("aria-pressed",o.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 o=e.children[r];o!==t&&(o?e.insertBefore(t,o):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),o={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,o)}else u&&(u.close(),u.trigger.remove(),u.setItems([]));c(n.actionsStart,d.start),c(n.actionsEnd,d.end)};return{resolve:()=>{if(o)return;let n=function(e){let{debug:t}=e,r=[],o=new Map,n=0,a=e=>{let n=o.get(e.id);n?Mn(t,`[Persona] composer action "${e.id}" is already contributed by ${In(n)}; the ${In(e)} copy is ignored.`):(o.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:n++,source:"core",builtIn:t});let s=(e,r,o)=>{let s=o?((e,t)=>t.includes(":")?t:`${e}:${t}`)(o,e.id):e.id,i=e.order??500;"end"===e.placement&&i>=Cn&&(Mn(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:n++,source:r,pluginId:o,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(n.map(e=>e.id));for(let[e,r]of t)s.has(e)||(d(r),t.delete(e));for(let e of n){let r=t.get(e.id);if(!r){let r=l(e,"bar");r&&t.set(e.id,r);continue}let o=r.resolved.action,n=e.action;if(!!o!=!!n||o&&n&&Ln(o)!==Ln(n)||o&&n&&Ln(o)&&Ln(n)&&o.render!==n.render){d(r),t.delete(e.id);let o=l(e,r.mode);o&&t.set(e.id,o)}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)):n&&!Ln(n)?a(r,n):n&&r.element.toggleAttribute(kn,!0===n.disableWhenStreaming)}r=n,w()},sync:w,getResolved:()=>r,getOverflowMenu:()=>u,destroy:()=>{if(!o){o=!0,m?.disconnect(),m=null,h=null;for(let e of t.values())d(e);t.clear(),u?.destroy(),u=null,r=[]}}}}let Rn=["--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"],Nn=()=>({wrapper:j("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),chevron:j("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}})});function $n(e){let t=e.label??"Model",r=e.presentation??"native",o=null,n=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=j("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),a=q("span","persona-composer-model-picker-label"),s=q("span","persona-composer-model-picker-suffix");r.append(a,s);let i=j("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||=yn({anchor:r,content:i,placement:"top-start",offset:6,onDismiss:()=>r.setAttribute("aria-expanded","false")}),dn(r,i,Rn),c.open(),r.setAttribute("aria-expanded","true");let o=[...l.keys()].indexOf(n(e.getModels())?.id??"");h(t??(o>=0?o: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 o=e.getModels(),c=o.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(...o.map(e=>{let t=(e=>{let t=j("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":e.id}});if(e.icon){let r=se(e.icon,16,"currentColor",1.5);if(r){let e=q("span","persona-composer-model-option-icon");e.appendChild(r),t.appendChild(e)}}let r=q("span","persona-composer-model-option-body"),o=q("span","persona-composer-model-option-label");if(o.textContent=e.label,r.appendChild(o),e.description){let t=q("span","persona-composer-model-option-description");t.textContent=e.description,r.appendChild(t)}t.appendChild(r);let n=q("span","persona-composer-model-option-check");n.setAttribute("aria-hidden","true");let a=se("check",16,"currentColor",2);return a&&n.appendChild(a),t.appendChild(n),t.addEventListener("click",f),t})(e);return l.set(e.id,t),t}))}let p=n(o);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(),o=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}=Nn();return x.append(r,C),{element:x,destroy:()=>{o===y&&(o=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=j("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),a="",s=()=>{let t=e.getModels(),o=t.map(e=>`${e.id}:${e.label}`).join("|");o!==a&&(a=o,r.replaceChildren(...t.map(e=>{let t=j("option",{attrs:{value:e.id}});return t.textContent=e.label,t}))),r.value=n(t)?.id??""};s(),o=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}=Nn();return d.append(r,c),{element:d,destroy:()=>{o===s&&(o=null),r.removeEventListener("change",i),r.removeEventListener("click",l)}}})()},repaint:()=>o?.()}}let Hn="[data-persona-composer-chip-row]";function Wn(e){e.style.display=e.childElementCount>0?"flex":"none"}function Dn(e){let t=e.querySelector(Hn);if(t)return t;let r=j("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});r.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(r,o):e.appendChild(r),r}function Fn(e){let t=e.row,r="",o=!1,n=new Set(e.initialIds??[]),a=t=>{let r=j("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=q("span","persona-mention-chip-icon"),o=se(t.iconName,12,"currentColor",1.5);o&&e.appendChild(o),r.appendChild(e)}let o=q("span","persona-mention-chip-label");o.textContent=t.shortLabel??t.label,r.appendChild(o);let n=j("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${t.label}`}}),a=se("x",12,"currentColor",2);return a?n.appendChild(a):n.textContent="×",n.addEventListener("click",r=>{r.preventDefault(),r.stopPropagation(),e.onRemove(t.id)}),r.appendChild(n),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(),Wn(t)},o=t.ownerDocument.defaultView,n="function"==typeof o?.getComputedStyle?o.getComputedStyle(e).animationName:"";n&&"none"!==n?(e.addEventListener("animationend",r,{once:!0}),e.addEventListener("animationcancel",r,{once:!0})):r()};return{element:t,render:(e,l)=>{if(o)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),n.has(e.id)||(r.setAttribute("data-persona-chip-enter",""),r.addEventListener("animationend",()=>r?.removeAttribute("data-persona-chip-enter"),{once:!0}))),n.delete(e.id),r!==u&&t.insertBefore(r,u),u=r.nextSibling}Wn(t)},destroy:()=>{o=!0,(()=>{for(let e of s())e.remove()})(),Wn(t)}}}let On=e=>`core:mode:${e}`,zn=e=>Math.min(300+e,499),qn=e=>`core:mode-group:${e}`;function jn(e,t){return!!e&&"segmented"===t?.find(t=>t.id===e)?.presentation}function _n(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function Un(e){let t=null;return{action:{id:qn(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let r=j("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),o=new Map,n="",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!==n){n=i;for(let e of o.values())e.removeEventListener("click",a);o.clear();let e=s.map(e=>{let t=(e=>{let t=j("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let r=se(e.iconName,16,"currentColor",1.5);r&&t.appendChild(r)}let r=q("span","persona-composer-segmented-label");return r.textContent=e.shortLabel??e.label,t.appendChild(r),t.addEventListener("click",a),t})(e);return o.set(e.id,t),t});r.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of o)t.setAttribute("aria-pressed",String(l.includes(e)))};return s(),t=s,{element:r,destroy:()=>{t===s&&(t=null);for(let e of o.values())e.removeEventListener("click",a);o.clear()}}}},repaint:()=>t?.()}}function Vn(e){let t=j("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let r="",o=!1,n=r=>{let o=q("span","persona-composer-quote-bar"),n=q("div","persona-composer-quote-content");if(r.sourceLabel){let e=q("div","persona-composer-quote-source");e.textContent=r.sourceLabel,n.appendChild(e)}let a=j("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});a.textContent=so(r.text),n.appendChild(a);let s=j("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),i=se("x",12,"currentColor",2);i?s.appendChild(i):s.textContent="×",s.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(o,n,s)};return{element:t,render:e=>{if(o)return;let a=e?`${e.sourceLabel??""}\0${e.text}`:"";a!==r&&(r=a,e?(n(e),t.style.display="flex"):(t.replaceChildren(),t.style.display="none"))},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function Kn(e){let t=j("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let r,o=!1,n=(e,t,r,o)=>{let n=j("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":t,[r]:""}}),a=se(e,12,"currentColor",2);return a?n.appendChild(a):n.textContent=t,n.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),o()}),n};return{element:t,render:a=>{if(o||a===r)return;if(r=a,!a)return t.replaceChildren(),void(t.style.display="none");let s=q("span","persona-composer-pending-badge");s.textContent=e.label??"Sends next";let i=j("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});i.textContent=(e=>{let t=so(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,n("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),n("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function Gn(e){let t=j("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),r=j("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 o=()=>{r.style.height="auto",r.style.height=`${r.scrollHeight}px`};r.addEventListener("input",o);let n=q("div","persona-message-edit-actions"),a=(e,t,r,o)=>{let n=j("button",{className:`persona-message-edit-button ${t}`,attrs:{type:"button",[r]:""},text:e});return n.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),o()}),n},s=()=>{let t=r.value.trim();t&&e.onSave(t)};return n.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,n),{element:t,getValue:()=>r.value,focus:()=>{r.focus();let e=r.value.length;r.setSelectionRange(e,e),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function Jn(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 Xn(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 Qn(e,t,r){let o;try{o=e(Jn(t),{signal:r})}catch(e){return{status:"error",error:e}}return(e=>"function"==typeof e?.then)(o)?Promise.resolve(o).then(e=>r.aborted?{status:"aborted"}:Xn(t,e),e=>r.aborted?{status:"aborted"}:{status:"error",error:e}):Xn(t,o)}let{setLoader:Yn,load:Zn}=U({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),ea=Yn,ta=Zn,{setLoader:ra,load:oa}=U({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),na=ra,aa=oa;function sa(e){let{config:t,onOpen:r}=e,o=t.buttonIconName??"plus",n=t.buttonTooltipText??"Add context",a=q("div","persona-send-button-wrapper"),s=j("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${sn} ${ln}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":n,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),i=se(o,24,"currentColor",1.5);return i?s.appendChild(i):s.textContent="+",s.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r()}),a.appendChild(s),Xo({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??n}),{button:s,wrapper:a}}let ia=e=>e?.launcher?.variant??(!0===e?.future?.v5Defaults?"circle":"pill"),la={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"},da="16px",ca="transparent",pa={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"}},ua={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"}},ha={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:P,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:da,canvasBackground:ca,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"}}},ma=pa.colors.gray,ga={...pa,colors:{...pa.colors,gray:ma}},fa={...pa,colors:{...pa.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"}},ya=ga,ba=ua,va={...ua,colors:{...ua.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...ua.typography,fontSize:"14px",lineHeight:"1.5"}},wa=ba,xa=ha,Ca={...ha,launcher:la,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:{...ha.input,borderRadius:"palette.radius.full"},introCard:{...ha.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...ha.suggestion.chip,fontWeight:"400"},card:{...ha.suggestion.card,fontWeight:"400"},list:{...ha.suggestion.list,fontWeight:"400"}},panel:{...ha.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...ha.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:{...ha.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...ha.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:{...ha.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...ha.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)"}},Sa=xa,ka=e=>"v5"===(e=>W({future:e}))(e)?{palette:fa,semantic:va,components:Ca}:{palette:ga,semantic:ba,components:xa};function Aa(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let e of r){if(null==o)return;o=o[e]}return"string"==typeof o&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Aa(e,o):o}function Ma(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let o=`${n}.${a}`;if("string"==typeof s){let r=Aa(e,s);void 0!==r&&(t[o]={path:o,value:r,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else"object"==typeof s&&s&&r(s,o)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function Ia(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 Ta(e,t){let r={...e};for(let[e,o]of Object.entries(t)){let t=r[e];r[e]=t&&"object"==typeof t&&!Array.isArray(t)&&o&&"object"==typeof o&&!Array.isArray(o)?Ta(t,o):o}return r}function Ea(e,t){return t?Ta(e,t):e}function La(e,t={}){let r=ka(t.future),o={palette:r.palette,semantic:r.semantic,components:r.components},n={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:Ea(o.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]&&(n.components[e][t]=a[t]);let s=e?.components?.collapsibleWidget?.surface;void 0!==s&&void 0===a?.bodySurface&&(n.components.activity={...n.components.activity,bodySurface:s});let i=e?.components?.header;void 0!==i?.padding&&void 0===i.minimalPadding&&(n.components.header.minimalPadding=n.components.header.padding);let l=e?.components?.message;if(void 0!==l?.gap&&void 0===l.fullscreenGap&&(n.components.message.fullscreenGap=n.components.message.gap),!1!==t.validate){let e=Ia(n);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(", ")}`)}if(t.plugins)for(let e of t.plugins)n=e.transform(n);return n}let Pa=e=>"0"===e.trim()?"0px":e,Ba="--persona-",Ra=(e,t)=>{for(let[r,...o]of t){let t;for(let r of o)if(t=61===r.charCodeAt(0)?r.slice(1):e[Ba+r],void 0!==t)break;void 0!==t&&(e[Ba+r]=t)}};function Na(e){let t=Ma(e),r={};for(let[e,o]of Object.entries(t))r[`--persona-${e.replace(/\./g,"-")}`]=o.value;Ra(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 o=r["--persona-components-launcher-foreground"];r["--persona-launcher-fg-muted"]=o&&o!==r["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:r["--persona-muted"],Ra(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"]]),Ra(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"]}`,Ra(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",Ra(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"]]),Ra(r,[["header-bg","components-header-background","surface"]]);let n=r["--persona-header-bg"],a=r["--persona-components-header-foreground"],s=a?`color-mix(in srgb, ${a} 72%, ${n})`:void 0;r["--persona-header-border"]=r["--persona-components-header-border"]??(a?`color-mix(in srgb, ${a} 14%, ${n})`:void 0)??r["--persona-divider"],Ra(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"],Ra(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 o=r[`--persona-components-history-overlay-${e}`];o&&(r[`--persona-history-overlay-${t}`]=o)}for(let[e,t]of[["background","bg"],["borderRadius","radius"]]){let o=r[`--persona-components-history-menu-${e}`];o&&(r[`--persona-history-menu-${t}`]=o)}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 o=e(p.exitDurationMs);void 0!==o&&(r["--persona-history-exit-ms"]=o),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 o=r[`--persona-components-tooltip-${e}`];o&&(r[`--persona-tooltip-${t}`]=o)}!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 o=r[`--persona-components-messageActions-${e}`];o&&(r[`--persona-message-action-${t}`]=o)}Ra(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,Ra(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"]]),Ra(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),Ra(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"]]),Ra(r,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Ra(r,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Ra(r,[["md-hr-color","components-markdown-hr-color","divider"]]),Ra(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 o=r[`--persona-components-collapsibleWidget-${e}`]??r[`--persona-${t}`];void 0!==o&&(r[`--persona-cw-${e}`]=o,r[`--cw-${e}`]=o)}Ra(r,[["message-border","components-message-border","border"]]),Ra(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"]=Pa(t.toggleGroupGap)),t.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=t.toggleBorderRadius),t.toggleGroupPadding&&(r["--persona-artifact-toolbar-toggle-group-padding"]=Pa(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"]=Aa(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"]=Pa(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"]=Aa(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"]=Aa(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"]=Aa(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(r["--persona-artifact-inline-chrome-border"]=Aa(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(r["--persona-artifact-inline-title-color"]=Aa(e,t.titleColor)??t.titleColor),t.mutedColor&&(r["--persona-artifact-inline-muted-color"]=Aa(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"]=Aa(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",R=!E||E===T,N=(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[o,n,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*o+.7152*n+.0722*a})(T??r["--persona-background"]),$=R&&void 0!==N&&N<.179,H=$?"rgba(255, 255, 255, 0.16)":B,W=R?$?"rgba(255, 255, 255, 0.08)":L:E,D=R?$?"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,R&&(r["--persona-icon-btn-active-border"]=r["--persona-icon-btn-active-border"]??H),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 $a={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)"}}}},Ha={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"}}},Wa={...Ha,colors:{...Ha.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"}}},Da=$a,Fa={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:{...$a.components,button:{...$a.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:{...$a.components?.eventStream,badge:{...$a.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"}}}}},Oa=e=>{if(e&&"object"==typeof e&&!Array.isArray(e))return e},za=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",qa=e=>(e=>{let t=e?.colorScheme??"light";return"light"===t?"light":"dark"===t?"dark":za()})(e),ja=e=>{let t=qa(e),r=Oa(e?.theme),o=y({components:{launcher:"circle"===ia(e)?la:{...xa.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}}}},r),n=Oa(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,o=t.darkTheme?.components?.panel?.width;return null==("dark"===qa(t)?o??r:r)?{...e,components:{...e.components,panel:{...e.components.panel,width:"v5"===W(t)?"400px":"420px"}}}:e})("dark"===t?((e,t={})=>{let r=(e=>"v5"===W({future:e})?{palette:Wa,components:Fa}:{palette:Ha,components:Da})(t.future),o=y(r.components,e??{})??{};return La({...o,palette:{...o.palette,colors:"v5"===W(t)?y(r.palette.colors,o.palette?.colors):{...r.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})})(y(o??{},n??{}),{future:e?.future}):((e,t={})=>La(e,t))(o,{future:e?.future}),e)},_a=(e,t)=>{let r=(e=>Na(e))(ja(t));for(let[t,o]of Object.entries(r))e.style.setProperty(t,o);e.setAttribute("data-persona-color-scheme",qa(t)),e.setAttribute("data-persona-defaults",W(t))},Ua=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let r=new MutationObserver(()=>{e(za())});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)"),o=()=>e(za());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(e=>e())}},Va=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px"),Ka=(e,t)=>t||"overlay"!==e?.composer?.placement?"block":"overlay",Ga=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},Ja=()=>{if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},Xa=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Qa=e=>{let t=e.toLowerCase().split("+").map(e=>e.trim()),r=t.pop(),o={key:r,mod:!1,shift:!1,alt:!1};for(let r of t)if("mod"===r||"cmd"===r||"ctrl"===r)o.mod=!0;else if("shift"===r)o.shift=!0;else{if("alt"!==r&&"option"!==r)return Xa("unknown modifier in",e),null;o.alt=!0}return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(r)||!/^([^+\s]|[a-z]{2,12})$/.test(r)?(Xa("unsupported",e),null):("space"===r&&(o.key=" "),o)},Ya=(e,t)=>{let r=Qa(e);if(!r)return"";let o=Ja(),n=(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&&o)return`${r.alt?"⌥":""}${r.shift?"⇧":""}⌘${n}`;let a=[t?o?"Meta":"Control":"Ctrl"];return r.alt&&a.push("Alt"),r.shift&&a.push("Shift"),a.push(n),a.join("+")},Za=e=>Ya(e,!1),es=e=>Ya(e,!0),ts=(e,t)=>t.key?.toLowerCase()===e.key&&(Ja()?t.metaKey:t.ctrlKey)===e.mod&&!(Ja()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,rs=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t||e.isContentEditable},os=e=>{let t=new Map,r=e?.ownerDocument??(typeof document<"u"?document:null),o=(t,r)=>{if("page"===(t.scope??"widget"))return!0;if(!e)return!1;let o=r.composedPath?.();return o?.length?o.includes(e):e.contains(r.target)},n=e=>{if(e.isComposing||!t.size)return;let r=e.composedPath?.()[0]??e.target;for(let n of t.values())if(ts(n.parsed,e)&&!1!==n.when?.()&&o(n,e)&&(n.allowInInput||!rs(r))){e.preventDefault();try{n.run(e)}catch(e){Xa(`${n.id} threw on`,n.combo),console.warn(e)}return}};return r?.addEventListener("keydown",n),{register(e){let r=Qa(e.combo);if(!r)return()=>{};let o=`${r.mod?"m":""}${r.shift?"s":""}${r.alt?"a":""}${r.key}`,n=t.get(o);return n?(Xa(`${n.id} already owns`,e.combo),()=>{}):(t.set(o,{...e,parsed:r}),e.element?.setAttribute("aria-keyshortcuts",es(e.combo)),()=>{t.get(o)?.id===e.id&&t.delete(o),e.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),r?.removeEventListener("keydown",n)}}};var ns=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,n){if(!1===n.callbacks.beforeNodeAdded(t))return null;if(n.idMap.has(t)){let a=document.createElement(t.tagName);return e.insertBefore(a,r),o(a,t,n),n.callbacks.afterNodeAdded(a),a}{let o=document.importNode(t,!0);return e.insertBefore(o,r),n.callbacks.afterNodeAdded(o),o}}let t=function(){function e(e,t,r){let o=e.idMap.get(t),n=e.idMap.get(r);if(!n||!o)return!1;for(let e of o)if(n.has(e))return!0;return!1}function t(e,t){let r=e,o=t;return r.nodeType===o.nodeType&&r.tagName===o.tagName&&(!r.getAttribute?.("id")||r.getAttribute?.("id")===o.getAttribute?.("id"))}return function(r,o,n,a){let s=null,i=o.nextSibling,l=0,d=n;for(;d&&d!=a;){if(t(d,o)){if(e(r,d,o))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 n(e,t,o){let n=t;for(;n&&n!==o;){let t=n;n=n.nextSibling,r(e,t)}return n}function a(e,t,r,o){let n=o.target.getAttribute?.("id")===t&&o.target||o.target.querySelector(`[id="${t}"]`)||o.pantry.querySelector(`[id="${t}"]`);return function(e,t){let r=e.getAttribute("id");for(;e=e.parentNode;){let o=t.idMap.get(e);o&&(o.delete(r),o.size||t.idMap.delete(e))}}(n,o),s(e,n,r),n}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&&n(s,d,e),o(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);o(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)}}}(),o=function(){function e(e,r,o){let a=r.nodeType;if(1===a){let a=e,i=r,l=a.attributes,d=i.attributes;for(let e of d)n(e.name,a,"update",o)||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(n(t.name,a,"remove",o))continue;a.removeAttribute(t.name)}}s(a,o)||t(a,i,o)}(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;o(e,t,"checked",r),o(e,t,"disabled",r),t.hasAttribute("value")?s!==a&&(n("value",e,"update",r)||(e.setAttribute("value",a),e.value=a)):n("value",e,"remove",r)||(e.value="",e.removeAttribute("value"))}else if(e instanceof HTMLOptionElement&&t instanceof HTMLOptionElement)o(e,t,"selected",r);else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let o=t.value,a=e.value;if(n("value",e,"update",r))return;o!==a&&(e.value=o),e.firstChild&&e.firstChild.nodeValue!==o&&(e.firstChild.nodeValue=o)}}function o(e,t,r,o){let a=t[r];if(a!==e[r]){let s=n(r,e,"update",o);s||(e[r]=t[r]),a?s||e.setAttribute(r,""):n(r,e,"remove",o)||e.removeAttribute(r)}}function n(e,t,r,o){return!("value"!==e||!o.ignoreActiveValue||t!==document.activeElement)||!1===o.callbacks.beforeAttributeUpdated(e,t,r)}function s(e,t){return!!t.ignoreActiveValue&&e===document.activeElement&&e!==document.body}return function(t,o,n){return n.ignoreActive&&t===document.activeElement?null:(!1===n.callbacks.beforeNodeMorphed(t,o)||(t instanceof HTMLHeadElement&&n.head.ignore||(t instanceof HTMLHeadElement&&"morph"!==n.head.style?a(t,o,n):(e(t,o,n),s(t,n)||r(n,t,o))),n.callbacks.afterNodeMorphed(t,o)),t)}}();function n(e,t,r,o){if(e.head.block){let n=t.querySelector("head"),s=r.querySelector("head");if(n&&s){let t=a(n,s,e);return Promise.all(t).then(()=>o(Object.assign(e,{head:{block:!1,ignore:!0}})))}}return o(e)}function a(e,t,r){let o=[],n=[],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),o=r.head.shouldReAppend(t),l=r.head.shouldPreserve(t);e||l?o?n.push(t):(i.delete(t.outerHTML),a.push(t)):"append"===r.head.style?o&&(n.push(t),s.push(t)):!1!==r.head.shouldRemove(t)&&n.push(t)}s.push(...i.values());let l=[];for(let t of s){let n=document.createRange().createContextualFragment(t.outerHTML).firstChild;if(!1!==r.callbacks.beforeNodeAdded(n)){if("href"in n&&n.href||"src"in n&&n.src){let e,t=new Promise(function(t){e=t});n.addEventListener("load",function(){e()}),l.push(t)}e.appendChild(n),r.callbacks.afterNodeAdded(n),o.push(n)}}for(let t of n)!1!==r.callbacks.beforeNodeRemoved(t)&&(e.removeChild(t),r.callbacks.afterNodeRemoved(t));return r.head.afterHeadMorphed(e,{added:o,kept:a,removed:n}),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 o(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 n(e){let t=Array.from(e.querySelectorAll("[id]"));return e.getAttribute?.("id")&&t.push(e),t}function a(e,t,r,o){for(let n of o){let o=n.getAttribute("id");if(t.has(o)){let t=n;for(;t;){let n=e.get(t);if(n??(n=new Set,e.set(t,n)),n.add(o),t===r)break;t=t.parentElement}}}}function s(e,t){let r=n(e),o=n(t),s=function(e,t){let r=new Set,o=new Map;for(let{id:t,tagName:n}of e)o.has(t)?r.add(t):o.set(t,n);let n=new Set;for(let{id:e,tagName:a}of t)n.has(e)?r.add(e):o.get(e)===a&&n.add(e);for(let e of r)n.delete(e);return n}(r,o),i=new Map;return a(i,s,e,r),a(i,s,t.__idiomorphRoot||t,o),{persistentIds:s,idMap:i}}return function(t,n,a){let{persistentIds:i,idMap:l}=s(t,n),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:n,config:d,morphStyle:c,ignoreActive:d.ignoreActive,ignoreActiveValue:d.ignoreActiveValue,restoreFocus:d.restoreFocus,idMap:l,persistentIds:i,pantry:r(),activeElementAndParents:o(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 o=r.querySelectorAll(e);for(let e=0;e<o.length;e++)t.push(o[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(o){if(null==o)return document.createElement("div");if("string"==typeof o)return r(function(t){let r=new DOMParser,o=t.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(o.match(/<\/html>/)||o.match(/<\/head>/)||o.match(/<\/body>/)){let n=r.parseFromString(t,"text/html");if(o.match(/<\/html>/))return e.add(n),n;{let t=n.firstChild;return t&&e.add(t),t}}{let o=r.parseFromString("<body><template>"+t+"</template></body>","text/html").body.querySelector("template").content;return e.add(o),o}}(o));if(e.has(o))return o;if(o instanceof Node){if(o.parentNode)return new t(o);{let e=document.createElement("div");return e.append(o),e}}{let e=document.createElement("div");for(let t of[...o])e.append(t);return e}}}}();return{morph:function(e,t,o={}){e=i(e);let a=l(t),d=s(e,a,o),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:o,selectionStart:n,selectionEnd:a}=r,s=t();return o&&o!==document.activeElement?.getAttribute("id")&&(r=e.target.querySelector(`[id="${o}"]`),r?.focus()),r&&!r.selectionEnd&&a&&r.setSelectionRange(n,a),s}(d,()=>n(d,e,a,t=>"innerHTML"===t.morphStyle?(r(t,e,a),Array.from(e.childNodes)):function(e,t,o){let n=l(t);return r(e,n,o,t,t.nextSibling),Array.from(n.childNodes)}(t,e,a)));return d.pantry.remove(),c},defaults:t}}();let as=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;ns.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement&&o){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}}}})},ss={index:-1,draft:""};function is(e){return"assistant"===e.role&&"tool"!==e.variant&&"reasoning"!==e.variant&&("approval"===e.variant||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length))}function ls(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ds(e,t){return ls(e)-e.scrollTop<=t}function cs(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 ps="none",us="none",hs=120,ms=1800,gs="none",fs=["pre","code","a","script","style"],ys=e=>({type:e?.type??ps,placeholder:e?.placeholder??us,speed:e?.speed??hs,duration:e?.duration??ms,buffer:e?.buffer??gs}),bs=[{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"}],vs=new Map;for(let e of bs)vs.set(e.name,e);let ws=["wipe","glyph-cycle"],xs=e=>{vs.set(e.name,e)},Cs=(e,t)=>"none"===e?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:vs.get(e)??null,Ss=(e,t,r,o,n)=>{if(!n)return e;if(r?.bufferContent)return r.bufferContent(e,o);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},ks=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},As=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},Ms=/\s/,Is=(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},Ts=(e,t,r)=>{let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(Ms.test(a[i])){let e=i;for(;e<a.length&&Ms.test(a[e]);)e+=1;s.appendChild(o.createTextNode(a.slice(i,e))),i=e}else{let e=o.createElement("span");e.className="persona-stream-word-group";let n=i;for(;n<a.length&&!Ms.test(a[n]);)e.appendChild(ks(o,a[n],t,r.value)),r.value+=1,n+=1;s.appendChild(e),i=n}n.replaceChild(s,e)},Es=(e,t,r)=>{let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let e of i)e&&(/^\s+$/.test(e)?s.appendChild(o.createTextNode(e)):(s.appendChild(As(o,e,t,r.value)),r.value+=1));n.replaceChild(s,e)},Ls=(e,t,r,o)=>{if(!e||typeof document>"u")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set((o?.skipTags??fs).map(e=>e.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],l=s.nextNode();for(;l;)Is(l,a)||i.push(l),l=s.nextNode();let d={value:o?.startIndex??0},c="char"===t?Ts:Es;for(let e of i)c(e,r,d);return n.innerHTML},Ps=(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},Bs=(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},Rs=new WeakMap,Ns=new WeakMap,$s=e=>{let t=Ns.get(e);if(t){for(let e of t.values())"function"==typeof e&&e();t.clear()}},Hs=(e,t)=>{((e,t)=>{if(!e.styles)return;let r=Rs.get(t);if(r||(r=new Set,Rs.set(t,r)),r.has(e.name)){let o=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${o}"]`))return;r.delete(e.name)}r.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)})(e,t),((e,t)=>{if(!e.onAttach)return;let r=Ns.get(t);if(r||(r=new Map,Ns.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)})(e,t)},{setLoader:Ws,load:Ds}=U({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),Fs=Ws,Os=Ds;function zs(e,t=1e5){let r=e.style.position,o=e.style.zIndex,n=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=o,e.style.isolation=n}}let qs=0,js=null;function _s(e=document){if(qs++,1===qs){let t=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;js={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,qs=Math.max(0,qs-1),0===qs&&js)){let t=e.body,r=e.defaultView??window;t.style.overflow=js.originalOverflow,t.style.position=js.originalPosition,t.style.top=js.originalTop,t.style.width=js.originalWidth,r.scrollTo(0,js.scrollY),js=null}}}let Us="right",Vs="420px",Ks=!0,Gs="resize",Js="100dvh",Xs=e=>"docked"===(e?.launcher?.mountMode??"floating"),Qs=e=>"composer-bar"===(e?.launcher?.mountMode??"floating"),Ys=e=>{let t=e?.launcher?.dock,r=T(e).dockWidth?t?.width:Aa(ja(e),"components.panel.width");return{side:t?.side??Us,width:r??Vs,animate:t?.animate??Ks,reveal:t?.reveal??Gs,maxHeight:t?.maxHeight??Js}},Zs=e=>"followUp"===e?"follow-up":e,ei=(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 o=e.prompt?.trim()||r;return{id:e.id?.trim()||o||`suggestion-${t}`,label:r,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},ti=new WeakSet,ri=e=>{let{item:t,index:r,surface:o,source:n,variant:a,streaming:s,config:i,plugins:l,chipsConfig:d,session:c,getTextarea:p,eventTarget:u,submitPrompt:h}=e,f="followUp"===o,y=t.behavior,b=()=>{if(c.isStreaming())return;let e={suggestion:{...t},surface:o,source:n,behavior:y},r=u.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(f&&u.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!r)return;for(let e of l)if(!1===e.onSuggestionSelect?.({suggestion:{...t},surface:o,source:n,variant:a,config:i}))return;let s=p();"fill"===y?(s.value=t.prompt,s.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),s.focus()):h?h(t.prompt):(s.value="",c.sendMessage(t.prompt))},v=()=>{let e=q("button",`persona-suggestion persona-suggestion--${a}`);if(e.type="button",e.disabled=s,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=y,"chip"===a&&(d?.fontWeight&&(e.style.fontWeight=d.fontWeight),d?.paddingX&&(e.style.paddingLeft=d.paddingX,e.style.paddingRight=d.paddingX),d?.paddingY&&(e.style.paddingTop=d.paddingY,e.style.paddingBottom=d.paddingY)),t.icon){let r=se(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 r=q("span","persona-suggestion__copy");if(r.appendChild(j("span",{className:"persona-suggestion__label",text:t.label})),t.description&&"chip"!==a&&r.appendChild(j("span",{className:"persona-suggestion__description",text:t.description})),e.appendChild(r),"chip"!==a){let t=g(m.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 l)if(e.renderSuggestion&&(w=e.renderSuggestion({suggestion:{...t},index:r,surface:o,source:n,variant:a,streaming:s,config:i,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",s?"true":"false"),w},oi=e=>{let t=[],r=[],o=null,n=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(n=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,o=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),s=o<=4,i=o>=t-4,l=r?!i:!s,d=r?!s:!i;e.toggleAttribute("data-scroll-left",l),e.toggleAttribute("data-scroll-right",d)},i=()=>{null!==n||"function"!=typeof requestAnimationFrame?"function"!=typeof requestAnimationFrame&&s():n=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!==n&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(n),n=null},render:(n,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";!ti.has(v)&&!0===v.debug&&"chip"!==f&&void 0!==v.suggestions?.[C]?.overflow&&(ti.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(ei).filter(e=>null!==e).map(e=>({...e,behavior:e.behavior??y})),k=S(n??[]);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,o=null,void a();if(!g&&(c??l.getMessages()).some(e=>"user"===e.role))return e.hidden=!0,void(o=null);e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Zs(m),e.dataset.variant=f,e.dataset.overflow=b;let M=document.createDocumentFragment(),I=l.isStreaming();A.forEach((o,n)=>{let a=ri({item:o,index:n,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!==o&&(o=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})))}}},ni={"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"},ai={x:[1.4,1.05]},si="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ii=(e,t,r={})=>{let{iconSize:o,iconText:n}=r,[a,s]=ai[t]??[1,1.5],i=!o;e.classList.toggle("persona-header-control--glyph",i),e.classList.toggle("persona-header-control--sparse",i&&1!==a);let l=se(t,`${Math.round((parseFloat(o??"")||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)):n&&(e.textContent=n)},li=e=>{let{ariaLabel:t,tooltip:r=!0,tooltipHint:o,iconName:n,iconText:a,wrapperClassName:s=si,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=q("div",s),w=!(!p&&!u),x=j("button",{className:_("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||pi.actionIconColor,backgroundColor:c,border:w?`${p||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:h,paddingLeft:m,paddingRight:m,paddingTop:g,paddingBottom:g}});return n?ii(x,n,{iconSize:l,iconText:a}):a&&(x.textContent=a),v.appendChild(x),Xo({anchor:x,trigger:v,text:()=>x.getAttribute("aria-label")??t,hint:o,enabled:r}),{button:x,wrapper:v}},di=(e,t={})=>{let{showClose:r=!0,wrapperClassName:o=si,buttonSize:n,iconSize:a}=t,s=e?.launcher??{},i=s.closeButtonTooltipText??"Close chat",l=s.closeButtonShowTooltip??!0,{button:d,wrapper:c}=li({ariaLabel:i,tooltip:l,iconName:s.closeButtonIconName??"x",iconText:s.closeButtonIconText??"×",wrapperClassName:o,size:n??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}},ci=(e,t={})=>{let{wrapperClassName:r="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",buttonSize:o,iconSize:n}=t,a=(e?.launcher??{}).clearChat??{},s=a.tooltipText??"Clear chat",i=a.showTooltip??!0,{button:l,wrapper:d}=li({ariaLabel:s,tooltip:i,iconName:a.iconName??"refresh-cw",wrapperClassName:r,size:o??a.size,iconSize:n,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}},pi={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)"},ui={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)"},hi={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)"},mi=e=>{let{config:t,showClose:r=!0}=e,o=j("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:pi.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)))"}}),n=t?.launcher??{},a=n.headerIconSize??"40px",s=n.closeButtonPlacement??"inline",i=n.headerIconHidden??!1,l=n.headerIconName,d=j("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(l){let e=parseFloat(a)||24,r=se(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=q("img");e.src=t.launcher.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=a,e.style.width=a,d.replaceChildren(e)}else d.textContent=t?.launcher?.agentIconText??"💬";let c=q("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=j("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:pi.titleColor,...ui}}),u=j("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:pi.subtitleColor,...hi}});c.append(p,u),i?o.append(c):o.append(d,c);let h=n.clearChat??{},m=h.enabled??!0,g=h.placement??"inline",f=null,y=null;if(m){let e=ci(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&&o.appendChild(y)}let{button:b,wrapper:v}=di(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&&o.appendChild(v),{header:o,iconHolder:d,headerTitle:p,headerSubtitle:u,closeButton:b,closeButtonWrapper:v,clearChatButton:f,clearChatButtonWrapper:y}},gi=(e,t,r)=>{let o=r?.launcher??{},n=o.closeButtonPlacement??"inline",a=o.clearChat?.placement??"inline";e.appendChild(t.header),"top-right"===n&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&"top-right"===a&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function fi(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a,onOpenChange:s}=e,i=q("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"===n?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=se(e.icon,16,"currentColor",1.5);r&&t.appendChild(r)}let o=document.createElement("span");o.textContent=e.label,t.appendChild(o),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=o.getBoundingClientRect();i.style.top=`${e.bottom+4}px`,"bottom-right"===n?(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)&&!o.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 yi(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,chromeless:s,onClick:i,aria:l}=e,d=q("button",_(!s&&"persona-icon-btn",a));d.type="button",d.setAttribute("aria-label",r),d.title=r;let c=se(t,o??16,"currentColor",n??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 bi(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:l}=e,d="persona-label-btn";"default"!==o&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+n,s&&(d+=" "+s);let c=q("button",d);if(c.type="button",c.setAttribute("aria-label",r),t){let e=se(t,a??14,"currentColor",2);e&&c.appendChild(e)}let p=q("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 vi(e){let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:l}=e,d=q("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=q("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let p=se(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=fi({items:o,onSelect:e=>{d.setAttribute("aria-expanded","false"),n(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 wi=e=>{let t=mi({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},xi=e=>{let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=t?.launcher??{},i=q("div","persona-flex persona-items-center persona-justify-between");i.setAttribute("data-persona-theme-zone","header"),i.style.minHeight=pi.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=n?.titleMenu;if(c){let e=vi({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}}))},o=c.onSelect(t);o instanceof Promise?o.then(r,()=>{}):r(o)},hover:c.hover,className:""});l=e.element,l.style.color=pi.titleColor,d=l.querySelector(".persona-combo-btn-label")??l}else{if(l=q("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=q("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=pi.titleColor,Object.assign(d.style,ui),d.textContent=s.title??"Chat Assistant",l.appendChild(d),n?.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let e=n.onTitleClick;l.addEventListener("click",t=>{t.target.closest("button")||e()}),l.addEventListener("keydown",t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),e())})}let e=n?.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}=di(t,{showClose:r,wrapperClassName:p});o&&u.addEventListener("click",o);let m=q("div","persona-flex persona-items-center persona-gap-1");c||function(e,t,r){if(t?.length)for(let o of t){let{button:t,wrapper:n}=li({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Za(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(t.setAttribute("data-persona-header-action",o.id),o.shortcut){let e=es(o.shortcut);e&&t.setAttribute("aria-keyshortcuts",e)}if(o.menuItems?.length){let e=fi({items:o.menuItems,onSelect:e=>r?.(e),anchor:n,position:"bottom-right"});n.appendChild(e.element),t.addEventListener("click",t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener("click",()=>r?.(o.id));e.appendChild(n)}}(m,n?.trailingActions,n?.onAction??a);let g=s.clearChat??{},f=null,y=null;if(g.enabled??1){let e=g.placement??"inline",r=ci(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=q("div");b.style.display="none";let v=q("span");return v.style.display="none",{header:i,iconHolder:b,headerTitle:d,headerSubtitle:v,closeButton:u,closeButtonWrapper:h,clearChatButton:f,clearChatButtonWrapper:y}},Ci={default:wi,minimal:xi},Si=e=>Ci[e]??Ci.default,ki=(e,t,r)=>{if(t?.render){let o=t.render({config:e,onClose:r?.onClose,onClearChat:r?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),n=q("div");n.style.display="none";let a=q("span"),s=q("span"),i=q("button");i.style.display="none";let l=q("div");return l.style.display="none",{header:o,iconHolder:n,headerTitle:a,headerSubtitle:s,closeButton:i,closeButtonWrapper:l,clearChatButton:null,clearChatButtonWrapper:null}}let o=Si(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&&(o.iconHolder.style.display="none"),!1===t.showTitle&&(o.headerTitle.style.display="none"),!1===t.showSubtitle&&(o.headerSubtitle.style.display="none"),!1===t.showCloseButton&&(o.closeButton.style.display="none"),!1===t.showClearChat&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o},Ai=e=>{let{config:t}=e,r=j("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=fn(),n=j("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""}}),{textarea:a,attachAutoResize:s}=cn(t);s();let i=un(t),l=hn(t),d=mn(t),c=gn(t),p=j("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(p),d&&(d.previewsContainer.style.gap="8px",p.append(d.previewsContainer),n.append(d.input)),n.append(a);let u=j("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=j("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),m=j("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return d&&h.append(d.wrapper),l&&m.append(l.wrapper),m.append(i.wrapper),u.append(h,m),n.append(u),n.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(o,c,n):r.append(o,n,c),{footer:r,suggestions:o,composerForm:n,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}},Mi=()=>{let e=j("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=q("span","persona-pill-peek__icon"),r=g(m.MessageSquare,16,"currentColor",1.5);r&&t.appendChild(r);let o=q("span","persona-pill-peek__text"),n=q("span","persona-pill-peek__caret"),a=g(m.ChevronUp,16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},Ii=e=>{let{config:t}=e,r=j("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=fn(),n=gn(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=cn(t,{defaultMaxLines:5});s();let i=un(t),l=hn(t),d=mn(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=j("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),p=j("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});d&&p.append(d.wrapper);let u=j("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=j("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(h),d&&h.append(d.previewsContainer),r.append(o,c,n);let m=c;return{footer:r,suggestions:o,composerForm:c,header:h,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:n,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 Ti(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let r=j("span",{className:_("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 o=se(e.iconName??"at-sign",13,"currentColor",2);if(o){let e=q("span","persona-mention-token-icon");e.appendChild(o),r.appendChild(e)}return r.appendChild(j("span",{className:"persona-mention-token-label",text:`@${e.label}`})),r}let Ei=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(":"))},Li=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let 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 o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let n=document.createElement("span");return n.className="persona-sr-only",n.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(o),e.appendChild(n),e},Pi=(e,t,r)=>{let o={config:r??{},streaming:!0,location:e,defaultRenderer:Li};if(t){let e=t(o);if(null!==e)return e}return Li()},Bi=(e,t,r="div")=>{let o=q(r,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return o.textContent=t.format?t.format(n):n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Ri=(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},Ni={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"}},$i=e=>`custom:${e}`,Hi=(e,t)=>"user"!==t&&"assistant"!==t?[]:(e?.custom??[]).filter(e=>(e.roles??["assistant"]).includes(t)),Wi=(e,t,r,o)=>{let n=t.showCopy??!0,a=t.showUpvote??!1,s=t.showDownvote??!1,i=t.showReadAloud??!1,l=(t.showRegenerate??!1)&&!0===o?.canRegenerate,d=(t.showEdit??!1)&&!0===o?.canEdit,c=(t.showQuote??!1)&&!1!==o?.canQuote,p=Hi(t,e.role);if(!(n||a||s||i||l||d||c||0!==p.length)){let t=q("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=q("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 o=yi({icon:e,label:t,size:14,className:"persona-message-action-btn",chromeless:!0});return o.setAttribute("data-action",r),o};n&&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,$i(e.id)));return g},Di=(e,t,r,o,n,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=Ri(e.role,i),g=q("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=ka(a?.widgetConfig?.future).components.message,y=a?.widgetConfig?.theme?.components?.message;((e,t,r="bubble",o)=>{if(!o)return;let n="user"===t?"user":"assistant",a=Ni[r??"bubble"]??Ni.bubble;o.padding&&(e.style.padding=`var(--persona-message-${n}-padding, ${a.padding})`),o.fontSize&&(e.style.fontSize=`var(--persona-message-${n}-font-size, ${a.fontSize})`),o.lineHeight&&(e.style.lineHeight=`var(--persona-message-${n}-line-height, ${a.lineHeight})`),o.fontFamily&&(e.style.fontFamily=`var(--persona-message-${n}-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=ys(a?.widgetConfig?.features?.streamAnimation),C=a?.widgetConfig?.features?.streamAnimation?.plugins,S="assistant"===e.role&&"none"!==x.type?Cs(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?Ss(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?Ls(r,"char",e.id,{skipTags:S.skipTags}):A&&"word"===S?.wrap?Ls(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,o)=>{let n=Math.random().toString(36).slice(2,8),a=e=>`${n}:${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 o of e)"text"===o.kind?r.appendChild(document.createTextNode(o.text)):r.appendChild(Ti(o.ref,{readonly:!0,render:t}));return r})(t,o));e.innerHTML=s;let i=RegExp(`${n}:(\\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 n=t[Number(e[1])],a=r.splitText(e.index);a.data=a.data.slice(e[0].length),"mention"===n?.kind&&a.parentNode?.insertBefore(Ti(n.ref,{readonly:!0,render:o}),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=Ps(),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=Bi(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 o=q("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r?.())};return e.forEach((e,t)=>{let r=q("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;n+=1,r.addEventListener("error",()=>{a||(a=!0,n=Math.max(0,n-1),r.remove(),0===n&&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,o.appendChild(r)):(a=!0,n=Math.max(0,n-1),r.remove())}),0===n?(s(),null):o}catch{return r?.(),null}})(b,!w&&!!v,()=>{w&&E&&(E.style.display="")});e?g.appendChild(e):w&&E&&(E.style.display="")}let L=(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(L.length>0){let e=(e=>{if(0===e.length)return null;try{let t=q("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(e=>{if(!Ei(e.audio))return;let o=q("audio");o.controls=!0,o.preload="metadata",o.src=e.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth="320px",t.appendChild(o),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(L);e&&g.appendChild(e)}let P=(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(P.length>0){let e=(e=>{if(0===e.length)return null;try{let t=q("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(e=>{if(!Ei(e.video))return;let o=q("video");o.controls=!0,o.preload="metadata",o.src=e.video,o.style.display="block",o.style.width="100%",o.style.maxWidth="320px",o.style.maxHeight="320px",o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),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=>"file"===e.type&&"string"==typeof e.data&&e.data.trim().length>0):[])(e);if(B.length>0){let e=(e=>{if(0===e.length)return null;try{let t=q("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(e=>{if(!Ei(e.data))return;let o=q("a");o.href=e.data,o.download=e.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=e.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(B);e&&g.appendChild(e)}let R=e.contentSegments?.length?null:(e=>{if(!e||0===e.length)return null;let t=j("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let r of e){let e=j("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:r.label}}),o=q("span","persona-mention-chip-icon"),n=se(r.iconName??"at-sign",13,"currentColor",2);n&&o.appendChild(n),e.appendChild(o),e.appendChild(j("span",{className:"persona-mention-chip-label",text:r.label})),t.appendChild(e)}return t})(e.contextMentions);if(R&&g.appendChild(R),g.appendChild(M),p&&"below"===h&&e.createdAt){let t=Bi(e,d);t.classList.add("persona-mt-1"),g.appendChild(t)}let N="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 o=t?.[e];return(void 0===o?r:o)||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(Bs());else if(t)g.appendChild(Bs());else{let e=Pi("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);e&&g.appendChild(e)}}N&&e.stopReason&&!e.streaming&&(v||(M.style.display="none"),g.appendChild(((e,t)=>{let r=q("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,N)));let $="assistant"===e.role&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&!1!==o?.enabled,H=a?.actionEligibility,W="user"===e.role&&!e.streaming&&!1!==o?.enabled&&(!0===o?.showEdit&&!0===H?.canEdit||!0===o?.showQuote&&!0===H?.canQuote||Hi(o,"user").length>0);if(($||W)&&o){let t=Wi(e,W?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,0,H);g.appendChild(t)}if(!c||"system"===e.role)return g;let D=q("div","persona-message-with-avatar persona-flex persona-gap-2 "+("user"===e.role?"persona-flex-row-reverse":"")),F=((e,t)=>{let r=q("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o="user"===t?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let e=q("img");e.src=o,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=o,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?D.append(g,F):D.append(F,g),D},Fi=(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)},Oi=(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=se(t.name,40);if(!r)return void(e.hidden=!0);e.appendChild(r)}else"image"===t.type?e.appendChild(j("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(j("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1}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")},zi="data-persona-welcome-overlay",qi="persona-welcome-overlay-active",ji=new WeakMap,_i=(e,t,r)=>{r.setAttribute("data-persona-welcome-plugin",""),t.appendChild(r),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(zi,""),e.classList.contains(qi)||(ji.set(e,e.scrollTop),e.classList.add(qi),e.scrollTop=0)},Ui=(e,t,r)=>{r&&r!==t&&r.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(zi),e.classList.contains(qi)&&(e.classList.remove(qi),e.scrollTop=ji.get(e)??e.scrollTop,ji.delete(e))},Vi=(e,t,r)=>{if(e.replaceChildren(),!t)return void(e.hidden=!0);let o=r?.layout?.messages?.layout??"bubble",n=j("div",{className:Ri("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:"flat"===o?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(j("div",{className:"persona-flex"},n)),e.hidden=!1},Ki=()=>typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Gi=(e,t)=>{if(Ki()||"function"!=typeof e.animate||!e.isConnected)return t(null),null;let r=e.getBoundingClientRect(),o=e.parentElement,n=0,a=0,s=0;if(o){let t=getComputedStyle(o);n=parseFloat(t.rowGap)||0;let i=e.previousElementSibling,l=e.nextElementSibling,d=o.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-o.scrollTop;a=Math.max(0,i?r.top-i.getBoundingClientRect().bottom-n:r.top-d),s=Math.max(0,l?l.getBoundingClientRect().top-r.bottom-n: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:-n+"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},Ji=(e,t,r,o=260)=>{if(t<=1||Ki()||"function"!=typeof e.animate||!e.isConnected)return null;let n="drop"===r?-t:t;return e.animate([{transform:`translateY(${n}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})},Xi=new WeakSet,Qi=(e,t)=>!!e&&void 0!==e[t],Yi=(e,t=!0===e?.launcher?.fullHeight&&!e.launcher.sidebarMode&&"docked"!==e.launcher.mountMode)=>{let r=e?.welcome,o=e?.copy,n=!0===e?.future?.v5Defaults,a=r?.layout??(n?"centered":"top"),s=Qi(r,"variant")?r.variant:!1===o?.showWelcomeCard?"none":"card",i="hero"!==s||n||void 0!==r?.layout?Qi(r,"dismiss")?r.dismiss:n||"hero"===s?"on-first-message":"never":"on-first-message",l=[];Qi(r,"title")&&Qi(o,"welcomeTitle")&&l.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Qi(r,"subtitle")&&Qi(o,"welcomeSubtitle")&&l.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Qi(r,"variant")&&Qi(o,"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.'),!n&&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!==Ga(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&&(Xi.has(e)||(Xi.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))})(e,l),{title:Qi(r,"title")?r.title:o?.welcomeTitle??(n?"What can I help with?":"Hello 👋"),kicker:r?.kicker??"",subtitle:Qi(r,"subtitle")?r.subtitle:o?.welcomeSubtitle??(n?"":"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"}},Zi=(e,t)=>"none"!==e.variant&&("never"===e.dismiss||!(t??[]).some(e=>"user"===e.role)),el="var(--persona-components-panel-height)",tl=e=>{let t=T(e),r=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0;return{width:r??"var(--persona-components-panel-width)",maxWidth:r??"var(--persona-components-panel-maxWidth)",height:0===o?`max(200px, ${el})`:`max(200px, calc(${el} - ${o}px))`,maxHeight:"var(--persona-components-panel-maxHeight)"}},rl="16px",ol="10px",nl="14px",al=e=>{let t=j("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Zs(e)}});return t.hidden=!0,t},sl=(e,t)=>{let r=((e,t,r={})=>{let o=j("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let n=q("p","persona-welcome-kicker");n.hidden=!0;let a=q("h2","persona-welcome-title"),s=q("p","persona-welcome-subtitle"),i=j("div",{className:"persona-welcome-head-text"},n,a),l=j("div",{className:"persona-welcome-title-row"},o,i);return{host:j("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:r.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},l,s,t),iconHolder:o,kicker:n,title:a,subtitle:s,starterSuggestions:t}})(0,al("starter"),{flatShadow:Xs(e)}),o=Yi(e);Oi(r,o),Fi(t,r.host,Zi(o,e?.initialMessages));let n=(()=>{let e=j("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e})();return Vi(n,o.message,e),{welcome:r,greetingHost:n}},il=(e,t)=>{let r=q("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 o=e=>{let t=e.launcher??{},o=Xs(e),n="circle"===ia(e);n?(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||o||n?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,o=se(t.agentIconName,.6*r,"var(--persona-text-inverse, #ffffff)",1.5);o?(l.appendChild(o),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||n)c.style.display="none";else if(c.style.display=o?"none":"",c.innerHTML="",t.callToActionIconName){let o=Math.max((parseFloat(e)||24)-r,8),n=se(t.callToActionIconName,o,"currentColor",1.5);n?c.appendChild(n):c.textContent=t.callToActionIconText??"↗"}else c.textContent=t.callToActionIconText??"↗"}let p=t.position&&ni[t.position]?ni[t.position]:ni["bottom-right"];r.className=o?"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}`,o||(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,o?(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&&o(e),{element:r,update:o,destroy:()=>{r.removeEventListener("click",t),r.remove()}}},ll=new Set,dl=e=>{let t=e?.persistState;return`${("object"==typeof t?t?.keyPrefix:void 0)??"persona-"}teaser-dismissed`},cl=(e,t)=>{let r=q("div","persona-launcher-surface");r.setAttribute("data-persona-launcher-surface","true");let o=e??{},n=null,a=null,s=null,i=null,l=null,d=!1,c=!1,p=!1,u=!1,h=()=>"once"===(n?.frequency??"once")&&!1!==o.persistState,m=()=>{null!==l&&(clearTimeout(l),l=null)},g=e=>{m(),p=!0,a&&d&&(d=!1,a.hidden=!0),((e,t)=>{if(ll.add(e),t)try{window.localStorage.setItem(e,"1")}catch{}})(dl(o),e&&h())},f=e=>{n&&!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=il(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=o.launcher?.position??"bottom-right",t=ni[e]??ni["bottom-right"];a?(r.className=_("persona-launcher-surface",t),r.setAttribute("data-teaser",e),r.style.zIndex=String(o.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&&!Xs(e??{})?t:null})(e);n=t,t?(a||(i=j("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),i.addEventListener("click",b),s=j("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"×"}),s.addEventListener("click",v),a=j("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"),n&&a&&(p||c||u||((e,t)=>{if(ll.has(e))return!0;if(!t)return!1;try{return"1"===window.localStorage.getItem(e)}catch{return!1}})(dl(o),h())||(m(),l=setTimeout(y,Math.max(0,n.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=>{o=e,w.update(e),S(e),C()},destroy:()=>{x(),w.destroy(),r.remove()}}},pl=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=(e=>{let t=e?.launcher?.enabled??!0,r=Xs(e);if(Qs(e)){let t=e?.launcher?.composerBar??{},r=q("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 o=q("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");o.style.width="100%",r.appendChild(o);let n=q("div","persona-widget-pill-root");return n.setAttribute("data-persona-composer-bar",""),n.dataset.state="collapsed",n.dataset.expandedSize=t.expandedSize??"anchored",n.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:r,panel:o,pillRoot:n}}if(r){let e=q("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),t=q("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=q("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),r=q("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),o=T(e),n=o.launcherWidth||o.legacyLauncherWidth||void 0!==e?.theme?.components?.panel?.width?tl(e).width:"100%";return t.style.width=n,r.style.width="100%",t.appendChild(r),{wrapper:t,panel:r}}let o=e?.launcher??{},n=o.position&&ni[o.position]?ni[o.position]:ni["bottom-right"],a=q("div",`persona-widget-wrapper persona-fixed ${n} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let s=q("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=tl(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(Qs(e))return((e,t)=>{let r=q("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:o,wrapper:n}=di(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:rl,iconSize:ol});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=null,s=null;if(e?.launcher?.clearChat?.enabled??1){let t=ci(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:rl,iconSize:nl});a=t.button,s=t.wrapper,s.style.position="absolute",s.style.top="8px",s.style.right="32px",s.style.zIndex="10"}let i=j("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=j("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});l.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:c}=sl(e,l),{host:p,title:u,subtitle:h}=d,m=d.starterSuggestions,g=q("div","persona-widget-messages persona-flex persona-flex-col");g.style.gap="var(--persona-components-message-gap, 12px)";let f=al("followUp"),y=Va(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=j("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),v=Ii({config:e}),{root:w,textNode:x}=Mi();return r.append(i,n,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:o,closeButtonWrapper:n,clearChatButton:a,clearChatButtonWrapper:s,iconHolder:q("span"),headerTitle:q("span"),headerSubtitle:q("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=j("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,n=!1!==e?.layout?.showHeader,a=o?ki(e,o,{showClose:t}):mi({config:e,showClose:t}),s=j("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});s.style.setProperty("scrollbar-gutter","stable");let{welcome:i,greetingHost:l}=sl(e,s),{host:d,title:c,subtitle:p}=i,u=i.starterSuggestions,h=q("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let m=al("followUp"),g=Va(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=Ai({config:e}),y=!1!==e?.layout?.showFooter;n||(a.header.style.display="none"),gi(r,a,e),r.append(s);let b=j("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return 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:o,pillRoot:n},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}}},ul=({config:e,plugins:t,onToggle:r})=>{let o=t.find(e=>e.renderLauncher);if(o?.renderLauncher){let t=o.renderLauncher({config:e,defaultRenderer:()=>il(e,r).element,onToggle:r});if(t)return{instance:null,element:t}}let n=cl(e,r);return{instance:n,element:n.element}},hl=(e,t,r)=>{let o=r;for(let r of t){let t=q("span","persona-tool-char");t.style.setProperty("--char-index",String(o)),t.textContent=" "===r?" ":r,e.appendChild(t),o++}return o},ml=(e,t,r)=>{me(e,t,{stateSet:r,previewKind:"reasoning",iconColor:"currentColor"})},gl=(e,t,r=new Set)=>{t=ge(t,"reasoning");let o=e.reasoning,n=le("persona-reasoning-bubble",e.id);if(!o)return be(n,e,t,"reasoning");let a=t?.features?.reasoningDisplay??{},s=a.expandable??R.expandable,i=s&&r.has(e.id),l="complete"!==o.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??R.previewMaxLines),c=de({expandable:s,expanded:i,bubbleType:"reasoning"}),p=q("div","persona-flex persona-flex-col persona-text-left"),u=q("span","persona-text-xs persona-text-persona-primary"),h="row"===fe(t,"reasoning"),m=h&&!l?`Thought for ${ye(o.durationMs??(void 0!==o.completedAt&&void 0!==o.startedAt?o.completedAt-o.startedAt:void 0))}`:"Thinking...",g=t?.reasoning??{},f=String(o.startedAt??Date.now()),y=()=>{let e=q("span","");return e.setAttribute("data-tool-elapsed",f),e.textContent=lr(o),e},b=g.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:m,previewText:d,isActive:l,config:t??{},elapsed:lr(o),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=q("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,o=(void 0===e.durationMs?Math.max(0,t-r):e.durationMs)/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`})(e):"pending"===e.status?"Waiting":"")(o),h||p.appendChild(v);let w=a.loadingAnimation??R.loadingAnimation,x=g.activeTextTemplate,C=g.completeTextTemplate,S=l?x:C,k=b instanceof HTMLElement,A=(e,t)=>{u.textContent="";let r=cr(e,""),n=0;for(let e of r){let r=e.styles.length>0?(()=>{let t=q("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?lr(o):e.text;t?n=hl(r,a,n):r.appendChild(document.createTextNode(a))}}};if(!k&&S)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`),A(S,!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)),A(S,!0))}else A(S,!1);else if(!k&&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="",hl(u,t,0)}"complete"===o.status&&!h&&(u.style.display="none")}else k||("complete"!==o.status||h?u.style.display="":u.style.display="none");if(a.iconName&&!k){let e=q("span","persona-reasoning-header-icon"),t=se(a.iconName,16,"currentColor",2);t&&(e.appendChild(t),c.appendChild(e))}let M="currentColor",I=pe(c,p,{expandable:s,expanded:i,iconColor:M,metaGap:!1}),T=ue({bubble:n,previewKind:"reasoning",expanded:i,isActive:l,previewText:d,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:d,isActive:l,config:t??{}})});if(!s)return n.append(c,T),be(n,e,t,"reasoning");let E=q("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");E.style.display=i?"":"none";let L=o.chunks.join(""),P=q("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return P.textContent=L||("complete"===o.status?"No additional context was shared.":"Waiting for details…"),E.appendChild(P),he({expanded:i,header:c,toggleIcon:I,content:E,collapsedPreview:T,iconColor:M}),n.append(c,T,E),be(n,e,t,"reasoning")},fl=e=>{if(null==e)return!0;if("string"==typeof e){if(!e.trim())return!0;try{return fl(JSON.parse(e))}catch{return!1}}return"object"==typeof e&&0===Object.keys(e).length},yl=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}},bl=new WeakMap;async function vl(e){let t=e.closest("[data-persona-tool-detail]"),r=t?.querySelector("pre");if(!r)return;let o=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(bl.get(e));try{await navigator.clipboard.writeText(r.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let t=se("check",14,"currentColor",2);t&&e.replaceChildren(t)}catch{e.setAttribute("aria-label","Copy failed — try again"),e.title="Copy failed — try again"}bl.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",o),e.title=o;let t=se("copy",14,"currentColor",1.7);t&&e.replaceChildren(t),bl.delete(e)},1800))}let wl=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),xl=(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)"},Cl=(e,t)=>{let r=e.toolCall,o=t?.features?.toolCallDisplay,n=o?.collapsedMode??B.collapsedMode,a=!1===r?.success?r.error||"Tool failed":((e,t)=>{let r=e.toolCall;if(!r)return"";let o=(r.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(-t).join("\n");let n=ar(r.args).trim();return n?n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join("\n"):""})(e,o?.previewMaxLines??B.previewMaxLines),s=r?.interrupted?`${r.name?.trim()||"Tool"} · Interrupted`:r?"row"===fe(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"===n?d=r.name?.trim()||s:"tool-preview"===n&&a&&(d=a),i&&l.activeTextTemplate?d=dr(r,l.activeTextTemplate,d):!i&&!r.interrupted&&l.completeTextTemplate&&(d=dr(r,l.completeTextTemplate,d)),r.interrupted?d.includes(" · Interrupted")||(d+=" · Interrupted"):!1===r.success?d+=" · Failed":r.superseded&&(d+=" · Approved, ran again below"),{summary:d,previewText:a,isActive:i}},Sl=(e,t,r,o)=>{me(e,t,{stateSet:r,previewKind:"tool",iconColor:wl(o?.toolCall??{},t.classList.contains("persona-activity-row"))})},kl=(e,t,r=new Set)=>{t=ge(t,"tool");let o=e.toolCall,n=t?.toolCall??{},a=le("persona-tool-bubble",e.id);if(n.backgroundColor&&(a.style.backgroundColor=n.backgroundColor),n.borderColor&&(a.style.borderColor=n.borderColor),n.borderWidth&&(a.style.borderWidth=n.borderWidth),n.borderRadius&&(a.style.borderRadius=n.borderRadius),a.style.boxShadow=void 0===n.shadow?"var(--persona-tool-bubble-shadow)":""===n.shadow.trim()?"none":n.shadow,!o)return be(a,e,t,"tool");let s=t?.features?.toolCallDisplay??{},i=s.expandable??B.expandable,l=i&&r.has(e.id),{summary:d,previewText:c,isActive:p}=Cl(e,t),u=de({expandable:i,expanded:l,bubbleType:"tool"});n.headerBackgroundColor&&(u.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(u.style.paddingLeft=n.headerPaddingX,u.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(u.style.paddingTop=n.headerPaddingY,u.style.paddingBottom=n.headerPaddingY);let h=q("div","persona-flex persona-flex-col persona-text-left"),m=q("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(m.style.color=n.headerTextColor);let g=String(o.startedAt??Date.now()),f=()=>{let e=q("span","");return p&&e.setAttribute("data-tool-elapsed",g),e.textContent=ir(o),e},y=n.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:d,previewText:c,collapsedMode:s.collapsedMode??B.collapsedMode,isActive:p,config:t??{},elapsed:ir(o),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??B.loadingAnimation,v=n.activeTextTemplate,w=o.interrupted?void 0:n.completeTextTemplate,x=p?v:w,C=(e,t)=>{m.textContent="";let r=o.name?.trim()||"tool",n=cr(e,r),a=0;for(let e of n){let r=e.styles.length>0?(()=>{let t=q("span",e.styles.map(e=>`persona-tool-text-${e}`).join(" "));return m.appendChild(t),t})():m;if(e.isDuration&&p)r.appendChild(f());else{let n=e.isDuration?ir(o):e.text;t?a=hl(r,n,a):r.appendChild(document.createTextNode(n))}}};if(!(y instanceof HTMLElement))if(p&&"none"!==b){let e=n.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`),x&&C(x,!1);else if(m.classList.add(`persona-tool-loading-${b}`),m.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===b&&(n.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),x)C(x,!0);else{let e=m.textContent||d;m.textContent="",hl(m,e,0)}}else x&&C(x,!1);let S=wl(n,"row"===fe(t,"tool")),k=pe(u,h,{expandable:i,expanded:l,iconColor:S,metaGap:!0}),A=ue({bubble:a,previewKind:"tool",expanded:l,isActive:p,previewText:c,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>n.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:c,isActive:p,config:t??{}})});if(!i)return a.append(u,A),be(a,e,t,"tool");let M=q("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(M.style.display=l?"":"none",n.contentBackgroundColor&&(M.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(M.style.color=n.contentTextColor),n.contentPaddingX&&(M.style.paddingLeft=n.contentPaddingX,M.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(M.style.paddingTop=n.contentPaddingY,M.style.paddingBottom=n.contentPaddingY),!0===t.future?.v5Defaults)!function(e,t,r){let o=t.toolCall;if(!o)return;let n=r.toolCall??{},a=(t,r)=>{let o=j("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":t.toLowerCase()},style:{backgroundColor:n.codeBlockBackgroundColor,borderColor:n.codeBlockBorderColor,borderWidth:n.codeBlockBorderColor?"1px":void 0}}),a=j("div",{className:"persona-tool-detail-label",text:t,style:{color:n.labelTextColor}}),s=ar(r),i=j("pre",{className:"persona-tool-detail-value"+(yl(r)?" persona-tool-detail-code":""),text:s,attrs:s.length>420||s.split("\n").length>7?{tabindex:"0","aria-label":`${t} content`}:{},style:{color:n.codeBlockTextColor??n.contentTextColor}}),l=j("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${t.toLowerCase()}`,title:`Copy ${t.toLowerCase()}`}}),d=se("copy",14,"currentColor",1.7);d&&l.appendChild(d),o.append(a,i,l),e.appendChild(o)};fl(o.args)||a("Request",o.args);let s="complete"===o.status&&void 0!==o.result?o.result:o.chunks?.join("");void 0!==s&&("string"!=typeof s||s.trim())&&a("Response",s),!1===o.success&&e.appendChild(j("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}(M,e,t);else{if(o.name){let e=q("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?e.style.color=n.contentTextColor:n.headerTextColor&&(e.style.color=n.headerTextColor),e.textContent=o.name,M.appendChild(e)}if(void 0!==o.args){let e=q("div","persona-space-y-1"),t=q("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(t.style.color=n.labelTextColor),t.textContent="Arguments";let r=q("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",xl(r,n),r.textContent=ar(o.args),e.append(t,r),M.appendChild(e)}if(o.chunks&&o.chunks.length){let e=q("div","persona-space-y-1"),t=q("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(t.style.color=n.labelTextColor),t.textContent="Activity";let r=q("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",xl(r,n),r.textContent=o.chunks.join(""),e.append(t,r),M.appendChild(e)}if(!1===o.success&&M.appendChild(j("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),"complete"===o.status&&void 0!==o.result){let e=q("div","persona-space-y-1"),t=q("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(t.style.color=n.labelTextColor),t.textContent="Result";let r=q("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",xl(r,n),r.textContent=ar(o.result),e.append(t,r),M.appendChild(e)}if("complete"===o.status&&"number"==typeof o.duration){let e=q("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(e.style.color=n.contentTextColor),e.textContent=`Duration: ${o.duration}ms`,M.appendChild(e)}}return he({expanded:l,header:u,toggleIcon:k,content:M,collapsedPreview:A,iconColor:S}),a.append(u,A,M),be(a,e,t,"tool")},{setLoader:Al,load:Ml,provide:Il,getSync:Tl}=U({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),El=Al,Ll=Ml,Pl=Tl,{setLoader:Bl,load:Rl}=U({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),Nl=Bl,$l=Rl,Hl=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)})}},Wl=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:Dl,load:Fl,provide:Ol,getSync:zl}=U({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),ql=null,jl=new Set,_l=e=>{if(ql)return ql;ql=e,e.initArtifactsUi({componentRegistry:Hl});for(let t of Wl)Hl.has(t)||Hl.register(t,"PersonaArtifactCard"===t?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Pe();t?e.__provideMarkdownParsers(t):Le(()=>{let t=Pe();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>J());let r=[...jl];jl.clear();for(let e of r)try{e()}catch{}return e},Ul=Dl,Vl=()=>Fl().then(_l),Kl=()=>{if(ql)return ql;let e=zl();return e?_l(e):null},Gl=e=>ql?()=>{}:(jl.add(e),()=>{jl.delete(e)});function Jl(e){return!0===e?.features?.artifacts?.enabled}function Xl(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"),!Jl(t))return;let r=t.features?.artifacts?.layout,o=r?.paneBorder?.trim(),n=r?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):n&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",n))}let Ql=["panel","seamless","detached"];function Yl(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Ql.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Zl(e){return!(!e||!Jl(e))&&"detached"===Yl(e)}function ed(e,t){if(!Jl(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 Xl(e,t);let r=t.features?.artifacts?.layout,o="detached"===Yl(t)?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",r?.splitGap??o),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 n=r?.paneBackground?.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):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 o=t?.trim();o?e.style.setProperty(r,o):e.style.removeProperty(r)}Xl(e,t)}function td(e,t){for(let t of Ql)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"),!Jl(t))return;let r=t.features?.artifacts?.layout,o=Yl(t);e.classList.add(`persona-artifact-appearance-${o}`);let n=r?.paneBorderRadius?.trim();n&&e.style.setProperty("--persona-artifact-pane-radius",n);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 rd=new Set(["__proto__","prototype","constructor"]),od=new Set(["collapsed","card","panel","inline"]),nd=new Set(["markdown","component"]),ad=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,sd=e=>"object"==typeof e&&!!e&&!Array.isArray(e),id=e=>!rd.has(e),ld=e=>"string"==typeof e&&od.has(e),dd=e=>Object.keys(e).length>0;function cd(e,t,r,o){e.push({path:t,code:r,message:o})}let pd="Ignored an unsupported value.",ud={kind:"mode",message:pd},hd={kind:"string",message:"Expected a CSS length string."},md={kind:"boolean"},gd={kind:"object",message:"Expected a preference object.",children:{showToolCalls:md,showReasoning:md,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:pd},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:pd},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:pd},expandable:md,grouped:md}},reasoningDisplay:{kind:"object",children:{expandable:md,activePreview:md}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:ud,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:ud,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:nd,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:nd}}},filePreview:{kind:"object",children:{enabled:md}},layout:{kind:"object",children:{paneWidth:hd,paneMaxWidth:hd,paneMinWidth:hd,expandedPanelWidth:hd,resizableMinWidth:hd,resizableMaxWidth:hd,expandLauncherPanelWhenOpen:md,resizable:md}}}}}};function fd(e,t,r,o){if(void 0!==e)switch(t.kind){case"boolean":return"boolean"==typeof e?e:cd(o,r,"invalid_type","Expected a boolean.");case"string":return"string"==typeof e?e:cd(o,r,"invalid_type",t.message);case"enum":return"string"==typeof e&&t.values.has(e)?e:cd(o,r,"invalid_value",t.message);case"mode":return ld(e)?to(e):cd(o,r,"invalid_value",t.message);case"modeMap":{if(!sd(e))return cd(o,r,"invalid_type","Expected an object.");let n="mediaType"===t.keys?void 0:t.keys,a={};for(let[t,s]of Object.entries(e)){let e=n?t:ro(t);id(t)&&(n?n.has(t):ad.test(e))?ld(s)?a[e]=to(s):cd(o,`${r}.${t}`,"invalid_value","Expected collapsed, panel, or inline."):cd(o,`${r}.${t}`,n?"unknown_key":"invalid_value",n?"Ignored an unsupported selector.":'Expected a MIME type such as "text/html" or a wildcard such as "image/*".')}return dd(a)?a:void 0}case"object":{if(t.bareMode&&ld(e))return to(e);if(!sd(e))return cd(o,r,"invalid_type",t.message??"Expected an object.");let n=Object.keys(t.children),a=e=>r?`${r}.${e}`:e;for(let t of Object.keys(e))(!id(t)||!n.includes(t))&&cd(o,a(t),"unknown_key","Ignored because this key is not part of the persisted preference schema.");let s={};for(let r of n){let n=t.children[r],i=fd(e[r],n,a(r),o);if(n.deprecated&&void 0!==e[r]&&cd(o,a(r),"deprecated_key",n.deprecated),void 0===i)continue;let l=n.alias??r,d=s[l];s[l]=sd(d)&&sd(i)?{...d,...i}:i}return dd(s)?s:void 0}}}function yd(e){let t=[];return{preferences:(null===e?void 0:fd(e,gd,"",t))??{},issues:t}}function bd(e){if(Array.isArray(e))return e.map(bd);if(!sd(e))return e;let t={};for(let[r,o]of Object.entries(e))id(r)&&void 0!==o&&(t[r]=bd(o));return t}function vd(e,t){let r=bd(e);for(let[e,o]of Object.entries(t)){if(!id(e)||void 0===o)continue;let t=r[e];r[e]=sd(t)&&sd(o)?vd(t,o):bd(o)}return r}function wd(e,t){if(void 0===t)return void 0===e?void 0:bd(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},o=t.default??r.default,n={...r.byType,...r.byKind,...t.byType,...t.byKind},a=function(e,t){if(void 0===t)return void 0===e?void 0:bd(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},o=t.default??r.default,n={...r.byMediaType,...t.byMediaType},a={...o?{default:o}:{},...dd(n)?{byMediaType:n}:{}};return dd(a)?a:void 0}(r.files,t.files),s={...o?{default:o}:{},...dd(n)?{byKind:n}:{},...void 0===a?{}:{files:a}};return dd(s)?s:void 0}function xd(e={},t){let r=function(e){let t,r={};for(let o of e){let e=yd(o).preferences;t=wd(t,e.artifacts?.display),r=vd(r,e)}let o=r;return o.artifacts&&(void 0===t?delete o.artifacts.display:o.artifacts.display=t),o}(t),o={...e};if(void 0!==r.showToolCalls&&(o.showToolCalls=r.showToolCalls),void 0!==r.showReasoning&&(o.showReasoning=r.showReasoning),r.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...r.toolCallDisplay}),r.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...r.reasoningDisplay}),r.artifacts){let t=e.artifacts??{},n={...t};if(void 0!==r.artifacts.display){let e=wd(t.display,r.artifacts.display);void 0!==e&&(n.display=e)}r.artifacts.filePreview&&(n.filePreview={...t.filePreview,enabled:r.artifacts.filePreview.enabled}),r.artifacts.layout&&(n.layout={...t.layout,...r.artifacts.layout}),o.artifacts=n}return o}function Cd(e){let t=e.preferences;return t&&dd(t)?{...e,features:xd(e.features??{},[t])}:e}function Sd(e,t){let r=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let n=/^([\d.]+)/.exec(r);return n?Number(n[1]):8}let{setLoader:kd,load:Ad,provide:Md,getSync:Id}=U({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),Td=kd,Ed=Ad,Ld=Id,Pd=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()}},Bd=e=>"object"==typeof e&&!!e&&!Array.isArray(e),Rd=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),Nd=(e,t,r)=>{if(!Bd(e)||!Bd(t)||Rd.has(r))return t;let o={...e};for(let n of Object.keys(t)){if(void 0===t[n]){delete o[n];continue}let a=r?`${r}.${n}`:n;o[n]=Nd(e[n],t[n],a)}return o};function $d(e,t){let r=w(H),o=function(e,t,r){let o=t[b];if(o)return o;let n=new Set(C(e,r));for(let e of r){let r=x(t,e);"clear"===r&&n.delete(e),"explicit"===r&&n.add(e)}return[...n]}(e,t,r),n=S(function(e,t,r){let o={...e};for(let e of t){if(r.includes(e))continue;let t=e.split("."),n=o;for(let e of t.slice(0,-1)){let t=n[e];if(!v(t)){n=void 0;break}n[e]={...t},n=n[e]}n&&delete n[t[t.length-1]]}return o}(Nd(e,t,""),r,o),o);return E(z(n),((e,t)=>{let r=t[A];if(r)return{...r};let o=T(e);return M(t,"launcherWidth")&&(o.legacyLauncherWidth=void 0!==t.launcherWidth),M(t,"launcher")&&void 0===t.launcher?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(M(t.launcher,"width")&&(o.launcherWidth=void 0!==t.launcher?.width),M(t.launcher,"sidebarWidth")&&(o.sidebarWidth=void 0!==t.launcher?.sidebarWidth),M(t.launcher,"dock")&&void 0===t.launcher?.dock?o.dockWidth=!1:M(t.launcher?.dock,"width")&&(o.dockWidth=void 0!==t.launcher?.dock?.width),o)})(e,t))}let Hd=({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 o=0;for(let e=r;e<t.length;e+=1){let n=t[e];if("{"===n&&(o+=1),"}"===n&&(--o,0===o))return t.slice(r,e+1)}return null})(t);if(!r)return null;let o=JSON.parse(r);if(!o||"object"!=typeof o||!o.action)return null;let{action:n,...a}=o;return{type:String(n),payload:a,raw:o}}catch{return null}},Wd=e=>"string"==typeof e?e:null==e?"":String(e),Dd={message:e=>{if("message"===e.type)return{handled:!0,displayText:Wd(e.payload.text)}},messageAndClick:(e,t)=>{if("message_and_click"!==e.type)return;let r=e.payload,o=Wd(r.element);if(o&&t.document?.querySelector){let e=t.document.querySelector(o);e?setTimeout(()=>{e.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Wd(r.text)}}},Fd=e=>Array.isArray(e)?e.map(e=>String(e)):[],Od=e=>{let t=new Set(Fd(e.getSessionMetadata().processedActionMessageIds));return{process:r=>{if(r.streaming||"assistant"!==r.message.role||!r.text||t.has(r.message.id))return null;let o="string"==typeof r.raw&&r.raw||"string"==typeof r.message.rawContent&&r.message.rawContent||"string"==typeof r.text&&r.text||null;!o&&"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 n=o?e.parsers.reduce((e,t)=>e||t?.({text:o,message:r.message})||null,null):null;if(!n)return null;t.add(r.message.id),(()=>{let r=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:r}))})();let a={action:n,message:r.message};e.emit("action:detected",a);for(let t of e.handlers)if(t)try{let o=t(n,{message:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{e.emit("action:resubmit",a)}});if(!o)continue;if(o.handled){let e=!1!==o.persistMessage;return{text:void 0===o.displayText?"":o.displayText,persist:e,resubmit:o.resubmit}}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",e)}return{text:"",persist:!0}},syncFromMetadata:()=>{t=new Set(Fd(e.getSessionMetadata().processedActionMessageIds))}}},zd=e=>e.map(e=>({...e,streaming:!1})),qd=e=>e.map(e=>({...e,status:"complete"})),jd=e=>`${e??"persona-"}state`,_d=(e=jd())=>{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 o=t();if(o)try{let t={...r,messages:r.messages?zd(r.messages):void 0,artifacts:r.artifacts?qd(r.artifacts):void 0};o.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)}}}},Ud=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)},Vd=(e,t,r)=>{let o="",n="",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(o)}catch{return s=!0,d}},m=(e,t)=>{if(i||e===d)return;let r=d;d=e,l+=1;let o={previousToken:r,token:e,source:t,revision:l};for(let e of p)e(o)},g=e=>{i||(null===e.key||e.key===o)&&m(null===e.key?null:e.newValue??null,"external")},f=(async()=>{let s=await(async(e,t)=>{let r=await Ud(e);return{storageKey:`${t}visitor:${r}`,leaseKey:`${t}visitor-init-lock:${r}`,lockName:`persona-visitor-init:${await Ud(`${e}\0${t}`)}`}})(e,t);o=s.storageKey,n=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(n);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(n)}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(o,e);function o(){clearTimeout(r),w.delete(o),window.removeEventListener("storage",a),t()}function a(e){(null===e.key||e.key===n)&&o()}w.add(o),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(o,e)}catch{s=!0}m(e,"local")},async clear(){await f;let e=u();if(e)try{e.removeItem(o)}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 o=Date.now(),a=b();if(a&&a.expiresAt>o&&a.ownerNonce!==t)await C(Math.min(a.expiresAt-o,500));else{try{r.setItem(n,JSON.stringify({ownerNonce:t,expiresAt:o+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:(o,n,a)=>o===e&&n===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:Kd,load:Gd}=U({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),Jd=Kd,Xd=Gd,{setLoader:Qd,load:Yd,provide:Zd,getSync:ec}=U({fallbackImport:()=>import("./history-shell")}),tc=Qd,rc=Yd,oc=ec;function nc(){return null}function ac(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.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,vt.parse)(r,vt.STR|vt.OBJ),r);t&&(e=t)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function sc(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=Hl.get(e.component);if(!a){if(Wl.includes(e.component)){Vl().catch(()=>{});let e=q("div","persona-w-full");return e.setAttribute("data-persona-artifact-pending","true"),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let s={message:o,config:r,updateProps:e=>{n&&n(e)}};try{return a(e.props,s)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function ic(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 lc(e){let t=ic(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 dc(e){let t=ic(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 cc=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function pc(e){let{onSubmit:t,onDismiss:r,title:o="How satisfied are you?",subtitle:n="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:l=!0,ratingLabels:d=cc}=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=o,h.appendChild(m);let g=document.createElement("p");g.className="persona-feedback-subtitle",g.textContent=n,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 o=r<e;t.classList.toggle("selected",o),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 uc(e){let{onSubmit:t,onDismiss:r,title:o="How likely are you to recommend us?",subtitle:n="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=o,m.appendChild(g);let f=document.createElement("p");f.className="persona-feedback-subtitle",f.textContent=n,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 hc="persona-chat-history",mc="data-persona-composer-reason",gc="data-persona-composer-notice",fc={"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 yc(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 o=fc[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${o}`,{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 bc(e){if(!e)return!1;let t=e.types;return!!t&&("function"==typeof t.contains?t.contains("Files"):Array.from(t).includes("Files"))}let vc=e=>e&&"object"==typeof e?{...e}:{},wc=e=>e.filter(e=>!Lr(e)).map(e=>({...e,streaming:!1})),xc=(e,t,r)=>{let o=e?.markdown?Re(e.markdown):null,n=je(e?.sanitize);e?.postprocessMessage&&n&&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!==Pe();if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:s,raw:i??a.text??""});l=n?n(t):t}else if(o){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 o=t[e],n=t[e+1];if(!Ue(o)||_e.test(o)||!_e.test(n))continue;let a=Ve(o).length;if(a<1)continue;let s=Ge(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()||!Ue(e))break;let o=Ke(Je(Ve(e),a));t[i]!==o&&(t[i]=o,r=!0)}e=i-1}return r?t.join("\n"):e})(s):s,t=o(e);l=n&&d?n(t):t}else l=He(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)),He(e.text??"")}}};function Cc(e){let t=q("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=se(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=q("span","persona-drop-overlay-label");r.textContent=e.label,t.appendChild(r)}return t}let Sc=(e,t)=>{let r={...e};for(let[e,o]of Object.entries(t)){let t=r[e];r[e]=t?{...t,...o}:o}return r},kc=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:Sc(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),Ac=(e,t,r)=>{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 o=z(t),n=new Set,s=new Set,i=function(e){let t=new Set,r=new Set,o=new Set,n=new Map,a=e=>{clearTimeout(n.get(e)),n.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&&!o.has(a.id))){if(o.add(a.id),!1===l.autoCollapseDelay)return;n.set(a.id,setTimeout(()=>{n.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 n of new Set([...t,...r,...o]))e.has(n)||(a(n),t.delete(n),r.delete(n),o.delete(n))},clear(){for(let e of n.keys())a(e);t.clear(),r.clear(),o.clear()}}}((e,t)=>{Ha.delete(e);let r=Array.from(dt.querySelectorAll("[data-message-id]")).find(t=>t.dataset.messageId===e);r&&("tool"===t?Sl(e,r,n,o):ml(e,r,s))}),l=new Map,d=()=>{Uo({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};d();let c=o.features;o=Cd(o);let p=Pd.getForInstance(o.plugins),h=os(e),f=[],b=!1,v=(e=>{let t=new Map,r=!1,o=()=>{if(r||!1===e()?.persistState)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return r=!0,null}};return n=>{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(),n,t);return{get:e=>{let n=a(e),s=o();if(s)try{return s.getItem(n)}catch{r=!0}return t.get(n)??null},set:(e,n)=>{let s=a(e),i=o();if(i)try{return void i.setItem(s,n)}catch{r=!0}t.set(s,n)},remove:e=>{let n=a(e);t.delete(n);let s=o();if(s)try{s.removeItem(n)}catch{r=!0}}}}})(()=>o),w=null,x=null,C=null,S=!1,k=null,A=e=>{w=e,e.initApprovalUi({webMcpToolTitle:a});let t=e.createBuiltInApprovalPlugin(l);x=t.plugin,C=t.teardown},M=()=>{if(w)return w;let e=Pl();return e?(A(e),e):(Ll().then(e=>{S||w||(A(e),k?.())}).catch(()=>{}),null)},I=!1,E=!1,L=null,P=(e,t,r,o)=>{if(!e.querySelector("[data-tv-form]"))return;let n=Ld();n?n.enhanceWithForms(e,t,r,o):Ed().then(()=>{I||E||!L||(E=!0,L())}).catch(()=>{})};o.components&&Hl.registerAll(o.components);let B,R,N=(()=>{let e=new Map,t=(t,r)=>{e.get(t)?.delete(r)};return{on:(r,o)=>(e.has(r)||e.set(r,new Set),e.get(r).add(o),()=>t(r,o)),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)}})}}})(),$=!1===o.persistState?null:o.storageAdapter??_d(jd("object"==typeof o.persistState?o.persistState.keyPrefix:void 0)),H=!!o.clientToken&&"function"!=typeof o.reconnectStream,W={},D=null,F=new Promise(e=>{B=e}),O=()=>{},j=new Promise(e=>{O=e}),_=!1,U=e=>{if(o.onStateLoaded)try{let t=o.onStateLoaded(e);if(t&&"object"==typeof t&&"state"in t){let{state:e,open:r}=t;return r&&(_=!0),e}return t}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}return e};if($?.load)try{let e=$.load();if(e&&"function"==typeof e.then)D=e.then(e=>U(e??{messages:[],metadata:{}}));else{let t=U(e??{messages:[],metadata:{}});t.metadata&&(W=vc(t.metadata)),t.messages?.length&&(o={...o,initialMessages:t.messages}),t.artifacts?.length&&(o={...o,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),R=t.draft}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",e)}else if(o.onStateLoaded)try{let e=U({messages:[],metadata:{}});e.messages?.length&&(o={...o,initialMessages:e.messages})}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}D||B();let V=()=>W,K=e=>{W=e({...W})??{},ai()},G=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Hd],J=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Dd.message,Dd.messageAndClick],X=Od({parsers:G,handlers:J,getSessionMetadata:V,updateSessionMetadata:K,emit:N.emit,documentRef:typeof document<"u"?document:null});X.syncFromMetadata();let Q=o.launcher?.enabled??!0,Y=o.launcher?.autoExpand??!1,Z=o.autoFocusInput??!1,ee=Y,te=Q,re=o.layout?.header?.layout,ne=!1,ae=()=>Qs(o),ie=()=>Q||ae(),le=!ae()&&(!Q||Y),de=!1,ce=null,pe=()=>{de=!0,ce&&clearTimeout(ce),ce=setTimeout(()=>{de&&=(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),!1)},1e4)},ue=xc(o,X,pe),he=o.features?.showReasoning??!0,me=o.features?.showToolCalls??!0,ge=o.features?.showEventStreamToggle??!1,be=o.features?.scrollToBottom??{},Se=o.features?.scrollBehavior??{},ke=()=>("object"==typeof o.persistState?o.persistState?.keyPrefix:void 0)??"persona-",Ae=`${ke()}event-stream`,Me=null,Ie=o.features?.eventStream?.maxEvents??2e3,Te=null,Be=null,Re=null,Ne=!1,$e=null,We=!1,De=null,Fe=0,Oe=(e,t)=>{Te?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},ze=(e,t)=>{Be?.processEvent(e,t),Te?Oe(e,t):Re&&(Re.length>=Ie&&Re.shift(),Re.push({type:e,payload:t}))},qe=()=>{!Te&&ge&&(Re??=[],$l().then(e=>{if(Ne||Te||!ge)return;Me=new e.EventStreamStore(Ae),Te=new e.EventStreamBuffer(Ie,Me),Be??=new e.ThroughputTracker,Me.open().then(()=>Te?.restore()).catch(e=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",e)});let t=Re??[];Re=null;for(let e of t)Be?.processEvent(e.type,e.payload),Oe(e.type,e.payload)}).catch(()=>{}))};ge&&qe();let je=!1,_e=null,Ue=()=>{},Ve=()=>{},Ke=()=>{},Ge=()=>{},Je=()=>{},Xe=e=>{N.emit("message:copy",e),wa?.isClientTokenMode()&&wa.submitMessageFeedback(e.id,"copy").catch(e=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",e)}),o.messageActions?.onCopy?.(e)},Qe=e=>{N.emit("message:feedback",e),wa?.isClientTokenMode()&&wa.submitMessageFeedback(e.messageId,e.type).catch(e=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",e)}),o.messageActions?.onFeedback?.(e)};o.statusIndicator;let Ye=(e,t=o.statusIndicator??{})=>"idle"===e?t.idleText??Pr.idle:"connecting"===e?t.connectingText??Pr.connecting:"connected"===e?t.connectedText??Pr.connected:"error"===e?t.errorText??Pr.error:"paused"===e?t.pausedText??Pr.paused:"resuming"===e?t.resumingText??Pr.resuming:Pr[e];function et(e,t,r,o){if(!ae()&&("transient"===r.mode||e.classList.contains("persona-mb-2"))&&(xe(e,gt,r),we(e,r,o)),!e.hasAttribute(mc)&&!e.hasAttribute(gc))if("idle"===o&&r.idleLink){e.textContent="";let o=document.createElement("a");o.href=r.idleLink,o.target="_blank",o.rel="noopener noreferrer",o.textContent=t,o.style.color="inherit",o.style.textDecoration="none",e.appendChild(o)}else e.textContent=t}let tt=pl({config:o,showClose:ie()}),{wrapper:rt,panel:ot,pillRoot:nt}=tt.shell,st=tt.panelElements,{container:it,body:lt,messagesWrapper:dt,starterSuggestions:ct,transcriptSuggestions:pt,suggestions:ut,textarea:ht,sendButton:mt,composerForm:gt,statusText:ft,welcomeHost:yt,welcomeIconHolder:bt,greetingHost:vt,introKicker:wt,introTitle:xt,introSubtitle:Ct,closeButton:St,iconHolder:kt,headerTitle:At,headerSubtitle:Mt,header:It,footer:Tt,actionsRow:Lt}=st,Bt=st.leftActions,Rt=st.rightActions,Nt=st.sendButtonWrapper,$t=st.setSendButtonMode,Ht=st.micButton,Wt=st.micButtonWrapper,Dt=st.attachmentButton,Ft=st.attachmentButtonWrapper,Ot=st.attachmentInput,zt=st.attachmentPreviewsContainer;it.classList.add("persona-relative"),lt.classList.add("persona-relative");let _t=()=>be.label??"",Ut=()=>Se.mode??"anchor-top",Vt=()=>"follow"===Ut()||"anchor-top"===Ut()&&fs,Gt=()=>Se.anchorTopOffset??16,Xt=()=>!0===Se.pauseOnInteraction,Yt=()=>!1!==Se.showActivityWhilePinned,Zt=()=>!0===Se.announce,er=()=>Se.scrollbar??"on-scroll",tr=q("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");tr.type="button",tr.style.display="none",tr.setAttribute("data-persona-scroll-to-bottom","true");let rr=q("span","persona-flex persona-items-center"),or=q("span",""),nr=q("span","");nr.setAttribute("data-persona-scroll-to-bottom-count",""),nr.style.display="none",tr.append(rr,or,nr),it.appendChild(tr);let ar=q("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",lt.appendChild(ar);let ir=q("div","persona-sr-only");ir.setAttribute("aria-live","polite"),ir.setAttribute("aria-atomic","true"),ir.setAttribute("role","status"),ir.setAttribute("data-persona-live-region",""),Object.assign(ir.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"}),it.appendChild(ir);let lr=null,dr=null,cr=e=>{Zt()&&e&&(dr=e,null===lr&&(lr=setTimeout(()=>{lr=null,dr&&Zt()&&(ir.textContent=dr),dr=null},400)))},pr=()=>{let t=e.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(Q||Xs(o))||!0===o.launcher?.fullHeight&&!o.launcher.sidebarMode&&!Xs(o)},ur=()=>Yi(o,pr()),hr="empty",mr=0,gr=()=>mr||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,fr=()=>{let e="none"===Tt.style.display?0:Tt.offsetHeight;tr.style.bottom=`${e+gr()+12}px`};fr();let yr=()=>{oo||(Tt.style.marginBottom=mr>0?`${mr}px`:"")},br=()=>{let t=Ka(o,ae()),r=ur();e.setAttribute("data-persona-welcome-fullscreen",String(pr())),e.setAttribute("data-persona-welcome-layout",r.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom");let n="none"===Tt.style.display?0:Tt.offsetHeight,a="center"===r.anchor&&"empty"===hr?Ga(r.anchorComposerTop)??Ga("44%"):null,s=null!==a&&"centered"===r.layout&&void 0===o.welcome?.anchor&&void 0===o.welcome?.anchorComposerTop,i=s?getComputedStyle(lt):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=s?lt.getBoundingClientRect().top-it.getBoundingClientRect().top:0,u=!s||yt.hidden?0:(yt.querySelector("[data-persona-welcome-plugin]")??yt).offsetHeight,h=null===a||ae()?0:s?Math.max(0,Math.round((it.clientHeight-p-u-c-n)/2)):(e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight))({columnHeight:it.clientHeight,footerHeight:n,fraction:a});e.style.setProperty("--persona-composer-overlay-height",`${n}px`),e.style.setProperty("--persona-composer-lift",`${"overlay"===t?h:0}px`),mr="block"===t?h:0,yr(),fr()},vr=()=>{let e=!!_t();tr.setAttribute("aria-label",_t()||"Jump to latest"),tr.title=_t(),tr.setAttribute("data-persona-scroll-to-bottom-has-label",e?"true":"false"),rr.innerHTML="";let t=se(be.iconName??"arrow-down","14px","currentColor",2);t?(rr.appendChild(t),rr.style.display=""):rr.style.display="none",or.textContent=_t(),or.style.display=e?"":"none"};vr();let wr=null,xr=null,Cr=Wo();Cr.subscribe(e=>{try{it.dispatchEvent(new CustomEvent("persona:composer:state",{detail:e,bubbles:!0,composed:!0}))}catch{}});let kr=()=>{Cr.setText(ht?.value??"")},Mr=()=>{Cr.setMentionRefs(xr?.getMentionRefs()??[])},Ir=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}),Tr=e=>{let t=Object.freeze(e.map(Ir));Cr.setAttachments(t);try{o.attachments?.onChange?.(t)}catch(e){console.error("[AgentWidget] attachments.onChange failed:",e)}Ol()};Cr.setSelectedModelId(o.composer?.selectedModelId);let Er=()=>o.composer?.modes??[],Lr=()=>function(e,t){return e?.length?e.filter(e=>!jn(e.groupId,t)&&!function(e,t){return!!e&&"hidden"===t?.find(t=>t.id===e)?.chipVisibility}(e.groupId,t)):[]}(Er(),o.composer?.modeGroups);{let e=_n(o.composer?.defaultActiveModeIds??[],Er());e.length&&Cr.setActiveModeIds(e)}function Rr(e){if(Cr.getState().selectedModelId!==e){Cr.setSelectedModelId(e),Hr?.repaint();try{o.composer?.onModelChange?.(e)}catch(e){console.error("[AgentWidget] composer.onModelChange failed:",e)}}}function Nr(e){Cr.setActiveModeIds(e),Dr?.render(e,Lr()),Or.forEach(e=>e.repaint()),yo?.resolve(),vd(),Io()}function $r(e){Nr(function(e,t,r,o){let n=r.find(e=>e.id===t);if(!n)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)(n,o)){let e=r.filter(e=>e.groupId===n.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,Er(),o.composer?.modeGroups))}let Hr=null,Wr=null,Dr=null,Or=new Map,zr=null;function qr(e){Cr.setQuote(e),zr?.render(Cr.getState().quote),Io(),ui()}let jr=!1;function _r(){let e=o.composer?.streamingSubmitBehavior??"block";return"interrupt"===e?o.clientToken?"interrupt":(!jr&&!0===o.debug&&(jr=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block"):e}let Kr=null;function Gr(e){Cr.setPendingSubmission(e),Kr?.render(Cr.getState().pendingSubmission),Io()}let Jr=()=>{let e=[],t=Cr.getState().activeModeIds,r=new Set;if(Er().forEach((n,a)=>{if(jn(n.groupId,o.composer?.modeGroups)){let t=n.groupId;if(r.has(t))return;r.add(t);let s=(e=>{let t=Or.get(e);if(t)return t;let r=Un({groupId:e,getGroup:()=>o.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>Er().filter(t=>t.groupId===e),getActiveIds:()=>Cr.getState().activeModeIds,onSelect:e=>$r(e)});return Or.set(e,r),r})(t);s.action.order=zn(a),s.action.label=o.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(s.action)}else e.push({id:On(n.id),kind:"button",placement:"start",order:zn(a),presentation:n.presentation??"auto",label:n.label,shortLabel:n.shortLabel,iconName:n.iconName,pressed:t.includes(n.id),onSelect:()=>$r(n.id)})}),o.composer?.models?.length&&!p.some(e=>e.renderComposer)){let t=o.composer?.modelPicker?.presentation??"native";(!Hr||Wr!==t)&&(Wr=t,Hr=$n({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Cr.getState().selectedModelId,onSelect:e=>Rr(e),presentation:t,getSuffix:()=>o.composer?.modelPicker?.suffix})),e.push(Hr.action)}return e},Xr=null,Qr=p.find(e=>e.renderHeader);if(Qr?.renderHeader){let e=Qr.renderHeader({config:o,defaultRenderer:()=>{let e=mi({config:o,showClose:ie()});return gi(it,e,o),e.header},onClose:()=>Rl(!1,"user")});e&&It&&(It.replaceWith(e),It=e,tt.header.element=e)}let Yr=()=>{$e&&(lt.style.display="none",Tt.parentNode?.insertBefore($e.element,Tt),$e.update())},Zr=()=>{if(!Te)return void qe();if(We=!0,$e?Yr():$l().then(e=>{!$e&&We&&Te&&($e=e.createEventStreamView({buffer:Te,getFullHistory:()=>Te.getAllFromStore(),onClose:()=>eo(),config:o,plugins:p,getThroughput:()=>Be?.getMetric()??{status:"idle"},renderIconByName:se}),Yr())}).catch(()=>{eo()}),to){to.style.boxShadow=`inset 0 0 0 1.5px ${pi.actionIconColor}`;let e=o.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&to.classList.add(e))}let e=()=>{if(!We)return;let t=Date.now();t-Fe>=200&&($e?.update(),Fe=t),De=requestAnimationFrame(e)};Fe=0,De=requestAnimationFrame(e),Ei(),N.emit("eventStream:opened",{timestamp:Date.now()})},eo=()=>{if(We){if(We=!1,$e&&$e.element.remove(),lt.style.display="",to){to.style.boxShadow="";let e=o.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&to.classList.remove(e))}null!==De&&(cancelAnimationFrame(De),De=null),Ei(),N.emit("eventStream:closed",{timestamp:Date.now()})}},to=null;if(ge){let e=o.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:"");to=q("button",t),to.style.width="28px",to.style.height="28px",to.style.color=pi.actionIconColor,to.type="button",to.setAttribute("aria-label","Event Stream"),to.title="Event Stream";let r=g(m.Activity,"18px","currentColor",1.5);r&&to.appendChild(r);let n=st.clearChatButtonWrapper,a=st.closeButtonWrapper,s=n||a;s&&s.parentNode===It?It.insertBefore(to,s):It.appendChild(to),to.addEventListener("click",()=>{We?eo():Zr()})}let ro=e=>{let t=o.attachments;if(!t?.enabled)return;let r=e.querySelector("[data-persona-composer-attachment-previews]")??e.querySelector(".persona-attachment-previews");if(!r){r=q("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=q("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Ar).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label",t.buttonTooltipText??"Attach files"),e.appendChild(r)}},oo=!1,ao=e=>{let t=p.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let r=o.composer,n=!!b&&wa.isStreaming();return t.renderComposer({config:o,defaultRenderer:e,requestRender:()=>cu(),storage:v(t.id),onSubmit:e=>{wa&&!wa.isStreaming()&&Zc(e.trim(),{consumeDraft:!1})},streaming:n,disabled:n,openAttachmentPicker:()=>{Wl()||Ot?.click()},models:r?.models,selectedModelId:Cr.getState().selectedModelId??r?.selectedModelId,onModelChange:e=>Rr(e),onVoiceToggle:!0===o.voiceRecognition?.enabled?()=>{Xr?.()}:void 0})},so=ao(()=>Ai({config:o}).footer);so&&(tt.replaceComposer(so),Tt=tt.composer.footer,oo=!0);let co=null;function po(){let e=ht;if(!e)return;let t=o.composer?.inputAttributes,r=t?.ariaLabel||e instanceof HTMLTextAreaElement?null:e.getAttribute("aria-label");nn(e,t),r&&e.setAttribute("aria-label",r),on(e,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:en(e)}),Zo(e,Yo(o.composer?.maxLines,ae()?5:3))}let uo=e=>{co=Oo(e,{debug:!0===o.debug}),co&&(e=>{gt=e.form,ht=e.input,Nt=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(mt=e.sendButton),e.micButton&&(Ht=e.micButton,Wt=e.micButton.parentElement),e.found.status&&(ft=e.found.status),e.found.suggestions&&(ut=e.found.suggestions),e.attachmentButton&&(Dt=e.attachmentButton,Ft=e.attachmentButton.parentElement),Ot=e.attachmentInput??null,zt=e.attachmentPreviews??null,e.found.actionsRow&&(Lt=e.found.actionsRow),Bt=e.found.actionsStart,Rt=e.found.actionsEnd})(co),po()};ro(Tt),uo(Tt),kr();let ho=Va(o,ae());ho&&(dt.style.maxWidth=ho,dt.style.marginLeft="auto",dt.style.marginRight="auto",dt.style.width="100%",vt.style.maxWidth=ho,vt.style.marginLeft="auto",vt.style.marginRight="auto",vt.style.width="100%",ct.style.maxWidth=ho,pt.style.maxWidth=ho,pt.style.marginLeft="auto",pt.style.marginRight="auto",pt.style.width="100%");let mo=()=>{let e=Va(o,ae());if(e&&!ae())for(let t of[gt,ut,zt,ft])t&&(t.style.maxWidth=e,t.style.marginLeft="auto",t.style.marginRight="auto",t.style.width="100%")};mo();let go=()=>{o.attachments?.enabled&&Ot&&zt&&(wr?wr.remountPreviews(zt):(wr=$o.fromConfig(o.attachments,Tr),wr.setPreviewsContainer(zt)),co?.addListener(Ot,"change",e=>{let t=e.target;wr?.handleFileSelect(t.files),t.value=""}),it.querySelector(".persona-attachment-drop-overlay")||it.appendChild(Cc(o.attachments.dropOverlay)))};go();let fo=()=>{if(!o.contextMentions?.enabled||!ht)return;let e=Vr();if(!e){let e=ht;return void Ur().then(()=>{!xr&&ht===e&&e.isConnected&&(fo(),yo?.resolve())},()=>{})}let t=co?.header??null,r=t?Dn(t):void 0;if(xr=e.createContextMentionOrchestrator({deps:{loadContextMentions:ta,loadContextMentionsInline:aa,renderLucideIcon:se,createMentionButton:sa},config:o,textarea:ht,anchor:gt??ht,getMessages:()=>wa.getMessages(),liveRegionHost:it,chipRow:r}),xr&&!r){let e=ht;e.parentElement?.insertBefore(xr.contextRow,e)}};fo();let yo=null,wo={getState:()=>Cr.getState(),getValue:()=>ht?.value??"",setValue:e=>{ht&&(ht.value=e,ht.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})))}(co?.form??null)},openAttachmentPicker:()=>{Wl()||Ot?.click()},toggleVoice:()=>{Xr?.()},requestRender:()=>yo?.resolve()},xo=()=>{let e=[];return(xr?.affordanceButtons??[]).forEach((t,r)=>{e.push({id:`core:mention-${r}`,placement:"start",order:100+r,element:t,managed:!0})}),Ft&&e.push({id:"core:attachment",placement:"start",order:200,element:Ft}),Wt&&e.push({id:"core:mic",placement:"end",order:800,element:Wt}),Nt&&e.push({id:"core:send",placement:"end",order:Cn,element:Nt}),e},Co=()=>{yo?.destroy(),yo=Bn({getBindings:()=>co,collect:()=>({builtIns:xo(),configActions:[...Jr(),...o.composer?.actions??[]],plugins:p,contributionContext:{config:o,getState:()=>Cr.getState(),requestRender:()=>yo?.resolve()},debug:!0===o.debug}),actionContext:wo,getState:()=>Cr.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(e,t)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),yo.resolve()};Co();let So=()=>{if(Dr?.destroy(),Dr=null,!Lr().length)return;let e=co?.header;e&&(Dr=Fn({row:Dn(e),onRemove:e=>$r(e),initialIds:Cr.getState().activeModeIds}),Dr.render(Cr.getState().activeModeIds,Lr()))};So();let ko=()=>{zr?.destroy(),zr=null,Kr?.destroy(),Kr=null;let e=co?.header;e&&(zr=Vn({onDismiss:()=>qr(void 0)}),e.appendChild(zr.element),zr.render(Cr.getState().quote),"defer-one"===_r()&&(Kr=Kn({onEdit:()=>function(){let e=Cr.getState().pendingSubmission;e&&(Gr(void 0),ht&&(ht.value=e.text,ht.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&&qr(e.options.quote),ht?.focus())}(),onRemove:()=>Gr(void 0)}),e.appendChild(Kr.element),Kr.render(Cr.getState().pendingSubmission)))};ko();let Ao=function(){let e=!1;return{observe:(t,r)=>r?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}(),Mo=()=>{let e=co?.header?.querySelector(Hn);if(e)return e.childElementCount>0;let t=Cr.getState();return t.mentionRefs.length>0||_n(t.activeModeIds,Lr()).length>0};function Io(){let e=Cr.getState(),t=Ao.observe(function(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let r=t.getComputedStyle(e),o=Number.parseFloat(r.lineHeight),n=Number.parseFloat(r.fontSize),a=Number.isFinite(o)&&o>0?o:Number.isFinite(n)&&n>0?1.4*n:0;if(!a)return!1;let s=(Number.parseFloat(r.paddingTop)||0)+(Number.parseFloat(r.paddingBottom)||0);return e.scrollHeight-s>1.5*a}(ht),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:Mo(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission}))}function To(){"single-row"!==o.composer?.layout||ae()?Tt.removeAttribute("data-persona-composer-layout"):Tt.setAttribute("data-persona-composer-layout","single-row")}To(),Cr.subscribe(()=>{yo?.sync(),Ol(),zl(),Io(),ui()}),zl();let Eo=!1;(()=>{let e=o.layout?.slots??{};(e=>{if(Eo||!0!==o.debug)return;let t=["messages","composer"].filter(t=>e[t]);t.length&&(Eo=!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 lt.querySelector("[data-persona-intro-card]");case"messages":return dt;case"footer-top":return ut;case"composer":return gt;case"footer-bottom":return ft;default:return null}},r=(e,t)=>{switch(e){case"header-left":case"header-center":case"header-right":if("header-left"===e)It.insertBefore(t,It.firstChild);else if("header-right"===e)It.appendChild(t);else{let e=It.querySelector(".persona-flex-col");e?e.parentNode?.insertBefore(t,e.nextSibling):It.appendChild(t)}break;case"body-top":{let e=lt.querySelector("[data-persona-intro-card]");e?e.replaceWith(t):lt.insertBefore(t,lt.firstChild);break}case"body-bottom":lt.appendChild(t);break;case"footer-top":ut.replaceWith(t);break;case"footer-bottom":ft.replaceWith(t)}};for(let[n,a]of Object.entries(e))if(a)try{let e=a({config:o,defaultContent:()=>t(n)});e&&r(n,e)}catch(e){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${n}":`,e)}})(),dt.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(),vl(r))});let Lo=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 a=r.getAttribute("data-message-id");if(!a)return;As(),Pi();let d=t.getAttribute("data-bubble-type");if(r.classList.contains("persona-activity-row")){i.manual(a);let e=r.parentElement?.closest("[data-persona-tool-group]");e?.dataset.messageId&&i.manual(e.dataset.messageId)}if("reasoning"===d)s.has(a)?s.delete(a):s.add(a),ml(a,r,s);else if("tool"===d)n.has(a)?n.delete(a):n.add(a),Sl(a,r,n,o);else if("approval"===d&&w){let e="expanded"===((!1===o.approval?void 0:o.approval)?.detailsDisplay??"collapsed"),t=l.get(a)??e;l.set(a,!t),w.updateApprovalDetailsUI(a,r,o,l)}Ha.delete(a)};dt.addEventListener("pointerdown",e=>{e.target.closest('button[data-expand-header="true"]')&&(e.preventDefault(),Lo(e))}),dt.addEventListener("click",e=>{0===e.detail&&e.target.closest(".persona-activity-row")&&Lo(e)}),dt.addEventListener("keydown",e=>{let t=e.target;("Enter"===e.key||" "===e.key)&&t.closest('button[data-expand-header="true"]')&&(e.preventDefault(),Lo(e))}),dt.addEventListener("copy",e=>{let{clipboardData:t}=e;if(!t)return;let r=dt.getRootNode(),o="function"==typeof r.getSelection?r.getSelection():window.getSelection();if(!o||o.isCollapsed)return;let n=o.toString(),a=(e=>e.replace(/^\n+/,"").replace(/\s+$/,""))(n);a&&a!==n&&(t.setData("text/plain",a),e.preventDefault())});let Bo=new Map,Ro=null,No="idle",Ho={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading…"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Do=()=>{dt.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:o}=Ho[t];e.setAttribute("aria-label",o),e.title=o,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 n=se(r,14,"currentColor",2);n&&(e.innerHTML="",e.appendChild(n))})(e,t&&t===Ro?No:"idle")})};dt.addEventListener("click",e=>{let t=e.target.closest(".persona-message-action-btn[data-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.closest("[data-actions-for]");if(!r)return;let n=r.getAttribute("data-actions-for");if(!n)return;let a=t.getAttribute("data-action");if("copy"===a){let e=wa.getMessages().find(e=>e.id===n);if(e&&Xe){let r=e.content||"";navigator.clipboard.writeText(r).then(()=>{t.classList.add("persona-message-action-success");let e=g(m.Check,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e)),setTimeout(()=>{t.classList.remove("persona-message-action-success");let e=g(m.Copy,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e))},2e3)}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",e)}),Xe(e)}}else if("read-aloud"===a)wa.toggleReadAloud(n);else if("upvote"===a||"downvote"===a){let e="upvote"===a?"thumbs-up":"thumbs-down";if((Bo.get(n)??null)===a){Bo.delete(n),t.classList.remove("persona-message-action-active");let r=se(e,14,"currentColor",2);r&&(t.innerHTML="",t.appendChild(r))}else{let o="upvote"===a?"downvote":"upvote",s=r.querySelector(`[data-action="${o}"]`);if(s){s.classList.remove("persona-message-action-active");let e=se("upvote"===o?"thumbs-up":"thumbs-down",14,"currentColor",2);e&&(s.innerHTML="",s.appendChild(e))}Bo.set(n,a),t.classList.add("persona-message-action-active");let i=se(e,14,"currentColor",2);i&&(i.setAttribute("fill","currentColor"),t.innerHTML="",t.appendChild(i)),t.classList.remove("persona-message-action-pop"),t.offsetWidth,t.classList.add("persona-message-action-pop");let l=wa.getMessages().find(e=>e.id===n);l&&Qe&&Qe({type:a,messageId:l.id,message:l})}}else if("regenerate"===a)Fo?.regenerate(n);else if("edit"===a)Fo?.edit(n);else if("quote"===a)Fo?.quote(n);else if(a?.startsWith("custom:")){let e=a.slice(7),r=o.messageActions?.custom?.find(t=>t.id===e),s=wa.getMessages().find(e=>e.id===n);if(!r||!s)return;try{r.onSelect(s)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let Fo=null;dt.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 o=r.getAttribute("data-message-id");if(!o)return;let n=t.getAttribute("data-approval-action");if(!n)return;let a="approve"===n?"approved":"denied",s=wa.getMessages().find(e=>e.id===o);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"}),u(s.approval)?wa.resolveWebMcpApproval(o,a):wa.resolveApproval(s.approval,a)});let zo=null,qo=!1,jo=null,_o=()=>{},Vo="none",Ko=null,Go={artifacts:[],selectedId:null},Jo=!1,Qo=!1,tn=!1,dn=!1,cn=()=>dn||Go.artifacts.some(e=>"panel"===no(o.features?.artifacts,e)),un=()=>Go.artifacts.length>0&&!Jo&&cn(),mn={current:null},gn=(e,t)=>{let r=wa.getArtifactById(t),o=r?.markdown,n=r?.title||"artifact",a=r?.file,s=r?.artifactType??"markdown";if(!o){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);o=t?.props?.markdown,n=t?.props?.title||n,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:o,title:n,file:a,artifactType:s}};dt.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===o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:r}))return;let{markdown:n,title:a,file:s}=gn(t,r);if(!n)return;let i=Kl();i&&i.triggerArtifactDownload(i.downloadInfoFor({title:a,markdown:n,file:s}))}),dt.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]"),a=n?null:t.closest("[data-open-artifact]"),s=n?n.getAttribute("data-artifact-inline"):a?.getAttribute("data-open-artifact")??null,i=(n?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(e=>e.id===r);if(!i)return;let{markdown:l,title:d,file:c,artifactType:p}=gn(t,s??""),u={artifactId:s,title:d,artifactType:p,markdown:l,file:c};try{Promise.resolve(i.onClick(u)).catch(()=>{})}catch{}}),dt.addEventListener("click",e=>{let t=e.target.closest("[data-copy-artifact]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-copy-artifact");if(!r)return;let o=wa.getArtifactById(r),n=Kl();if(!n)return;let a="";if(o)a=n.artifactCopyText(o);else{let{markdown:e,file:o,artifactType:s}=gn(t,r);"markdown"===s&&(a=n.artifactCopyText({id:r,artifactType:"markdown",status:"complete",markdown:e??"",...o?{file:o}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=g(m.Check,16,"currentColor",2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=g(m.Copy,16,"currentColor",2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),dt.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!==o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:r})&&(Jo=!1,dn=!0,Qo=!0,tn=!0,wa.selectArtifact(r),Yn())}),dt.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!==o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:n})&&(e.preventDefault(),e.stopPropagation(),Jo=!1,dn=!0,wa.selectArtifact(n),Yn())}),dt.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 fn=st.composerOverlay,yn=e=>{Ur().catch(()=>{}),qt(e,o,fn)},bn=null,vn={mount:e,overlay:fn,sessionRef:mn,config:()=>o},wn=!1,xn=e=>t=>{let r=t.target,o=r?.closest?.("[data-persona-ask-sheet-for]");if(!o||!("click"===e?r?.closest("[data-ask-user-action]"):"Enter"===t.key&&r?.matches?.('[data-ask-free-text-input="true"]')))return;let n=r=>{bn??=r.createAskUserSheetHandlers(vn),bn[e](t)},a=Vr();a?n(a):wn||(wn=!0,Ur().then(e=>{wn=!1,o.isConnected&&n(e)},()=>{wn=!1}))};fn.addEventListener("click",xn("click")),fn.addEventListener("keydown",xn("keydown"));let Sn=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=fn.querySelector("[data-persona-ask-sheet-for]");if(!r||"rows"!==r.getAttribute("data-ask-layout")||"true"===r.getAttribute("data-multi-select"))return;let o=Number(e.key),n=r.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[o-1];n&&(e.preventDefault(),n.click())};document.addEventListener("keydown",Sn);let kn=null,An=null,Mn=null,In=null,Tn=()=>{},En=!1,Ln="",Pn="";function Rn(){In?.(),In=null}let Nn=()=>{if(!kn||!An)return;let t=e.classList.contains("persona-artifact-welded-split"),r=e.ownerDocument.defaultView??window,o=r.innerWidth<=640;if(!t||e.classList.contains("persona-artifact-narrow-host")||o)return An.style.removeProperty("position"),An.style.removeProperty("left"),An.style.removeProperty("top"),An.style.removeProperty("bottom"),An.style.removeProperty("width"),void An.style.removeProperty("z-index");let n=kn.firstElementChild;if(!n||n===An)return;An.style.position="absolute",An.style.top="0",An.style.bottom="0",An.style.width="10px",An.style.zIndex="5";let a=Sd(kn,r),s=n.offsetWidth+a/2-5;An.style.left=`${Math.max(0,s)}px`},Wn=()=>{},qn=()=>{let t=e.ownerDocument.defaultView??window,r=o.launcher?.mobileFullscreen??!0,n=o.launcher?.mobileBreakpoint??640;return!(!r||t.innerWidth>n)&&(Q||Xs(o))},Xn=()=>!Jl(o)||!un()||e.classList.contains("persona-artifact-narrow-host")||qn()||(e.ownerDocument.defaultView??window).innerWidth<641?"none":Zl(o)?"detached":"welded",Yn=()=>{if(!zo||!Jl(o))return;ed(e,o),td(e,o),Wn();let t=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,r=ot.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",r>0&&r<=t);let n=un();zo.setVisible(n),zo.update(Go),Jo?(zo.setMobileOpen(!1),zo.element.classList.add("persona-hidden"),zo.backdrop?.classList.add("persona-hidden"),Qo=!1,tn=!1):Go.artifacts.length>0&&cn()?(zo.element.classList.remove("persona-hidden"),zo.setMobileOpen(!0)):(zo.setMobileOpen(!1),zo.element.classList.add("persona-hidden"),zo.backdrop?.classList.add("persona-hidden"),Qo=!1,tn=!1);let a=!0===o.features?.artifacts?.layout?.showExpandToggle;if(zo.setExpandToggleVisible(a),zo.setCopyButtonVisible(!0===o.features?.artifacts?.layout?.showCopyButton),zo.setRefreshButtonVisible("function"==typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh),zo.setCustomActions(o.features?.artifacts?.toolbarActions??[]),zo.setTabFade(o.features?.artifacts?.layout?.tabFade),zo.setRenderTabBar(o.features?.artifacts?.renderTabBar),!a&&!tn&&(Qo=!1),Qo!==En){let e=zo.element;Qo?(Ln=e.style.width,Pn=e.style.maxWidth,e.style.removeProperty("width"),e.style.removeProperty("max-width")):(Ln&&(e.style.width=Ln),Pn&&(e.style.maxWidth=Pn),Ln="",Pn=""),En=Qo}e.classList.toggle("persona-artifact-expanded",Qo),zo.setExpanded(Qo);let s=Xn();s!==Vo&&(Vo=s,_o()),Tn()};if(Jl(o)){ot.style.position="relative";let t=q("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),r=q("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");t.appendChild(it),kn=r,r.appendChild(t),ot.appendChild(r);let n=e=>{qo||zo||(zo=e.createArtifactPane(o,{onSelect:e=>mn.current?.selectArtifact(e),onDismiss:()=>{Jo=!0,Yn()},onToggleExpand:()=>{let e=!Qo,t=Go.selectedId??Go.artifacts[Go.artifacts.length-1]?.id??null;!0!==o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:t,expanded:e})&&(Qo=e,e||(tn=!1),Yn())}}),zo.element.classList.add("persona-hidden"),r.appendChild(zo.element),zo.backdrop&&ot.appendChild(zo.backdrop),Tn(),Yn())},a=Kl();a?n(a):(Gl(()=>{let e=Kl();e&&n(e)}),Vl().catch(()=>{})),Tn=()=>{if(kn&&zo)if(!0!==o.features?.artifacts?.layout?.resizable)Mn?.(),Mn=null,Rn(),An&&=(An.remove(),null),zo.element.style.removeProperty("width"),zo.element.style.removeProperty("maxWidth");else{if(!An){let t=q("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");t.setAttribute("role","separator"),t.setAttribute("aria-orientation","vertical"),t.setAttribute("aria-label","Resize artifacts panel"),t.tabIndex=0;let r=e.ownerDocument,n=r.defaultView??window,a=a=>{if(!zo||0!==a.button||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||n.innerWidth<=640)return;a.preventDefault(),Rn();let s=a.clientX,i=zo.element.getBoundingClientRect().width,l=o.features?.artifacts?.layout,d=r=>{let o=kn.getBoundingClientRect().width,a=e.classList.contains("persona-artifact-welded-split"),d=Sd(kn,n),c=a?0:t.getBoundingClientRect().width||6,p=function(e,t,r,o,n,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}(n),l=function(e,t,r,o){let n=e-o-2*t-r;return Math.max(0,n)}(t,r,o,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-s),o,d,c,l?.resizableMinWidth,l?.resizableMaxWidth,(()=>{let e=ac?.railShell?ac.railHost:null,t=e?.isConnected?e:null,r=t?t.getBoundingClientRect().width:0;return r<=0?200:r+360})());zo.element.style.width=`${p}px`,zo.element.style.maxWidth="none",Nn()},c=()=>{r.removeEventListener("pointermove",d),r.removeEventListener("pointerup",c),r.removeEventListener("pointercancel",c),In=null;try{t.releasePointerCapture(a.pointerId)}catch{}};In=c,r.addEventListener("pointermove",d),r.addEventListener("pointerup",c),r.addEventListener("pointercancel",c);try{t.setPointerCapture(a.pointerId)}catch{}};t.addEventListener("pointerdown",a),An=t,kn.insertBefore(t,zo.element),Mn=()=>{t.removeEventListener("pointerdown",a)}}if(An){let e=un();An.classList.toggle("persona-hidden",!e),Nn()}}},Wn=()=>{if(!Q||!zo||o.launcher?.sidebarMode||Xs(o)&&"emerge"===Ys(o).reveal)return;let t=e.ownerDocument.defaultView??window,r=o.launcher?.mobileFullscreen??!0,n=o.launcher?.mobileBreakpoint??640;if(r&&t.innerWidth<=n||!function(e,t){return!(!t||!Jl(e))&&!1!==e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen}(o,Q))return;let a=tl(o).width,s=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";un()?(ot.style.width=s,ot.style.maxWidth=s):(ot.style.width=a,ot.style.maxWidth=a)},typeof ResizeObserver<"u"&&(jo=new ResizeObserver(()=>{Yn()}),jo.observe(ot))}else ot.appendChild(it);ae()&&nt&&(st.peekBanner&&nt.appendChild(st.peekBanner),nt.appendChild(Tt)),e.appendChild(rt),nt&&e.appendChild(nt);let Zn=()=>{let t=qn()||ae()&&"fullscreen"===o.launcher?.composerBar?.expandedSize||!0===o.launcher?.fullHeight&&!o.launcher?.sidebarMode&&!Xs(o);if(dt.style.gap=t?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",dt.style.setProperty("--persona-transcript-gap",dt.style.gap),ae()){ot.style.width="100%",ot.style.maxWidth="100%";let e=o.launcher?.composerBar??{},t="expanded"===rt.dataset.state,r=e.expandedSize??"anchored";if(!t||"fullscreen"===r)return it.style.background="",it.style.border="",it.style.borderRadius="",it.style.overflow="",void(it.style.boxShadow="");let n=o.theme?.components?.panel,a=ja(o),s=(e,t)=>null==e||""===e?t:Aa(a,e)??e;return it.style.background="var(--persona-surface, #ffffff)",it.style.border=s(n?.border,"1px solid var(--persona-border)"),it.style.borderRadius=s(n?.borderRadius,"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))"),it.style.boxShadow=s(n?.shadow,"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))"),void(it.style.overflow="hidden")}let r=Xs(o),n=o.launcher?.sidebarMode??!1,a=r||n||(o.launcher?.fullHeight??!1),s=!1===o.launcher?.enabled,i=!0===o.launcher?.detachedPanel,l=o.theme?.components?.panel,d=o.darkTheme?.components?.panel,c="dark"===qa(o)?y(l??{},d??{}):l,p=ja(o),u=(e,t)=>null==e||""===e?t:Aa(p,e)??e,h=e.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,g=o.launcher?.mobileBreakpoint??640,f=h.innerWidth<=g,b=m&&f&&Q,v=r&&m&&f,w=o.launcher?.position??"bottom-left",x="bottom-left"===w||"top-left"===w,C=o.launcher?.zIndex??1e5,S=(e,t,r)=>`var(--persona-components-panel-modes-${e}-${t}, ${r})`,k=c?.modes?.floating,A=u(k?.border??c?.border,S("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),M=u(k?.shadow??c?.shadow,S("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),I=u(k?.borderRadius??c?.borderRadius,S("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),E=i&&!b&&!v,L=b||v?"mobile":E?"floating":r?"docked":n?"sidebar":s?"inline":"floating",P=c?.modes?.[L];E?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let B=E?A:n||b?"none":A,R=E?M:b?"none":n?x?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":s?"none":M;r&&!b&&!E&&(R="none",B="none");let N=E?I:n||b?"0":I,$=u(P?.border??c?.border,S(L,"border",B)),H=u(P?.shadow??c?.shadow,S(L,"shadow",R)),W=u(P?.borderRadius??c?.borderRadius,S(L,"borderRadius",N)),D=Xn(),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"===o.features?.artifacts?.layout?.chatSurface?"flush":"card")&&Jl(o)&&Zl(o)&&s&&!r;e.classList.toggle("persona-artifact-chat-flush",q);let j=F||q?"none":H,_=F?A:O?"none":$,U=F?I:W;q&&(_="none",U="0");let V=null!=P?.borderRadius&&""!==P.borderRadius||null!=c?.borderRadius&&""!==c.borderRadius,K=q&&!V?"0":W,G=lt.scrollTop;e.style.cssText="",rt.style.cssText="",ot.style.cssText="",it.style.cssText="",lt.style.cssText="",oo||(Tt.style.cssText=""),We&&(lt.style.display="none"),(a||s)&&(e.style.minWidth="0");let J=()=>{G<=0||(lt.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(lt.scrollTop===G)return;let e=lt.scrollHeight-lt.clientHeight;e<=0||(lt.scrollTop=Math.min(G,e))})};if(b)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: ${C} !important;\n background-color: var(--persona-surface, #ffffff) !important;\n `,ot.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 ",it.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 ",lt.style.flex="1 1 0%",lt.style.minHeight="0",lt.style.overflowY="auto",Tt.style.flexShrink="0",yr(),ne=!0,void J();let X=tl(o);if(n||r){if(r)if("emerge"!==Ys(o).reveal||i)ot.style.width="100%",ot.style.maxWidth="100%";else{let e=Ys(o).width;ot.style.width=e,ot.style.maxWidth=e}}else s&&a?(ot.style.width="100%",ot.style.maxWidth="100%"):(ot.style.width=X.width,ot.style.maxWidth=X.maxWidth);if(Wn(),ot.style.boxShadow=j,ot.style.borderRadius=K,F?ot.style.border="none":O&&(ot.style.border=$),it.style.border=_,it.style.borderRadius=U,it.style.boxShadow=F&&!q?z:"",q&&(it.style.background="transparent",lt.style.background="transparent",Tt.style.background="transparent",Tt.style.borderTop="none"),O){let e=o.features?.artifacts?.layout;Ko=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||W}else Ko=null;let Y=null!=P?.border||null!=c?.border;if(r&&!b&&!E&&!F&&!O&&!Y&&(it.style.border="none","right"===Ys(o).side?it.style.borderLeft="1px solid var(--persona-border)":it.style.borderRight="1px solid var(--persona-border)"),r&&!b&&O&&!Y&&("right"===Ys(o).side?ot.style.borderLeft="1px solid var(--persona-border)":ot.style.borderRight="1px solid var(--persona-border)"),a&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",s&&(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%",s&&(rt.style.overflow="hidden"),ot.style.display="flex",ot.style.flexDirection="column",ot.style.flex="1 1 0%",ot.style.minHeight="0",ot.style.maxHeight="100%",ot.style.height="100%",F||(ot.style.overflow="hidden"),it.style.display="flex",it.style.flexDirection="column",it.style.flex="1 1 0%",it.style.minHeight="0",it.style.maxHeight="100%",it.style.overflow="hidden",lt.style.flex="1 1 0%",lt.style.minHeight="0",lt.style.overflowY="auto",Tt.style.flexShrink="0"),s&&(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&&!s&&!r&&(ni[w]??ni["bottom-right"]).split(" ").forEach(e=>rt.classList.add(e)),n){let e=T(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":Aa(ja(o),"components.panel.width")??"420px";rt.style.cssText=i?`\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: ${C} !important;\n ${x?"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: ${C} !important;\n ${x?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}\n `,ot.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: ${K} !important;\n ${F?"border: none !important;":O?`border: ${$} !important;`:""}\n `,ot.style.setProperty("width","100%","important"),ot.style.setProperty("max-width","100%","important"),it.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 `,oo||(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(!s&&!r){let e=n?"":"padding-top: 1.25em !important;",t=n?"":`z-index: ${o.launcher?.zIndex??1e5} !important;`;rt.style.cssText+="max-height: -moz-available !important; max-height: stretch !important;"+e+t}yr(),J()},ea=()=>{e.style.setProperty("--persona-content-max-width",Va(o,ae()))},ra=!1;function oa(){o.layout?.topFade&<.scrollTop>1?lt.setAttribute("data-persona-top-fade","true"):lt.removeAttribute("data-persona-top-fade")}let na=()=>{oa();let t=Ka(o,ae());ae()&&o.composer?.placement&&!0===o.debug&&!ra&&(ra=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let r=ur();e.setAttribute("data-persona-composer-placement",t),e.setAttribute("data-persona-conversation-state",hr),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",r.composerGap??"24px"),br()},ia=()=>{if(ae())return;let t=Xs(o),r=o.launcher?.sidebarMode??!1;if(t||r||o.launcher?.fullHeight||!Q)return;let n=e.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,s=o.launcher?.mobileBreakpoint??640;if(a&&n.innerWidth<=s)return;let i=tl(o);ot.style.height=i.height,ot.style.maxHeight=i.maxHeight};Zn(),_a(e,o),ed(e,o),td(e,o),ea(),na(),_o=()=>{Zn(),ia(),_a(e,o),ed(e,o),td(e,o),ea(),na(),Ko?e.style.setProperty("--persona-artifact-welded-outer-radius",Ko):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Ve(),Ue()};let la=[];la.push(()=>{qo=!0}),la.push(()=>{f.forEach(e=>e()),h.destroy()}),la.push(()=>{document.removeEventListener("keydown",Sn)}),la.push(()=>{null!==lr&&clearTimeout(lr)});let da=null,ca=null;la.push(()=>{da?.(),da=null,ca?.(),ca=null}),jo&&la.push(()=>{jo?.disconnect(),jo=null}),la.push(()=>{Mn?.(),Mn=null,Rn(),An&&=(An.remove(),null),zo?.element.style.removeProperty("width"),zo?.element.style.removeProperty("maxWidth"),zo?.destroy()}),ge&&la.push(()=>{Ne=!0,Re=null,null!==De&&(cancelAnimationFrame(De),De=null),$e?.destroy(),$e=null,Te?.destroy(),Te=null,Me=null});let pa=null,ua=()=>{pa&&=(pa(),null),"auto"===o.colorScheme&&(pa=Ua(()=>{_a(e,o)}))};ua(),la.push(()=>{pa&&=(pa(),null)}),la.push(()=>{S=!0,C?.()}),la.push(()=>{I=!0});let ha=!1;la.push(()=>{ha=!0});let ma=(t,r)=>{let o=Cs(t,r);return o||!ws.includes(t)?o:(Os().then(o=>{if(ha)return;xs(o.wipe),xs(o.glyphCycle);let n=Cs(t,r);n&&Hs(n,e)}).catch(()=>{}),null)},ga=o.features?.streamAnimation;if(ga?.type&&"none"!==ga.type){let t=ma(ga.type,ga.plugins);t&&Hs(t,e),la.push(()=>$s(e))}let fa=oi(ut),ya=oi(ct),ba=oi(pt),va=[fa,ya,ba];la.push(()=>{va.forEach(e=>e.destroy())});let wa,xa=null,Ca=null,Sa=!1,ka=0,Ma=null,Ia=e=>e.reduce((e,t)=>"user"===t.role?e+1:e,0),Ta=e=>{for(let t=e.length-1;t>=0;t--)if(Kt(e[t]))return e[t].id??null;return null},Ea=!1,La=!1,Pa=!1,Ba=(e,t)=>{La||!0!==o.debug||t.enabled&&!t.expose&&(Sa||Pa&&(wa.isStreaming()||e.some(Kt)||(La=!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."))))},Ra=e=>{if(!wa)return;let t=e??wa.getMessages(),r=e=>{e.render([],wa,ht,t)},n=e=>{va.forEach(t=>{t!==e&&r(t)})};Ca&&(Ia(t)>ka||Ta(t)!==Ma)&&(Ca=null);let a=Qt(o);Ba(t,a);let s=a.enabled?Jt(t):null,i=Ca??s,l=Ca?"host":"agent";if(i){let e=o.suggestions?.followUps,r=e?.placement??(e?"auto":"composer"),a="after-message"===("auto"===r?ae()?"composer":"after-message":r)?ba:fa;return n(a),void a.render(i,wa,ht,t,o.suggestionChipsConfig,{source:l,surface:"followUp",variant:e?.variant??"chip",behavior:e?.behavior??"send",overflow:e?.overflow??"wrap",maxItems:e?.maxItems??4,config:o,plugins:p,submitPrompt:Yc})}if(t.some(e=>"user"===e.role))return void va.forEach(r);let d=!0===o.future?.v5Defaults,c=pr(),u=o.suggestions?.starters??(d?{}:void 0);if(u){let e=Zi(ur(),t),a=u.placement??"auto",s="auto"===a?e?"welcome":"composer":a;if("welcome"===s&&!e)return Ea||!0!==o.debug||(Ea=!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"===s?ya:fa;n(i),i.render(u.items??o.suggestionChips,wa,ht,t,o.suggestionChipsConfig,{surface:"starter",variant:u.variant??(d&&!c?"chip":"card"),behavior:u.behavior??"send",overflow:u.overflow??"wrap",maxItems:u.maxItems??(d&&!c?3:4),config:o,plugins:p,submitPrompt:Yc})}else n(fa),fa.render(o.suggestionChips,wa,ht,t,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:p,submitPrompt:Yc})},Na=()=>{Ca&&(Ca=null,Ra())},$a=!1,Ha=new Map,Wa=new Map,Da=new Map,Fa=new Map,Oa=null,za=null;function Ja(){if(!Oa)return;let e=Oa;Oa=null,za?.destroy(),za=null,Ha.delete(e),it.querySelector(`#wrapper-${e}`)?.removeAttribute("data-preserve-runtime"),wa&&fl(dt,wa.getMessages(),ue)}let Xa=0,Qa=null!==Pe(),Ya=function(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>!!t&&(t=!1,!0),resume:()=>!t&&(t=!0,!0)}}(),Za=0,es=null,ts=!1,rs=!1,ns=0,ps=null,us=null,hs=!1,ms=!1,gs=null,fs=!0,bs=!1,vs=null,ks=!1,As=()=>{ks=!0,Es()},Ms=null,Is=null,Ts=()=>{e.setAttribute("data-persona-scrollbar",er()),"on-scroll"!==er()&&(null!==Is&&clearTimeout(Is),Is=null,lt.removeAttribute("data-persona-scrollbar-visible"))},Es=()=>{"on-scroll"===er()&&(lt.setAttribute("data-persona-scrollbar-visible",""),null!==Is&&clearTimeout(Is),Is=setTimeout(()=>{Is=null,ds(lt,24)&<.removeAttribute("data-persona-scrollbar-visible")},1e3))};Ts(),la.push(()=>{null!==Is&&clearTimeout(Is)});let Rs=new Map,Ns=!1,Ws=null,Ds={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Io();let Fs=o.voiceRecognition?.autoResume??!1,qs=()=>wa.isVoiceActive()||wa.isBargeInActive(),js=!1,Us=e=>{N.emit("voice:state",{active:Ds.active,source:e,timestamp:Date.now()})},Vs=()=>{K(e=>({...e,voiceState:{active:Ds.active,timestamp:Date.now(),manuallyDeactivated:Ds.manuallyDeactivated}}))},Ks=e=>{js=!e.persisted,Ds.active&&Vs()};typeof window<"u"&&(window.addEventListener("pagehide",Ks),la.push(()=>window.removeEventListener("pagehide",Ks)));let Gs=()=>wa?wc(wa.getMessages()).filter(e=>!e.__skipPersist):[],Js=null,Zs=(e,t)=>{typeof console<"u"&&console.error(e,t)},ti=(e,t)=>{let r=()=>{try{let r=e();return r&&"function"==typeof r.then?Promise.resolve(r).catch(e=>{Zs(t,e)}):null}catch(e){return Zs(t,e),null}},o=Js?Js.then(()=>r()??void 0):r();if(!o)return;let n=o.finally(()=>{Js===n&&(Js=null)});Js=n};function ai(e){if(!$?.save)return;let t=e?wc(e):wa?Gs():[],r=H&&wa?.getResumableHandle();r&&(W={...W,durableResume:{executionId:r.executionId,after:r.lastEventId}});let o={messages:t,metadata:W,artifacts:Go.artifacts,selectedArtifactId:Go.selectedId,...si?{draft:si}:{}};ti(()=>$.save(o),"[AgentWidget] Failed to persist state:")}let si,di=()=>!(!$?.save||!1===o.persistState||"object"==typeof o.persistState&&!1===o.persistState.persist?.draft),ci=function(e){let t=e.delay??500,r=null,o=!1,n=()=>{null!==r&&(clearTimeout(r),r=null)};return{schedule:()=>{o||(n(),r=setTimeout(()=>{r=null,e.write()},t))},flush:()=>{o||null===r||(n(),e.write())},cancel:n,destroy:()=>{o=!0,n()}}}({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:jc(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(si)&&(si=t,ai())}});function ui(){di()&&ci.schedule()}function hi(){ci.flush()}function fi(e){if(!di())return;let t=function(e,t){if(!e||"string"!=typeof e.text)return;let r=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(e=>r.has(e.sourceId)),n=o.length===(e.mentionRefs?.length??0)&&o.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,...n?{mentionRefs:o}:{},...n&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...i?{selectedModelId:i}:{},...s.length?{activeModeIds:s}:{},...e.quote?.text?{quote:e.quote}:{}}}(e,{mentionSourceIds:(o.contextMentions?.sources??[]).map(e=>e.id),modelIds:(o.composer?.models??[]).map(e=>e.id),modes:o.composer?.modes??[]});t&&(si=e,ht&&!ht.value&&(ht.value=t.text,ht.dispatchEvent(new Event("input",{bubbles:!0})),kr()),t.selectedModelId&&(Cr.setSelectedModelId(t.selectedModelId),Hr?.repaint()),Nr(t.activeModeIds??[]),t.quote&&qr(t.quote),ci.cancel())}function yi(){ci.cancel(),si&&(si=void 0,di()&&ai())}let bi=null,vi=()=>rt.querySelector("#persona-scroll-container")||lt,wi=()=>{null!==bi&&(cancelAnimationFrame(bi),bi=null),ts=!1},xi=()=>{null!==es&&(cancelAnimationFrame(es),es=null),rs=!1,wi()},Ci=()=>{let e=_t()||"Jump to latest",t=$a&&Mi()&&("anchor-top"!==Ut()||Yt());tr.toggleAttribute("data-persona-scroll-to-bottom-streaming",t),ns>0?(nr.textContent=String(ns),nr.style.display="",tr.setAttribute("aria-label",`${e} (${ns} new)`)):(nr.textContent="",nr.style.display="none",tr.setAttribute("aria-label",t?`${e} (response streaming below)`:e))},Si=()=>{0!==ns&&(ns=0,Ci())},Mi=()=>Vt()?!Ya.isFollowing():!(()=>{let e=ps?.spacerHeight??0;return e<=0?ds(lt,24):Xi(e)-lt.scrollTop-lt.clientHeight<=24})(),Ti=()=>!!wa&&wa.getMessages().length>0,Ei=()=>{if(!1===be.enabled||We||je&&"panel"===_e)return tr.parentNode&&tr.remove(),void(tr.style.display="none");tr.parentNode!==it&&it.appendChild(tr),fr();let e=ls(lt)>0&&Mi()&&Ti();e?Ci():Si(),tr.style.display=e?"":"none"},Pi=()=>{Ya.pause()&&(xi(),Ei())},Bi=()=>{Ya.resume(),Si(),Ei()},Ni=(e=!1)=>{Vt()&&Ti()&&Ya.isFollowing()&&(e||$a)&&(null!==es&&(cancelAnimationFrame(es),es=null),rs=!0,es=requestAnimationFrame(()=>{es=null,rs=!1,Ya.isFollowing()&&Hi(vi(),e?220:140)}))},$i=(e,t,r,o=()=>!0)=>{let n=e.scrollTop,a=t(),s=a-n;if(wi(),Math.abs(s)<1)return ts=!0,e.scrollTop=a,Za=e.scrollTop,void(ts=!1);let i=performance.now();ts=!0;let l=d=>{if(!o())return void wi();let c=t();c!==a&&(a=c,s=a-n);let p=d-i,u=Math.min(p/r,1),h=(e=>1-(1-e)**3)(u);e.scrollTop=n+s*h,Za=e.scrollTop,u<1?bi=requestAnimationFrame(l):(e.scrollTop=a,Za=e.scrollTop,bi=null,ts=!1)};bi=requestAnimationFrame(l)},Hi=(e,t=500)=>{let r=ls(e)-e.scrollTop;Math.abs(r)<1?Za=e.scrollTop:Math.abs(r)>=80?(wi(),ts=!0,e.scrollTop=ls(e),Za=e.scrollTop,ts=!1):$i(e,()=>ls(e),t,()=>Ya.isFollowing())},Wi=()=>{if(!Ti())return void Ei();let e=vi();ts=!0,e.scrollTop=ls(e),Za=e.scrollTop,ts=!1,Ei()},zi=e=>{let t=0,r=e;for(;r&&r!==lt;)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=lt.getRootNode();return("function"==typeof e.getSelection?e.getSelection():null)??lt.ownerDocument.getSelection()})(),lt),ji=()=>{if("last-user-turn"!==(Se.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,'\\"'),o=lt.querySelector(`[data-message-id="${r}"]`);if(!o)return!1;let n=Math.min(Math.max(0,zi(o)-Gt()),ls(lt));return ts=!0,lt.scrollTop=n,Za=lt.scrollTop,ts=!1,"follow"===Ut()&&!ds(lt,24)&&Ya.pause(),Ei(),!0},Ki=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))},Xi=e=>{let t=parseFloat(getComputedStyle(lt).paddingBottom)||0,r=0;for(let e of Array.from(lt.children)){if(e===ar||0===e.offsetHeight)continue;let t=zi(e)+e.offsetHeight;t>r&&(r=t)}let o=lt.scrollHeight-e;return r>0?Math.min(r+t,o):o},Qi=()=>{null!==us&&(cancelAnimationFrame(us),us=null),wi(),ps=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,'\\"'),rl=e=>lt.querySelector(`[data-message-id="${el(e)}"]`),al=e=>{null!==us&&cancelAnimationFrame(us),us=requestAnimationFrame(()=>{us=null;let t=el(e),r=lt.querySelector(`[data-message-id="${t}"]`);if(!r)return;let o=zi(r),n=Xi(ps?.spacerHeight??0),{targetScrollTop:a,spacerHeight:s}=cs({anchorOffsetTop:o,topOffset:Gt(),viewportHeight:lt.clientHeight,contentHeight:n,slack:24});ps={initialSpacerHeight:s,contentHeightAtAnchor:n,spacerHeight:s},Ki(s),$i(lt,()=>r.isConnected?Math.max(0,zi(r)-Gt()):a,220)})},sl=()=>{if("anchor-top"!==Ut()||!ps||!vs)return;let e=rl(vs);if(!e)return;wi();let t=ps.spacerHeight,r=Xi(t),{targetScrollTop:o,spacerHeight:n}=cs({anchorOffsetTop:zi(e),topOffset:Gt(),viewportHeight:lt.clientHeight,contentHeight:r,slack:24});ps={initialSpacerHeight:n,contentHeightAtAnchor:r,spacerHeight:n},Ki(n),ts=!0,lt.scrollTop=o,Za=lt.scrollTop,ts=!1,Ei()},il=e=>{if(null===gs)return!0;let t=rl(gs),r=rl(e);if(!t||!r)return!0;let o=zi(r)-zi(t);return Gt()+o>lt.clientHeight-96},ll=(e,t)=>{let r="user"===t?"user":"assistant",n=o.layout?.messages?.[r],a=n?.width??"content",s=n?.maxWidth??("full"===a?`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-${a}`),e.classList.toggle("persona-justify-end","user"===t),e.setAttribute("data-message-role",t),e.setAttribute("data-message-width",a),s?e.style.setProperty("--persona-message-row-max-width",s):e.style.removeProperty("--persona-message-row-max-width")},dl=(e,t)=>{let r=document.createElement("div");return r.className="persona-flex",r.id=`wrapper-${e}`,r.setAttribute("data-wrapper-id",e),ll(r,t),r},cl=!1,hl=()=>{cl||(cl=!0,at().catch(()=>{}),Ee().catch(()=>{cl=!1}))},fl=(e,t,r)=>{t.length>0&&hl(),((e,t,r)=>{let a=new Set;for(let e of t){let t="tool"===e.variant?"tool":"reasoning"===e.variant?"reasoning":null;if(!t||"row"!==fe(o,t))continue;let r="tool"===t?o.features?.toolCallDisplay:o.features?.reasoningDisplay;!1!==r?.expandable&&(a.add(e.id),i.observe(e,t,"tool"===t?n:s,r))}let d=document.createElement("div"),c=(()=>{let e=p.find(e=>e.renderLoadingIndicator);return e?.renderLoadingIndicator?e.renderLoadingIndicator:o.loadingIndicator?.render?o.loadingIndicator.render:void 0})(),h=new Set,m=new Map,g=new Set,f=p.some(e=>e.renderAskUserQuestion),y=[],b=[],v=!1!==o.enableComponentStreaming,w=!1!==o.approval,C=[],S=o.messageActions,k=!0===S?.showRegenerate&&!1!==S.enabled&&!0!==mn.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 io(e,r.id)?r.id:null}return null}(t):null,A=!0===S?.showEdit&&!1!==S.enabled,I=!0===S?.showQuote&&!1!==S.enabled,T=null,E=o.features?.reasoningDisplay?.completedVisibility,L=e=>"removed"===E||"removed-when-short"===E&&((e,t)=>{let r=t?.durationMs??15e3,o=t?.chars??1200;return"number"==typeof e.durationMs?e.durationMs<r:(e.chunks??[]).join("").length<o})(e,o.features?.reasoningDisplay?.shortThinkThreshold),B="removed"===o.features?.toolCallDisplay?.completedVisibility,R=e=>"reasoning"===e.variant&&"complete"===e.reasoning?.status?L(e.reasoning):B&&"tool"===e.variant&&"complete"===e.toolCall?.status&&!e.toolCall.interrupted;if(t.forEach(t=>{if(R(t))return;if(h.add(t.id),m.set(t.id,t.role),Oa===t.id&&za){let e=dl(t.id,t.role);return e.setAttribute("data-persona-message-edit-stub","true"),e.setAttribute("data-preserve-runtime","true"),d.appendChild(e),void(T={messageId:t.id,element:za.element})}let a=f&&Et(t),i=w&&"approval"===t.variant&&!!t.approval,S=!a&&"assistant"===t.role&&!t.variant&&v&&lc(t);!i&&Fa.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),Fa.delete(t.id)),!S&&Da.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),Da.delete(t.id));let E=Et(t)?`:${t.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:"",L={canRegenerate:k===t.id,canEdit:A&&lo(t),canQuote:I&&!t.variant&&(t.content?.trim().length??0)>0},B=`${L.canRegenerate?"r":""}${L.canEdit?"e":""}${L.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,Xa)+E+`:${B}`,$=a||i||S?null:function(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}(Ha,t.id,N);if($)return d.appendChild($.cloneNode(!0)),void(Et(t)&&t.toolCall?.id&&!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(g.add(t.toolCall.id),yn(t)));let H=null,W=p.find(e=>!!("reasoning"===t.variant&&e.renderReasoning||"tool"===t.variant&&e.renderToolCall||!t.variant&&e.renderMessage)),D=o.layout?.messages;if(Et(t)&&!0===t.agentMetadata?.askUserQuestionAnswered)return Wa.delete(t.id),void e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime");if(Kt(t)&&Qt(o).enabled)return;if(Et(t)&&!1!==o.features?.askUserQuestion?.enabled){let e=p.find(e=>"function"==typeof e.renderAskUserQuestion);if(e&&mn.current){let r=Wa.get(t.id),n=r!==N,a=null;if(n){let{payload:r,complete:n}=Pt(t),s=t.id,i=()=>mn.current?.getMessages().find(e=>e.id===s);a=e.renderAskUserQuestion({message:t,payload:r,complete:n,resolve:e=>{let t=i();t&&mn.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=i();e?.agentMetadata?.awaitingLocalTool&&(mn.current?.markAskUserQuestionResolved(e),mn.current?.resolveAskUserQuestion(e,"(dismissed)"))},config:o})}if(n&&null===a&&null==r)return void(!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(g.add(t.toolCall.id),yn(t)));let s=dl(t.id,t.role);return s.setAttribute("data-ask-plugin-stub","true"),s.setAttribute("data-preserve-runtime","true"),d.appendChild(s),void y.push({messageId:t.id,fingerprint:N,bubble:a})}return void(!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(g.add(t.toolCall.id),yn(t)))}if(i){let r=M();if(!r)return void d.appendChild(dl(t.id,t.role));let n=p.find(e=>"function"==typeof e.renderApproval)??x,a=Fa.get(t.id)!==N,s=null;if(a&&n?.renderApproval){let e=t.id,a=(t,r)=>{let o=mn.current?.getMessages().find(t=>t.id===e);o?.approval&&(u(o.approval)?mn.current?.resolveWebMcpApproval(o.id,t):mn.current?.resolveApproval(o.approval,t,r))};s=n.renderApproval({message:t,defaultRenderer:()=>r.createApprovalBubble(t,o,l),config:o,approve:e=>a("approved",e),deny:e=>a("denied",e)})}if(!a||null!==s){let e=dl(t.id,t.role);return e.setAttribute("data-approval-plugin-stub","true"),e.setAttribute("data-preserve-runtime","true"),d.appendChild(e),void C.push({messageId:t.id,fingerprint:N,bubble:s})}e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),Fa.delete(t.id),H=r.createApprovalBubble(t,o,l)}else if(W)if("reasoning"===t.variant&&t.reasoning&&W.renderReasoning){if(!he)return;H=W.renderReasoning({message:t,defaultRenderer:()=>gl(t,o,s),config:o})}else if("tool"===t.variant&&t.toolCall&&W.renderToolCall){if(!me)return;H=W.renderToolCall({message:t,defaultRenderer:()=>kl(t,o,n),config:o})}else W.renderMessage&&(H=W.renderMessage({message:t,defaultRenderer:()=>{let e=Di(t,r,D,o.messageActions,0,{loadingIndicatorRenderer:c,widgetConfig:o,actionEligibility:L});return"user"!==t.role&&P(e,t,o,wa),e},config:o}));if(!H&&S){let n=dc(t);if(n){let a=Da.get(t.id),s=a!==N,i=!1!==o.wrapComponentDirectiveInBubble&&!1!==Hl.getOptions(n.component)?.bubbleChrome,l=null;if(s){let a=sc(n,{config:o,message:t,transform:r});if(a&&"PersonaArtifactInline"===n.component){let r=a.hasAttribute("data-artifact-inline")?a:a.querySelector("[data-artifact-inline]"),o=r?.getAttribute("data-artifact-inline")??"",n=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(o):o,s=o?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${n}"]`)??null:null;r&&s&&s!==r&&Kl()?.hasLiveInlineArtifactBlock(s)&&(r===a?a=s:r.replaceWith(s))}if(a)if(i){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 o=document.createElement("div");o.className="persona-mb-3 persona-text-sm persona-leading-relaxed",o.innerHTML=r({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(o)}e.appendChild(a),l=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 o=document.createElement("div");o.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",o.innerHTML=r({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(o)}e.appendChild(a),l=e}}if(l||null!=a){let e=dl(t.id,t.role);return e.setAttribute("data-component-directive-stub","true"),e.setAttribute("data-preserve-runtime","true"),d.appendChild(e),void b.push({messageId:t.id,fingerprint:N,bubble:l})}}}if(!H)if("reasoning"===t.variant&&t.reasoning){if(!he)return;H=gl(t,o,s)}else if("tool"===t.variant&&t.toolCall){if(!me)return;H=kl(t,o,n)}else if("approval"===t.variant&&t.approval){if(!1===o.approval)return;let e=M();if(!e)return;H=e.createApprovalBubble(t,o,l)}else{let e=o.layout?.messages;H=e?.renderUserMessage&&"user"===t.role?e.renderUserMessage({message:t,config:o,streaming:!!t.streaming}):e?.renderAssistantMessage&&"assistant"===t.role?e.renderAssistantMessage({message:t,config:o,streaming:!!t.streaming}):Di(t,r,e,o.messageActions,0,{loadingIndicatorRenderer:c,widgetConfig:o,actionEligibility:L}),"user"!==t.role&&H&&P(H,t,o,wa)}let F=dl(t.id,t.role);F.appendChild(H),function(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}(Ha,t.id,N,F),d.appendChild(F)}),st.composerOverlay&&st.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(e=>{let t=e.getAttribute("data-persona-ask-sheet-for");t&&!g.has(t)&&jt(st.composerOverlay,t)}),o.features?.toolCallDisplay?.grouped){let e=[],r=[],s="summary"===o.features.toolCallDisplay.groupedMode;t.forEach(t=>{if("tool"===t.variant&&t.toolCall&&me){if(B&&"complete"===t.toolCall.status&&!t.toolCall.interrupted)return;r.push(t)}else("reasoning"!==t.variant||he&&("complete"!==t.reasoning?.status||!L(t.reasoning)))&&((r.length>1||s&&r.length>0)&&e.push(r),r=[])}),(r.length>1||s&&r.length>0)&&e.push(r),e.forEach(e=>{let t=e.map(e=>Array.from(d.children).find(t=>t instanceof HTMLElement&&t.getAttribute("data-wrapper-id")===e.id)).filter(e=>!!e);if(t.length<(s?1:2))return;let r=dl(`tool-group-${e[0].id}`,"assistant");if(r.setAttribute("data-persona-tool-group-row","true"),"collapsible"===o.features?.toolCallDisplay?.groupedMode){let s=`tool-group-${e[0].id}`,l=e.some(e=>"complete"!==e.toolCall?.status),d={...e[0],id:s,toolCall:{id:s,name:`${e.length} tools`,status:l?"running":"complete",chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>!1===e.toolCall?.success),interrupted:!l&&e.some(e=>e.toolCall?.interrupted)}};a.add(s),i.observe(d,"tool",n,o.features.toolCallDisplay);let c=d.toolCall?.interrupted?`${e.length} tools · Interrupted`:`${l?"Using":"Used"} ${e.length} tools`,p=o.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:c,config:o}),u=ve(d,o,n.has(s),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=`${e.length} ${1===e.length?"tool":"tools"}`,u=e.some(e=>e.toolCall?.interrupted)?`${p} · Interrupted`:`Called ${p}`,h=o.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:u,config:o});((e,t)=>null!=t&&("string"==typeof t?(e.textContent=t,!0):(e.appendChild(t),!0)))(c,h)||(c.textContent=u);let m=document.createElement("div");m.className="persona-tool-group-stack persona-flex persona-flex-col",m.id=`tool-group-stack-${e[0].id}`,m.setAttribute("data-persona-tool-group-stack","true"),l.appendChild(c),s||l.appendChild(m),r.appendChild(l),t[0].before(r),t.forEach((e,r)=>{if(s)return void e.remove();e.style.setProperty("--persona-message-row-max-width","100%");let o=document.createElement("div");o.className="persona-tool-group-item persona-relative",o.setAttribute("data-persona-tool-group-item","true"),r<t.length-1&&o.setAttribute("data-persona-tool-group-connector","true"),o.appendChild(e),m.appendChild(o)})})}i.prune(a),function(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}(Ha,h);let N=e=>"tool"===e.variant&&!me||"reasoning"===e.variant&&!he||R(e),$=t.some(e=>"assistant"===e.role&&e.streaming&&!N(e)),H=t.length-1;for(;H>=0&&N(t[H]);)H--;let W=H>=0?t[H]:void 0,D=H<t.length-1,F="assistant"===W?.role&&!W.streaming&&"approval"!==W.variant&&!D;if($a&&t.some(e=>"user"===e.role)&&!$&&!F){let e={config:o,streaming:!0,location:"standalone",defaultRenderer:Li},t=p.find(e=>e.renderLoadingIndicator),r=null;if(t?.renderLoadingIndicator&&(r=t.renderLoadingIndicator(e)),null===r&&o.loadingIndicator?.render&&(r=o.loadingIndicator.render(e)),null===r&&(r=Li()),r){let e=document.createElement("div"),t=!1!==o.loadingIndicator?.showBubble,n=o.layout?.messages?.layout??"bubble";e.className=t?Ri("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=dl("typing-indicator","assistant");a.appendChild(e),d.appendChild(a)}}if(!$a&&t.length>0){let e=t[t.length-1],r={config:o,lastMessage:e,messageCount:t.length},n=p.find(e=>e.renderIdleIndicator),a=null;if(n?.renderIdleIndicator&&(a=n.renderIdleIndicator(r)),null===a&&o.loadingIndicator?.renderIdle&&(a=o.loadingIndicator.renderIdle(r)),a){let e=document.createElement("div");e.className=!1===o.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=dl("idle-indicator","assistant");t.appendChild(e),d.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)})}(d),as(e,d),Ze(e),T){let{messageId:t,element:r}=T,o=e.querySelector(`#wrapper-${t}`);o&&r.parentElement!==o&&(ll(o,m.get(t)??"user"),o.replaceChildren(r))}if(y.length>0)for(let{messageId:t,fingerprint:r,bubble:o}of y){let n=e.querySelector(`#wrapper-${t}`);n&&(ll(n,m.get(t)??"assistant"),null!==o&&(n.replaceChildren(o),n.setAttribute("data-bubble-fp",r),Wa.set(t,r)))}if(Wa.size>0)for(let e of Wa.keys())h.has(e)||Wa.delete(e);if(b.length>0)for(let{messageId:t,fingerprint:r,bubble:o}of b){let n=e.querySelector(`#wrapper-${t}`);n&&(ll(n,m.get(t)??"assistant"),null!==o&&(n.replaceChildren(o),n.setAttribute("data-bubble-fp",r),Da.set(t,r)))}if(Da.size>0)for(let e of Da.keys())h.has(e)||Da.delete(e);if(C.length>0)for(let{messageId:t,fingerprint:r,bubble:o}of C){let n=e.querySelector(`#wrapper-${t}`);n&&(ll(n,m.get(t)??"assistant"),null!==o&&(n.replaceChildren(o),n.setAttribute("data-bubble-fp",r),Fa.set(t,r)))}if(Fa.size>0)for(let e of Fa.keys())h.has(e)||Fa.delete(e)})(e,t,r),Do()},yl=null,bl=()=>{if(yl)return;let t=e=>{let t=e.composedPath();t.includes(rt)||nt&&t.includes(nt)||Rl(!1,"user")};yl=t,(e.ownerDocument??document).addEventListener("pointerdown",t,!0)},wl=()=>{yl&&=((e.ownerDocument??document).removeEventListener("pointerdown",yl,!0),null)};la.push(()=>wl());let xl=null,Cl=()=>{if(xl)return;let t=e=>{"Escape"===e.key&&(e.isComposing||Rl(!1,"user"))};xl=t,(e.ownerDocument??document).addEventListener("keydown",t,!0)},Al=()=>{xl&&=((e.ownerDocument??document).removeEventListener("keydown",xl,!0),null)};la.push(()=>Al());let Ml=!1,Il=new Set,Tl=()=>o.launcher?.composerBar?.peek?.streamAnimation||o.features?.streamAnimation,El=()=>{if(!ae())return;let t=st.peekBanner,r=st.peekTextNode;if(!t||!r)return;if(le)return void t.classList.remove("persona-pill-peek--visible");let o,n=wa?.getMessages()??[];for(let e=n.length-1;e>=0;e--){let t=n[e];if("assistant"===t.role&&t.content){o=t;break}}if(!o)return void t.classList.remove("persona-pill-peek--visible");let a=o.content,s=!!o.streaming,i=Tl(),l=ys(i),d="none"===l.type?null:ma(l.type,i?.plugins),c=!0===d?.isAnimating?.(o),p=null!==d&&(s||c);p&&d&&!Il.has(d.name)&&(Hs(d,e),Il.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?Ss(a,l.buffer,d,o,s):a;if(!p||"skeleton"!==l.placeholder||!s||m&&m.trim()){let e=Math.max(0,m.length-100),n=m.length>100?m.slice(-100):m,a=He(n);if(p&&d){let s=a;("char"===d.wrap||"word"===d.wrap)&&(s=Ls(a,d.wrap,`peek-${o.id}`,{skipTags:d.skipTags,startIndex:e}));let i=document.createElement("div");if(i.innerHTML=s,d.useCaret&&n.length>0){let e=Ps(),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)}as(r,i),d.onAfterRender?.({container:r,bubble:t,messageId:o.id,message:o,speed:l.speed,duration:l.duration})}else{let e=m.length>100?`…${n}`:n;r.textContent!==e&&(r.textContent=e)}}else{let e=document.createElement("div"),t=Bs();t.classList.add("persona-pill-peek__skeleton"),e.appendChild(t),as(r,e)}let g=$a||Ml;t.classList.toggle("persona-pill-peek--visible",g)};if(ae()){let e=st.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),Rl(!0,"user")};e.addEventListener("pointerdown",t),la.push(()=>{e.removeEventListener("pointerdown",t)})}let t=()=>{Ml||(Ml=!0,El())},r=()=>{Ml&&(Ml=!1,El())};ot.addEventListener("pointerenter",t),ot.addEventListener("pointerleave",r),la.push(()=>{ot.removeEventListener("pointerenter",t),ot.removeEventListener("pointerleave",r)}),nt&&(nt.addEventListener("pointerenter",t),nt.addEventListener("pointerleave",r),la.push(()=>{nt.removeEventListener("pointerenter",t),nt.removeEventListener("pointerleave",r)}))}let Bl=()=>{if(le&&hl(),!ie())return;if(ae()){let e=(o.launcher?.composerBar??{}).expandedSize??"anchored",t=le?"expanded":"collapsed";return rt.dataset.state=t,rt.dataset.expandedSize=e,nt&&(nt.dataset.state=t,nt.dataset.expandedSize=e),rt.style.removeProperty("display"),rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ot.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),(e=>{let t=o.launcher?.composerBar??{},r=t.expandedSize??"anchored",n=t.bottomOffset??"16px",a=t.collapsedMaxWidth,s=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="",nt){let e=nt.style;e.bottom=n,e.width=a??""}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=s,p.maxWidth=c))})(le),it.style.display=le?"flex":"none",_o(),le?(bl(),Cl()):(wl(),Al()),void El()}let t=Xs(o),r=e.ownerDocument.defaultView??window,n=o.launcher?.mobileBreakpoint??640,a=o.launcher?.mobileFullscreen??!0,s=r.innerWidth<=n,i=a&&s&&Q,l=Ys(o).reveal;le?(rt.style.removeProperty("display"),rt.style.display=t?"flex":"",rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ot.classList.remove("persona-scale-95","persona-opacity-0"),ot.classList.add("persona-scale-100","persona-opacity-100"),jp?(jp.setPanelOpen(!0),jp.element.style.display="none"):_p&&(_p.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"),ot.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"),ot.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"),ot.classList.remove("persona-scale-100","persona-opacity-100"),ot.classList.add("persona-scale-95","persona-opacity-0")),jp?(jp.setPanelOpen(!1),jp.element.style.display=t?"none":""):_p&&(_p.style.display=t?"none":""))},Rl=(t,r="user")=>{if(!ie()||le===t)return;let n=le;le=t,Bl();let a=(()=>{let t=o.launcher?.sidebarMode??!1,r=e.ownerDocument.defaultView??window,n=o.launcher?.mobileFullscreen??!0,a=o.launcher?.mobileBreakpoint??640,s=r.innerWidth<=a,i=Xs(o)&&n&&s,l=ae()&&"fullscreen"===(o.launcher?.composerBar?.expandedSize??"fullscreen");return t||n&&s&&Q||i||l})();if(le&&a){if(!da){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&(da=zs(r,o.launcher?.zIndex??1e5))}ca||=_s(e.ownerDocument)}else le||(da?.(),da=null,ca?.(),ca=null);le&&(Gp(),ji()||("follow"===Ut()?Ni(!0):Wi()));let s={open:le,source:r,timestamp:Date.now()};le&&!n?N.emit("widget:opened",s):!le&&n&&N.emit("widget:closed",s),N.emit("widget:state",{open:le,launcherEnabled:Q,voiceActive:Ds.active,streaming:wa.isStreaming()})},Nl={inputDisabled:!1,sendDisabled:!1},Wl=()=>Nl.inputDisabled,Dl=()=>Ce(o.voiceRecognition?.provider)&&!!wa&&(wa.isBargeInActive()||["listening","processing","speaking"].includes(wa.getVoiceStatus())),Fl=()=>Nl.inputDisabled||Nl.sendDisabled;function Ol(){if(!mt)return;if("streaming"===Cr.getState().phase)return void(mt.disabled=!1);let e=!!wr&&!wr.isReady();mt.disabled=Fl()||e}function zl(){if(!Nt)return;let e=Cr.getState(),t="when-text"===o.sendButton?.visibility&&"streaming"!==e.phase&&0===e.text.trim().length&&0===e.attachments.length;Nt.toggleAttribute("data-persona-send-hidden",t)}function ql(){let e=an(o.composer?.inputDisabled),t=an(o.composer?.sendDisabled);Nl={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,a=r||n;ht&&(ht instanceof HTMLTextAreaElement?ht.disabled=n:ht.setAttribute("contenteditable",n?"false":"true"),ht.setAttribute("aria-disabled",n?"true":"false")),Dt&&(Dt.disabled=n),Ot&&(Ot.disabled=n);for(let e of xr?.affordanceButtons??[])e.querySelectorAll("button").forEach(e=>{e.disabled=n});Ht&&(Ht.disabled=n||r&&!Dl()),va.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute("data-disabled",a),e instanceof HTMLButtonElement||e.setAttribute("aria-disabled",a?"true":"false")}),e.buttons.forEach(e=>{e.disabled=a})}),hd.forEach(e=>{e.toggleAttribute("data-disabled",a),e instanceof HTMLButtonElement?e.disabled=a:e.setAttribute("aria-disabled",a?"true":"false"),e.querySelectorAll("button").forEach(e=>{e.disabled=a})}),Tt.dataset.personaComposerStreaming=r?"true":"false",Tt.dataset.personaComposerInputDisabled=n?"true":"false",Tt.dataset.personaComposerSendDisabled=Fl()?"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)}),Ol(),function(){let e=(Nl.inputDisabled?Nl.inputReason:void 0)??(Nl.sendDisabled?Nl.sendReason:void 0);if(ae()){let t=gt??Tt;e?t.setAttribute("title",e):t.removeAttribute("title"),Tt.toggleAttribute(mc,!!e)}else if(e)ft.setAttribute("role","status"),ft.setAttribute("aria-live","polite"),ft.setAttribute(mc,""),ft.removeAttribute(gc),ft.textContent=e,we(ft,o.statusIndicator??{},"idle");else if(ft.hasAttribute(mc)&&(ft.removeAttribute("role"),ft.removeAttribute("aria-live"),ft.removeAttribute(mc),b)){let e=wa.getStatus();et(ft,Ye(e),o.statusIndicator??{},e)}}()}let jl=e=>{Cr.setStreaming(e),$t(e?"stop":"send"),ql()},_l=()=>{Ds.active||ht&&ht.focus()};N.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>_l(),200)});let Ul=null,Xl=!1,Ql=!yt.hidden,Yl=null,rd=!D,od=null;la.push(()=>{od?.cancel(),od=null});let nd,ad,sd=t=>{let r=(e=>(e??[]).some(e=>"user"===e.role)?"active":"empty")(t);if(r===hr)return;hr=r,e.setAttribute("data-persona-conversation-state",r);let o=gr();br(),rd&&(od?.cancel(),od=Ji(Tt,"active"===r?o:gr(),"active"===r?"drop":"rise","centered"===ur().layout?320:260)),sl()},id=null,ld=null,dd=null,cd=!1,pd=e=>{let t=ur(),r=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??"bottom"}|${t.align??""}|${t.iconPlacement}|${t.kicker??""}|${t.title}|${t.subtitle}`;(r!==id||t.icon!==nd)&&(id=r,nd=t.icon,Oi({host:yt,iconHolder:bt,kicker:wt,title:xt,subtitle:Ct,starterSuggestions:ct},t));let n=void 0===t.message?null:`${o.layout?.messages?.layout??"bubble"}|${t.message}`;n!==ld&&(ld=n,Vi(vt,t.message,o));let a=e??(wa?wa.getMessages():o.initialMessages);sd(a);let s=Xl,i=!s&&Zi(t,a),l=i!==Ql;if(Ql=i,dd)return Yl?.cancel(),Yl=null,s!==cd&&(cd=s,s?Ui(lt,yt,null):_i(lt,yt,dd)),void Fi(lt,yt,!s);if(l&&!i&&!s&&"on-first-message"===t.dismiss&&rd)return void(Yl=Gi(yt,e=>{Yl===e&&(Yl=null),!Ql&&!dd&&(Fi(lt,yt,!1),sl()),e?.cancel()}));if(Yl){if(!i&&!s)return;Yl.cancel(),Yl=null}let d=!yt.hidden;Fi(lt,yt,i),!i&&d&&sl()},ud=[],hd=[],md=!1,gd=null,fd=()=>{hd.length=0;let e=ud.splice(0,ud.length);for(let t of e)try{t()}catch(e){console.warn("[persona] renderWelcome cleanup threw",e)}};la.push(fd);let yd=(e,t)=>{let r=ei(e,t);if(!r)return!0===o.debug&&console.warn("[persona] renderStarter received a suggestion with no label"),q("span");let n=o.suggestions?.starters,a=ri({item:{...r,behavior:r.behavior??n?.behavior??"send"},index:t,surface:"starter",source:"config",variant:n?.variant??"card",streaming:!!b&&wa.isStreaming(),config:o,plugins:p,chipsConfig:o.suggestionChipsConfig,session:wa,getTextarea:()=>ht,eventTarget:yt,submitPrompt:Yc});return hd.push(a),a},bd=()=>{if(md)return;md=!0;let e=ur();gd=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`,ad=e.icon;try{fd(),Ui(lt,yt,dd),dd=null,cd=!1;let t=wa?wa.getMessages():o.initialMessages,r=Zi(e,t),n=0,a=null;for(let t of p)if(t.renderWelcome&&(a=t.renderWelcome({config:e,variant:e.variant,visible:r,defaultRenderer:()=>yt,sendMessage:e=>{if(!wa||wa.isStreaming())return;let t=e.trim();t&&wa.sendMessage(t)},requestRender:()=>bd(),renderStarter:e=>yd(e,n++),storage:v(t.id),onCleanup:e=>{ud.push(e)}}),a))break;a&&a!==yt&&(dd=a,_i(lt,yt,a))}finally{md=!1}pd()},vd=()=>{pd(),oo||(ht.placeholder=function(e,t){if(t?.length&&0!==e.length)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}(Cr.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!o.sendButton?.useIcon&&!wa?.isStreaming()&&(mt.textContent=o.copy?.sendButtonLabel??"Send")),ht.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ht.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},wd=!!o.setStoredConversationId,xd=e=>K(t=>{let r={...t};return delete r[e],r}),kd=e=>{let t=W[e];return"string"==typeof t?t:null},Ad=()=>{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};o.clientToken&&(o={...o,getStoredSessionId:()=>kd("sessionId"),setStoredSessionId:e=>{K(t=>({...t,sessionId:e}))},clearStoredSessionId:o.clearStoredSessionId??(()=>xd("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>kd("conversationId")),setStoredConversationId:o.setStoredConversationId??(e=>{K(t=>({...t,conversationId:e}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>xd("conversationId"))});let Md=()=>o.clientToken??null,Id=e=>Vd(e,ke(),!1===o.persistState),Td=Md(),Bd=Td?Id(Td):null,Rd={...Bd?{visitorStore:Bd}:{},historyBootstrapReady:!0!==o.features?.history?.enabled||oc()?F:Promise.all([F,j]).then(()=>{}),getStoredMessageCursor:()=>kd("historyMessageCursor"),setStoredMessageCursor:e=>{null===e?xd("historyMessageCursor"):K(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?K(t=>({...t,pendingDisplayProjections:e})):xd("pendingDisplayProjections")},getStoredResumableHandle:Ad,setStoredResumableHandle:e=>{e?K(t=>({...t,durableResume:e})):xd("durableResume")},shouldResumeDurableConversation:()=>H&&null!==Ad(),...wd?{}:{getStoredConversationRevision:()=>kd("conversationRevision"),setStoredConversationRevision:e=>{null===e?xd("conversationRevision"):K(t=>({...t,conversationRevision:e}))}}};if(H){let t=o.onExecutionState,r=e.ownerDocument.defaultView,n=!1,a=()=>n=!0,s=()=>n=!1;r?.addEventListener("pagehide",a),r?.addEventListener("pageshow",s),la.push(()=>{r?.removeEventListener("pagehide",a),r?.removeEventListener("pageshow",s)}),o={...o,reconnectStream:o.reconnectStream??(e=>wa.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!n)&&Rd.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let Nd=()=>{let e=Md();if(e&&Bd?.matches(e,ke(),!1===o.persistState)||!e&&!Bd)return;Bd?.destroy(),Bd=e?Id(e):null;let t={...Rd};Bd?t.visitorStore=Bd:delete t.visitorStore,Rd=t,wa.setHistoryInternals(Rd)},Wd=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,o=t,n=Object.keys(r),a=Object.keys(o);return n.length===a.length&&n.every(e=>Object.prototype.hasOwnProperty.call(o,e)&&Fd(r[e],o[e]))},zd=e=>{let{content:t,rawContent:r,llmContent:o,...n}=e;return n},qd=e=>!("assistant"!==e.role||!0!==e.streaming||e.variant||e.toolCall||e.tools||e.approval||e.reasoning||e.contentParts||e.stopReason||lc(e)),Ud=null,Kd=null,Gd=null,Jd=null,Qd=null,Yd=e=>{let t,r;Ud=e,Kd=null;for(let o=e.length-1;o>=0;--o){let n=e[o];if(!t&&"user"===n.role&&(t=n),!r&&"assistant"===n.role&&(r=n),!Kd&&qd(n)&&(Kd={index:o,id:n.id}),t&&r&&Kd)break}fl(dt,e,ue),Kl()?.updateInlineArtifactBlocks(dt,Go.artifacts,{suppressTransition:$a}),Wd??=setInterval(()=>{let e=dt.querySelectorAll("[data-tool-elapsed]");if(0===e.length)return clearInterval(Wd),void(Wd=null);let t=Date.now();e.forEach(e=>{let r=Number(e.getAttribute("data-tool-elapsed"));r&&(e.textContent=e.closest(".persona-activity-row")?ye(t-r):sr(t-r))})},100),pd(e),Ra(e),Ni(!$a),(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&&(N.emit("assistant:message",e),!ms&&("anchor-top"!==Ut()||Yt())&&Mi()&&(ns+=1,Ci(),Ei(),cr(1===ns?"1 new message below.":`${ns} new messages below.`))),"assistant"===e.role&&r?.streaming&&!1===e.streaming&&N.emit("assistant:complete",e),"approval"===e.variant&&e.approval&&(r?"pending"!==e.approval.status&&N.emit("approval:resolved",{approval:e.approval,decision:e.approval.status}):N.emit("approval:requested",{approval:e.approval,message:e}))}),Rs.clear(),t.forEach((e,t)=>{Rs.set(t,e)})})(e),0===e.length&&(Qi(),fs=!0,bs=!1,vs=null,ks=!1),!hs||ms?(hs=!0,gs=t?.id??null,Ms=r?.id??null):t&&t.id!==gs?(gs=t.id,(e=>{let t=Ut();"follow"===t?(Bi(),Ni(!0)):"anchor-top"===t&&(fs=!1,bs=!0,ks=!1,vs=e,al(e))})(t.id)):r&&r.id!==Ms&&"anchor-top"===Ut()&&(bs?fs=!1:(fs=!0,Qi(),Bi(),Ni(!0))),r&&(Ms=r.id),(e=>{if("anchor-top"!==Ut()||!bs||ks||qi())return;let t=null===gs;for(let r of e)if(t){if(is(r)){if(r.id===vs||!il(r.id))return;return vs=r.id,void al(r.id)}}else r.id===gs&&(t=!0)})(e);let o=Ds.lastUserMessageId;t&&t.id!==o&&(Ds.lastUserMessageId=t.id,N.emit("user:message",t)),Ds.lastUserMessageWasVoice=!!t?.viaVoice,(e=>{if(!H)return ai(e);Qd=e,queueMicrotask(()=>{Qd===e&&(Qd=null,ai(e))})})(e),El()},Zd=()=>{null!==Jd&&(cancelAnimationFrame(Jd),Jd=null);let e=Gd;Gd=null,e&&Yd(e)},ec=()=>{null!==Jd&&cancelAnimationFrame(Jd),Jd=null,Gd=null};wa=new Po(o,{onMessagesChanged(e){(e=>{let t=Gd??Ud;$a&&t&&Kd&&((e,t,r)=>{if(e.length!==t.length)return!1;let o=e[r.index],n=t[r.index];return!(!o||!n||o.id!==r.id||n.id!==r.id)&&(!Object.is(o.content,n.content)||!Object.is(o.rawContent,n.rawContent)||!Object.is(o.llmContent,n.llmContent))&&qd(o)&&qd(n)&&Fd(zd(o),zd(n))})(t,e,Kd)?(Gd=e,null===Jd&&(Jd=requestAnimationFrame(()=>{Jd=null;let e=Gd;Gd=null,e&&Yd(e)}))):0===e.length?(ec(),Yd(e)):(Zd(),Yd(e))})(e)},onStatusChanged(e){let t=o.statusIndicator??{};et(ft,(e=>"idle"===e?t.idleText??Pr.idle:"connecting"===e?t.connectingText??Pr.connecting:"connected"===e?t.connectedText??Pr.connected:"error"===e?t.errorText??Pr.error:"paused"===e?t.pausedText??Pr.paused:"resuming"===e?t.resumingText??Pr.resuming:Pr[e])(e),t,e),Je()},onStreamingChanged(e){e||(0===wa?.getMessages().length?ec():Zd()),$a=e,jl(e),Je(),wa&&fl(dt,wa.getMessages(),ue),e||(Ni(!0),(()=>{if(!ps||ps.spacerHeight<=0)return;let e=Xi(ps.spacerHeight),t=Math.max(0,Math.round(lt.scrollTop)+lt.clientHeight-e+24);t<ps.spacerHeight&&(Ki(t),Ei())})(),Pa=!0,wa&&Ba(wa.getMessages(),Qt(o))),Ei(),cr(e?"Responding…":"Response complete."),El()},onVoiceStatusChanged(e){if(N.emit("voice:status",{status:e,timestamp:Date.now()}),"disconnected"!==e&&!Ce(o.voiceRecognition?.provider))return;let t=wa.getVoiceNotice();switch(t&&Gc(t,1e4),e){case"listening":if(!Ns){let e=wa.getVoiceDisclosure();e&&(Ns=!0,ae()?(Ws=ht.placeholder,ht.placeholder=e,cr(e)):Gc(e,1e4))}Tp(),Ap();break;case"processing":Tp(),Mp();break;case"speaking":Tp(),Ip();break;default:"idle"===e&&wa.isBargeInActive()?(Tp(),Ap(),Ht?.setAttribute("aria-label","End voice session")):(Ds.active=!1,Ns=!1,null!==Ws&&(ht.placeholder=Ws,Ws=null),Tp(),Us("system"),js||Vs())}},onArtifactsState(e){Go=e,0===e.artifacts.length&&(dn=!1),Kl()?.updateInlineArtifactBlocks(dt,e.artifacts,{suppressTransition:$a}),Yn(),ai()},onHistoryStateChanged(e){Ke(e)},onHistoryNotice(e){Ge(e)},onReconnect(e){let{executionId:t,lastEventId:r}=e.handle;"paused"===e.phase?N.emit("stream:paused",{executionId:t,after:r}):"resuming"===e.phase?N.emit("stream:resuming",{executionId:t,after:r,attempt:e.attempt??1}):N.emit("stream:resumed",{executionId:t,after:r})}},Rd),mn.current=wa,la.push(()=>wa.cancel()),la.push(()=>{wa.destroy(),Bd?.destroy(),Bd=null});let tc=null;if(wa.onReadAloudChange((e,t)=>{Ro=e,No=t,Do();let r=e??tc;e&&(tc=e);let o=r?wa.getMessages().find(e=>e.id===r)??null:null;N.emit("message:read-aloud",{messageId:r,message:o,state:t,timestamp:Date.now()}),"idle"===t&&(tc=null)}),b=!0,hs=!0,!0===o.voiceRecognition?.enabled&&Ce(o.voiceRecognition.provider))try{wa.setupVoice()}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",e)}let ac=null,ic=null,cc=!1,fc=wa.getHistoryState(),Sc=()=>!0===o.features?.history?.enabled,Ac=e=>{e&&(ir.textContent="",ir.textContent=e)},Mc=()=>{f.forEach(e=>e()),f=[];let t=ac,r=t?.railCollapseShortcut();t&&r&&f.push(h.register({id:"history-rail-collapse",combo:r.combo,scope:"page"===o.features?.history?.rail?.collapseShortcutScope?"page":"widget",when:()=>je&&"rail"===_e&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of o.layout?.header?.trailingActions??[])t.shortcut&&f.push(h.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let r=e.querySelector(`[data-persona-header-action="${t.id}"]`);r?r.click():o.layout?.header?.onAction?.(t.id)}}));for(let e of p)for(let t of e.shortcuts??[])f.push(h.register({...t,id:`${e.id}:${t.id}`}))};Mc();let Ic=null,Tc=!1,Ec=()=>{if(!At)return;let e="conversation"===o.layout?.header?.titleSource,t=e&&Ic?.trim()||null;At.textContent=t??o.launcher?.title??"Chat Assistant";let r=At.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 a=r.querySelector("svg");a&&(a.style.display=n?"":"none")};Ec(),it.addEventListener("persona:title-menu-builtin",e=>{let t=e.detail?.actionId,r=wa.getActiveConversationId();r&&("delete"===t?Rc(e=>e.requestDeleteConversation(r)):"star"===t&&wa.canUpdateConversations()&&Rc(e=>e.updateHistoryConversation(r,{starred:!Tc})).catch(()=>{}))}),Ke=e=>{fc=e,ac?.historySurface?.view.setNewConversationRequired("new_conversation_required"===e.recovery),jl(e.sendBlocked||$a),ac?.syncEarlierMessagesPill()},Ge=e=>{("history_continuity_reset"===e.code||"conversation_deleted_recovered"===e.code)&&(Ha.clear(),Qi(),Bi()),Ac(e.message),ac?.historySurface?.view.refresh()};let Lc={get actionManager(){return X},get activeConversationTitle(){return Ic},announceHistory:Ac,get applyRailChrome(){return Ve},set applyRailChrome(e){Ve=e},get artifactSplitRoot(){return kn},get body(){return lt},get config(){return o},get container(){return it},get conversationOpenPendingEl(){return Ul},set conversationOpenPendingEl(e){Ul=e},get conversationOpenTakeover(){return Xl},set conversationOpenTakeover(e){Xl=e},currentKeyPrefix:ke,destroyCallbacks:la,eventBus:N,get footer(){return Tt},get header(){return It},get historyChromeSync(){return Je},set historyChromeSync(e){Je=e},historyFeatureEnabled:Sc,get historyInternals(){return Rd},set historyInternals(e){Rd=e},get historyPresentation(){return _e},set historyPresentation(e){_e=e},get historySessionState(){return fc},get historyVisible(){return je},set historyVisible(e){je=e},get isStreaming(){return $a},jumpToBottomInstant:Wi,get lastAppliedMessages(){return Ud},set lastAppliedMessages(e){Ud=e},get launcherEnabled(){return Q},get launcherSurfaceInstance(){return jp},maybeFocusInput:_l,messageCache:Ha,get messagesWrapper(){return dt},mount:e,get open(){return le},panel:ot,panelElements:st,get persistentMetadata(){return W},set persistentMetadata(e){W=e},plugins:p,get reapplyHistoryHostChrome(){return Ue},set reapplyHistoryHostChrome(e){Ue=e},repinAnchoredMessage:sl,resetAnchorState:Qi,restoreScrollPosition:ji,resumeAutoScroll:Bi,runStorageMutation:ti,get session(){return wa},setActiveConversationSummary:e=>{Tc=!0===e?.starred,(e=>{e!==Ic&&(Ic=e,Ec())})(e&&e.title.trim()||null),Ec()},storageAdapter:$,get suppressScrollSend(){return ms},set suppressScrollSend(e){ms=e},syncScrollToBottomButton:Ei,updateWelcome:pd,getHistoryProviderFactory:nc,historyErrors:{HistoryClientError:Br,HistoryProviderError:Fr},isDockedMountMode:Xs,renderLucideIcon:se,loadHistoryView:Xd,createHeaderIconButton:li,attachTooltip:Xo},Pc=e=>(!ac&&!cc&&(ac=e.createHistoryShell(Lc),ac.railCollapseShortcut()&&Mc()),ac),Bc=()=>{if(ac)return Promise.resolve(ac);let e=oc();return e?Promise.resolve(Pc(e)):(ic??=rc().then(Pc,e=>{throw ic=null,e}),ic)},Rc=e=>{let t=oc(),r=ac??(t?Pc(t):null);return r?e(r):Bc().then(t=>{if(!t)throw Error("[AgentWidget] The widget was destroyed");return e(t)})},Nc=()=>{ac?.syncHistoryPresentation()};la.push(()=>{cc=!0}),Sc()&&Bc().catch(()=>{}).finally(O),o.clientToken&&(!0===o.features?.history?.enabled||"mount"===o.sessionInit)&&wa.initClientSession().then(()=>{let e=ac;if(e?.historyAvailable())return wa.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{ac?.syncEarlierMessagesPill()}).catch(e=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",e)});let $c=()=>wa.warmClientSession(),Hc=e=>{let t=o.sessionInit??"input",r=co?.input??ht,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:(co?.form??gt)?.contains(n)))&&$c()},Wc=["input","pointerdown","keyup"];Wc.forEach(t=>e.addEventListener(t,Hc));let Dc,Fc,Oc=()=>{let e=Fc;Fc=void 0;try{"function"==typeof e&&e()}catch{}},zc=()=>{let t=o.clientToken&&"function"==typeof o.sessionInit?o.sessionInit:void 0;if(t!==Dc){Oc(),Dc=t;try{Fc=t?.({warm:$c,mount:e})}catch{}}};zc(),la.push(()=>{Wc.forEach(t=>e.removeEventListener(t,Hc)),Oc()}),(ge||o.onSSEEvent)&&wa.setSSEEventCallback((e,t)=>{o.onSSEEvent?.(e,t),ze(e,t)});let qc=()=>{let e=o.resume??(H?Rd.getStoredResumableHandle?.():null);e&&"function"==typeof o.reconnectStream&&wa.resumeFromHandle(e)};D?D.then(e=>{if(e){if(e.metadata&&(W=vc(e.metadata),X.syncFromMetadata()),e.messages?.length){ms=!0;try{wa.hydrateMessages(e.messages)}finally{ms=!1}hl()}e.artifacts?.length&&wa.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),fi(e.draft)}}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",e)}).finally(()=>{rd=!0,B(),qc()}):(fi(R),qc());let jc=()=>{let e=ht.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>"mention"===e.kind)?e.contentSegments:void 0},_c=!1,Uc=null,Vc=()=>{ht.value="",ht.style.height="auto",kr(),op()},Kc=null;function Gc(e,t=4e3){cr(e),!ae()&&ft&&(ft.hasAttribute(mc)||(ft.setAttribute(gc,""),ft.setAttribute("role","status"),ft.setAttribute("aria-live","polite"),ft.textContent=e,we(ft,o.statusIndicator??{},"idle"),Kc&&clearTimeout(Kc),Kc=setTimeout(()=>{if(Kc=null,ft?.hasAttribute(gc)&&(ft.removeAttribute(gc),ft.removeAttribute("role"),ft.removeAttribute("aria-live"),b)){let e=wa.getStatus();et(ft,Ye(e),o.statusIndicator??{},e)}},t)))}let Jc=(e={})=>{let t=(e.overrideText??ht?.value??"").trim();return e.resolveInlineCommand&&t?(xr?.takeInlineCommand(t)??Promise.resolve(null)).then(r=>Xc(e,t,r)):Xc(e,t,null)},Xc=(e,t,r)=>{if("action"===r?.kind)return Vc(),xr?.clear(),void Mr();let n="server"===r?.kind?r.mentions:null,a="prompt"===r?.kind?r.sendText:t,s=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:a,hasAttachments:(wr?.hasAttachments()??!1)||(s?.length??0)>0,attachmentsReady:wr?.isReady()??!0,hasMentions:xr?.hasMentions()??!1,hasServerMentions:!!n,inputDisabled:Wl(),sendDisabled:Fl()}))return;let i=wa.isStreaming()?_r():"block";if("defer-one"===i&&!e.pending)return Cr.getState().pendingSubmission?void Gc("One message is already queued. Edit or remove it first."):void function(e){let t=Cr.getState(),r=wr?.hasAttachments()??!1,o=r?[...wr.getContentParts()]:[];r&&e.sendText&&o.push(Sr(e.sendText)),Gr(Jn({text:e.sendText,contentParts:o.length?o:void 0,mentionRefs:[...xr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:jc(),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&&Vc(),r&&wr.clearAttachments(),xr?.clear(),Mr(),t.quote&&qr(void 0),yi(),Ao.release(),Io(),cr("Message queued. It sends when the response finishes.")}({intent:e,sendText:a,serverMentions:n});let l={text:a,mentionRefs:[...xr?.getMentionRefs()??[],...n?.refs??[]],contentSegments:"prompt"===r?.kind?void 0:jc(),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(s?.length)return[...s];if(!wr?.hasAttachments())return;let e=[...wr.getContentParts()];return l.text&&e.push(Sr(l.text)),e};l.contentParts=d();let c=()=>{Ja(),ae()&&(le||(o.launcher?.composerBar?.expandOnSubmit??1)&&Rl(!0,"auto"));let t=xr?.collectForSubmit()??null,r=((e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[r,o]=await Promise.allSettled([e.finalize(),t.finalize()]),n=[];return"fulfilled"===r.status?n.push(r.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",r.reason),"fulfilled"===o.status?n.push(o.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",o.reason),kc(n)}}:e:t)(t,n),a=d();!1!==e.consumeDraft&&Vc();let s={selectedModelId:l.options.selectedModelId,activeModeIds:l.options.activeModeIds},c="interrupt"===i;c&&wa.cancel(),wa.sendMessage(l.text,{contentParts:a,mentions:r??void 0,contentSegments:l.contentSegments,viaVoice:l.viaVoice,composerOptions:s,...l.options.quote&&{quote:l.options.quote},...c&&{interrupt:!0}}),wr?.hasAttachments()&&wr.clearAttachments(),t&&xr?.clear(),Mr();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,o.composer?.modes);u.length!==p.length&&Nr(u),Cr.getState().quote&&qr(void 0),yi(),Ao.release(),Io()},p=o.composer?.onBeforeSend;if(!p)return void c();let u=new AbortController;Uc=u;let h=e=>{Uc=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=Qn(p,l,u.signal);if(m instanceof Promise)return Cr.setPreparing(!0),m.then(h).finally(()=>Cr.setPreparing(!1));h(m)};Fo={regenerate:function(e){if(wa.isStreaming())return;let t=io(wa.getMessages(),e);t&&(Ja(),wa.resubmitFrom(t,{reason:"retry"})&&sl())},edit:function(e){if(!0!==o.messageActions?.showEdit)return;let t=wa.getMessages().find(t=>t.id===e);t&&lo(t)&&Oa!==e&&(Ja(),Oa=e,za=Gn({messageId:e,initialText:t.content,onSave:t=>function(e,t){let r=za;Oa=null,za=null,r?.destroy(),Ha.delete(e),wa.resubmitFrom(e,{reason:"edit",replacement:{text:t,mentionRefs:[],options:{}}})?sl():fl(dt,wa.getMessages(),ue)}(e,t),onCancel:()=>Ja()}),Ha.delete(e),fl(dt,wa.getMessages(),ue),za.focus())},quote:e=>{let t=wa.getMessages().find(t=>t.id===e)?.content?.trim();t&&(qr({text:t,messageId:e}),ht?.focus())}};let Qc=async e=>{if(!_c){_c=!0;try{await Jc({resolveInlineCommand:!0,...e})}finally{_c=!1}}};function Yc(e){Fl()||(Vc(),Zc(e,{consumeDraft:!1}))}let Zc=(e,t)=>{if(_c)return;_c=!0;let r=()=>{_c=!1};try{let o=Jc({...t,overrideText:e});o instanceof Promise?o.finally(r):r()}catch(e){throw r(),e}},ep=e=>{e.preventDefault(),wa.isStreaming()?(wa.cancel(),Be?.reset(),$e?.update()):_c||Qc()},tp={...ss},rp=!1,op=()=>{tp={...ss}},np=e=>{"Escape"!==e.key||e.isComposing||e.composedPath().includes(it)&&(Uc?(Uc.abort(),Uc=null,e.preventDefault(),e.stopImmediatePropagation()):wa.isStreaming()&&(wa.cancel(),Be?.reset(),$e?.update(),op(),e.preventDefault(),e.stopImmediatePropagation()))},ap=null,sp=!1,ip=null,lp=null,dp=()=>"review"===o.voiceRecognition?.completionBehavior;function cp(e){Ht?.setAttribute("data-state",e),"recording"===e?function(){if(null!==hp)return;if("function"!=typeof requestAnimationFrame)return void yp(b?wa.getVoiceLevel()??up:up);let e=()=>{hp=requestAnimationFrame(e);let t=b?wa.getVoiceLevel():null;null===t?yp(up):(gp+=.3*(t-gp),yp(gp))};hp=requestAnimationFrame(e)}():vp()}let pp="--persona-voice-level",up=.5,hp=null,mp=-1,gp=0,fp=()=>{let e=[],t=Wt??Ht?.parentElement??null;return t&&e.push(t),Tt&&e.push(Tt),e},yp=e=>{let t=Math.round(100*Math.max(0,Math.min(1,e)))/100;if(t!==mp){mp=t;for(let e of fp())e.style.setProperty(pp,String(t))}},bp=()=>{mp=-1,gp=0;for(let e of fp())e.style.removeProperty(pp)};function vp(){null!==hp&&(cancelAnimationFrame(hp),hp=null),bp()}let wp=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,xp=(e="user")=>{if(sp||wa.isStreaming())return;let t=wp();if(!t)return;ap=new t;let r=o.voiceRecognition??{},n=r.pauseDuration??2e3;ap.continuous=r.provider?.browser?.continuous??!0,ap.interimResults=!0,ap.lang=r.provider?.browser?.language??"en-US";let a=ht.value;ap.onresult=e=>{let t="",r="";for(let o=0;o<e.results.length;o++){let n=e.results[o],a=n[0].transcript;n.isFinal?t+=a+" ":r=a}let o=a+t+r;ht.value=o,kr(),ip&&clearTimeout(ip),(t||r)&&(ip=window.setTimeout(()=>{if(ht.value.trim()&&ap&&sp){if(Cp(),dp())return;Qc({viaVoice:!0})}},n))},ap.onerror=e=>{"no-speech"!==e.error&&Cp()},ap.onend=()=>{if(sp){let e=ht.value.trim();!dp()&&e&&e!==a.trim()&&Qc({viaVoice:!0}),Cp()}};try{if(ap.start(),sp=!0,Ds.active=!0,"system"!==e&&(Ds.manuallyDeactivated=!1),Us(e),Vs(),Io(),Ht){let e=o.voiceRecognition??{};lp={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"),cp("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{Cp("system")}},Cp=(e="user")=>{if(sp){if(sp=!1,ip&&=(clearTimeout(ip),null),ap){try{ap.stop()}catch{}ap=null}if(Ds.active=!1,Us(e),Vs(),Io(),Ht){if(Ht.classList.remove("persona-voice-recording"),cp("idle"),lp){Ht.style.backgroundColor=lp.backgroundColor,Ht.style.color=lp.color,Ht.style.borderColor=lp.borderColor;let e=Ht.querySelector("svg");e&&e.setAttribute("stroke",lp.color||"currentColor"),lp=null}Ht.setAttribute("aria-label","Start voice recognition")}}},Sp=null,kp=e=>{let t=t=>{Sp??=t.createMicStateStyles({mic:()=>Ht,config:()=>o,session:()=>wa,get original(){return lp},set original(e){lp=e},setMicState:cp,renderIcon:se,iconFallbackPx:24}),e(Sp)},r=vo();r?t(r):bo().then(t,()=>{})},Ap=()=>kp(e=>e.recording()),Mp=()=>kp(e=>e.processing()),Ip=()=>kp(e=>e.speaking()),Tp=()=>kp(e=>e.reset()),Ep=()=>{if(!Wl())if(Ce(o.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(()=>{Ds.active=!1,Ds.manuallyDeactivated=!0,Vs(),Us("user"),Tp()});wa.toggleVoice().then(()=>{Ds.active=qs(),Ds.manuallyDeactivated=!Ds.active,Vs(),Us("user"),Ds.active?Ap():Tp()})}else if(sp){let e=ht.value.trim();Ds.manuallyDeactivated=!0,Vs(),Cp("user"),e&&!dp()&&Qc()}else Ds.manuallyDeactivated=!1,Vs(),xp("user")};Xr=Ep;let Lp=()=>wa.prewarmVoice(),Pp=()=>{let e=o.voiceRecognition;return!0===e?.enabled&&(e.prewarm??(!!o.clientToken&&"hover"))},Bp=e=>{"hover"===Pp()&&Ht?.contains(e.target)&&Lp()},Rp=["pointerover","pointerdown","focusin"];Rp.forEach(t=>e.addEventListener(t,Bp));let Np,$p,Hp=null,Wp=()=>{let e=$p;$p=void 0;try{"function"==typeof e&&e()}catch{}},Dp=()=>{let t=Pp(),r="function"==typeof t&&Ht?t:void 0,o=r?Ht:null;if((r!==Np||o!==Hp)&&(Wp(),Np=r,Hp=o,r&&o))try{$p=r({warm:Lp,micButton:o,mount:e})}catch{}};Dp(),la.push(()=>{Rp.forEach(t=>e.removeEventListener(t,Bp)),Wp()}),Ht&&la.push(()=>{Ce(o.voiceRecognition?.provider)?(wa.isVoiceActive()&&wa.toggleVoice(),Tp()):Cp("system")});let Fp=N.on("assistant:complete",()=>{Cr.getState().pendingSubmission&&setTimeout(()=>{wa.isStreaming()||function(){let e=Cr.getState().pendingSubmission;e&&(Gr(void 0),Zc(e.text,{consumeDraft:!1,pending:e}))}()},0)});la.push(Fp);let Op=N.on("assistant:complete",()=>{Fs&&(Ds.active||Ds.manuallyDeactivated||("assistant"!==Fs||Ds.lastUserMessageWasVoice)&&setTimeout(()=>{!Ds.active&&!Ds.manuallyDeactivated&&(Ce(o.voiceRecognition?.provider)?wa.toggleVoice().then(()=>{Ds.active=wa.isVoiceActive(),Us("auto"),wa.isVoiceActive()&&Ap()}):xp("auto"))},600))});la.push(Op);let zp=N.on("action:resubmit",()=>{setTimeout(()=>{wa&&!wa.isStreaming()&&wa.continueConversation()},100)});la.push(zp);let qp=()=>{Rl(!le,"user")},jp=null,_p=null;if(Q&&!ae()){let{instance:e,element:t}=ul({config:o,plugins:p,onToggle:qp});jp=e,e||(_p=t)}jp?e.appendChild(jp.element):_p&&e.appendChild(_p),Bl(),Ra(),vd(),bd(),jl(wa.isStreaming()),ji()||("follow"===Ut()?Ni(!0):Wi()),(()=>{if(!1===o.voiceRecognition?.enabled)return;let e=vc(W.voiceState),t=!!e.active,r=Number(e.timestamp??0);Ds.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-r<3e4&&setTimeout(()=>{Ds.active||(Ds.manuallyDeactivated=!1,Ce(o.voiceRecognition?.provider)?wa.toggleVoice().then(()=>{Ds.active=qs(),Us("restore"),Ds.active?Ap():(Vs(),Gc("Tap the mic to resume your voice call",1e4))}):xp("restore"))},Ce(o.voiceRecognition?.provider)?0:1e3)})(),Z&&(!Q||ae()?setTimeout(()=>_l(),0):le&&setTimeout(()=>_l(),200));let Up=null,Vp=()=>{Up&&(Up.disconnect(),Up.observe(Tt),Up.observe(it),Up.observe(yt))},Kp=pr(),Gp=()=>{if(ae())return fr(),void Bl();let t=Xs(o),r=o.launcher?.sidebarMode??!1,n=e.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,s=o.launcher?.mobileBreakpoint??640,i=n.innerWidth<=s,l=a&&i&&Q;try{if(l)return _o(),void(Vo=Xn());let e=!1;ne&&(ne=!1,_o(),e=!0);let n=Xn();if(!e&&n!==Vo&&(_o(),e=!0),Vo=n,e&&Tn(),!Q&&!t)return ot.style.height="",void(ot.style.width="");if(!r&&!t){let e=tl(o);ot.style.width=e.width,ot.style.maxWidth=e.maxWidth}Wn(),ia()}finally{fr(),br();let t=pr();if(t!==Kp&&(Kp=t,pd(),Ra()),Bl(),le&&Q){let t=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),r=o.launcher?.sidebarMode??!1,n=o.launcher?.mobileFullscreen??!0,a=Xs(o)&&n&&t,s=r||n&&t&&Q||a;if(s&&!ca){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&!da&&(da=zs(r,o.launcher?.zIndex??1e5)),ca=_s(e.ownerDocument)}else s||(da?.(),da=null,ca?.(),ca=null)}}};Gp();let Jp=e.ownerDocument.defaultView??window;if(Jp.addEventListener("resize",Gp),la.push(()=>Jp.removeEventListener("resize",Gp)),typeof ResizeObserver<"u"){Up=new ResizeObserver(()=>{br()}),Vp(),la.push(()=>{Up?.disconnect(),Up=null});let e=new ResizeObserver(()=>{Nc()});e.observe(it),la.push(()=>e.disconnect())}Jp.addEventListener("resize",Nc),la.push(()=>Jp.removeEventListener("resize",Nc)),Za=lt.scrollTop;let Xp=ls(lt),Qp=()=>{oa();let e=lt.scrollTop,t=ls(lt),r=t<Xp;if(Xp=t,!Vt())return Za=e,void Ei();let{action:o,nextLastScrollTop:n}=function(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:l=!0,resumeRequiresDownwardScroll:d=!1}=e,c=r-o;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:r}:!t&&n&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:r}:t&&i&&c<0||t&&l&&!n?{action:"pause",delta:c,nextLastScrollTop:r}:{action:"none",delta:c,nextLastScrollTop:r}}({following:Ya.isFollowing(),currentScrollTop:e,lastScrollTop:Za,nearBottom:ds(lt,24),userScrollThreshold:4,isAutoScrolling:ts||rs||r,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});Za=n,"resume"===o?qi()||Bi():"pause"===o&&Pi()};if(lt.addEventListener("scroll",Qp,{passive:!0}),la.push(()=>lt.removeEventListener("scroll",Qp)),typeof ResizeObserver<"u"){let e=new ResizeObserver(()=>{(()=>{if(Vt()){if(!Ya.isFollowing()||ds(lt,1))return;Ni(!$a)}else{if(ps&&ps.initialSpacerHeight>0){let e=lt.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&&Ki(t)}Ei()}})(),Ze(dt)});e.observe(dt),e.observe(lt),la.push(()=>e.disconnect())}let Yp=()=>{Vt()&&Ya.isFollowing()&&qi()&&Pi()},Zp=lt.ownerDocument;Zp.addEventListener("selectionchange",Yp),la.push(()=>{Zp.removeEventListener("selectionchange",Yp)});let eu=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),tu=e=>{eu.has(e.key)&&(As(),Xt()&&Vt()&&Ya.isFollowing()&&Pi())},ru=e=>{e.target?.closest("a, button, [tabindex], input, textarea, select")&&(As(),Xt()&&Vt()&&Ya.isFollowing()&&Pi())};lt.addEventListener("keydown",tu),lt.addEventListener("focusin",ru),la.push(()=>{lt.removeEventListener("keydown",tu),lt.removeEventListener("focusin",ru)});let ou=e=>{if(0!==e.deltaY&&As(),!Vt())return;let t=function(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}({following:Ya.isFollowing(),deltaY:e.deltaY,nearBottom:ds(lt,24),resumeWhenNearBottom:!0});"pause"===t?Pi():"resume"===t&&!qi()&&Bi()};lt.addEventListener("wheel",ou,{passive:!0}),lt.addEventListener("touchmove",As,{passive:!0}),lt.addEventListener("pointerdown",As,{passive:!0}),la.push(()=>{lt.removeEventListener("touchmove",As),lt.removeEventListener("pointerdown",As)}),la.push(()=>lt.removeEventListener("wheel",ou)),tr.addEventListener("click",()=>{Qi(),lt.scrollTop=lt.scrollHeight,Za=lt.scrollTop,Bi(),Ni(!0),Ei()}),la.push(()=>tr.remove()),la.push(()=>{xi(),Qi()});let nu=()=>{St&&(xa&&=(St.removeEventListener("click",xa),null),ie()?(St.style.display="",xa=()=>{Rl(!1,"user")},St.addEventListener("click",xa)):St.style.display="none")};nu(),(()=>{let{clearChatButton:e}=st;e&&e.addEventListener("click",()=>{let e=ac;if(e?.historyAvailable())return void e.startNewConversation({focusComposer:!0}).catch(e=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",e)});wa.clearMessages(),o.layout?.topFade&&(lt.scrollTop=0),lt.removeAttribute("data-persona-top-fade"),Ha.clear(),Bi(),jt(st.composerOverlay);try{localStorage.removeItem(hc),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${hc}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==hc)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.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),$?.clear&&ti(()=>$.clear(),"[AgentWidget] Failed to clear storage adapter:"),W={},X.syncFromMetadata(),wr?.clearAttachments(),yi(),Gr(void 0),qr(void 0),Ja(),Te?.clear(),Be?.reset(),$e?.update()})})();let au=[["keydown",e=>{if(ht&&!Wl()&&(e.isComposing||!xr?.handleKeydown(e))){if(!(!1===o.features?.composerHistory||"ArrowUp"!==e.key&&"ArrowDown"!==e.key||e.shiftKey||e.metaKey||e.ctrlKey||e.altKey||e.isComposing)){let t=0===ht.selectionStart&&0===ht.selectionEnd,r=function(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=-1!==a.index;if(0===r.length)return{handled:!1,state:a};if("up"===t){if(!s&&!n)return{handled:!1,state:a};if(!s){let e=r.length-1;return{handled:!0,value:r[e],state:{index:e,draft:o}}}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:ht.value,atStart:t,state:tp});if(tp=r.state,r.handled)return e.preventDefault(),void(void 0!==r.value&&(e=>{if(!ht)return;rp=!0,ht.value=e,ht.dispatchEvent(new Event("input",{bubbles:!0})),rp=!1;let t=ht.value.length;ht.setSelectionRange(t,t)})(r.value))}if(rn(e,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:en(ht)}))if(wa.isStreaming()){if(e.preventDefault(),"block"===_r()||_c||Fl())return;op(),Qc()}else _c||Fl()?e.preventDefault():(op(),e.preventDefault(),mt.click())}}],["input",e=>{rp||(e.isComposing||xr?.handleInput(e.inputType??void 0),op())}],["input",kr],["input",Mr],["keyup",Mr],["paste",async e=>{if(!0!==o.attachments?.enabled||!wr||Wl())return;let t=yc(e.clipboardData);0!==t.length&&(e.preventDefault(),await wr.handleFiles(t))}],["focus",()=>xr?.prefetch()]],su=e=>{if(e)for(let[t,r]of au)co?.addListener(e,t,r)},iu=()=>{co&&(co.addListener(co.form,"submit",ep),co.addListener(co.footer,"click",Mr),su(ht),Ht&&co.addListener(Ht,"click",Ep),Dp())};iu();let lu=()=>{xr?.onComposerSwap((e,t)=>{(e=>{if(e)for(let[t,r]of au)co?.removeListener(e,t,r)})(t),ht=e,co&&(co.input=e),su(e),po(),ql(),kr()})};lu();let du=!1;function cu(){if(!du){du=!0;try{let e=ht?.value??"",t=Tt.ownerDocument??document,r=!!ht&&t.activeElement===ht;vp(),co?.destroy(),co=null,xr?.destroy(),xr=null;let n=null,a=()=>(n=ae()?Ii({config:o}):Ai({config:o}),n.footer),s=ao(a)??a();tt.replaceComposer(s),Tt=tt.composer.footer;let i=null!==n&&s===n.footer;oo=!i,$t=i?n.setSendButtonMode:()=>{},ro(Tt),uo(Tt),mo(),go(),fo(),lu(),Co(),So(),ko(),iu();let l=va.indexOf(fa);if(fa.destroy(),fa=oi(ut),l>=0&&(va[l]=fa),ht&&(ht.value=e),kr(),Mr(),vd(),Ra(),jl(wa.isStreaming()),"transient"===o.statusIndicator?.mode&&!ae()){let e=wa.getStatus();et(ft,Ye(e),o.statusIndicator,e)}Ds.active&&cp("recording"),_o(),Vp(),fr(),Io(),zl(),r&&ht?.focus()}finally{du=!1}}}let pu=e.ownerDocument??document;pu.addEventListener("keydown",np,!0);let uu=()=>{hi()},hu=()=>{"hidden"===pu.visibilityState&&hi()};typeof window<"u"&&(window.addEventListener("pagehide",uu),pu.addEventListener("visibilitychange",hu),la.push(()=>{window.removeEventListener("pagehide",uu),pu.removeEventListener("visibilitychange",hu)}));let mu="persona-attachment-drop-active",gu=0,fu=()=>{gu=0,it.classList.remove(mu)},yu=()=>!0===o.attachments?.enabled&&null!==wr&&!Wl(),bu=e=>{bc(e.dataTransfer)&&yu()&&(gu++,1===gu&&it.classList.add(mu))},vu=e=>{bc(e.dataTransfer)&&yu()&&(gu--,gu<=0&&fu())},wu=e=>{bc(e.dataTransfer)&&yu()&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},xu=e=>{if(!bc(e.dataTransfer)||!yu())return;e.preventDefault(),e.stopPropagation(),fu();let t=Array.from(e.dataTransfer.files??[]);0!==t.length&&wr.handleFiles(t)};it.addEventListener("dragenter",bu,!0),it.addEventListener("dragleave",vu,!0),e.addEventListener("dragover",wu,!0),e.addEventListener("drop",xu,!0);let Cu=e.ownerDocument,Su=e=>{yu()&&e.preventDefault()},ku=e=>{yu()&&e.preventDefault()};Cu.addEventListener("dragover",Su),Cu.addEventListener("drop",ku),la.push(()=>{co?.destroy(),co=null,vp(),yo?.destroy(),yo=null,Dr?.destroy(),Dr=null,zr?.destroy(),zr=null,Kr?.destroy(),Kr=null,Hr=null,Wr=null,hi(),ci.destroy(),Kc&&clearTimeout(Kc),Ja(),Uc?.abort(),Uc=null,wr?.destroy(),wr=null,Cr.destroy(),pu.removeEventListener("keydown",np,!0),xr?.destroy()}),la.push(()=>{it.removeEventListener("dragenter",bu,!0),it.removeEventListener("dragleave",vu,!0),e.removeEventListener("dragover",wu,!0),e.removeEventListener("drop",xu,!0),Cu.removeEventListener("dragover",Su),Cu.removeEventListener("drop",ku),fu()}),la.push(()=>{wa.cancel()}),jp?la.push(()=>{jp?.destroy()}):_p&&la.push(()=>{_p?.remove()});let Au={update(t){let r=!0===o.future?.v5Defaults,n=o.toolCall,a=o.messageActions,s=o.layout?.messages,i=o.colorScheme,l=o.loadingIndicator,u=o.iterationDisplay,h=o.features?.showReasoning,f=o.features?.showToolCalls,y=o.features?.toolCallDisplay,b=o.features?.reasoningDisplay,v=o.features?.streamAnimation?.type,w=!0===o.features?.history?.enabled,x=o.features?.history?.provider,C=o.getIdentityProof,S=o.clientToken,k=o.contextMentions;o=$d({...o,features:c},t),c=o.features,o=Cd(o),d(),Zn(),_a(e,o),ed(e,o),td(e,o),Ve(),Yn(),o.colorScheme!==i&&ua();let A=Pd.getForInstance(o.plugins);p.length=0,p.push(...A),Mc(),Q=o.launcher?.enabled??!0,Y=o.launcher?.autoExpand??!1,he=o.features?.showReasoning??!0,me=o.features?.showToolCalls??!0,be=o.features?.scrollToBottom??{};let M=Ut();Se=o.features?.scrollBehavior??{},M!==Ut()&&(Qi(),Bi()),Ts(),vr(),Ei();let I=ge;if(ge=o.features?.showEventStreamToggle??!1,ge&&!I){if(Te||(qe(),wa.setSSEEventCallback((e,t)=>{o.onSSEEvent?.(e,t),ze(e,t)})),!to&&It){let e=o.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:"");to=q("button",t),to.style.width="28px",to.style.height="28px",to.style.color=pi.actionIconColor,to.type="button",to.setAttribute("aria-label","Event Stream"),to.title="Event Stream";let r=g(m.Activity,"18px","currentColor",1.5);r&&to.appendChild(r);let n=st.clearChatButtonWrapper,a=st.closeButtonWrapper,s=n||a;s&&s.parentNode===It?It.insertBefore(to,s):It.appendChild(to),to.addEventListener("click",()=>{We?eo():Zr()})}}else!ge&&I&&(eo(),to&&=(to.remove(),null),Te?.clear(),Me?.destroy(),Te=null,Me=null,Be?.reset(),Be=null,Re=null);if(!1===o.launcher?.enabled&&jp&&(jp.destroy(),jp=null),!1===o.launcher?.enabled&&_p&&(_p.remove(),_p=null),!1!==o.launcher?.enabled&&!jp&&!_p){let{instance:t,element:r}=ul({config:o,plugins:p,onToggle:qp});jp=t,t||(_p=r),e.appendChild(r)}jp&&jp.update(o),Ec(),Mt&&void 0!==o.launcher?.subtitle&&(Mt.textContent=o.launcher.subtitle);let T=o.layout?.header;if(T?.layout!==re&&It){let e=T?ki(o,T,{showClose:ie(),onClose:()=>Rl(!1,"user")}):mi({config:o,showClose:ie(),onClose:()=>Rl(!1,"user")});tt.replaceHeader(e),It=tt.header.element,kt=tt.header.iconHolder,At=tt.header.headerTitle,Mt=tt.header.headerSubtitle,St=tt.header.closeButton,re=T?.layout,Ec()}else if(T){if(kt&&(kt.style.display=!1===T.showIcon?"none":""),At&&(At.style.display=!1===T.showTitle?"none":""),Mt&&(Mt.style.display=!1===T.showSubtitle?"none":""),St){let e=ie()&&!1!==T.showCloseButton;St.style.display=e?"":"none"}if(st.clearChatButtonWrapper){let e=T.showClearChat;if(void 0!==e){st.clearChatButtonWrapper.style.display=e?"":"none";let{closeButtonWrapper:t}=st;t&&!t.classList.contains("persona-absolute")&&(e?t.classList.remove("persona-ml-auto"):t.classList.add("persona-ml-auto"))}}}let E=!1!==o.layout?.showHeader;It&&(It.style.display=E?"":"none");let L=!1!==o.layout?.showFooter;Tt&&(Tt.style.display=L?"":"none"),fr(),Ei(),Q===te?Y!==ee&&Rl(Y,"auto"):Q?Rl(Y,"auto"):(le=!0,Bl()),ee=Y,te=Q,Gp(),nu();let P=JSON.stringify(o.toolCall)!==JSON.stringify(n),B=JSON.stringify(o.messageActions)!==JSON.stringify(a),R=JSON.stringify(o.layout?.messages)!==JSON.stringify(s),$=o.loadingIndicator?.render!==l?.render||o.loadingIndicator?.renderIdle!==l?.renderIdle||o.loadingIndicator?.showBubble!==l?.showBubble,H=o.iterationDisplay!==u,W=(o.features?.showReasoning??!0)!==(h??!0)||(o.features?.showToolCalls??!0)!==(f??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(y)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(b);(!0===o.future?.v5Defaults!==r||P||B||R||$||H||W)&&wa&&(Xa++,fl(dt,wa.getMessages(),ue));let D=o.features?.streamAnimation?.type;if(D!==v&&D&&"none"!==D){let t=ma(D,o.features?.streamAnimation?.plugins);t&&Hs(t,e)}let F=o.launcher??{},O=F.headerIconHidden??!1,z=o.layout?.header?.showIcon,j=O||!1===z,_=F.headerIconName,U=F.headerIconSize??"40px";if(kt){let e=It,t=e?.querySelector(".persona-flex-col");if(j)kt.style.display="none",e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(kt.style.display="",kt.style.height=U,kt.style.width=U,e&&t&&(e.contains(kt)?kt.nextSibling!==t&&(kt.remove(),e.insertBefore(kt,t)):e.insertBefore(kt,t)),_){let e=parseFloat(U)||24,t=se(_,.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))`,kt.replaceChildren(t)):kt.textContent=F.agentIconText??"💬"}else if(F.iconUrl){let e=kt.querySelector("img");if(e)e.src=F.iconUrl,e.style.height=U,e.style.width=U;else{let e=document.createElement("img");e.src=F.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=U,e.style.width=U,kt.replaceChildren(e)}}else{let e=kt.querySelector("svg"),t=kt.querySelector("img");(e||t)&&kt.replaceChildren(),kt.textContent=F.agentIconText??"💬"}let r=kt.querySelector("img");r&&(r.style.height=U,r.style.width=U)}}let G=o.layout?.header?.showTitle,J=o.layout?.header?.showSubtitle;if(At&&(At.style.display=!1===G?"none":""),Mt&&(Mt.style.display=!1===J?"none":""),St){let e=ie()&&!1!==o.layout?.header?.showCloseButton;if(St.style.display=e?"":"none",!ae()){let e=F.closeButtonSize??"";St.style.height=e,St.style.width=e,St.style.minWidth=e,St.style.minHeight=e}let t=F.closeButtonPlacement??"inline",{closeButtonWrapper:r}=st,n="top-right"===t,a=r?.classList.contains("persona-absolute");if(r&&n!==a)if(r.remove(),n){r.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let e=ac?.railColumn??it;e.style.position="relative",e.appendChild(r)}else{let e=F.clearChat?.placement??"inline";r.className=(F.clearChat?.enabled??1)&&"inline"===e?"":"persona-ml-auto",It&&It.appendChild(r)}if(St.style.color=F.closeButtonColor||pi.actionIconColor,F.closeButtonBackgroundColor?(St.style.backgroundColor=F.closeButtonBackgroundColor,St.classList.remove("hover:persona-bg-gray-100")):(St.style.backgroundColor="",St.classList.add("hover:persona-bg-gray-100")),F.closeButtonBorderWidth||F.closeButtonBorderColor){let e=F.closeButtonBorderWidth||"0px",t=F.closeButtonBorderColor||"transparent";St.style.border=`${e} solid ${t}`,St.classList.remove("persona-border-none")}else St.style.border="",St.classList.add("persona-border-none");F.closeButtonBorderRadius?(St.style.borderRadius=F.closeButtonBorderRadius,St.classList.remove("persona-rounded-full")):(St.style.borderRadius="",St.classList.add("persona-rounded-full")),F.closeButtonPaddingX?(St.style.paddingLeft=F.closeButtonPaddingX,St.style.paddingRight=F.closeButtonPaddingX):(St.style.paddingLeft="",St.style.paddingRight=""),F.closeButtonPaddingY?(St.style.paddingTop=F.closeButtonPaddingY,St.style.paddingBottom=F.closeButtonPaddingY):(St.style.paddingTop="",St.style.paddingBottom=""),ii(St,F.closeButtonIconName??"x",{iconSize:ae()?ol:void 0,iconText:F.closeButtonIconText??"×"});let s=F.closeButtonTooltipText??"Close chat",i=F.closeButtonShowTooltip??!0;St.setAttribute("aria-label",s),r&&Xo({anchor:St,trigger:r,text:()=>St?.getAttribute("aria-label")??s,enabled:i})}let{clearChatButton:Z,clearChatButtonWrapper:oe}=st;if(Z){let e=F.clearChat??{},t=e.enabled??!0,r=o.layout?.header?.showClearChat,n=void 0===r?t:r,a=e.placement??"inline";if(oe){oe.style.display=n?"":"none";let{closeButtonWrapper:e}=st;!ae()&&e&&!e.classList.contains("persona-absolute")&&(n?e.classList.remove("persona-ml-auto"):e.classList.add("persona-ml-auto"));let t="top-right"===a,r=oe.classList.contains("persona-absolute");if(!ae()&&t!==r&&n){if(oe.remove(),t){oe.className="persona-absolute persona-top-4 persona-z-50",oe.style.right="48px";let e=ac?.railColumn??it;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=st.closeButtonWrapper;It&&e&&e.parentElement===It?It.insertBefore(oe,e):It&&It.appendChild(oe)}let e=st.closeButtonWrapper;e&&!e.classList.contains("persona-absolute")&&(t?e.classList.add("persona-ml-auto"):e.classList.remove("persona-ml-auto"))}}if(n){if(!ae()){let t=e.size??"";Z.style.height=t,Z.style.width=t,Z.style.minWidth=t,Z.style.minHeight=t}let t=e.iconColor??"";if(Z.style.color=t||pi.actionIconColor,ii(Z,e.iconName??"refresh-cw",{iconSize:ae()?nl:void 0}),e.backgroundColor?(Z.style.backgroundColor=e.backgroundColor,Z.classList.remove("hover:persona-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:persona-bg-gray-100")),e.borderWidth||e.borderColor){let t=e.borderWidth||"0px",r=e.borderColor||"transparent";Z.style.border=`${t} solid ${r}`,Z.classList.remove("persona-border-none")}else Z.style.border="",Z.classList.add("persona-border-none");e.borderRadius?(Z.style.borderRadius=e.borderRadius,Z.classList.remove("persona-rounded-full")):(Z.style.borderRadius="",Z.classList.add("persona-rounded-full")),e.paddingX?(Z.style.paddingLeft=e.paddingX,Z.style.paddingRight=e.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),e.paddingY?(Z.style.paddingTop=e.paddingY,Z.style.paddingBottom=e.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let r=e.tooltipText??"Clear chat",o=e.showTooltip??!0;Z.setAttribute("aria-label",r),oe&&Xo({anchor:Z,trigger:oe,text:()=>Z?.getAttribute("aria-label")??r,enabled:o})}}let ne=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Hd],de=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Dd.message,Dd.messageAndClick];X=Od({parsers:ne,handlers:de,getSessionMetadata:V,updateSessionMetadata:K,emit:N.emit,documentRef:typeof document<"u"?document:null}),ue=xc(o,X,pe),Nd(),wa.updateConfig(o),zc(),(!0===o.features?.history?.enabled!==w||o.features?.history?.provider!==x||o.getIdentityProof!==C||o.clientToken!==S)&&(ac?.closeHistory({restoreFocus:!1}),ac?.installHistoryProvider()),ac?.syncHistoryChromeImpl(),Nc(),Sc()&&!ac&&Bc().catch(()=>{}),fl(dt,wa.getMessages(),ue),Ra(),vd(),(()=>{let e=ur();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`!==gd||e.icon!==ad)&&bd()})(),jl(wa.isStreaming()),k!==o.contextMentions&&cu();let ce=!0===o.voiceRecognition?.enabled,fe=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),ye=Ce(o.voiceRecognition?.provider);if(ce&&(fe||ye))if(Ht&&Wt){let e=o.voiceRecognition??{},t=o.sendButton??{},r=e.iconName??"mic",n=e.iconSize,a=parseFloat(n??"")||24;Ht.classList.add(sn),Ht.classList.toggle(ln,!n),Ht.style.width=n??"",Ht.style.height=n??"",Ht.style.minWidth=n??"",Ht.style.minHeight=n??"";let s=e.iconColor??t.textColor;Ht.innerHTML="";let i=se(r,a,s||"currentColor",1.5);i?Ht.appendChild(i):Ht.textContent="🎤";let l=e.backgroundColor??t.backgroundColor;Ht.style.backgroundColor=l||"",Ht.style.color=s||"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),Wt&&Xo({anchor:Ht,trigger:Wt,text:()=>Ht?.getAttribute("aria-label")??d,enabled:c}),Wt.style.display="",Ht.disabled=Wl()||wa.isStreaming()&&!Dl()}else{let e=hn(o);if(e){Ht=e.button,Wt=e.wrapper;let t=Nt&&Nt.parentElement===Rt?Nt:null;Rt?Rt.insertBefore(Wt,t):gt?.appendChild(Wt),co&&(co.micButton=Ht),co?.addListener(Ht,"click",Ep),Ht.disabled=Wl()||wa.isStreaming()&&!Dl()}}else Ht&&Wt&&(Wt.style.display="none",Ce(o.voiceRecognition?.provider)?wa.isVoiceActive()&&wa.toggleVoice():sp&&Cp());if(Dp(),!0===o.attachments?.enabled){if(Ft&&Dt){Ft.style.display="";let e=o.attachments??{};Ot&&(Ot.accept=(e.allowedTypes??Ar).join(","),Ot.multiple=(e.maxFiles??4)>1),wr&&wr.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}else{let e=o.attachments??{};zt||(zt=q("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),zt.style.display="none",(ht.parentElement??gt).insertBefore(zt,ht)),Ot||(Ot=document.createElement("input"),Ot.type="file",Ot.accept=(e.allowedTypes??Ar).join(","),Ot.multiple=(e.maxFiles??4)>1,Ot.style.display="none",Ot.setAttribute("aria-label","Attach files"),(ht.parentElement??gt).insertBefore(Ot,ht)),Ft=q("div","persona-send-button-wrapper"),Dt=q("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${sn} ${ln}`),Dt.type="button",Dt.setAttribute("aria-label",e.buttonTooltipText??"Attach file");let t=e.buttonIconName??"paperclip";Dt.style.fontSize="18px",Dt.style.lineHeight="1";let r=se(t,24,"currentColor",1.5);r?Dt.appendChild(r):Dt.textContent="📎",Dt.addEventListener("click",e=>{e.preventDefault(),Ot?.click()}),Ft.appendChild(Dt);let n=e.buttonTooltipText??"Attach file";Xo({anchor:Dt,trigger:Ft,text:()=>Dt?.getAttribute("aria-label")??n}),Bt?Bt.append(Ft):gt.appendChild(Ft),co&&(co.attachmentButton=Dt,co.attachmentInput=Ot??void 0,co.attachmentPreviews=zt??void 0),!wr&&Ot&&zt&&(wr=$o.fromConfig(e,Tr),wr.setPreviewsContainer(zt),co?.addListener(Ot,"change",async()=>{wr&&Ot?.files&&(await wr.handleFileSelect(Ot.files),Ot.value="")}))}if(it.querySelector(".persona-attachment-drop-overlay")?.remove(),it.appendChild(Cc(o.attachments?.dropOverlay)),Dt){let e=o.attachments??{},t=e.buttonTooltipText??"Attach file";Dt.setAttribute("aria-label",t),Dt.textContent="";let r=se(e.buttonIconName??"paperclip",24,"currentColor",1.5);r?Dt.appendChild(r):Dt.textContent="📎",Ft&&Xo({anchor:Dt,trigger:Ft,text:()=>Dt?.getAttribute("aria-label")??t})}}else Ft&&(Ft.style.display="none"),wr&&wr.clearAttachments(),it.querySelector(".persona-attachment-drop-overlay")?.remove();let ve=o.sendButton??{},ke=ve.useIcon??!1,Ae=ve.iconText??"↑",Ie=ve.iconName,Ee=ve.tooltipText??"Send message",Le=ve.showTooltip??!1,Pe=ve.size,Ne=parseFloat(Pe??"")||40,$e=ve.backgroundColor,He=ve.textColor;if(ke){if(mt.style.width=Pe??"",mt.style.height=Pe??"",mt.style.minWidth=Pe??"",mt.style.minHeight=Pe??"",mt.style.fontSize="18px",mt.style.lineHeight="1",mt.style.color=He||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!wa.isStreaming())if(mt.innerHTML="",Ie){let e=parseFloat(ve.iconSize??"")||Math.round(.5*Ne),t=He?.trim()||"currentColor",r=ve.iconStrokeWidth??2,o=se(Ie,e,t,r),n=se(ve.stopIconName??"square",e,t,r);o&&n?mt.appendChild(pn(o,n)):o?mt.appendChild(o):mt.textContent=Ae}else mt.textContent=Ae;mt.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${sn}`,$e?(mt.style.backgroundColor=$e,mt.classList.remove("persona-bg-persona-primary")):(mt.style.backgroundColor="",mt.classList.add("persona-bg-persona-primary"))}else mt.textContent=o.copy?.sendButtonLabel??"Send",mt.style.width="",mt.style.height="",mt.style.minWidth="",mt.style.minHeight="",mt.style.fontSize="",mt.style.lineHeight="",mt.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?(mt.style.backgroundColor=$e,mt.classList.remove("persona-bg-persona-accent")):mt.classList.add("persona-bg-persona-accent"),He?mt.style.color=He:mt.classList.add("persona-text-white");ve.borderWidth?(mt.style.borderWidth=ve.borderWidth,mt.style.borderStyle="solid"):(mt.style.borderWidth="",mt.style.borderStyle=""),ve.borderColor?mt.style.borderColor=ve.borderColor:mt.style.borderColor="",ve.paddingX?(mt.style.paddingLeft=ve.paddingX,mt.style.paddingRight=ve.paddingX):(mt.style.paddingLeft="",mt.style.paddingRight=""),ve.paddingY?(mt.style.paddingTop=ve.paddingY,mt.style.paddingBottom=ve.paddingY):(mt.style.paddingTop="",mt.style.paddingBottom=""),wa.isStreaming()||mt.setAttribute("aria-label",Ee),zl(),Nt&&Xo({anchor:mt,trigger:Nt,text:()=>mt.getAttribute("aria-label")??Ee,enabled:Le}),To(),na();let De=_n(Cr.getState().activeModeIds,o.composer?.modes);Cr.setActiveModeIds(De),Lr().length>0!=!!Dr&&So(),Dr?.render(De,Lr());for(let e of[...Or.keys()])jn(e,o.composer?.modeGroups)||Or.delete(e);Or.forEach(e=>e.repaint()),Hr?.repaint(),yo?.resolve();let Fe=Va(o,ae());if(ea(),Fe){dt.style.maxWidth=Fe,dt.style.marginLeft="auto",dt.style.marginRight="auto",dt.style.width="100%",vt.style.maxWidth=Fe,vt.style.marginLeft="auto",vt.style.marginRight="auto",vt.style.width="100%";for(let e of[gt,ut,zt,ft])e&&(e.style.maxWidth=Fe,e.style.marginLeft="auto",e.style.marginRight="auto",e.style.width="100%")}else{dt.style.maxWidth="",dt.style.marginLeft="",dt.style.marginRight="",dt.style.width="",vt.style.maxWidth="",vt.style.marginLeft="",vt.style.marginRight="",vt.style.width="";for(let e of[gt,ut,zt,ft])e&&(e.style.maxWidth="",e.style.marginLeft="",e.style.marginRight="",e.style.width="")}let Oe=o.statusIndicator??{};if(xe(ft,gt,Oe),we(ft,Oe,wa?.getStatus()??"idle"),wa){let e=wa.getStatus();et(ft,(e=>"idle"===e?Oe.idleText??Pr.idle:"connecting"===e?Oe.connectingText??Pr.connecting:"connected"===e?Oe.connectedText??Pr.connected:"error"===e?Oe.errorText??Pr.error:"paused"===e?Oe.pausedText??Pr.paused:"resuming"===e?Oe.resumingText??Pr.resuming:Pr[e])(e),Oe,e)}ft.classList.remove("persona-text-left","persona-text-center","persona-text-right");let je="left"===Oe.align?"persona-text-left":"center"===Oe.align?"persona-text-center":"persona-text-right";ft.classList.add(je),po(),ql(),Io(),Ue()},open(){ie()&&Rl(!0,"api")},close(){ie()&&Rl(!1,"api")},toggle(){ie()&&Rl(!le,"api")},reconnect(){wa.reconnectNow()},clearChat(){Jo=!1,i.clear(),n.clear(),s.clear(),l.clear(),wa.clearMessages(),o.layout?.topFade&&(lt.scrollTop=0),lt.removeAttribute("data-persona-top-fade"),Ha.clear(),Bi();try{localStorage.removeItem(hc),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${hc}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==hc)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.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),$?.clear&&ti(()=>$.clear(),"[AgentWidget] Failed to clear storage adapter:"),W={},X.syncFromMetadata(),wr?.clearAttachments(),yi(),Gr(void 0),qr(void 0),Ja(),Te?.clear(),Be?.reset(),$e?.update()},setMessage:e=>!(!ht||wa.isStreaming()||Wl()||(!le&&ie()&&Rl(!0,"system"),ht.value=e,ht.dispatchEvent(new Event("input",{bubbles:!0})),0)),submitMessage(e){if(wa.isStreaming()||Fl())return!1;let t=e?.trim()||ht.value.trim();return!!t&&(!le&&ie()&&Rl(!0,"system"),ht.value="",ht.style.height="auto",kr(),Zc(t,{consumeDraft:!1}),!0)},getComposerState:()=>Cr.getState(),setQuote(e){let t=e?.text?.trim();t&&qr({...e,text:t})},clearQuote(){qr(void 0)},startVoiceRecognition:()=>!wa.isStreaming()&&(Ce(o.voiceRecognition?.provider)?(wa.isVoiceActive()||wa.isBargeInActive()||(!le&&ie()&&Rl(!0,"system"),Ds.manuallyDeactivated=!1,Vs(),wa.toggleVoice().then(()=>{Ds.active=qs(),Vs(),Us("user"),Ds.active&&Ap()})),!0):!!sp||!!wp()&&(!le&&ie()&&Rl(!0,"system"),Ds.manuallyDeactivated=!1,Vs(),xp("user"),!0)),stopVoiceRecognition:()=>Ce(o.voiceRecognition?.provider)?!(!wa.isVoiceActive()&&!wa.isBargeInActive()||((wa.isBargeInActive()?wa.deactivateBargeIn():wa.toggleVoice()).then(()=>{Ds.active=!1,Ds.manuallyDeactivated=!0,Vs(),Us("user"),Tp()}),0)):!!sp&&(Ds.manuallyDeactivated=!0,Vs(),Cp("user"),!0),injectMessage:e=>(!le&&ie()&&Rl(!0,"system"),wa.injectMessage(e)),injectAssistantMessage(e){!le&&ie()&&Rl(!0,"system");let t=wa.injectAssistantMessage(e);return de&&(de=!1,ce&&=(clearTimeout(ce),null),setTimeout(()=>{wa&&!wa.isStreaming()&&wa.continueConversation()},100)),t},injectUserMessage:e=>(!le&&ie()&&Rl(!0,"system"),wa.injectUserMessage(e)),injectSystemMessage:e=>(!le&&ie()&&Rl(!0,"system"),wa.injectSystemMessage(e)),injectMessageBatch:e=>(!le&&ie()&&Rl(!0,"system"),wa.injectMessageBatch(e)),injectComponentDirective:e=>(!le&&ie()&&Rl(!0,"system"),wa.injectComponentDirective(e)),injectTestMessage(e){!le&&ie()&&Rl(!0,"system"),wa.injectTestEvent(e)},connectStream:async(e,t)=>wa.connectStream(e,t),__pushEventStreamEvent(e){ge&&(qe(),ze(e.type,e.payload))},showEventStream(){ge&&Zr()},hideEventStream(){We&&eo()},isEventStreamVisible:()=>We,listConversations:e=>wa.listConversations(e),getActiveConversationId:()=>wa.getActiveConversationId(),openConversation:(e,t)=>Rc(r=>r.openHistoryConversation(e,{focusComposer:!0===t?.focus})),startNewConversation:e=>Rc(t=>t.startNewConversation({focusComposer:!0===e?.focus})),warmSession(){$c()},deleteConversation:e=>Rc(t=>t.deleteHistoryConversation(e)),renameConversation:(e,t)=>Rc(r=>r.updateHistoryConversation(e,{title:t})),setConversationStarred:(e,t)=>Rc(r=>r.updateHistoryConversation(e,{starred:t})),clearConversationHistory:e=>Rc(t=>t.clearConversationHistory(e)),resetHistoryIdentity:()=>Rc(e=>e.resetHistoryIdentity()),async getVisitorToken(){let e=Bd;if(!e)return null;let t=await e.get();return e===Bd?t:null},getHistoryIdentityStatus(){let e=ac?.historyProvider;return e?e.getIdentityStatus():Sc()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory:e=>Sc()?Rc(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...void 0===e?.focus?{}:{focus:e.focus}})):Promise.resolve(),hideHistory(e){ac?.closeHistory(void 0===e?.restoreFocus?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible:()=>je,showArtifacts(){Jl(o)&&(Jo=!1,dn=!0,Yn(),zo?.setMobileOpen(!0))},hideArtifacts(){Jl(o)&&(Jo=!0,Yn())},upsertArtifact:e=>Jl(o)?("panel"===no(o.features?.artifacts,{artifactType:e.artifactType,..."markdown"===e.artifactType&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})&&(Jo=!1,dn=!0),wa.upsertArtifact(e)):null,selectArtifact(e){Jl(o)&&wa.selectArtifact(e)},clearArtifacts(){Jl(o)&&wa.clearArtifacts()},getArtifacts:()=>wa?.getArtifacts()??[],getSelectedArtifactId:()=>wa?.getSelectedArtifactId()??null,focusInput:()=>!(Q&&!le&&!ae()||!ht||(ht.focus(),0)),async resolveApproval(e,t,r){let o=wa.getMessages().find(t=>"approval"===t.variant&&t.approval?.id===e);if(!o?.approval)throw Error(`Approval not found: ${e}`);if(!u(o.approval))return wa.resolveApproval(o.approval,t,r);wa.resolveWebMcpApproval(o.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=Ia(r),Ma=Ta(r),Ra(r)})(e)},clearFollowUpSuggestions(){Na()},getMessages:()=>wa.getMessages(),getStatus:()=>wa.getStatus(),getPersistentMetadata:()=>({...W}),updatePersistentMetadata(e){K(e)},on:(e,t)=>N.on(e,t),off(e,t){N.off(e,t)},isOpen:()=>ie()&&le,isVoiceActive:()=>Ds.active,toggleReadAloud(e){wa.toggleReadAloud(e)},stopReadAloud(){wa.stopSpeaking()},getReadAloudState:e=>wa.getReadAloudState(e),onReadAloudChange:e=>wa.onReadAloudChange(e),getState:()=>({open:ie()&&le,launcherEnabled:Q,voiceActive:Ds.active,streaming:wa.isStreaming()}),showCSATFeedback(e){!le&&ie()&&Rl(!0,"system");let t=dt.querySelector(".persona-feedback-container");t&&t.remove();let r=pc({onSubmit:async(t,r)=>{wa.isClientTokenMode()&&await wa.submitCSATFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e});dt.appendChild(r),r.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(e){!le&&ie()&&Rl(!0,"system");let t=dt.querySelector(".persona-feedback-container");t&&t.remove();let r=uc({onSubmit:async(t,r)=>{wa.isClientTokenMode()&&await wa.submitNPSFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e});dt.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(){Zd(),null!=Wd&&(clearInterval(Wd),Wd=null),i.clear(),n.clear(),s.clear(),l.clear(),la.forEach(e=>e()),rt.remove(),nt?.remove(),jp?.destroy(),_p?.remove(),xa&&St.removeEventListener("click",xa)}};if((r?.debugTools||o.debug)&&typeof window<"u"){let e=window.AgentWidgetBrowser,t={controller:Au,getMessages:Au.getMessages,getStatus:Au.getStatus,getMetadata:Au.getPersistentMetadata,updateMetadata:Au.updatePersistentMetadata,clearHistory:()=>Au.clearChat(),setVoiceActive:e=>e?Au.startVoiceRecognition():Au.stopVoiceRecognition()};window.AgentWidgetBrowser=t,la.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)&&Au.focusInput()};if(window.addEventListener("persona:focusInput",r),la.push(()=>{window.removeEventListener("persona:focusInput",r)}),ge){let e=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Au.showEventStream()},r=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Au.hideEventStream()};window.addEventListener("persona:showEventStream",e),window.addEventListener("persona:hideEventStream",r),la.push(()=>{window.removeEventListener("persona:showEventStream",e),window.removeEventListener("persona:hideEventStream",r)})}let o=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Au.showHistory()},n=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Au.hideHistory()};window.addEventListener("persona:showHistory",o),window.addEventListener("persona:hideHistory",n),la.push(()=>{window.removeEventListener("persona:showHistory",o),window.removeEventListener("persona:hideHistory",n)});let a=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Au.showArtifacts()},s=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Au.hideArtifacts()},i=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==t||r?.artifact&&Au.upsertArtifact(r.artifact)},l=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==t||"string"==typeof r?.id&&Au.selectArtifact(r.id)},d=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Au.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),la.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 Mu=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}(o.persistState);if(Mu&&ie()){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}}(Mu.storage),r=`${Mu.keyPrefix}widget-open`,o=`${Mu.keyPrefix}widget-voice`,n=`${Mu.keyPrefix}widget-voice-mode`;if(t){let a=Mu.persist?.openState&&"true"===t.getItem(r),s=Mu.persist?.voiceState&&"true"===t.getItem(o),i=Mu.persist?.voiceState&&"true"===t.getItem(n);if(a&&(jp?.setPanelOpen(!0,"auto"),setTimeout(()=>{Au.open(),setTimeout(()=>{if(s||i)Au.startVoiceRecognition();else if(Mu.persist?.focusInput){let t=e.querySelector("textarea");t&&t.focus()}},100)},0)),Mu.persist?.openState&&(N.on("widget:opened",()=>{t.setItem(r,"true")}),N.on("widget:closed",()=>{t.setItem(r,"false")})),Mu.persist?.voiceState&&(N.on("voice:state",e=>{t.setItem(o,e.active?"true":"false")}),N.on("user:message",e=>{t.setItem(n,e.viaVoice?"true":"false")})),Mu.clearOnChatClear){let e=()=>{t.removeItem(r),t.removeItem(o),t.removeItem(n)},a=()=>e();window.addEventListener("persona:clear-chat",a),la.push(()=>{window.removeEventListener("persona:clear-chat",a)})}}}if(_&&ie()&&(jp?.setPanelOpen(!0,"auto"),setTimeout(()=>{Au.open()},0)),El(),!Qa){let e=Le(()=>{wa&&(Xa++,Ha.clear(),fl(dt,wa.getMessages(),ue))});la.push(e)}k=()=>{wa&&(Xa++,Ha.clear(),fl(dt,wa.getMessages(),ue))},wa.getMessages().length>0&&hl(),L=()=>{wa&&(Xa++,Ha.clear(),fl(dt,wa.getMessages(),ue))};let Iu=oe(()=>{wa&&(Xa++,Ha.clear(),fl(dt,wa.getMessages(),ue))});la.push(Iu);let Tu=Gl(()=>{wa&&(Xa++,Ha.clear(),fl(dt,wa.getMessages(),ue),Kl()?.updateInlineArtifactBlocks(dt,Go.artifacts,{suppressTransition:!0}),Yn())});return la.push(Tu),Au},Mc=(e,t)=>{let r=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(o)return Math.max(0,parseFloat(o[1]));let n=/^(\d+(?:\.\d+)?)%$/i.exec(r);return n?Math.max(0,t*parseFloat(n[1])/100):420},Ic=(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"},Tc=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=""},Ec=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Tc(e)},Lc=e=>{e.style.transition=""},Pc=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=""},Bc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Rc=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Nc=(e,t,r,o)=>{t?(e.style.boxSizing="border-box",e.style.padding=r,e.style.background=o):(e.style.padding="",e.style.background="",e.style.boxSizing="")},$c=(e,t)=>Xs(t)?((e,t)=>{let{ownerDocument:r}=e,o=e.parentElement;if(!o)throw Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if("BODY"===n||"HTML"===n)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),o.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=ja(e),r=t.components?.panel,o=(e,r)=>null==e||""===e?r:Aa(t,e)??e;return{inset:o(r?.inset,da),canvasBackground:o(r?.canvasBackground,ca)}})(t):null};g();let f=()=>{((e,t,r,o,n,a,s,i)=>{let l=Ys(a),d="push"===l.reveal,c=null!=i,p=i?.inset??"",u=i?.canvasBackground??"";((e,t,r,o,n)=>{n?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,o),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(o))})(e,t,r,o,d),((e,t,r,o,n,a)=>{let s=a?t:e;"left"===n?s.firstElementChild!==o&&s.replaceChildren(o,r):s.lastElementChild!==o&&s.replaceChildren(r,o)})(e,t,r,o,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",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.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"),Pc(t),Lc(o),Ec(o),Bc(r),Rc(n,o),Nc(o,!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",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(a?.launcher?.zIndex??1e5),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.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"),Ec(o),((e,t)=>{!1===t?e.style.maxHeight="":(e.style.maxHeight="100vh",e.style.maxHeight=t)})(o,l.maxHeight),Nc(o,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",Pc(t),Lc(o),Bc(r),Rc(n,o);let a=l.animate?"transform 180ms ease":"none",i="right"===l.side?"translateX(100%)":"translateX(-100%)",d=s?"translateX(0)":i;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=l.width,o.style.maxWidth=l.width,o.style.minWidth=l.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=a,o.style.transform=d,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2","right"===l.side?(o.style.right="0",o.style.left=""):(o.style.left="0",o.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",Lc(o),Tc(o),Rc(n,o);let a=Mc(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`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=l.width,o.style.minWidth=l.width,o.style.maxWidth=l.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Pc(t),Tc(o),Bc(r),Rc(n,o);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(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${i}`,o.style.width=i,o.style.maxWidth=i,o.style.minWidth=i,o.style.minHeight="0",((e,t)=>{!1===t?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")})(o,l.maxHeight),o.style.overflow=a||u?"hidden":"visible",o.style.transition=d,a){o.style.alignItems="right"===l.side?"flex-start":"flex-end";let t=c?`calc(${Mc(l.width,e.clientWidth)}px - (2 * ${p}))`:l.width;n.style.width=t,n.style.minWidth=t,n.style.maxWidth=t,n.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=Ua(()=>{g(),f()}))},v=!1,w=()=>{f(),h(),"push"===Ys(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 o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(o);let n=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.remove(),n&&!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,Ys(t)))},x=s.ownerDocument.defaultView,C=()=>{w()};return x?.addEventListener("resize",C),"push"===Ys(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(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}})(e,t):((e,t)=>{let r=e.ownerDocument.createElement("div");return Ic(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(e){Ic(r,e)},destroy(){r.remove()}}})(e,t),Hc=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let r=t.head.querySelector("link[data-persona]");if(!r)return;let o=r.cloneNode(!0);e.insertBefore(o,e.firstChild)},Wc=[],Dc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Fc=new Set(["button","a","input","select","textarea","details","summary"]),Oc=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),zc=/\b(product|card|item|listing|result)\b/i,qc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i;function jc(e){let t="string"==typeof e.className?e.className:"";if(zc.test(t)||e.id&&zc.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&zc.test(r.value))return!0}return!1}function _c(e){return qc.test((e.textContent??"").trim())}function Uc(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 Vc(e){let t=e.match(qc);return t?t[0]:null}function Kc(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 Gc(e){return jc(e)&&_c(e)&&(Uc(e)||function(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}(e))?5200:0}function Jc(e){return!jc(e)||_c(e)||!Uc(e)||(e.textContent??"").trim().length<20||!e.querySelector("h1, h2, h3, h4, h5, h6, .title")&&!e.querySelector(".snippet, .description, p")?0:2800}let Xc=[{id:"commerce-card",scoreElement:e=>Gc(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||qc.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(0===Gc(e))return null;let{title:r,href:o}=Kc(e),n=Vc((e.textContent??"").trim())??Vc(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[o&&r?`[${r}](${o})${n?`: ${n}`:""}`:r?`${r}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join("\n")}},{id:"result-card",scoreElement:e=>Jc(e),formatSummary(e,t){if(0===Jc(e))return null;let{title:r,href:o}=Kc(e);return[o&&r?`[${r}](${o})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join("\n")}}];function Qc(e){return typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}let Yc=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Zc(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||Fc.has(t)||r&&Oc.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||"true"===e.getAttribute("contenteditable")?"clickable":"static"}function ep(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 tp(e){let t={},r=e.id;r&&(t.id=r);let o=e.getAttribute("href");o&&(t.href=o);let n=e.getAttribute("aria-label");n&&(t["aria-label"]=n);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 o=e.attributes[r];o.name.startsWith("data-")&&(t[o.name]=o.value)}return t}function rp(e){let t=e.tagName.toLowerCase();if(e.id){let t=`#${Qc(e.id)}`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}for(let r of Yc){let o=e.getAttribute(r);if(o){let n=`${t}[${r}="${Qc(o)}"]`;try{if(1===e.ownerDocument.querySelectorAll(n).length)return n}catch{}}}let r=Array.from(e.classList).filter(e=>e&&!e.startsWith("persona-")).slice(0,3);if(r.length>0){let o=`${t}.${r.map(e=>Qc(e)).join(".")}`;try{if(1===e.ownerDocument.querySelectorAll(o).length)return o}catch{}let n=e.parentElement;if(n){let r=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0){let t=`${o}:nth-of-type(${r+1})`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}}}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function op(e,t){let r=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:rp(e),tagName:r,text:o,role:e.getAttribute("role"),interactivity:Zc(e),attributes:tp(e)}}function np(e,t,r,o){let n=function(e){return"static"===e?100:3e3}(t.interactivity),a=null;for(let s of r){let r=s.scoreElement(e,t,o);r>0&&(n+=r,s.formatSummary&&!a&&(a=s))}return{score:n,formattingRule:a}}function ap(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 sp={components:{panel:{borderRadius:"0",shadow:"none"}}},ip={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:P},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"]}},lp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:sp}},dp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:sp}},cp={shop:ip,minimal:lp,fullscreen:dp},pp=typeof document<"u"?document.currentScript?.src??null:null,up=(e,t=`host ${e} alongside it`)=>()=>{let r=pp?.replace(/index\.global\.js($|\?)/,`${e}$1`);return r&&r!==pp?import(r):Promise.reject(Error(`Could not derive the ${e} URL from the widget script URL (${pp??"unavailable"}). Self-hosted deployments that rename index.global.js should ${t}.`))};return(e=>{s=e})(up("webmcp-polyfill.js","install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp")),Te(up("markdown-parsers.js")),nt(up("client-stream.js")),wr(up("client-history.js")),_r(up("ui-extras.js")),Qr(up("session-actions.js")),tc(up("history-shell.js")),(e=>{xo=e})(up("runtype-tts.js","host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly")),ea(up("context-mentions.js")),na(up("context-mentions-inline.js")),Jd(up("history-view.js")),Fs(up("animations-extra.js","host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin")),El(up("approval-ui.js")),yo(up("voice-runtime.js")),ht(up("voice-client-tools.js")),Ul(up("artifacts-ui.js")),Td(up("forms-ui.js")),G(up("icons-extra.js","host icons-extra.js alongside it, or register the icons they use via registerIcons()")),dt(up("webmcp-runtime.js")),Ao(up("session-reconnect.js")),Nl(up("event-stream-view.js")),e.ASK_USER_QUESTION_CLIENT_TOOL=Zt,e.ASK_USER_QUESTION_PARAMETERS_SCHEMA=Yt,e.ASK_USER_QUESTION_TOOL_NAME=wt,e.AgentWidgetClient=Dr,e.AgentWidgetSession=Po,e.AttachmentManager=$o,e.BrowserSpeechEngine=po,e.DEFAULT_COMPONENTS=Sa,e.DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH="440px",e.DEFAULT_FLOATING_LAUNCHER_WIDTH=P,e.DEFAULT_PALETTE=ya,e.DEFAULT_SEMANTIC=wa,e.DEFAULT_WIDGET_CONFIG=F,e.HistoryProviderError=Fr,e.PRESETS=cp,e.PRESET_FULLSCREEN=dp,e.PRESET_MINIMAL=lp,e.PRESET_SHOP=ip,e.ReadAloudController=uo,e.SUGGEST_REPLIES_CLIENT_TOOL=Vt,e.SUGGEST_REPLIES_PARAMETERS_SCHEMA=Ut,e.SUGGEST_REPLIES_TOOL_NAME=_t,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=fr,e.WEBMCP_TOOL_PREFIX=r,e.applyFeaturePreferences=xd,e.applyThemeVariables=_a,e.attachHeaderToContainer=gi,e.buildComposer=Ai,e.buildDefaultHeader=wi,e.buildHeader=mi,e.buildHeaderWithLayout=ki,e.buildMinimalHeader=xi,e.builtInClientToolsForDispatch=er,e.canonicalArtifactDisplayMode=to,e.collectEnrichedPageContext=function(e={}){let t=function(e){let t=e.options??{},r=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",n=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??Xc;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:o,maxTextLength:n,visibleOnly:a,root:s,rules:d}}(e),r=t.root??document.body;return r?"simple"===t.mode?function(e,t){let r=[],o=new Set,n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=n.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let t=a,s=t.tagName.toLowerCase();if(Dc.has(s)){a=n.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){a=n.nextNode();continue}}catch{}if(e.visibleOnly&&!ep(t)){a=n.nextNode();continue}let i=op(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=n.nextNode();continue}o.has(i.selector)||(o.add(i.selector),r.push(i))}a=n.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},o=new Set,n=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&n.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let t=i,l=t.tagName.toLowerCase();if(Dc.has(l)){i=s.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!ep(t)){i=s.nextNode();continue}let d=op(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||o.has(d.selector)){i=s.nextNode();continue}o.add(d.selector);let{score:u,formattingRule:h}=np(t,d,e.rules,r);n.push({el:t,domIndex:a,enriched:d,score:u,formattingRule:h}),a+=1}i=s.nextNode()}n.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),o=+("static"===t.enriched.interactivity);return r===o?t.score===e.score?e.domIndex-t.domIndex:t.score-e.score:r-o});let l=[];for(let t of n){if(l.length>=e.maxElements)break;ap(l,t)||l.push(t)}return l.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),o=+("static"===t.enriched.interactivity);return r===o?1===r&&t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex:r-o}),l.map(e=>{let t;if(e.formattingRule?.formatSummary){let o=e.formattingRule.formatSummary(e.el,e.enriched,r);o&&(t=o)}let o={...e.enriched};return t&&(o.formattedSummary=t),o})}(t,r):[]},e.componentRegistry=Hl,e.createActionManager=Od,e.createAgentExperience=Ac,e.createAskUserQuestionBubble=(e,t)=>{let r=q("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 o=Lt(t);Rt(r,o);let n=q("span","persona-ask-stub-label"),{complete:a}=Pt(e);return n.textContent=a?"Awaiting your response…":"Preparing options…",r.appendChild(n),r},e.createBubbleWithLayout=(e,t,r,o,n,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}):Di(e,t,r,o,0,a)},e.createCSATFeedback=pc,e.createComboButton=vi,e.createComponentMiddleware=function(){let e=ac();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}},e.createComponentStreamParser=ac,e.createDefaultSanitizer=qe,e.createDirectivePostprocessor=e=>{let t=Re(e);return e=>{let r=[],o=Fe(e,r),n=t(o);return r.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=`<div class="persona-form-directive" data-tv-form="${We(t)}"></div>`;n=n.replace(r,o)}),n}},e.createDropdownMenu=fi,e.createFlexibleJsonStreamParser=e=>{let t=null,r=0,o=e||(e=>{if(!e||"object"!=typeof e)return null;let t=e=>"string"==typeof e?nr(e):null;if(e.component&&"string"==typeof e.component)return"string"==typeof e.text?nr(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 n=e.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(e.length<=r)return null===t?null:{text:t,raw:e};try{let r=(0,vt.parse)(e,vt.STR|vt.OBJ),n=o(r);null!==n&&(t=n)}catch{}return r=e.length,{text:t||"",raw:e}},close:()=>{}}},e.createIconButton=yi,e.createImagePart=function(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}},e.createJsonStreamParser=mr,e.createLabelButton=bi,e.createLocalStorageAdapter=_d,e.createMarkdownProcessor=Be,e.createMarkdownProcessorFromConfig=Re,e.createMessageActions=Wi,e.createNPSFeedback=uc,e.createPlainTextParser=ur,e.createRegexJsonParser=hr,e.createSplitButton=function(e){let{label:t,icon:r,iconSize:o,iconOnly:n,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=q("div","persona-split-btn"+(u?" "+u:"")),f={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:i},y=n&&r?yi({...f,icon:r,size:o??14}):bi({...f,icon:r,iconSize:o??14}),b=yi({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=fi({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=Di,e.createTextPart=Sr,e.createTheme=La,e.createThemeObserver=Ua,e.createToggleGroup=function(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=q("div","persona-toggle-group"+(n?" "+n:""));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=yi({icon:e.icon,label:e.label,className:e.className,onClick:()=>{s=e.id,l(),o(e.id)}}):(t=q("button","persona-icon-btn"+(e.className?" "+e.className:"")),t.type="button",t.setAttribute("aria-label",e.label),t.title=e.label,t.textContent=e.label,t.addEventListener("click",()=>{s=e.id,l(),o(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=Li,e.createWidgetHostLayout=$c,e.createXmlParser=gr,e.defaultActionHandlers=Dd,e.defaultJsonActionParser=Hd,e.defaultParseRules=Xc,e.detectColorScheme=za,e.directivePostprocessor=e=>{let t=[],r=Fe(e,t),o=$e(r);return t.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n=`<div class="persona-form-directive" data-tv-form="${We(t)}"></div>`;o=o.replace(r,n)}),o},e.ensureAskUserQuestionSheet=qt,e.escapeHtml=He,e.extractComponentDirectiveFromMessage=dc,e.fileToImagePart=async function(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>r(Error("Failed to read file")),o.readAsDataURL(e)})},e.formatEnrichedContext=function(e,t={}){if(0===e.length)return"No page elements found.";let r=t.mode??"structured",o=[];if("structured"===r){let t=e.map(e=>e.formattedSummary).filter(e=>!!e&&e.length>0);t.length>0&&o.push(`Structured summaries:\n${t.map(e=>`- ${e.split("\n").join("\n ")}`).join("\n")}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let t of e)"structured"===r&&t.formattedSummary||n[t.interactivity].push(t);if(n.clickable.length>0){let e=n.clickable.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}" (clickable)`);o.push(`Interactive elements:\n${e.join("\n")}`)}if(n.navigable.length>0){let e=n.navigable.map(e=>`- ${e.selector}${e.attributes.href?`[href="${e.attributes.href}"]`:""}: "${e.text.substring(0,100)}" (navigable)`);o.push(`Navigation links:\n${e.join("\n")}`)}if(n.input.length>0){let e=n.input.map(e=>`- ${e.selector}${e.attributes.type?`[type="${e.attributes.type}"]`:""}: "${e.text.substring(0,100)}" (input)`);o.push(`Form inputs:\n${e.join("\n")}`)}if(n.static.length>0){let e=n.static.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}"`);o.push(`Content:\n${e.join("\n")}`)}return o.join("\n\n")},e.generateAssistantMessageId=yt,e.generateMessageId=function(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`},e.generateStableSelector=rp,e.generateUserMessageId=ft,e.getActiveTheme=ja,e.getAgentWidgetHandles=()=>[...Wc],e.getColorScheme=qa,e.getDisplayText=function(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("")},e.getHeaderLayout=Si,e.getImageParts=function(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)},e.getPreset=function(e){return cp[e]},e.hasComponentDirective=lc,e.hasImages=Cr,e.headerLayouts=Ci,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),o=!0===e.useShadowDom,n=r.ownerDocument,a=e.config,s=$c(r,a),i=[],l=(e,t)=>{let a=!(t?.launcher?.enabled??1)||Xs(t),s=n.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"),o){let t=e.attachShadow({mode:"open"});t.appendChild(s),Hc(t,n)}else e.appendChild(s),Hc(e,n);return r.id&&s.setAttribute("data-persona-instance",r.id),s},d=()=>{s.syncWidgetState(t.getState())},c=()=>{let r=l(s.host,a);t=Ac(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=$c(r,e),a=e,c()},h=new Proxy({update(e){let r=$d(a??{},e),o=Xs(a),n=Xs(r),i=Qs(a),l=Qs(r);o!==n||i!==l?u(r):(a=r,s.updateConfig(a),t.update(e),d())},destroy(){p(),s.destroy();let t=Wc.indexOf(h);-1!==t&&Wc.splice(t,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},{get(e,r,o){if("host"===r)return s.host;if(r in e)return Reflect.get(e,r,o);let n=t[r];return"function"==typeof n?n.bind(t):n}});return Wc.push(h),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=h),h},e.isAskUserQuestionMessage=Et,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=Xs,e.isHistoryProviderError=function(e){return e instanceof Fr},e.isSuggestRepliesMessage=Kt,e.isWebMcpToolName=c,e.isWelcomeVisible=Zi,e.latestAgentSuggestions=Jt,e.listRegisteredStreamAnimations=()=>Array.from(vs.keys()),e.loadMarkdownParsers=Ee,e.markdownPostprocessor=$e,e.mergeWithDefaults=z,e.normalizeContent=function(e){return"string"==typeof e?[{type:"text",text:e}]:e},e.normalizeMediaType=ro,e.onMarkdownParsersReady=Le,e.parseAskUserQuestionPayload=Pt,e.parseSuggestRepliesPayload=Gt,e.parseWidgetPreferenceSlice=yd,e.pickBestVoice=co,e.pluginRegistry=Pd,e.registerIcons=e=>{for(let[t,r]of Object.entries(e))Y.set(t,r);ne()>0&&!ee&&re(!1)},e.registerStreamAnimationPlugin=xs,e.removeAskUserQuestionSheet=jt,e.renderComponentDirective=sc,e.renderLoadingIndicatorWithFallback=Pi,e.renderLucideIcon=se,e.resolveArtifactDisplay=oo,e.resolveArtifactDisplayMode=no,e.resolveConfigPreferences=Cd,e.resolveDockConfig=Ys,e.resolveSanitizer=je,e.resolveTokens=Ma,e.resolveWelcomeConfig=Yi,e.stripWebMcpPrefix=d,e.themeToCssVariables=Na,e.unregisterStreamAnimationPlugin=e=>{bs.some(t=>t.name===e)||vs.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=Ia,e}({});
|
|
7
|
+
*/var m=t(e=>{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 g=(e,t=24,r="currentColor",o=2)=>{if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.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 o=document.createElementNS("http://www.w3.org/2000/svg",t);Object.entries(r).forEach(([e,t])=>{"stroke"!==e&&o.setAttribute(e,String(t))}),n.appendChild(o)}),n},f=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function y(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[e,o]of Object.entries(t)){let t=r[e];r[e]=f(t)&&f(o)?y(t,o):o}return r}let b=Symbol("persona.defaultsProvenance"),v=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function w(e,t=""){return Object.entries(e).flatMap(([e,r])=>{let o=t?`${t}.${e}`:e;return v(r)?w(r,o):[o]})}function x(e,t){for(let r of t.split(".")){if(!v(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?.[b]??t.filter(t=>"explicit"===x(e,t))}function S(e,t){return Object.defineProperty(e,b,{value:t,enumerable:!0,configurable:!0}),e}function k(e,t,r){return S(e,C(t,w(r)))}let A=Symbol("persona.panelAliasProvenance"),M=(e,t)=>null!=e&&Object.prototype.hasOwnProperty.call(e,t),I=(e,t)=>M(e,t)&&void 0!==e[t],T=e=>{let t=e?.[A];return t?{...t}:(e=>({launcherWidth:I(e?.launcher,"width"),legacyLauncherWidth:I(e,"launcherWidth"),sidebarWidth:I(e?.launcher,"sidebarWidth"),dockWidth:I(e?.launcher?.dock,"width")}))(e)},E=(e,t)=>(Object.defineProperty(e,A,{value:t,enumerable:!0,configurable:!0}),e),L=(e,t)=>E(e,T(t)),P="min(440px, calc(100vw - 24px))",B={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},N={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},R={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:P,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:B,reasoningDisplay:N,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},$={},H={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 W(e){return!0===e?.future?.v5Defaults?"v5":"v4"}function D(e){let t="v5"===W(e)?H:$;return y(R,t)}let F=D();function O(e,t){if(e||t)return e?t?y(e,t):e:t}function z(e){let t=D(e);return e?k(L({...t,...e,theme:O(t.theme,e.theme),darkTheme:O(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,o=e.features?.artifacts,n=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===o?void 0:{...r,...o,layout:{...r?.layout,...o?.layout}},g=void 0===n&&void 0===a?void 0:{...n,...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,H):k(L(t),void 0,H)}let q=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},j=(e,t={},...r)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),void 0!==t.text&&(o.textContent=t.text),t.attrs)for(let[e,r]of Object.entries(t.attrs))o.setAttribute(e,r);if(t.style){let e=o.style,r=t.style;for(let t of Object.keys(r)){let o=r[t];null!=o&&(e[t]=o)}}let n=r.filter(e=>null!=e);return n.length>0&&o.append(...n),o},_=(...e)=>e.filter(Boolean).join(" "),U=e=>{let{fallbackImport:t,resetOnSetLoader:r=!1}=e,o=null,n=null,a=null;return{setLoader:e=>{o=e,r&&(n=null,a=null)},load:()=>n?Promise.resolve(n):a||(a=(o??t)().then(e=>(n=e,e)).catch(e=>{throw a=null,e}),a),provide:e=>{n=e},getSync:()=>n}},{setLoader:V,load:K}=U({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),J=V,G=K,X={activity:m.Activity,"arrow-down":m.ArrowDown,"arrow-up":m.ArrowUp,"arrow-up-right":m.ArrowUpRight,bot:m.Bot,"chevron-down":m.ChevronDown,"chevron-up":m.ChevronUp,"chevron-right":m.ChevronRight,"chevron-left":m.ChevronLeft,check:m.Check,clipboard:m.Clipboard,"clipboard-copy":m.ClipboardCopy,"code-xml":m.CodeXml,copy:m.Copy,file:m.File,"file-code":m.FileCode,"file-spreadsheet":m.FileSpreadsheet,"file-text":m.FileText,"image-plus":m.ImagePlus,loader:m.Loader,"loader-circle":m.LoaderCircle,mic:m.Mic,paperclip:m.Paperclip,quote:m.Quote,"refresh-cw":m.RefreshCw,search:m.Search,send:m.Send,"shield-alert":m.ShieldAlert,"shield-check":m.ShieldCheck,"shield-x":m.ShieldX,square:m.Square,"thumbs-down":m.ThumbsDown,"thumbs-up":m.ThumbsUp,upload:m.Upload,"volume-2":m.Volume2,x:m.X,"at-sign":m.AtSign,"arrow-left":m.ArrowLeft,"arrow-right":m.ArrowRight,"external-link":m.ExternalLink,ellipsis:m.Ellipsis,"ellipsis-vertical":m.EllipsisVertical,menu:m.Menu,"panel-left":m.PanelLeft,plus:m.Plus,minus:m.Minus,pencil:m.Pencil,trash:m.Trash,"trash-2":m.Trash2,download:m.Download,maximize:m.Maximize,minimize:m.Minimize,"message-square":m.MessageSquare,star:m.Star,eye:m.Eye,history:m.History},Q="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("."),Y=new Map(Object.entries(X)),Z=new Set,ee=!1,te=new Set,re=e=>{let t=[...te];e&&te.clear();for(let e of t)try{e()}catch{}},oe=e=>ee?()=>{}:(te.add(e),()=>{te.delete(e)}),ne=()=>{let e=0;for(let t of[...Z]){let r=Y.get(t.name);if(!r)continue;Z.delete(t),e++;let o=g(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},ae=!1,se=(e,t=24,r="currentColor",o=2)=>{let n=Y.get(e);if(n)return g(n,t,r,o);if(Q.includes(e)){ae&&=!1;let n=((e,t,r)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o})(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}),G().then(e=>{if(!ee){for(let[t,r]of Object.entries(e.EXTRA_LUCIDE_ICONS))Y.has(t)||Y.set(t,r);ee=!0,ne(),re(!0)}}).catch(e=>{ae=!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},ie=["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"],le=(e,t)=>{let r=q("div",["persona-message-bubble",e,...ie].join(" "));return r.id=`bubble-${t}`,r.setAttribute("data-message-id",t),r},de=e=>{let t=q("button",e.expandable?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},ce=(e,t,r)=>{e.innerHTML="";let o=g(t?m.ChevronUp:m.ChevronDown,16,r,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},pe=(e,t,r)=>{if(!r.expandable)return e.append(t),null;let o=q("div","persona-flex persona-items-center");ce(o,r.expanded,r.iconColor);let n=q("div",r.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return n.append(o),e.append(t,n),o},ue=e=>{let t=q("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let 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},he=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&ce(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"},me=(e,t,r)=>{let o=r.stateSet.has(e),n=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),s=t.querySelector(`[data-persona-collapsed-preview="${r.previewKind}"]`);if(!n||!a)return;n.setAttribute("aria-expanded",o?"true":"false");let i=n.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");i&&ce(i,o,r.iconColor),a.style.display=o?"":"none",s&&(s.style.display=o?"none":s.textContent||s.childNodes.length?"":"none")};function ge(e,t){let r="tool"===t?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[r]:{..."tool"===t?B:N,...!0===e?.future?.v5Defaults?H.features?.[r]:{},...e?.features?.[r]}}}}function fe(e,t){let r="tool"===t?"toolCallDisplay":"reasoningDisplay";return e?.features?.[r]?.variant??(e?.future?.v5Defaults?"row":"card")}function ye(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 be(e,t,r,o){if("row"!==fe(r,o))return e;e.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,e.dataset.activityKind=o,"tool"===o&&void 0===r.toolCall?.shadow&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let n=e.querySelector(":scope > button");if(!n)return e;n.className="persona-activity-header";let a="tool"===o?t.toolCall:t.reasoning,s="complete"!==a?.status,i=t.approval?.status??t.toolCall?.approvalStatus,l=t.toolCall?.interrupted?"interrupted":"denied"===i?"denied":"pending"===i?"awaiting-approval":!1===t.toolCall?.success?"error":s?"pending"===a?.status?"pending":"running":"done";e.dataset.activityState=l;let d=q("span","persona-activity-icon");d.dataset.activityIcon=l;let c="reasoning"===o?r.features?.reasoningDisplay?.iconName:void 0,p=c?se(c,16,"currentColor",2):"pending"===l?g(m.Circle,16,"currentColor",2):"awaiting-approval"===l?g(m.Clock,16,"currentColor",2):se({pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x",interrupted:"x","awaiting-approval":"clock"}[l],16,"currentColor",2);p&&d.appendChild(p),n.querySelector(".persona-reasoning-header-icon")?.remove();let u="tool"===o?"toolCallDisplay":"reasoningDisplay",h=r.features?.[u]?.iconVisibility??(r.future?.v5Defaults?"active":"always");if(("always"===h||"active"===h&&"done"!==l)&&n.prepend(d),"tool"===o&&a){let e=q("span","persona-activity-duration");s&&a.startedAt&&e.setAttribute("data-tool-elapsed",String(a.startedAt));let r=("tool"===o?t.toolCall?.duration:void 0)??a.durationMs??(void 0!==a.completedAt&&void 0!==a.startedAt?a.completedAt-a.startedAt:void 0);e.textContent=void 0===r?"":ye(r),n.appendChild(e)}n.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),n.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}`,n.setAttribute("aria-controls",f.id)),e}function ve(e,t,r,o){let n=q("div","");n.id=`bubble-${e.id}`,n.dataset.messageId=e.id;let a=q("button","");a.type="button",a.dataset.expandHeader="true",a.dataset.bubbleType="tool",a.setAttribute("aria-expanded",String(r));let s=q("div","");"string"==typeof o?s.textContent=o:s.appendChild(o),pe(a,s,{expandable:!0,expanded:r,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let i=q("div","persona-border-t");return i.id=`activity-details-${e.id}`,i.style.display=r?"":"none",a.setAttribute("aria-controls",i.id),n.append(a,i),be(n,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),n.dataset.personaToolGroup="true","shimmer"===t.features?.toolCallDisplay?.loadingAnimation&&(n.dataset.activityGroupShimmer="true"),{bubble:n,body:i}}let we=(e,t,r)=>{let o="transient"===t.mode,n=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)||o&&n&&!1!==t.visible?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},xe=(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:Se,load:ke,provide:Ae,getSync:Me}=U({fallbackImport:()=>import("./markdown-parsers-entry")}),Ie=new Set,Te=Se,Ee=()=>{let e=Me();return e?Promise.resolve(e):ke().then(e=>((()=>{let e=[...Ie];Ie.clear();for(let t of e)try{t()}catch{}})(),e))},Le=e=>Me()?()=>{}:(Ie.add(e),()=>{Ie.delete(e)}),Pe=Me,Be=e=>{let t=null;return r=>{let o=Pe();if(!o)return He(r);if(!t){let{Marked:r}=o,n=e?.markedOptions;t=new r({gfm:n?.gfm??!0,breaks:n?.breaks??!0,pedantic:n?.pedantic,silent:n?.silent});let a=(e=>{if(!e)return;let t={},r=e;if(r.heading){let e=r.heading;t.heading=(t,r,o)=>e({type:"heading",raw:o,depth:r,text:t,tokens:[]})}if(r.code){let e=r.code;t.code=(t,r,o)=>e({type:"code",raw:"",text:t,lang:r,escaped:o})}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,o)=>e({type:"link",raw:"",href:t,title:r??null,text:o,tokens:[]})}if(r.image){let e=r.image;t.image=(t,r,o)=>e({type:"image",raw:"",href:t,title:r??null,text:o})}if(r.list){let e=r.list;t.list=(t,r,o)=>e({type:"list",raw:"",ordered:r,start:o,loose:!1,items:[],itemsHtml:t})}if(r.listitem){let e=r.listitem;t.listitem=(t,r,o)=>e({type:"list_item",raw:"",task:r,checked:o,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)}},Ne=e=>e?Be({markedOptions:e.options,renderer:e.renderer}):Be(),Re=Be(),$e=e=>Re(e),He=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),We=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),De=e=>`%%FORM_PLACEHOLDER_${e}%%`,Fe=(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=De(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 o=De(t.length);return t.push({token:o,type:r}),o}),r},Oe={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(".")},ze=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,qe=()=>{let e=null;return t=>{let r=Pe();if(!r)return He(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:")&&!ze.test(e)&&(t.attrValue="",t.keepAttr=!1)}})}return e.sanitize(t,Oe)}},je=e=>!1===e?null:"function"==typeof e?e:qe(),_e=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Ue=e=>e.includes("|"),Ve=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())},Ke=e=>`| ${e.join(" | ")} |`,Je=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Ge=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Xe="var(--persona-md-table-scroll-fade, 24px)",Qe=new WeakSet;function Ye(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,o=t-r;e.style.setProperty("--persona-fade-l",r<=1?"0px":Xe),e.style.setProperty("--persona-fade-r",o<=1?"0px":Xe)}function Ze(e){Qe.has(e)||(Qe.add(e),e.addEventListener("scroll",e=>{let t=e.target;t?.classList?.contains("persona-table-scroll")&&Ye(t)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Ye)}let{setLoader:et,load:tt,provide:rt,getSync:ot}=U({fallbackImport:()=>import("./client-stream")}),nt=et,at=tt,st=ot,{setLoader:it,load:lt}=U({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),dt=it,ct=lt,{setLoader:pt,load:ut}=U({fallbackImport:()=>import("@runtypelabs/persona/voice-client-tools")}),ht=pt,mt=ut;function gt(e){return e.startsWith("agent_")?{kind:"agentId",agentId:e}:e.startsWith("flow_")?{kind:"flowId",flowId:e}:null}function ft(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function yt(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}var bt=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}),vt=t(e=>{var t=e&&e.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var o in e)"default"!==o&&!Object.prototype.hasOwnProperty.call(r,o)&&t(r,e,o)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let o=bt();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return o.Allow}}),r(bt(),e);var n=class extends Error{};e.PartialJSON=n;var a=class extends Error{};function s(e,t=o.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 n(`${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)||o.Allow.NULL&t&&r-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||o.Allow.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||o.Allow.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||o.Allow.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||o.Allow._INFINITY&t&&1<r-s&&r-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):"NaN"===e.substring(s,s+3)||o.Allow.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):h()),c=()=>{let n=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(n,++s-Number(a)))}catch(e){l(String(e))}else if(o.Allow.STR&t)try{return JSON.parse(e.substring(n,s-Number(a))+'"')}catch{return JSON.parse(e.substring(n,e.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},p=()=>{s++,m();let n={};try{for(;"}"!==e[s];){if(m(),s>=r&&o.Allow.OBJ&t)return n;let a=c();m(),s++;try{n[a]=d()}catch(e){if(o.Allow.OBJ&t)return n;throw e}m(),","===e[s]&&s++}}catch{if(o.Allow.OBJ&t)return n;i("Expected '}' at end of object")}return s++,n},u=()=>{s++;let r=[];try{for(;"]"!==e[s];)r.push(d()),m(),","===e[s]&&s++}catch{if(o.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(o.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}l(String(r))}}let n=s;for("-"===e[s]&&s++;e[s]&&-1===",]}".indexOf(e[s]);)s++;s==r&&!(o.Allow.NUM&t)&&i("Unterminated number literal");try{return JSON.parse(e.substring(n,s))}catch{"-"===e.substring(n,s)&&i("Not sure what '-' is");try{return JSON.parse(e.substring(n,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 wt="ask_user_question",xt="data-persona-ask-sheet-for",Ct="Type your own answer here",St="Send",kt="data-ask-question-count",At="data-ask-answers",Mt="data-ask-grouped",It=!1,Tt=e=>e.replace(/["\\]/g,"\\$&"),Et=e=>"tool"===e.variant&&!!e.toolCall&&"ask_user_question"===e.toolCall.name,Lt=e=>e?.features?.askUserQuestion??{},Pt=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 o=t.chunks;if(!o||0===o.length)return{payload:null,complete:r};try{let e=o.join(""),t=(0,vt.parse)(e,vt.STR|vt.OBJ|vt.ARR);if(t&&"object"==typeof t)return{payload:t,complete:r}}catch{}return{payload:null,complete:r}},Bt=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!It&&(It=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},Nt=(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))},Rt=(e,t,r)=>{if("rows"!==e)return null;let o=q("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let e=q("span","persona-ask-row-check");o.appendChild(e)}else{let e=q("span","persona-ask-row-badge");e.textContent=String(r+1),o.appendChild(e)}return o},$t=e=>{let t=q("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},Ht=(e,t)=>{let r=q("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 o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=e.freeTextPlaceholder??Ct,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),"rows"!==t){let t=q("button","persona-ask-free-text-submit persona-pointer-events-auto");t.type="button",t.textContent=e.submitLabel??St,t.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(t)}return r},Wt=e=>{let t=e.getAttribute(At);if(!t)return{};try{let e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch{return{}}},Dt=e=>{let t=Number(e.getAttribute("data-ask-current-index")??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Ft=e=>{let t=Number(e.getAttribute("data-ask-question-count")??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ot=e=>"true"===e.getAttribute(Mt),zt=(e,t,r)=>{let o=Lt(r),n=(e=>"pills"===e.getAttribute("data-ask-layout")?"pills":"rows")(e),{payload:a,complete:s}=Pt(t),i=Ot(e),l=Dt(e),d=Ft(e),c=i?((e,t)=>Bt(e)[t]??null)(a,l):(e=>Bt(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,o)=>{let n=q("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");n.setAttribute("role","group"),n.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++)n.appendChild($t(o));return n}if(s.forEach((e,t)=>{n.appendChild(((e,t,r,o)=>{let n=q("button","rows"===r?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(n.type="button",n.setAttribute("role",o?"checkbox":"button"),n.setAttribute("aria-pressed","false"),n.setAttribute("data-ask-user-action","pick"),n.setAttribute("data-option-index",String(t)),n.setAttribute("data-option-label",e.label),"rows"===r){let a=q("span","persona-ask-row-content"),s=q("span","persona-ask-row-label");if(s.textContent=e.label,a.appendChild(s),e.description){let t=q("span","persona-ask-row-description");t.textContent=e.description,a.appendChild(t)}n.appendChild(a);let i=Rt(r,o,t);i&&n.appendChild(i)}else n.textContent=e.label,e.description&&(n.title=e.description);return n})(e,t,o,a))}),!1!==e?.allowFreeText){let e="rows"===o?"Other":"Other…";if("rows"===o){let r=q("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=q("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??Ct,l.setAttribute("data-ask-free-text-input","true"),l.setAttribute("aria-label",t.freeTextLabel??e),i.appendChild(l),r.appendChild(i);let d=Rt(o,a,s.length);d&&r.appendChild(d),n.appendChild(r)}else{let r=q("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,n.appendChild(r)}}return n})(c,o,s,n);g.replaceWith(e)}if("rows"!==n){let t=e.querySelector('[data-ask-free-text-row="true"]');t&&t.replaceWith(Ht(o,n))}let f=e.querySelector('[data-ask-multi-actions="true"]');i||!p||f?(!p||i)&&f&&f.remove():e.appendChild((e=>{let t=q("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=q("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=e.submitLabel??St,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t})(o)),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 o=q("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=q("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=r.backLabel??"Back",n.setAttribute("data-ask-user-action","back"),n.disabled=0===e,o.appendChild(n);let a=q("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=q("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=q("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),o.appendChild(a),o})(l,d,o);y?y.replaceWith(t):e.appendChild(t)}else y&&y.remove();(e=>{let t=Wt(e)[Dt(e)],r=new Set;"string"==typeof t?r.add(t):Array.isArray(t)&&t.forEach(e=>r.add(e));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(e=>{let t=e.getAttribute("data-option-label")??"",o=r.has(t);e.setAttribute("aria-pressed",o?"true":"false"),e.classList.toggle("persona-ask-pill-selected",o)});let n=new Set(Array.from(o).map(e=>e.getAttribute("data-option-label")??"")),a=e.querySelector('[data-ask-free-text-input="true"]');a&&("string"==typeof t&&t.length>0&&!n.has(t)?(a.value=t,a.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):a.value="")})(e),(e=>{if(!Ot(e))return;let t=Wt(e)[Dt(e)],r="string"==typeof t&&t.length>0||Array.isArray(t)&&t.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!r);let n=e.querySelector('[data-ask-user-action="submit-multi"]');n&&(n.disabled=0===Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).length)})(e)},qt=(e,t,r)=>{if(!r||!Et(e)||!1===Lt(t).enabled)return;let o=e.toolCall.id;r.querySelectorAll(`[${xt}]`).forEach(e=>{e.getAttribute(xt)!==o&&e.remove()});let n=r.querySelector(`[${xt}="${Tt(o)}"]`);if(n)return void((e,t,r)=>{let{payload:o}=Pt(t),n=Math.max(1,Bt(o).length);n>Ft(e)&&(e.setAttribute(kt,String(n)),n>1&&!Ot(e)&&e.setAttribute(Mt,"true")),zt(e,t,r)})(n,e,t);let{payload:a}=Pt(e),s=((e,t,r)=>{let o=Lt(t),n=(e=>"pills"===e.layout?"pills":"rows")(o),a=e.toolCall.id,s=Bt(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 o={};return t.forEach((e,t)=>{let n="string"==typeof e?.question?e.question:"";if(n&&Object.prototype.hasOwnProperty.call(r,n)){let e=r[n];("string"==typeof e||Array.isArray(e))&&(o[t]=e)}}),o})(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=q("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(xt,a),p.setAttribute("data-tool-call-id",a),p.setAttribute("data-message-id",e.id),p.setAttribute(kt,String(i)),p.setAttribute("data-ask-current-index",String(c)),p.setAttribute(Mt,l?"true":"false"),p.setAttribute("data-ask-layout",n),((e,t)=>{e.setAttribute(At,JSON.stringify(t))})(p,d),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),void 0!==o.slideInMs&&p.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Nt(p,o);let u=q("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=q("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",u.appendChild(h);let m=q("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",u.appendChild(m),p.appendChild(u);let g=q("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");return g.setAttribute("data-ask-pill-list","true"),g.setAttribute("role","group"),p.appendChild(g),"rows"!==n&&p.appendChild(Ht(o,n)),zt(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p})(e,t,a);r.appendChild(s)},jt=(e,t)=>{if(!e)return;let r=t?`[${xt}="${Tt(t)}"]`:`[${xt}]`;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)})},_t="suggest_replies",Ut={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},Vt={name:_t,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:Ut,origin:"sdk",annotations:{readOnlyHint:!0}},Kt=e=>"tool"===e.variant&&"suggest_replies"===e.toolCall?.name,Jt=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 o=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 o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Gt=e=>{for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role)return null;if(!Kt(r))continue;let o=Jt(r.toolCall?.args);return o.length>0?o:null}return null},Xt=new Set,Qt=e=>{let t=e?.suggestions?.followUps,r=e?.features?.suggestReplies,o=e=>{let o=t?.[e],n=r?.[e];void 0!==o&&void 0!==n&&o!==n&&((e,t,r)=>{let o=`${e}:${t}:${r}`;Xt.has(o)||(Xt.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))})(e,n,o)};e&&(o("enabled"),o("expose"));let n=t?.enabled??r?.enabled??!0;return{enabled:n,expose:!!n&&(t?.expose??r?.expose??!1)}},Yt={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},Zt={name:wt,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:Yt,origin:"sdk",annotations:{readOnlyHint:!0}},er=e=>{let t=[],r=e?.features?.askUserQuestion;return!0===r?.expose&&!1!==r.enabled&&t.push(Zt),Qt(e).expose&&t.push(Vt),t},tr=e=>"object"==typeof e&&!!e&&!Array.isArray(e),rr=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:tr(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:r,result:t.result}}:null},or=(e,t)=>{let r,o=[],n=[],a=[],s="",i=()=>{0!==n.length&&(o.push({role:"assistant",content:"",createdAt:s,toolCalls:n},{role:"tool",content:"",createdAt:s,toolResults:a}),n=[],a=[])};for(let l of e){let e=rr(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;n.length>0&&(void 0===t||t!==r)&&i(),0===n.length&&(s=l.createdAt,r=t),n.some(t=>t.toolCallId===e.call.toolCallId)||(n.push(e.call),a.push(e.result));continue}let d=t(l);d&&(i(),o.push(d))}return i(),o},nr=e=>e.replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ar=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)}},sr=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ir=e=>{if(e.interrupted&&void 0===e.duration&&void 0===e.durationMs&&(void 0===e.startedAt||void 0===e.completedAt))return"";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 sr(t)},lr=e=>{let t=void 0===e.durationMs?Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())):e.durationMs;return sr(t)},dr=(e,t,r)=>{if(!t)return r;let o=e.name?.trim()||"tool",n=ir(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},cr=(e,t)=>{let r,o=e.replace(/\{toolName\}/g,t),n=[],a=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0;for(;null!==(r=a.exec(o));)r.index>s&&pr(n,o.slice(s,r.index),[]),void 0===r[1]?void 0===r[2]?void 0!==r[3]&&pr(n,r[3],["dim"]):pr(n,r[2],["italic"]):pr(n,r[1],["bold"]),s=r.index+r[0].length;return s<o.length&&pr(n,o.slice(s),[]),n},pr=(e,t,r)=>{let o=t.split("{duration}");for(let t=0;t<o.length;t++)o[t]&&e.push({text:o[t],styles:r}),t<o.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},ur=()=>({processChunk:()=>null,getExtractedText:()=>null,__isPlainTextParser:!0}),hr=()=>{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 o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let n=(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!==n&&(e=n),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)}},mr=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return null!==e||""===e?{text:e||"",raw:r}:null;try{let t=(0,vt.parse)(r,vt.STR|vt.OBJ);t&&"object"==typeof t&&(t.component&&"string"==typeof t.component?e="string"==typeof t.text?nr(t.text):"":"init"===t.type&&t.form?e="":"string"==typeof t.text&&(e=nr(t.text)))}catch{}return t=r.length,null===e?null:{text:e,raw:r}},close:()=>{}}},gr=()=>{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}},fr="4.29.2",{setLoader:yr,load:br,provide:vr}=U({fallbackImport:()=>import("./client-history")}),wr=yr,xr=br;function Cr(e){return"string"!=typeof e&&e.some(e=>"image"===e.type)}function Sr(e){return{type:"text",text:e}}let kr=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ar=[...kr,"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 Mr(e){return function(e){return kr.includes(e)||e.startsWith("image/")}(e.type)}function Ir(e,t=Ar,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 Tr(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 Er(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(),o=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let n=e.sequence??0,a=t.sequence??0;return n===a?e.id.localeCompare(t.id):n-a})}let Lr=e=>!0===e.localOnly||"assistant"===e.role&&"string"==typeof e.id&&e.id.startsWith("reconnect-failed-"),Pr={idle:"Online",connecting:"Connecting…",connected:"Streaming…",error:"Offline",paused:"Connection lost…",resuming:"Reconnecting…"};var Br=class extends Error{constructor(e,t,r){super(t),this.name="HistoryClientError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};let Nr=e=>"reason"in e?e.reason:void 0,Rr=(e,t)=>e instanceof Br&&e.code===t,$r=e=>!e.voiceCaption&&!Lr(e)&&!!(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),Hr=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),Wr=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});var Dr=class{#e;#t;#r;#o;#n;#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":fr,...e.headers},this.debug=!!e.debug,this.#r=e.streamParser??function(e){switch(e){case"json":return mr;case"regex-json":return hr;case"xml":return gr;default:return ur}}(e.parserType),this.#o=e.contextProviders??[],this.#n=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 ct().then(t=>{let r=new t.WebMcpBridge(e,{recordToolDisplayTitles:n,getToolDisplayTitle:a,loadPolyfill:p});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 mt()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await((await e())?.snapshotForDispatch())??[];return{tools:t,fingerprint:i(t)}},onChange:t=>{let r=null,o=!1;return e().then(e=>{e&&!o&&(r=e.watchToolChanges(t))}),()=>{o=!0,r?.()}},execute:async(t,r,o)=>{let n=await e();return n?n.executeVoiceToolCall(t,r,o):{status:"failed",error:{message:"WebMCP runtime failed to load."}}}};return t}executeWebMcpToolCall(e,t,r){return!0===this.config.webmcp?.enabled?this.#k().then(o=>o?o.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:o}=this.config;if(!r)return{agentId:e,flowId:t};let n=function(e,t){let r=e.trim();if(!r)throw Error("[Persona] `target` is empty.");let o=r.indexOf(":");if(o>0){let e=r.slice(0,o),n=r.slice(o+1);if("runtype"===e){let e=gt(n);if(e)return e;throw Error(`[Persona] target "runtype:${n}" 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(n).payload}}let n=gt(r);if(n)return n;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,o);return"agentId"===n.kind?{agentId:n.agentId}:"flowId"===n.kind?{flowId:n.flowId}:{targetPayload:n.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 o=t.conversationId,n=await this.readVisitorToken();if(!0!==t.durableRecovery?.enabled||!o||!n)throw new Br("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.#M()}/v1/client/conversations/${encodeURIComponent(o)}/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":fr,"X-Visitor-Token":n},signal:e.signal});if(401!==i.status||r){if(!i.ok)throw await(await xr()).historyErrorFor(this.#T(),i,!0);return i}{r=!0;let e=await xr();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.#$()}#$(){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&&Nr(t)===Nr(e);if(this.#f=e,!r){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#y])t(e)}}async#H(e){let t=this.#L()&&!e.omitVisitorFields,r=!e.omitVisitorFields,o=null;(t||r)&&(await this.historyInternals.historyBootstrapReady,o=await this.readVisitorToken());let n=this.#A(),a=n.agentId??n.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)&&o?{visitorToken:o}:{},...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":fr},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 Br("history_disabled","Visitor history is disabled for this surface");return this.#H({...e,omitVisitorFields:!0})}throw 403===l.status&&"durable_recovery_disabled"===r.error?new Br("history_disabled","Durable recovery is disabled for this surface"):(t||e.durableResume)&&401===l.status&&"visitor_required"===r.error?new Br("visitor_required","Visitor credential no longer resolves"):s&&404===l.status?new Br("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.#H({conversationId:e,durableResume:t});return t&&!0!==r.durableRecovery?.enabled&&this.historyInternals.setStoredResumableHandle?.(null),this.#D(r,e,!1)}catch(r){if(!Rr(r,"not_found")&&!Rr(r,"visitor_required")&&!Rr(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,o=await this.#H({storedSessionId:r}),n=await this.#O(o);return this.#D(n,e,t)}async#z(e){let t=this.config.getStoredSessionId?.()||null,r=this.config.getStoredConversationId?.()||null,o=await this.#H({storedSessionId:t,identityProof:e}),n=this.#D(o,r,!1);return this.clientSession=n,this.#c=null,this.#p=!1,this.resetClientToolsFingerprint(),n}async#O(e){if(!e.visitor?.token||this.#g||!this.#L()&&!0!==e.durableRecovery?.enabled)return e;this.#g=!0;try{return await this.#H({storedSessionId:e.sessionId})}catch{return e}finally{this.#g=!1}}#D(e,t,r){let o=e.conversationId;return o&&t&&(r||o!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:o}),this.config.setStoredSessionId?.(e.sessionId),o&&(this.config.setStoredConversationId?.(o),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 Br("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 Br("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let o=await this.#H({conversationId:e,identityProof:r});return this.#q(o)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.#H({});return this.#q(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#L()&&this.#B(this.#$())}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":fr},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,o,n=this.config.getIdentityProof;if(!t.trim()||!n)throw Error("Chat identity requires identityProvider and getIdentityProof.");try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,r)=>{o=()=>r(e.reason),e.addEventListener("abort",o,{once:!0}),e.aborted&&o()})]):await t}catch{throw e?.throwIfAborted(),Error("The identity proof provider failed.")}finally{o&&e?.removeEventListener("abort",o)}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,o,n)=>e.#V(t,r,o,n),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#C;#T(){let e=this;return this.#C??={HistoryClientError:Br,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.#$(),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 xr()).listConversations(this.#T(),e)}async getConversation(e,t){return(await xr()).getConversation(this.#T(),e,t)}async finalizeDisplayProjections(e,t){return(await xr()).finalizeDisplayProjections(this.#T(),e,t)}async deleteConversation(e,t){return(await xr()).deleteConversation(this.#T(),e,t)}async deleteAllConversations(e){return(await xr()).deleteAllConversations(this.#T(),e)}async resetVisitor(){return(await xr()).resetVisitor(this.#T())}async dispatch(e,t){return e.signal?.throwIfAborted(),at().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#J(e,t):this.#G(e,t)}async#K(e,t){let r=`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`;this.#d=r;let o=()=>this.#d===r,n=e=>{o()&&t(e)};t({type:"status",status:"connecting"});try{let t=()=>{if(e.signal?.throwIfAborted(),!o())throw new DOMException("Turn superseded","AbortError")},a=this.clientSession??await this.initSession();t();let s=async()=>{t();let r=a,o=!0===r.durableRecovery?.enabled;if(o&&(!r.conversationId||!await this.readVisitorToken()))throw Error("Renewing this conversation requires its visitor credential.");t();let n=await this.#H({...o||this.#L()?{conversationId:r.conversationId,durableResume:o}:{storedSessionId:r.sessionId},signal:e.signal});if(t(),r.conversationId&&n.conversationId!==r.conversationId||o&&!0!==n.durableRecovery?.enabled)throw Error("Session renewal did not preserve this conversation.");a=this.#D(n,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.#X(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($r).map(e=>{let t=d?Tr(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,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},p=async()=>{t();let r=!0===a.durableRecovery?.enabled?await this.readVisitorToken():null;return t(),this.#V(a.sessionId,i.clientTools,async o=>{t();let n=await this.#_(e.signal);t();let s={...c,sessionId:a.sessionId,...o,...n&&{identityProof:n}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...s,...n&&{identityProof:{provider:n.provider,token:"[REDACTED]"}}}),fetch(this.#I("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr,...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 Br("invalid_identity_proof","The identity proof was rejected");throw n({type:"error",error:e}),e}if(401===h.status){this.clearClientSession(),this.config.onSessionExpired?.();let e=Error("Session expired. Please refresh to continue.");throw n({type:"error",error:e}),e}if(429===h.status){let t=Error(e.hint||"Message limit reached for this session.");throw n({type:"error",error:t}),t}if(410===h.status&&"conversation_deleted"===e.error){let e=new Br("conversation_deleted","This conversation was deleted");throw n({type:"error",error:e}),e}let t=Error(e.error||"Failed to send message");throw n({type:"error",error:t}),t}if(!h.body){let e=Error("No response body received");throw n({type:"error",error:e}),e}m(),n({type:"status",status:"connected"});try{await this.#Q(h.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof Br)&&!t.message.includes("Session expired")&&!t.message.includes("Message limit")&&n({type:"error",error:t}),t}}async#G(e,t){t({type:"status",status:"connecting"});let r=await this.#X(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let o,n={...this.#t};if(this.#i)try{let e=await this.#i();n={...n,...e}}catch(e){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",e)}if(this.#a)try{o=await this.#a(this.#e,{method:"POST",headers:n,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 o=await fetch(this.#e,{method:"POST",headers:n,body:JSON.stringify(r),signal:e.signal});if(!o.ok||!o.body){let e=Error(`Chat backend request failed: ${o.status} ${o.statusText}`);throw t({type:"error",error:e}),e}t({type:"status",status:"connected"});try{await this.#Q(o.body,t)}finally{t({type:"status",status:"idle"})}}async#J(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 o,n={...this.#t};if(this.#i)try{let e=await this.#i();n={...n,...e}}catch(e){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",e)}if(this.#a)try{o=await this.#a(this.#e,{method:"POST",headers:n,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 o=await fetch(this.#e,{method:"POST",headers:n,body:JSON.stringify(r),signal:e.signal});if(!o.ok||!o.body){let e=Error(`Agent execution request failed: ${o.status} ${o.statusText}`);throw t({type:"error",error:e}),e}t({type:"status",status:"connected"});try{await this.#Q(o.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,o){t({type:"status",status:"connected"});try{await this.#Q(e,t,r,o)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t,r){return(await at()).resolveApproval(this.#U(),e,t,r)}async#V(e,t,r,o){let n,a=!!(t&&t.length>0),s=a?i(t):void 0,l=this.clientToolsFingerprintSessionId===e,d=a&&l&&this.lastSentClientToolsFingerprint===s,c=!a&&!0===o?.emptyMeansReplace&&this.#u===e,p=!1;for(let e=0;n=await r({...a&&(p||!d)&&t?{clientTools:t}:{},...c?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),409===n.status&&0===e&&a&&"client_tools_resend_required"===(await n.clone().json().catch(()=>null))?.error;e++)p=!0,this.lastSentClientToolsFingerprint=null;return{response:n,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=e,a?this.#u=e:c&&(this.#u=null)}}}async resumeFlow(e,t,r){return(await at()).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.#o.length&&await Promise.all(this.#o.map(async r=>{try{let o=await r({messages:e,config:this.config});o&&"object"==typeof o&&Object.assign(t,o)}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 o=or(Hr(e),e=>!$r(e)||"user"!==e.role&&"assistant"!==e.role&&"system"!==e.role||e.variant&&"assistant"!==e.variant?null:Wr(e)),n=this.#te(t),a={agent:this.#re(this.config.agent??{agentId:r},n),messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};n&&(a.composerOptions=n);let s=[...er(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#X(e,t){let r=or(Hr(e),e=>$r(e)?Wr(e):null),o=this.#A(),n={messages:r,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[e,t]of Object.entries(o.targetPayload))"messages"!==e&&(n[e]=t);let a=[...er(this.config),...await((await this.#k())?.snapshotForDispatch())??[]];a.length>0&&(n.clientTools=a);let s=await this.#ee(e);s&&(n.context=s);let i=this.#te(t);if(i&&(n.composerOptions=i),this.#n)try{let e=await this.#n({payload:{...n},config:this.config});if(e&&"object"==typeof e){let t=e;return void 0!==n.clientTools&&!("clientTools"in t)&&(t.clientTools=n.clientTools),t}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",e)}return n}async#Q(e,t,r,o){let{streamResponse:n}=st()??await at();return n({config:()=>this.config,createStreamParser:this.#r,parseSSEEvent:this.#s,onSSEEvent:(e,t)=>this.#l?.(e,t)},e,t,r,o)}},Fr=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:Or,load:zr,provide:qr,getSync:jr}=U({fallbackImport:()=>import("./ui-extras-entry")}),_r=Or,Ur=zr,Vr=jr,{setLoader:Kr,load:Jr,provide:Gr,getSync:Xr}=U({fallbackImport:()=>import("./session-actions")}),Qr=Kr,Yr=Jr,Zr=Xr,eo=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function to(e){return"card"===e?"collapsed":e}function ro(e){return e.split(";",1)[0].trim().toLowerCase()}function oo(e,t){let r=e?.display,o="string"==typeof r?{default:r}:r??{};if(t.file&&o.files){if("string"==typeof o.files)return{mode:to(o.files),matchedBy:{type:"files"}};let e=t.file.mimeType?ro(t.file.mimeType):void 0,r=e?function(e,t){if(!e)return;let r=Object.entries(e);for(let[e,o]of r)if(ro(e)===t)return{mode:to(o),selector:ro(e)};let o=`${t.split("/",1)[0]}/*`;for(let[e,t]of r)if(ro(e)===o)return{mode:to(t),selector:o}}(o.files.byMediaType,e):void 0;if(e&&r)return{mode:r.mode,matchedBy:{type:"mediaType",mediaType:e,selector:r.selector}};if(o.files.default)return{mode:to(o.files.default),matchedBy:{type:"files"}}}let n=o.byKind?.[t.artifactType];if(n)return{mode:to(n),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=o.byType?.[t.artifactType];if(a)return{mode:to(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:to(s),matchedBy:{type:"preferredMode"}}:o.default?{mode:to(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function no(e,t){return oo(e,t).mode}function ao(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 so(e,t=140){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-1)}…`}function io(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 lo(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 co(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 po=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 o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(n.voice=e)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):co(a));void 0!==t.rate&&(n.rate=t.rate),void 0!==t.pitch&&(n.pitch=t.pitch),n.onend=()=>r.onEnd?.(),n.onerror=e=>{let t=e.error;"canceled"===t||"interrupted"===t?r.onEnd?.():r.onError?.(Error(t||"Speech synthesis failed"))},setTimeout(()=>{o.speak(n),r.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},uo=class{#e=null;#t=null;#r="idle";#o=new Set;#n=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.#o.add(e),()=>this.#o.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.#n;this.#e?.stop(),this.#s(e,"loading");try{if(!this.#e){let e=await this.#a();if(r!==this.#n)return;if(!e)return void this.#s(null,"idle");this.#e=e}this.#e.speak(t,{onStart:()=>{r===this.#n&&this.#s(e,"playing")},onEnd:()=>{r===this.#n&&this.#s(null,"idle")},onError:()=>{r===this.#n&&this.#s(null,"idle")}})}catch{r===this.#n&&this.#s(null,"idle")}}stop(){this.#n++,this.#e?.stop(),this.#s(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#o.clear()}#s(e,t){this.#t="idle"===t?null:e,this.#r=t;for(let e of this.#o)e(this.#t,this.#r)}},ho=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:mo,load:go,getSync:fo}=U({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),yo=mo,bo=go,vo=fo;function wo(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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /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 xo=null,Co=()=>xo?xo():import("./voice/runtype-tts-entry"),{setLoader:So,load:ko}=U({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),Ao=So,Mo=ko,Io="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 To=class extends Error{constructor(e,t){super(t),this.name="SessionHistoryError",this.code=e}};function Eo(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 o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return r.message?`${o}\n\n_Details: ${r.message}_`:o}let Lo=e=>c(e)||"suggest_replies"===e;var Po=class e{#e;#t;#r;#o;#n;#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;#$;#B;#H;#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.#o=null,this.#n=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.#$=null,this.#B=!1,this.#H=null,this.#E=null,this.#W=!1,this.#F=null,this.#D=null,this.#q=null,this.#j=new ho,this.#_=Promise.resolve(),this.#x=null,this.#U=null,this.ttsSpokenMessageIds=new Set,this.readAloud=new uo(()=>this.#C()),this.#oe=null,this.#ne=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.#n=e.message.id),("approval"===e.message.variant||!0===e.message.agentMetadata?.awaitingLocalTool)&&Yr().catch(()=>{});let o=e.message.toolCall,n=!!o?.name&&(c(o.name)||"suggest_replies"===o.name&&Qt(this.config).enabled);!0===e.message.agentMetadata?.awaitingLocalTool&&n&&!0===this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool&&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=>({...h(e),sequence:e.sequence??this.#ye()})),this.messages=this.#be(this.messages),this.client=new Dr(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&&bo().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&&Co().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=po.isSupported()?new po({pickVoice:e?.pickVoice}):null;if("runtype"===e?.provider){let r=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,n=this.config.clientToken,a=!1!==e.browserFallback;if(r&&o&&n)return Co().then(({RuntypeSpeechEngine:s,FallbackSpeechEngine:i})=>{let l=new s({host:r,agentId:o,clientToken:n,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 n&&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.#_,o=++this.#m;this.#h=bo().then(async e=>{await r,o===this.#m&&this.#T(e,e.createVoiceProvider(t))}).catch(e=>{console.error("Failed to setup voice:",e)}).finally(()=>{o===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.#K(),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.#J(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()}#K(){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.#G(e)}this.#f=!1,this.#y="disconnected",this.#J(!0),this.#x?.settle(),this.#x=null,this.#j=new ho,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#G(e){try{await e.disconnect()}catch(e){console.error("Failed to disconnect voice:",e)}}#J(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.#$=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],o={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(o)}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.#H?.(),this.#H=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 To("history_unavailable","No conversation history provider is installed");return e}#re(e){let t=this.#te(),r=e??this.config.features?.history?.scope,o=this.config.getIdentityProof?"verified-user":"browser",n=r??(t.capabilities.scopes.includes(o)?o:t.capabilities.scopes[0]??o);if(!t.capabilities.scopes.includes(n))throw new Fr("unsupported_scope","This history scope is not supported.");return{scope:n}}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())}#X(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(()=>{})}#Q(){if(this.streaming||"paused"===this.status||"resuming"===this.status)throw new To("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.#Q();let o=this.#re(t?.scope);await this.awaitHistorySettled();let n=++this.#S,a=await r.getPage(e,{context:o});if(n!==this.#S)throw new To("superseded","A later selection won");let s=await r.prepareOpen(e,{context:o});if(n!==this.#S)throw s.discard(),new To("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 o=this.#te(),n=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(o,e,a,n).finally(()=>{this.#L.delete(s)});return this.#L.set(s,l),l}async#Ie(e,t,r,o){let n=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:r,...n?{beforeCreatedAt:n}:{},context:o});if(this.#b&&this.#b!==t)return{messages:[],nextMessageCursor:a.nextCursor};let s=this.#Te(a.messages),i=Er(this.messages,s);this.messages=this.#be(i.map(e=>this.#Ee(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:s,nextMessageCursor:a.nextCursor}}#Te(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let r=t.get(e.id);if(r){if(this.webMcpApprovalResolvers.has(r.id)||r.approval&&u(r.approval)&&r.approval.id===e.approval?.id&&"pending"!==r.approval.status&&"pending"===e.approval?.status)return r;let t=r.agentMetadata?.executionId,o=[...r.toolCall?[r.toolCall]:[],...r.tools??[]];if(t&&o.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return r}return h(e)})}async startNewConversation(e){let t=this.#te(),r=this.#re(e?.scope);await this.awaitHistorySettled();let o=++this.#S,n=await t.prepareStartNew({context:r});if(o!==this.#S)throw n.discard(),new To("superseded","A later action won");await this.#Le(n)}async#Le(e){this.#Pe(),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(),o=this.#re(t?.scope);await this.awaitHistorySettled(),await r.delete(e,{context:o}),e===this.#b&&await this.#Be(o)}async updateConversation(e,t,r){let o=this.#te();if(!o.update)throw new To("history_unavailable","This history provider cannot update conversations");let n=this.#re(r?.scope);return await this.awaitHistorySettled(),o.update(e,t,{context:n})}canUpdateConversations(){return"function"==typeof this.#ee?.update}async clearConversationHistory(e){let t=this.#te(),r=this.#re(e?.scope);await this.awaitHistorySettled();let o=await t.deleteAll({...void 0===e?.targetId?{}:{targetId:e.targetId},context:r});return await this.#Be(r),o}async resetHistoryDevice(){let e=this.#te();if(!e.resetDevice)throw new To("history_unavailable","This history provider cannot reset the device");this.#S+=1,this.#P=null;try{return await e.resetDevice()}finally{this.#Pe(),this.#b=null,this.#v=null,this.#w=null,this.#A=null,this.#M=!1,this.#Y()}}async#Be(e){this.#S+=1,this.#P=null,this.#Pe(),this.#b=null,this.#v=null,this.#w=null,this.#M=!0,this.#A=null,this.#Y(),await this.#Ne(e)}async#Ne(e){let t=this.#ee;if(t)try{let r=await t.prepareStartNew({context:e});await this.#Le(r)}catch{this.#M=!0,this.#A="new_conversation_required",this.#Y(),this.#X("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}else this.#M=!1,this.#Y()}async#Re(){if("new_conversation_required"===this.#A&&this.#ee&&(this.#A=null,await this.#Ne(this.#re()),"new_conversation_required"===this.#A))throw new To("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.#$e(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#N.clear(),this.#He(null)}#Pe(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#We(),this.#De(),this.#ne++,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.#Pe(),this.#b=e.conversationId,this.#v=null,this.#w=null,this.#A=null,this.#Y(),this.#X("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.#H?.(),this.#H=null,this.#E=e,e&&(this.#H=e.subscribe(e=>this.#Fe(e))))}#Fe(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.#Pe():(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.#X("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#Oe(){return this.#W?(this.#F||=this.#ze().finally(()=>{this.#F=null}),this.#F):Promise.resolve()}async#ze(){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 o=this.#re(e?.scope);this.#M=!0,this.#Y();let n=this.#qe(t,r,o).finally(()=>{this.#M=null!==this.#A,this.#I===n&&(this.#I=null),this.#Y()});return this.#I=n,n}async#qe(e,t,r){this.#b=t;let o=this.clientSession?.conversationRevision??this.#v??null,n=this.#B?this.#$:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#B=!1,this.#w=this.historyInternals.getStoredMessageCursor?.()??this.#w,await this.replayPendingProjections(),o&&n&&o===n)return void(this.#v=o);let a,s=await e.getPage(t,{context:r}),i=this.#Te(s.messages),l=new Set(s.messages.map(e=>e.id)),d=this.messages.some(e=>l.has(e.id)),c=s.messages[0]?.createdAt;if(d){let e=this.#o?this.#n:null;a=Er(this.messages.filter(t=>!(!l.has(t.id)&&t.id!==e)||void 0!==c&&t.createdAt<c),i).map(e=>this.#Ee(e))}else a=i.map(e=>this.#Ee(e));this.#w=s.nextCursor,this.#v=s.conversationRevision||o||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])}#je(){return!0===this.config.features?.history?.enabled&&this.isClientTokenMode()}#He(e){this.#R=e,this.historyInternals.setPendingDisplayProjections?.(e)}#_e(){return this.historyInternals.getPendingDisplayProjections?.()??this.#R}#Ue(e){if(this.#je())for(let t of e){let e=Tr(t);void 0!==e&&this.#N.set(t.id,e)}}#me(){if(!this.#je())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=Tr(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.#Ke(e,t,!1)).finally(()=>{this.#P===r&&(this.#P=null)});this.#P=r}async#Ke(e,t,r){if(this.#b!==e)return;let o=t.filter(e=>this.#N.get(e.id)!==e.displayContent);if(0===o.length)this.#Je(e,t);else try{let{conversationRevision:r}=await this.client.finalizeDisplayProjections(e,o);for(let e of o)this.#N.set(e.id,e.displayContent);this.#b===e&&r&&(this.#v=r),this.#Je(e,t)}catch(n){if(!r&&this.#Ge(n))return void await this.#Ke(e,o,!0);if(n instanceof Br&&("not_found"===n.code||"conversation_deleted"===n.code))return void this.#Je(e,t);this.#X("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#Ge(e){return e instanceof Br?"request_failed"===e.code:e instanceof Error}#Je(e,t){let r=this.#_e();if(!r||r.conversationId!==e)return;let o=new Set(t.map(e=>e.id)),n=r.messageIds.filter(e=>!o.has(e));this.#He(n.length?{conversationId:e,messageIds:n}:null)}async replayPendingProjections(){if(!this.#je())return;let e=this.#_e();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#Xe(){await this.awaitHistorySettled(),await this.#Oe(),"new_conversation_required"===this.#A&&await this.#Re()}static#Qe(e){return e instanceof Br&&"conversation_deleted"===e.code}async#Ye(t,r,o,n,a){this.#Ue(t);try{return void await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:o,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent)}catch(t){if(!e.#Qe(t))throw t;let s=await this.#Ze(n);if(!s)throw t;this.#Ue([s]),await this.client.dispatch({messages:[s],signal:r.signal,assistantMessageId:o,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent)}}async#Ze(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let r={...t};this.#S+=1,this.#P=null,this.#Pe(),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.#Le(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.#X("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.#X("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},o=function(e,t){let r=e.voiceRecognition,o=t.voiceRecognition;return!0===r?.enabled!=(!0===o?.enabled)||r?.provider?.type!==o?.provider?.type||r?.provider?.custom!==o?.provider?.custom||r?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(r?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}(this.config,r),n=function(e,t){return Io.some(r=>e[r]!==t[r])}(this.config,r);this.config=r,o&&(this.cleanupVoice(),!0===r.voiceRecognition?.enabled&&Ce(r.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(r.features?.artifacts?.display);if(!n)return this.client.updateConfig(r),void(a&&this.#et());this.#De(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.client=new Dr(this.config,this.historyInternals),a&&this.#et(),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:o,contentParts:n,id:a,createdAt:s,sequence:i,streaming:l=!1,voiceProcessing:d,voiceCaption:c,rawContent:p}=e,u={id:a??("user"===t?ft():"assistant"===t?yt():`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!==o&&{llmContent:o},...void 0!==n&&{contentParts:n},...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:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:l,streaming:d=!1,voiceProcessing:c,rawContent:p}=r,u={id:s??("user"===e?ft():"assistant"===e?yt():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:o,createdAt:i??(new Date).toISOString(),sequence:l??this.#ye(),streaming:d,...void 0!==n&&{llmContent:n},...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:o="",llmContent:n,id:a,createdAt:s,sequence:i}=e,l={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...void 0!==n&&{llmContent:n},...void 0!==a&&{id:a},...void 0!==s&&{createdAt:s},...void 0!==i&&{sequence:i}})}async#tt(e,t,r){let o;try{o=await r()}catch{return}let n=o.blocks.join("\n\n"),a=[n,t].filter(Boolean).join("\n\n"),s=Array.isArray(e.contentParts)&&e.contentParts.length>0,i=o.contentParts.length>0;if(s){let t=[];n&&t.push(Sr(n)),t.push(...o.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(i){let t=[];a&&t.push(Sr(a)),t.push(...o.contentParts),e.contentParts=t}else n&&(e.llmContent=a);Object.keys(o.context).length>0&&(e.mentionContext=o.context)}async sendMessage(e,t){let r=e.trim(),o=!!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||o))return;this.#U&&!t?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#I||this.#P||this.#M||this.#W)&&await this.#Xe(),this.stopSpeaking(),this.abortController?.abort(),this.#De(),this.#ne++,this.#We();let n=t?.voiceTurn?.userMessageId,a=n?this.messages.find(e=>e.id===n&&"user"===e.role):void 0,s=a?.id??ft(),i=yt();this.#n=null;let l=t?.contentParts&&Cr(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.#tt(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:[Sr(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=(new Date).toISOString(),u=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:p}]:[...this.messages],h=(a??this.messages.find(e=>e.id===s))?.createdAt??p,m=((e,t)=>{let r=new Set;return(Array.isArray(e)?e:[]).flatMap(e=>{if(!eo(e))return[];let{toolCallId:o,name:n}=e;if("string"!=typeof o||!o||"string"!=typeof n||!n||r.has(o))return[];r.add(o);let a=eo(e.arguments)?e.arguments:{},s=e.result??null;return[{id:`voice-tool-${o}`,role:"assistant",variant:"tool",content:"",createdAt:t,streaming:!1,toolCall:{id:o,name:n,status:"complete",args:a,result:s},agentMetadata:{clientToolAnswer:{toolCallId:o,toolName:n,args:a,result:s}}}]})})(t?.voiceTurn?.priorToolResults,h);for(let e of m)this.messages.some(t=>t.id===e.id)||(this.#Ce(e),u.push({...e,createdAt:p}));let g=m.map(({agentMetadata:e})=>{let{toolCallId:t,toolName:r,args:o,result:n}=e.clientToolAnswer;return{toolCallId:t,name:r,arguments:o,result:n}});try{await this.#Ye(u,c,i,s,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn,...g.length>0&&{voicePriorToolResults:g}})}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=Eo(e,this.config.errorMessage);if(t){let e={id:i,role:"assistant",createdAt:(new Date).toISOString(),content:t,localOnly:!0,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 o=r+1;for(;o<e.length&&"user"!==e[o].role;)o+=1;return{start:r,end:o}}(this.messages,e);if(!r)return!1;let o=this.messages[r.start],n=t.replacement,a=n?n.text:o.content,s=n?n.contentParts:o.contentParts;if(!(a?.trim()||(s?.length??0)>0||!n&&(o.llmContent?.trim()?.length??0)>0))return!1;let i=n?void 0:{...void 0!==o.llmContent&&{llmContent:o.llmContent},...void 0!==o.rawContent&&{rawContent:o.rawContent},...o.mentionContext&&{mentionContext:o.mentionContext},...o.contextMentions&&{contextMentions:o.contextMentions},...o.quote&&{quote:o.quote}},l=n?this.#rt(n.options):o.composerOptions,d=n?n.contentSegments:o.contentSegments,c=n?n.options?.quote:void 0,p=n?n.viaVoice:o.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}#rt(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.#Xe(),this.abortController?.abort(),this.#We();let e=yt();this.#n=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=Eo(t,this.config.errorMessage);if(r){let t={id:e,role:"assistant",createdAt:(new Date).toISOString(),content:r,localOnly:!0,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.#n=t.assistantMessageId);let r=t?.preserveAssistantId?t.assistantMessageId:void 0,o=!1;for(let e of this.messages)e.streaming&&e.id!==r&&(e.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.#ce(!0);let n={};try{await this.client.processStream(e,e=>{let t=this.#t;this.#t=n;try{this.handleEvent(e)}finally{this.#t=t}},t?.assistantMessageId,t?.seedContent),this.#ot(n)}catch(e){if("resuming"===this.status||this.#a)return void this.#nt(n);this.#ot(n),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;do{t="webmcp-"+ ++this.#p}while(this.messages.some(e=>e.id===`approval-${t}`||e.approval?.id===t));let r={id:t,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(t=>{this.webMcpApprovalResolvers.set(o,t),e.signal?.addEventListener("abort",()=>this.resolveWebMcpApproval(o,"timeout"),{once:!0})})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(t=>t.id===e);o?.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r("approved"===t)}#oe;#ne;#at(e){let t=this.#oe??={s:this,setStreaming:e=>this.#ce(e),appendMessage:e=>this.#Ce(e),nextSequence:()=>this.#ye(),settleApprovalPausedToolCall:e=>this.#st(e),resumeAfter:e=>this.#o?.executionId===e?this.#o.lastEventId:void 0},r=Zr();if(r)return e(r,t);let o=this.#ne;return Yr().then(r=>o===this.#ne?e(r,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,r){return this.#at((o,n)=>o.resolveApproval(n,e,t,r))}resolveAskUserQuestion(e,t){return this.#at((r,o)=>r.resolveAskUserQuestion(o,e,t))}resolveWebMcpToolCall(e){return this.#at((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 o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.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.#it(e)})}#it(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.#at((t,o)=>t.resolveWebMcpToolCallBatch(o,e,r))}#De(){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.#We(),this.#De(),this.#ne++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#ce(!1),this.#de("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#We(),this.#De(),this.#ne++,this.messages=[],this.agentExecution=null,this.#$e(),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.#$e()}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.#lt(r),r}#lt(e){let t=`artifact-ref-${e.id}`,r=ao(no(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}}),o=this.messages.find(e=>e.id===t);o?(o.rawContent=r,o.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:"",rawContent:r})}#et(){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 o=ao(no(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!==o&&(r.rawContent=o,r.streaming="streaming"===t.status,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#$e(){(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.#We(),this.#De(),this.#ne++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#be(e.map(e=>({...h(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.#n||"running"!==this.agentExecution?.status)return;let r=null===this.#o;this.#o={executionId:t,lastEventId:e,assistantMessageId:this.#n,status:"running"},this.#dt(r)}#ie(){return null!==this.#o&&"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.#o&&"function"==typeof this.config.reconnectStream&&(this.#a=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#o}),this.#ce(!0),this.#de("resuming"),this.#ct().then(e=>{this.#a&&this.#o&&e.begin()}))}#ct(){return this.#s?Promise.resolve(this.#s):(this.#i||(this.#i=Mo().then(({createReconnectController:e})=>{let t=e(this.#pt());return this.#s=t,t}),this.#i.catch(()=>{this.#i=null})),this.#i)}#pt(){let e=this;return{get config(){return e.config},getResumable:()=>e.#o,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,o)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:t=>e.#Ce(t),settleParked:t=>e.#ut(t),nextSequence:()=>e.#ye(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>Eo(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;if(this.#pe())return this.#ht(e.executionId),void(this.#o={executionId:e.executionId,lastEventId:e.after,assistantMessageId:this.#n??"",status:"running"});let t=this.#mt(e.executionId)?yt():this.#gt();t||(t=yt(),this.#Ce({id:t,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,sequence:this.#ye()})),this.#n=t,this.#ht(e.executionId),this.#o={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.#le()}#ut(e){let t=this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0;if(!t&&!this.#pe()){if(!this.#mt(e))return!1;this.#ue()}if(this.#a=!1,!t){let e=!1;for(let t of this.messages)t.streaming&&(t.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.#ce(!1),this.abortController=null}return this.#de("idle"),!0}#ht(e){this.agentExecution||={executionId:e,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}}#mt(e){return this.messages.some(t=>t.agentMetadata?.executionId===e&&[t.toolCall,...t.tools??[]].some(e=>!0===e?.interrupted))}#gt(){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}#We(){this.#a=!1,this.#s?.teardown(),this.#ue()}#ue(){this.#l&&=(clearTimeout(this.#l),null);let e=null!==this.#o;this.#o=null,e&&this.config.onExecutionState?.(null)}#dt(e){let t=this.config.onExecutionState;t&&(e?(this.#l&&=(clearTimeout(this.#l),null),t(this.#o)):this.#l||=setTimeout(()=>{this.#l=null,this.config.onExecutionState?.(this.#o)},500))}getResumableHandle(){return this.#o}#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.#ot(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 o=wo(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return co(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||"assistant"!==t.role)return;let r=wo(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o?.voice,rate:o?.rate,pitch:o?.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()}#ot(e){for(let[t,r]of[...this.#e])r===e&&(this.#e.delete(t),this.#st(t))}#nt(e){for(let[t,r]of this.#e)r===e&&this.#e.set(t,void 0)}#st(e){let t=this.messages.find(t=>t.id===e)?.approval,r=t?.toolCallId,o=r&&this.messages.find(e=>e.toolCall?.id===r),n=o&&o.toolCall;if(!n||"complete"===n.status||"pending"===t.status)return;let a={...n,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({...o,streaming:!1,toolCall:a})}#Ce(e){let t=this.#Ee(e),r=this.messages[this.messages.length-1];this.messages=!r||this.#ft(r,t)<=0?[...this.messages,t]:this.#be([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#Ee(e),r=this.messages.findIndex(e=>e.id===t.id);if(-1===r)return void this.#Ce(t);this.messages=this.messages.map((e,o)=>{if(o!==r||e.toolCall?.name&&c(e.toolCall.name)&&"complete"===e.toolCall.status&&t.toolCall?.id===e.toolCall.id&&"complete"!==t.toolCall.status&&("pending"===t.toolCall.status&&!t.toolCall.name||!e.toolCall.interrupted&&(void 0!==e.toolCall.result||void 0!==e.toolCall.success)&&(!t.agentMetadata?.executionId||t.agentMetadata.executionId===e.agentMetadata?.executionId)))return e;let n={...e,...t};!0===e.agentMetadata?.askUserQuestionAnswered&&t.agentMetadata&&(n.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),!0===e.agentMetadata?.suggestRepliesResolved&&t.agentMetadata&&(n.agentMetadata={...n.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&n.agentMetadata&&!n.agentMetadata.clientToolAnswer&&(n.agentMetadata={...n.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let r=e.approval,o=t.approval;n.approval={...r,...o,executionId:o.executionId||r.executionId,toolName:o.toolName||r.toolName,description:o.description||r.description,toolType:o.toolType??r.toolType,reason:o.reason??r.reason,parameters:o.parameters??r.parameters,toolCallId:o.toolCallId??r.toolCallId}}let s=t.toolCall?.name,i=t.agentMetadata?.executionId,l=t.toolCall?.id;if(s&&Lo(s)&&i&&l&&!0===t.agentMetadata?.awaitingLocalTool){let t=`${i}:${l}`,r=this.webMcpInflightKeys.has(t),o=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,s=e.agentMetadata?.executionId===i&&e.toolCall?.id===l&&void 0!==a&&Lo(a)&&"complete"===e.toolCall?.status&&!e.toolCall.interrupted;(r||o||s)&&(n.agentMetadata={...n.agentMetadata??{},awaitingLocalTool:!1},n.toolCall=e.toolCall,n.streaming=e.streaming)}return n});let o=this.messages[r],n=this.messages[r-1],a=this.messages[r+1];(n&&this.#ft(n,o)>0||a&&this.#ft(o,a)>0)&&(this.messages=this.#be(this.messages)),this.callbacks.onMessagesChanged([...this.messages])}#Ee(e){return void 0===e.sequence?{...e,sequence:this.#ye()}:{...e}}#ye(){return this.#r++}#ft(e,t){let r=new Date(e.createdAt).getTime(),o=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let n=e.sequence??0,a=t.sequence??0;return n===a?e.id.localeCompare(t.id):n-a}#be(e){return[...e].sort((e,t)=>this.#ft(e,t))}};let Bo={add:e=>async function(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Mr(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>r(Error("Failed to read file")),o.readAsDataURL(e)})}(e)},No={allowedTypes:Ar,maxFileSize:10485760,maxFiles:4};function Ro(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}var $o=class e{#e;#t;#r;constructor(e={}){this.attachments=[],this.#e=null,this.#t=new Map,this.#r=!1,this.config={allowedTypes:e.allowedTypes??No.allowedTypes,maxFileSize:e.maxFileSize??No.maxFileSize,maxFiles:e.maxFiles??No.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#o(){return"function"==typeof this.config.adapter?.add}#n(){return this.#o()?this.config.adapter:Bo}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:No.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=Ir(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 o={id:Ro(),file:r,previewUrl:Mr(r)?URL.createObjectURL(r):null,contentPart:null,status:this.#o()?"uploading":"processing",progress:this.#o()?0:void 0};this.attachments.push(o),this.#d(o),t.push(o)}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 o=await this.#n().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=o,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.#o()?"uploading":"processing",t.progress=this.#o()?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 o=this.#e?.querySelector(`[data-attachment-id="${e}"]`);o&&o.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=Mr(e.file),r=q("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let t=q("img");t.src=e.previewUrl,t.alt=e.file.name,t.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",t.style.width="48px",t.style.height="48px",t.style.objectFit="cover",t.style.borderRadius="8px",r.appendChild(t)}else{let t=q("div");t.style.width="48px",t.style.height="48px",t.style.borderRadius="8px",t.style.backgroundColor="var(--persona-container, #f3f4f6)",t.style.border="1px solid var(--persona-border, #e5e7eb)",t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="center",t.style.justifyContent="center",t.style.gap="2px",t.style.overflow="hidden";let o=function(e){return"application/pdf"===e||e.startsWith("text/")||e.includes("word")?m.FileText:e.includes("excel")||e.includes("spreadsheet")?m.FileSpreadsheet:"application/json"===e?m.FileCode:m.File}(e.file.type),n=g(o,20,"var(--persona-muted, #6b7280)",1.5);n&&t.appendChild(n);let a=q("span");a.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),a.style.fontSize="8px",a.style.fontWeight="600",a.style.color="var(--persona-muted, #6b7280)",a.style.textTransform="uppercase",a.style.lineHeight="1",t.appendChild(a),r.appendChild(t)}let o=j("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),n=q("div","persona-attachment-progress");n.appendChild(q("div","persona-attachment-progress__bar"));let a=j("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),s=se("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);s?a.appendChild(s):a.textContent="↻",a.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),o.append(n,a),r.appendChild(o);let i=q("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");i.type="button",i.setAttribute("aria-label","Remove attachment"),i.style.position="absolute",i.style.top="-4px",i.style.insetInlineEnd="-4px",i.style.width="18px",i.style.height="18px",i.style.borderRadius="50%",i.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",i.style.border="none",i.style.cursor="pointer",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.padding="0";let l=g(m.X,10,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):(i.textContent="×",i.style.color="var(--persona-text-inverse, #ffffff)",i.style.fontSize="14px",i.style.lineHeight="1"),i.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(i),this.#e.appendChild(r),this.#p(r,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 o=e.querySelector(".persona-attachment-progress__bar");if(o){let e=t.progress;o.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 Ho=(e,t)=>e.length===t.length&&e.every((e,r)=>e===t[r]);function Wo(){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,o=!1,n=!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(o=!1,n||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,!n&&!o&&(o=!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 o=t[r];return e.id===o.id&&e.name===o.name&&e.mimeType===o.mimeType&&e.size===o.size&&e.status===o.status&&e.progress===o.progress&&e.error===o.error}))(e.attachments,t)||(e.attachments=[...t],i())},setMentionRefs:t=>{Ho(e.mentionRefs,t)||(e.mentionRefs=[...t],i())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,i())},setActiveModeIds:t=>{Ho(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:()=>{o&&s()},destroy:()=>{n=!0,o=!1,t.clear()}}}let Do=(e,...t)=>{for(let r of t){let t=e.querySelector(r);if(t)return t}return null},Fo=(e,t)=>{let r=q("div",e);return r.setAttribute(t,""),r.setAttribute("data-persona-composer-synthesized",""),r.style.display="contents",r};function Oo(e,t={}){let r=Do(e,"[data-persona-composer-form]"),o=Do(e,"[data-persona-composer-input]");if(!r||!o){let e=`[Persona] composer surface is missing required element(s): ${[!r&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(r||o))throw Error(e);return typeof console<"u"&&console.warn(e),null}let n={header:Do(e,"[data-persona-composer-header]"),body:Do(e,"[data-persona-composer-body]"),actionsStart:Do(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Do(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Do(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Do(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Do(e,"[data-persona-composer-status]")},a=new Set,s=n.header;s||(a.add("header"),s=Fo("persona-widget-composer__header","data-persona-composer-header"),r.parentNode?r.parentNode.insertBefore(s,r):e.appendChild(s));let i=n.body??o.parentElement??r,l=(e,t,r,o,n)=>{if(t)return t;a.add(e);let s=Fo(r,o);return n.appendChild(s),s},d=l("actionsStart",n.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",r),c=l("actionsEnd",n.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",r),p=l("suggestions",n.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),u=l("status",n.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[];return{footer:e,form:r,input:o,header:s,body:i,actionsStart:d,actionsEnd:c,suggestions:p,status:u,attachmentInput:Do(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0,attachmentPreviews:Do(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Do(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Do(e,"[data-persona-composer-submit]")??void 0,micButton:Do(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:n,addListener:(e,t,r,o)=>{e.addEventListener(t,r,o),h.push({target:e,type:t,handler:r,options:o})},removeListener:(e,t,r,o)=>{e.removeEventListener(t,r,o),h=h.filter(o=>!((e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler)(o,{target:e,type:t,handler:r}))},destroy:()=>{for(let e of h)e.target.removeEventListener(e.type,e.handler,e.options);h=[]}}}let zo=200,qo=300,jo=0,_o=e=>Math.max(0,e);function Uo(e){void 0!==e.delayMs&&(zo=_o(e.delayMs)),void 0!==e.skipDelayMs&&(qo=_o(e.skipDelayMs))}let Vo=new WeakMap,Ko=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Jo=(e,t,r)=>Math.min(Math.max(e,t),Math.max(t,r)),Go=[...["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 Xo(e){Vo.get(e.anchor)?.destroy();let t,{anchor:r,trigger:o=r,text:n,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 n?n():n).trim(),v=()=>("function"==typeof a?a():a??"").trim(),w=()=>_o(e.delayMs??zo),x=()=>_o(e.skipDelayMs??qo),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=>{jo=e>0?Date.now()+e:0})(x())},k=()=>{if(!p)return;let e=d(),t=c(),o=r.getBoundingClientRect(),n=p.getBoundingClientRect(),a=e.documentElement.clientWidth||t.innerWidth,s=e.documentElement.clientHeight||t.innerHeight,u=a-l-n.width,h=o.left+o.width/2-n.width/2,m=Jo(h,l,u),g=o.top-l,f=s-l-o.bottom,y=g>=n.height+i||g>=f?"top":"bottom",b="top"===y?o.top-i-n.height:o.bottom+i,v=s-l-n.height,w=Jo(b,l,v),x=o.left+o.width/2,C=Math.max(10,n.width-10),S=Jo(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 Ko(t)?t:e.ownerDocument.body})(r);if(!e||!t)return;let o=d(),n=c();p=o.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex="100001";let a=n.getComputedStyle?.(r);if(a){for(let e of Go){let t=a.getPropertyValue(e).trim();t&&p.style.setProperty(e,t)}a.fontFamily&&(p.style.fontFamily=a.fontFamily)}u=o.createElement("span"),u.className="persona-control-tooltip__label",u.textContent=e,p.appendChild(u);let i=v();i&&(h=o.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=i,p.appendChild(h));let l=o.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()};n.addEventListener("scroll",g,!0),n.addEventListener("resize",g);let f=r.getRootNode(),w=Ko(f)?f:o.documentElement,x=typeof MutationObserver>"u"?null:new MutationObserver(()=>{r.isConnected||S()});x?.observe(w,{childList:!0,subtree:!0}),m=()=>{n.removeEventListener("scroll",g,!0),n.removeEventListener("resize",g),x?.disconnect()}},M=()=>{g||f?(e=>{y||p||(C(),e||w()<=0||Date.now()<jo?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()};o.addEventListener("mouseenter",I),o.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(),o.removeEventListener("mouseenter",I),o.removeEventListener("mouseleave",T),r.removeEventListener("focus",E),r.removeEventListener("blur",L),r.removeEventListener("keydown",B),r.removeEventListener("click",P),Vo.delete(r))}};return Vo.set(r,N),N}function Qo(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 o=parseFloat(r);return Number.isFinite(o)&&o>0?o:20}function Yo(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function Zo(e,t){e.style.maxHeight=t*Qo(e)+"px",e.style.overflowY="auto"}function en(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 tn(e){return!0===e.insertNewlineOnTouchEnter&&!0===e.coarsePointer}function rn(e,t){if("Enter"!==e.key||e.shiftKey||e.isComposing)return!1;let r=!0===e.metaKey||!0===e.ctrlKey,o=t.submitKey??"enter";return"none"!==o&&("mod-enter"===o?r:r||!tn(t))}function on(e,t){e.setAttribute("enterkeyhint",function(e){return"enter"===(e.submitKey??"enter")?tn(e)?"enter":"send":"enter"}(t))}function nn(e,t){let r=t?.autocomplete;e.setAttribute("autocomplete","string"==typeof r&&r?r:"off");let o=(t,r)=>{void 0===r?e.removeAttribute(t):e.setAttribute(t,r)};o("autocapitalize","string"==typeof t?.autocapitalize?t.autocapitalize:void 0),o("spellcheck","boolean"==typeof t?.spellcheck?String(t.spellcheck):void 0),o("inputmode","string"==typeof t?.inputmode&&t.inputmode?t.inputmode:void 0),o("aria-label","string"==typeof t?.ariaLabel&&t.ariaLabel?t.ariaLabel:void 0)}function an(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 sn="persona-composer-control",ln="persona-composer-control--glyph",dn=(e,t,r)=>{let o=e.ownerDocument?.defaultView;if(!o)return;let n=o.getComputedStyle(e);for(let e of r){let r=n.getPropertyValue(e).trim();r?t.style.setProperty(e,r):t.style.removeProperty(e)}},cn=(e,t)=>{let r=q("textarea");r.setAttribute("data-persona-composer-input",""),r.placeholder=e?.copy?.inputPlaceholder??"How can I help...",r.dir="auto",on(r,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:en(r)}),nn(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 o=Yo(e?.composer?.maxLines,t?.defaultMaxLines??3),n=20*o+"px";return r.style.maxHeight=n,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!==n){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=o*Qo(r);return n=`${t}px`,r.style.maxHeight=n,t})());r.style.height=`${e}px`})}}},pn=(e,t,r="send")=>{let o=j("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"),o.append(e,t),o},un=e=>{let t=e?.sendButton??{},r=t.useIcon??!1,o=t.iconText??"↑",n=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=q("div","persona-send-button-wrapper"),f=j("button",{className:_("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?`persona-flex persona-items-center persona-justify-center ${sn}`:"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(n&&(y=se(n,e,s,r)),b=se(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=pn(y,b),f.appendChild(v)):y?f.appendChild(y):(f.textContent=o,b=null)}else f.textContent=l;f.setAttribute("aria-label",s),g.appendChild(f),Xo({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}},hn=e=>{let t=e?.voiceRecognition??{};if(!0!==t.enabled)return null;let r=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),o="runtype"===t.provider?.type,n="custom"===t.provider?.type;if(!(r||o||n))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=q("div","persona-send-button-wrapper"),p=j("button",{className:_("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",sn,!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=se(a,i,d||"currentColor",1.5);u?p.appendChild(u):p.textContent="🎤",c.appendChild(p);let h=t.tooltipText??"Start voice recognition";return Xo({anchor:p,trigger:c,text:()=>p.getAttribute("aria-label")??h,enabled:t.showTooltip??!1}),{button:p,wrapper:c}},mn=e=>{let t=e?.attachments??{};if(!0!==t.enabled)return null;let r=q("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 o=q("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??Ar).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let n=t.buttonIconName??"paperclip",a=q("div","persona-send-button-wrapper"),s=j("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${sn} ${ln}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),i=se(n,24,"currentColor",1.5);i?s.appendChild(i):s.textContent="📎",s.addEventListener("click",e=>{e.preventDefault(),o.click()}),a.appendChild(s);let l=t.buttonTooltipText??"Attach file";return Xo({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??l}),{button:s,wrapper:a,input:o,previewsContainer:r}},gn=e=>{let t=e?.statusIndicator??{},r="left"===t.align?"persona-text-left":"center"===t.align?"persona-text-center":"persona-text-right",o=q("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),we(o,t,"idle");let n=t.idleText??"Online";if(t.idleLink){let e=q("a");e.href=t.idleLink,e.target="_blank",e.rel="noopener noreferrer",e.textContent=n,e.style.color="inherit",e.style.textDecoration="none",o.appendChild(e)}else o.textContent=n;return o},fn=()=>j("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function yn(e){let{anchor:t,content:r,placement:o="bottom-start",offset:n=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"===o||"top-end"===o?c-n-l.height:e.bottom+n,h="bottom-end"===o||"top-end"===o?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,o=t.ownerDocument??document,n=()=>{t.isConnected?m():(g(),c?.("anchor-removed"))},a=e=>{let o="function"==typeof e.composedPath?e.composedPath():[];o.includes(r)||o.includes(t)||(g(),c?.("outside"))},s=e.setTimeout(()=>{o.addEventListener("pointerdown",a,!0)},0);e.addEventListener("scroll",n,!0),e.addEventListener("resize",n),h=()=>{e.clearTimeout(s),o.removeEventListener("pointerdown",a,!0),e.removeEventListener("scroll",n,!0),e.removeEventListener("resize",n)},d?.()};return{get isOpen(){return u},open:f,close:g,toggle:()=>u?g():f(),reposition:m,destroy:g}}let bn=["--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"],vn="data-persona-menu-focus",wn=new Set(["ArrowDown","ArrowUp","Home","End"]);function xn(e){return"menuitem"===e.getAttribute("role")?e:e.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')??e}let Cn=1e3,Sn="data-persona-composer-action",kn="data-persona-composer-disable-when-streaming";function An(e){let t=e.clientWidth;if(!t)return 0;let r=e.ownerDocument?.defaultView;if(!r?.getComputedStyle)return t;let o=r.getComputedStyle(e),n=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,t-n)}let Mn=(e,t)=>{e&&typeof console<"u"&&console.warn(t)},In=e=>"plugin"===e.source?`plugin "${e.pluginId}"`:"config"===e.source?"composer.actions":"a core built-in",Tn=(e,t,r)=>void 0===e?r:"function"==typeof e?!0===e(t):!0===e;function En(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 Ln=e=>"custom"===e.kind,Pn=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e;function Bn(e){let t=new Map,r=[],o=!1,n=()=>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(kn,!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 o=q("span","persona-composer-overflow-menu__icon");if(t.iconName){let e=se(t.iconName,16,"currentColor",1.5);e&&o.appendChild(e)}let n=q("span","persona-composer-overflow-menu__label");n.textContent=t.shortLabel??t.label,r.append(o,n)})(e,t);r.removeAttribute("role"),r.removeAttribute("tabindex"),r.removeAttribute("title");let o=n(),a=!!t.shortLabel;if(r.className=_("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",sn,ln,a&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),r.style.width=o&&!a?o:"",r.style.height=o??"",r.style.minWidth=o&&!a?o:"",r.style.minHeight=o??"",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=se(t.iconName,24,"currentColor",1.5);e&&r.appendChild(e)}if(a){let e=q("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=Xo({anchor:r,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,r)=>{let o=t.action,n=j("button",{attrs:{type:"button"}}),s=n;if("bar"===r){let e=q("div","persona-send-button-wrapper");e.appendChild(n),s=e}s.setAttribute(Sn,t.id);let i={resolved:t,element:s,button:n,owned:!0,managed:!0,busy:!1,visible:!0,mode:r},l=t=>{if(t.preventDefault(),t.stopPropagation(),i.busy||n.disabled)return;let r,o=i.resolved.action;"menu"===i.mode&&u?.close(!0);try{r=o.onSelect(e.actionContext,t)}catch(t){return void e.reportError(t,{actionId:i.resolved.id})}r&&"function"==typeof r.then&&(i.busy=!0,n.setAttribute("aria-busy","true"),r.catch(t=>{e.reportError(t,{actionId:i.resolved.id})}).finally(()=>{i.busy=!1,n.removeAttribute("aria-busy")}))};return n.addEventListener("click",l),i.detach=()=>n.removeEventListener("click",l),a(i,o),i},i=t=>{let r,o=t.action;try{r=o.render({...e.actionContext,id:t.id,action:o})}catch(o){return e.reportError(o,{actionId:t.id}),null}return r?.element?(r.element.setAttribute(Sn,t.id),r.element.toggleAttribute(kn,!0===o.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?Ln(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 o=t[r];if(!o.managed)continue;let n=null;for(let o=r+1;o<t.length;o++){let r=t[o];if(!r.managed&&r.element.parentElement===e){n=r.element;break}}n?(o.element.parentElement!==e||o.element.nextSibling!==n)&&e.insertBefore(o.element,n):e.lastChild!==o.element&&e.appendChild(o.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 o=r instanceof HTMLButtonElement||r instanceof HTMLSelectElement||r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement?r:r.querySelector("button, select, input, textarea");o&&(o.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,o=q("div","persona-send-button-wrapper"),n=j("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${sn} ${ln}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(n);let a=j("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),s=()=>{let t=e.getButtonSize?.()??"";n.style.width=t,n.style.height=t,n.style.minWidth=t,n.style.minHeight=t,n.style.lineHeight="1",n.replaceChildren();let r=se("plus",24,"currentColor",1.5);r?n.appendChild(r):n.textContent="+"},i=()=>{n.setAttribute("aria-label",t),n.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&&xn(t)===e;t.toggleAttribute(vn,r&&c)}},u=()=>l.filter(e=>e.isConnected||a.contains(e)).map(xn).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=()=>o.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(),n.setAttribute("aria-expanded","false"),v(),w(),d=-1,c=!1;for(let e of l)e.removeAttribute(vn);e&&n.focus()}},k=(e=0,t=!1)=>{if(r||C())return;c=t,dn(n,a,bn),(x||=yn({anchor:n,content:a,placement:"top-start",offset:6,onDismiss:()=>{n.setAttribute("aria-expanded","false"),v()}}),x).open(),n.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(o)||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(wn.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 n.addEventListener("click",A),n.addEventListener("keydown",M),a.addEventListener("keydown",I),{trigger:o,triggerButton:n,panel:a,setItems:e=>{for(let t of l)e.includes(t)||t.removeAttribute(vn);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(),n.removeEventListener("click",A),n.removeEventListener("keydown",M),a.removeEventListener("keydown",I),x?.destroy(),x=null,o.remove(),a.remove(),l=[]}}}({label:e.getOverflowLabel?.()??"More actions",getButtonSize:n}),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 o=e.resolved.presentation;return"overflow"===o||"auto"===o&&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 o=e;"function"==typeof o.matches&&o.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=Pn(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""})(e.element);r?(e.menuLabel||=q("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 o=e.resolved.action;if(o&&!Ln(o)){d(e),t.delete(e.resolved.id);let o=s(e.resolved,r);return t.set(e.resolved.id,o),o}if("menu"===r){let t=j("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none","data-persona-tooltip-suppressed":""}});t.appendChild(e.element),function(e){Vo.get(e)?.hide()}(Pn(e.element)),e.menuSlot=t;let r=t=>{let r=Pn(e.element);if(r.disabled)return;let o=t.target===r||r.contains(t.target);u?.close(!0),o||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(o)return;let n=e.getBindings();if(!n)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=An(e),typeof ResizeObserver<"u"&&(m=new ResizeObserver(t=>{let r=t[t.length-1]?.contentRect?.width??An(e);r!==g&&(g=r,w())}),m.observe(e)))})(n.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 o=q("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let n=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(n)&&n>0?n:Number.isFinite(r)?r:null}(e.collapseAutoActionsBelow,t);if(null===r)return!1;let o=g||An(t);return o>0&&o<r})(i,n.footer),d={start:[],end:[]},x=[];for(let e of r){let r=t.get(e.id);if(!r)continue;let o=e.action,n=!o||Tn(o.visible,a,!0)&&En(o.visibility,a);if(r.visible!==n&&(r.visible=n,!n&&r.managed&&(r.menuSlot??r.element).remove()),n){if(r=v(r,y(r,i,l)),o){let e=Tn(o.disabled,a,!1)||!0===o.disableWhenStreaming&&s;p(r,e),!Ln(o)&&void 0!==o.pressed&&r.button?.setAttribute("aria-pressed",o.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 o=e.children[r];o!==t&&(o?e.insertBefore(t,o):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),o={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,o)}else u&&(u.close(),u.trigger.remove(),u.setItems([]));c(n.actionsStart,d.start),c(n.actionsEnd,d.end)};return{resolve:()=>{if(o)return;let n=function(e){let{debug:t}=e,r=[],o=new Map,n=0,a=e=>{let n=o.get(e.id);n?Mn(t,`[Persona] composer action "${e.id}" is already contributed by ${In(n)}; the ${In(e)} copy is ignored.`):(o.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:n++,source:"core",builtIn:t});let s=(e,r,o)=>{let s=o?((e,t)=>t.includes(":")?t:`${e}:${t}`)(o,e.id):e.id,i=e.order??500;"end"===e.placement&&i>=Cn&&(Mn(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:n++,source:r,pluginId:o,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(n.map(e=>e.id));for(let[e,r]of t)s.has(e)||(d(r),t.delete(e));for(let e of n){let r=t.get(e.id);if(!r){let r=l(e,"bar");r&&t.set(e.id,r);continue}let o=r.resolved.action,n=e.action;if(!!o!=!!n||o&&n&&Ln(o)!==Ln(n)||o&&n&&Ln(o)&&Ln(n)&&o.render!==n.render){d(r),t.delete(e.id);let o=l(e,r.mode);o&&t.set(e.id,o)}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)):n&&!Ln(n)?a(r,n):n&&r.element.toggleAttribute(kn,!0===n.disableWhenStreaming)}r=n,w()},sync:w,getResolved:()=>r,getOverflowMenu:()=>u,destroy:()=>{if(!o){o=!0,m?.disconnect(),m=null,h=null;for(let e of t.values())d(e);t.clear(),u?.destroy(),u=null,r=[]}}}}let Nn=["--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"],Rn=()=>({wrapper:j("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),chevron:j("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}})});function $n(e){let t=e.label??"Model",r=e.presentation??"native",o=null,n=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=j("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),a=q("span","persona-composer-model-picker-label"),s=q("span","persona-composer-model-picker-suffix");r.append(a,s);let i=j("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||=yn({anchor:r,content:i,placement:"top-start",offset:6,onDismiss:()=>r.setAttribute("aria-expanded","false")}),dn(r,i,Nn),c.open(),r.setAttribute("aria-expanded","true");let o=[...l.keys()].indexOf(n(e.getModels())?.id??"");h(t??(o>=0?o: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 o=e.getModels(),c=o.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(...o.map(e=>{let t=(e=>{let t=j("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":e.id}});if(e.icon){let r=se(e.icon,16,"currentColor",1.5);if(r){let e=q("span","persona-composer-model-option-icon");e.appendChild(r),t.appendChild(e)}}let r=q("span","persona-composer-model-option-body"),o=q("span","persona-composer-model-option-label");if(o.textContent=e.label,r.appendChild(o),e.description){let t=q("span","persona-composer-model-option-description");t.textContent=e.description,r.appendChild(t)}t.appendChild(r);let n=q("span","persona-composer-model-option-check");n.setAttribute("aria-hidden","true");let a=se("check",16,"currentColor",2);return a&&n.appendChild(a),t.appendChild(n),t.addEventListener("click",f),t})(e);return l.set(e.id,t),t}))}let p=n(o);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(),o=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}=Rn();return x.append(r,C),{element:x,destroy:()=>{o===y&&(o=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=j("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),a="",s=()=>{let t=e.getModels(),o=t.map(e=>`${e.id}:${e.label}`).join("|");o!==a&&(a=o,r.replaceChildren(...t.map(e=>{let t=j("option",{attrs:{value:e.id}});return t.textContent=e.label,t}))),r.value=n(t)?.id??""};s(),o=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}=Rn();return d.append(r,c),{element:d,destroy:()=>{o===s&&(o=null),r.removeEventListener("change",i),r.removeEventListener("click",l)}}})()},repaint:()=>o?.()}}let Hn="[data-persona-composer-chip-row]";function Wn(e){e.style.display=e.childElementCount>0?"flex":"none"}function Dn(e){let t=e.querySelector(Hn);if(t)return t;let r=j("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});r.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(r,o):e.appendChild(r),r}function Fn(e){let t=e.row,r="",o=!1,n=new Set(e.initialIds??[]),a=t=>{let r=j("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=q("span","persona-mention-chip-icon"),o=se(t.iconName,12,"currentColor",1.5);o&&e.appendChild(o),r.appendChild(e)}let o=q("span","persona-mention-chip-label");o.textContent=t.shortLabel??t.label,r.appendChild(o);let n=j("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${t.label}`}}),a=se("x",12,"currentColor",2);return a?n.appendChild(a):n.textContent="×",n.addEventListener("click",r=>{r.preventDefault(),r.stopPropagation(),e.onRemove(t.id)}),r.appendChild(n),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(),Wn(t)},o=t.ownerDocument.defaultView,n="function"==typeof o?.getComputedStyle?o.getComputedStyle(e).animationName:"";n&&"none"!==n?(e.addEventListener("animationend",r,{once:!0}),e.addEventListener("animationcancel",r,{once:!0})):r()};return{element:t,render:(e,l)=>{if(o)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),n.has(e.id)||(r.setAttribute("data-persona-chip-enter",""),r.addEventListener("animationend",()=>r?.removeAttribute("data-persona-chip-enter"),{once:!0}))),n.delete(e.id),r!==u&&t.insertBefore(r,u),u=r.nextSibling}Wn(t)},destroy:()=>{o=!0,(()=>{for(let e of s())e.remove()})(),Wn(t)}}}let On=e=>`core:mode:${e}`,zn=e=>Math.min(300+e,499),qn=e=>`core:mode-group:${e}`;function jn(e,t){return!!e&&"segmented"===t?.find(t=>t.id===e)?.presentation}function _n(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function Un(e){let t=null;return{action:{id:qn(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let r=j("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),o=new Map,n="",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!==n){n=i;for(let e of o.values())e.removeEventListener("click",a);o.clear();let e=s.map(e=>{let t=(e=>{let t=j("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let r=se(e.iconName,16,"currentColor",1.5);r&&t.appendChild(r)}let r=q("span","persona-composer-segmented-label");return r.textContent=e.shortLabel??e.label,t.appendChild(r),t.addEventListener("click",a),t})(e);return o.set(e.id,t),t});r.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of o)t.setAttribute("aria-pressed",String(l.includes(e)))};return s(),t=s,{element:r,destroy:()=>{t===s&&(t=null);for(let e of o.values())e.removeEventListener("click",a);o.clear()}}}},repaint:()=>t?.()}}function Vn(e){let t=j("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let r="",o=!1,n=r=>{let o=q("span","persona-composer-quote-bar"),n=q("div","persona-composer-quote-content");if(r.sourceLabel){let e=q("div","persona-composer-quote-source");e.textContent=r.sourceLabel,n.appendChild(e)}let a=j("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});a.textContent=so(r.text),n.appendChild(a);let s=j("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),i=se("x",12,"currentColor",2);i?s.appendChild(i):s.textContent="×",s.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(o,n,s)};return{element:t,render:e=>{if(o)return;let a=e?`${e.sourceLabel??""}\0${e.text}`:"";a!==r&&(r=a,e?(n(e),t.style.display="flex"):(t.replaceChildren(),t.style.display="none"))},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function Kn(e){let t=j("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let r,o=!1,n=(e,t,r,o)=>{let n=j("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":t,[r]:""}}),a=se(e,12,"currentColor",2);return a?n.appendChild(a):n.textContent=t,n.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),o()}),n};return{element:t,render:a=>{if(o||a===r)return;if(r=a,!a)return t.replaceChildren(),void(t.style.display="none");let s=q("span","persona-composer-pending-badge");s.textContent=e.label??"Sends next";let i=j("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});i.textContent=(e=>{let t=so(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,n("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),n("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function Jn(e){let t=j("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),r=j("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 o=()=>{r.style.height="auto",r.style.height=`${r.scrollHeight}px`};r.addEventListener("input",o);let n=q("div","persona-message-edit-actions"),a=(e,t,r,o)=>{let n=j("button",{className:`persona-message-edit-button ${t}`,attrs:{type:"button",[r]:""},text:e});return n.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),o()}),n},s=()=>{let t=r.value.trim();t&&e.onSave(t)};return n.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,n),{element:t,getValue:()=>r.value,focus:()=>{r.focus();let e=r.value.length;r.setSelectionRange(e,e),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function Gn(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 Xn(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 Qn(e,t,r){let o;try{o=e(Gn(t),{signal:r})}catch(e){return{status:"error",error:e}}return(e=>"function"==typeof e?.then)(o)?Promise.resolve(o).then(e=>r.aborted?{status:"aborted"}:Xn(t,e),e=>r.aborted?{status:"aborted"}:{status:"error",error:e}):Xn(t,o)}let{setLoader:Yn,load:Zn}=U({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),ea=Yn,ta=Zn,{setLoader:ra,load:oa}=U({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),na=ra,aa=oa;function sa(e){let{config:t,onOpen:r}=e,o=t.buttonIconName??"plus",n=t.buttonTooltipText??"Add context",a=q("div","persona-send-button-wrapper"),s=j("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${sn} ${ln}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":n,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),i=se(o,24,"currentColor",1.5);return i?s.appendChild(i):s.textContent="+",s.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r()}),a.appendChild(s),Xo({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??n}),{button:s,wrapper:a}}let ia=e=>e?.launcher?.variant??(!0===e?.future?.v5Defaults?"circle":"pill"),la={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"},da="16px",ca="transparent",pa={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"}},ua={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"}},ha={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:P,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:da,canvasBackground:ca,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"}}},ma=pa.colors.gray,ga={...pa,colors:{...pa.colors,gray:ma}},fa={...pa,colors:{...pa.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"}},ya=ga,ba=ua,va={...ua,colors:{...ua.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...ua.typography,fontSize:"14px",lineHeight:"1.5"}},wa=ba,xa=ha,Ca={...ha,launcher:la,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:{...ha.input,borderRadius:"palette.radius.full"},introCard:{...ha.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...ha.suggestion.chip,fontWeight:"400"},card:{...ha.suggestion.card,fontWeight:"400"},list:{...ha.suggestion.list,fontWeight:"400"}},panel:{...ha.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...ha.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:{...ha.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...ha.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:{...ha.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...ha.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)"}},Sa=xa,ka=e=>"v5"===(e=>W({future:e}))(e)?{palette:fa,semantic:va,components:Ca}:{palette:ga,semantic:ba,components:xa};function Aa(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let e of r){if(null==o)return;o=o[e]}return"string"==typeof o&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Aa(e,o):o}function Ma(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let o=`${n}.${a}`;if("string"==typeof s){let r=Aa(e,s);void 0!==r&&(t[o]={path:o,value:r,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else"object"==typeof s&&s&&r(s,o)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function Ia(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 Ta(e,t){let r={...e};for(let[e,o]of Object.entries(t)){let t=r[e];r[e]=t&&"object"==typeof t&&!Array.isArray(t)&&o&&"object"==typeof o&&!Array.isArray(o)?Ta(t,o):o}return r}function Ea(e,t){return t?Ta(e,t):e}function La(e,t={}){let r=ka(t.future),o={palette:r.palette,semantic:r.semantic,components:r.components},n={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:Ea(o.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]&&(n.components[e][t]=a[t]);let s=e?.components?.collapsibleWidget?.surface;void 0!==s&&void 0===a?.bodySurface&&(n.components.activity={...n.components.activity,bodySurface:s});let i=e?.components?.header;void 0!==i?.padding&&void 0===i.minimalPadding&&(n.components.header.minimalPadding=n.components.header.padding);let l=e?.components?.message;if(void 0!==l?.gap&&void 0===l.fullscreenGap&&(n.components.message.fullscreenGap=n.components.message.gap),!1!==t.validate){let e=Ia(n);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(", ")}`)}if(t.plugins)for(let e of t.plugins)n=e.transform(n);return n}let Pa=e=>"0"===e.trim()?"0px":e,Ba="--persona-",Na=(e,t)=>{for(let[r,...o]of t){let t;for(let r of o)if(t=61===r.charCodeAt(0)?r.slice(1):e[Ba+r],void 0!==t)break;void 0!==t&&(e[Ba+r]=t)}};function Ra(e){let t=Ma(e),r={};for(let[e,o]of Object.entries(t))r[`--persona-${e.replace(/\./g,"-")}`]=o.value;Na(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 o=r["--persona-components-launcher-foreground"];r["--persona-launcher-fg-muted"]=o&&o!==r["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:r["--persona-muted"],Na(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"]]),Na(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"]}`,Na(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",Na(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"]]),Na(r,[["header-bg","components-header-background","surface"]]);let n=r["--persona-header-bg"],a=r["--persona-components-header-foreground"],s=a?`color-mix(in srgb, ${a} 72%, ${n})`:void 0;r["--persona-header-border"]=r["--persona-components-header-border"]??(a?`color-mix(in srgb, ${a} 14%, ${n})`:void 0)??r["--persona-divider"],Na(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"],Na(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 o=r[`--persona-components-history-overlay-${e}`];o&&(r[`--persona-history-overlay-${t}`]=o)}for(let[e,t]of[["background","bg"],["borderRadius","radius"]]){let o=r[`--persona-components-history-menu-${e}`];o&&(r[`--persona-history-menu-${t}`]=o)}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 o=e(p.exitDurationMs);void 0!==o&&(r["--persona-history-exit-ms"]=o),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 o=r[`--persona-components-tooltip-${e}`];o&&(r[`--persona-tooltip-${t}`]=o)}!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 o=r[`--persona-components-messageActions-${e}`];o&&(r[`--persona-message-action-${t}`]=o)}Na(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,Na(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"]]),Na(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),Na(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"]]),Na(r,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Na(r,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Na(r,[["md-hr-color","components-markdown-hr-color","divider"]]),Na(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 o=r[`--persona-components-collapsibleWidget-${e}`]??r[`--persona-${t}`];void 0!==o&&(r[`--persona-cw-${e}`]=o,r[`--cw-${e}`]=o)}Na(r,[["message-border","components-message-border","border"]]),Na(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"]=Pa(t.toggleGroupGap)),t.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=t.toggleBorderRadius),t.toggleGroupPadding&&(r["--persona-artifact-toolbar-toggle-group-padding"]=Pa(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"]=Aa(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"]=Pa(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"]=Aa(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"]=Aa(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"]=Aa(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(r["--persona-artifact-inline-chrome-border"]=Aa(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(r["--persona-artifact-inline-title-color"]=Aa(e,t.titleColor)??t.titleColor),t.mutedColor&&(r["--persona-artifact-inline-muted-color"]=Aa(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"]=Aa(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[o,n,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*o+.7152*n+.0722*a})(T??r["--persona-background"]),$=N&&void 0!==R&&R<.179,H=$?"rgba(255, 255, 255, 0.16)":B,W=N?$?"rgba(255, 255, 255, 0.08)":L:E,D=N?$?"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"]??H),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 $a={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)"}}}},Ha={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"}}},Wa={...Ha,colors:{...Ha.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"}}},Da=$a,Fa={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:{...$a.components,button:{...$a.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:{...$a.components?.eventStream,badge:{...$a.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"}}}}},Oa=e=>{if(e&&"object"==typeof e&&!Array.isArray(e))return e},za=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",qa=e=>(e=>{let t=e?.colorScheme??"light";return"light"===t?"light":"dark"===t?"dark":za()})(e),ja=e=>{let t=qa(e),r=Oa(e?.theme),o=y({components:{launcher:"circle"===ia(e)?la:{...xa.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}}}},r),n=Oa(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,o=t.darkTheme?.components?.panel?.width;return null==("dark"===qa(t)?o??r:r)?{...e,components:{...e.components,panel:{...e.components.panel,width:"v5"===W(t)?"400px":"420px"}}}:e})("dark"===t?((e,t={})=>{let r=(e=>"v5"===W({future:e})?{palette:Wa,components:Fa}:{palette:Ha,components:Da})(t.future),o=y(r.components,e??{})??{};return La({...o,palette:{...o.palette,colors:"v5"===W(t)?y(r.palette.colors,o.palette?.colors):{...r.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})})(y(o??{},n??{}),{future:e?.future}):((e,t={})=>La(e,t))(o,{future:e?.future}),e)},_a=(e,t)=>{let r=(e=>Ra(e))(ja(t));for(let[t,o]of Object.entries(r))e.style.setProperty(t,o);e.setAttribute("data-persona-color-scheme",qa(t)),e.setAttribute("data-persona-defaults",W(t))},Ua=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let r=new MutationObserver(()=>{e(za())});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)"),o=()=>e(za());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(e=>e())}},Va=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px"),Ka=(e,t)=>t||"overlay"!==e?.composer?.placement?"block":"overlay",Ja=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},Ga=()=>{if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},Xa=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Qa=e=>{let t=e.toLowerCase().split("+").map(e=>e.trim()),r=t.pop(),o={key:r,mod:!1,shift:!1,alt:!1};for(let r of t)if("mod"===r||"cmd"===r||"ctrl"===r)o.mod=!0;else if("shift"===r)o.shift=!0;else{if("alt"!==r&&"option"!==r)return Xa("unknown modifier in",e),null;o.alt=!0}return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(r)||!/^([^+\s]|[a-z]{2,12})$/.test(r)?(Xa("unsupported",e),null):("space"===r&&(o.key=" "),o)},Ya=(e,t)=>{let r=Qa(e);if(!r)return"";let o=Ga(),n=(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&&o)return`${r.alt?"⌥":""}${r.shift?"⇧":""}⌘${n}`;let a=[t?o?"Meta":"Control":"Ctrl"];return r.alt&&a.push("Alt"),r.shift&&a.push("Shift"),a.push(n),a.join("+")},Za=e=>Ya(e,!1),es=e=>Ya(e,!0),ts=(e,t)=>t.key?.toLowerCase()===e.key&&(Ga()?t.metaKey:t.ctrlKey)===e.mod&&!(Ga()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,rs=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t||e.isContentEditable},os=e=>{let t=new Map,r=e?.ownerDocument??(typeof document<"u"?document:null),o=(t,r)=>{if("page"===(t.scope??"widget"))return!0;if(!e)return!1;let o=r.composedPath?.();return o?.length?o.includes(e):e.contains(r.target)},n=e=>{if(e.isComposing||!t.size)return;let r=e.composedPath?.()[0]??e.target;for(let n of t.values())if(ts(n.parsed,e)&&!1!==n.when?.()&&o(n,e)&&(n.allowInInput||!rs(r))){e.preventDefault();try{n.run(e)}catch(e){Xa(`${n.id} threw on`,n.combo),console.warn(e)}return}};return r?.addEventListener("keydown",n),{register(e){let r=Qa(e.combo);if(!r)return()=>{};let o=`${r.mod?"m":""}${r.shift?"s":""}${r.alt?"a":""}${r.key}`,n=t.get(o);return n?(Xa(`${n.id} already owns`,e.combo),()=>{}):(t.set(o,{...e,parsed:r}),e.element?.setAttribute("aria-keyshortcuts",es(e.combo)),()=>{t.get(o)?.id===e.id&&t.delete(o),e.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),r?.removeEventListener("keydown",n)}}};var ns=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,n){if(!1===n.callbacks.beforeNodeAdded(t))return null;if(n.idMap.has(t)){let a=document.createElement(t.tagName);return e.insertBefore(a,r),o(a,t,n),n.callbacks.afterNodeAdded(a),a}{let o=document.importNode(t,!0);return e.insertBefore(o,r),n.callbacks.afterNodeAdded(o),o}}let t=function(){function e(e,t,r){let o=e.idMap.get(t),n=e.idMap.get(r);if(!n||!o)return!1;for(let e of o)if(n.has(e))return!0;return!1}function t(e,t){let r=e,o=t;return r.nodeType===o.nodeType&&r.tagName===o.tagName&&(!r.getAttribute?.("id")||r.getAttribute?.("id")===o.getAttribute?.("id"))}return function(r,o,n,a){let s=null,i=o.nextSibling,l=0,d=n;for(;d&&d!=a;){if(t(d,o)){if(e(r,d,o))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 n(e,t,o){let n=t;for(;n&&n!==o;){let t=n;n=n.nextSibling,r(e,t)}return n}function a(e,t,r,o){let n=o.target.getAttribute?.("id")===t&&o.target||o.target.querySelector(`[id="${t}"]`)||o.pantry.querySelector(`[id="${t}"]`);return function(e,t){let r=e.getAttribute("id");for(;e=e.parentNode;){let o=t.idMap.get(e);o&&(o.delete(r),o.size||t.idMap.delete(e))}}(n,o),s(e,n,r),n}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&&n(s,d,e),o(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);o(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)}}}(),o=function(){function e(e,r,o){let a=r.nodeType;if(1===a){let a=e,i=r,l=a.attributes,d=i.attributes;for(let e of d)n(e.name,a,"update",o)||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(n(t.name,a,"remove",o))continue;a.removeAttribute(t.name)}}s(a,o)||t(a,i,o)}(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;o(e,t,"checked",r),o(e,t,"disabled",r),t.hasAttribute("value")?s!==a&&(n("value",e,"update",r)||(e.setAttribute("value",a),e.value=a)):n("value",e,"remove",r)||(e.value="",e.removeAttribute("value"))}else if(e instanceof HTMLOptionElement&&t instanceof HTMLOptionElement)o(e,t,"selected",r);else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let o=t.value,a=e.value;if(n("value",e,"update",r))return;o!==a&&(e.value=o),e.firstChild&&e.firstChild.nodeValue!==o&&(e.firstChild.nodeValue=o)}}function o(e,t,r,o){let a=t[r];if(a!==e[r]){let s=n(r,e,"update",o);s||(e[r]=t[r]),a?s||e.setAttribute(r,""):n(r,e,"remove",o)||e.removeAttribute(r)}}function n(e,t,r,o){return!("value"!==e||!o.ignoreActiveValue||t!==document.activeElement)||!1===o.callbacks.beforeAttributeUpdated(e,t,r)}function s(e,t){return!!t.ignoreActiveValue&&e===document.activeElement&&e!==document.body}return function(t,o,n){return n.ignoreActive&&t===document.activeElement?null:(!1===n.callbacks.beforeNodeMorphed(t,o)||(t instanceof HTMLHeadElement&&n.head.ignore||(t instanceof HTMLHeadElement&&"morph"!==n.head.style?a(t,o,n):(e(t,o,n),s(t,n)||r(n,t,o))),n.callbacks.afterNodeMorphed(t,o)),t)}}();function n(e,t,r,o){if(e.head.block){let n=t.querySelector("head"),s=r.querySelector("head");if(n&&s){let t=a(n,s,e);return Promise.all(t).then(()=>o(Object.assign(e,{head:{block:!1,ignore:!0}})))}}return o(e)}function a(e,t,r){let o=[],n=[],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),o=r.head.shouldReAppend(t),l=r.head.shouldPreserve(t);e||l?o?n.push(t):(i.delete(t.outerHTML),a.push(t)):"append"===r.head.style?o&&(n.push(t),s.push(t)):!1!==r.head.shouldRemove(t)&&n.push(t)}s.push(...i.values());let l=[];for(let t of s){let n=document.createRange().createContextualFragment(t.outerHTML).firstChild;if(!1!==r.callbacks.beforeNodeAdded(n)){if("href"in n&&n.href||"src"in n&&n.src){let e,t=new Promise(function(t){e=t});n.addEventListener("load",function(){e()}),l.push(t)}e.appendChild(n),r.callbacks.afterNodeAdded(n),o.push(n)}}for(let t of n)!1!==r.callbacks.beforeNodeRemoved(t)&&(e.removeChild(t),r.callbacks.afterNodeRemoved(t));return r.head.afterHeadMorphed(e,{added:o,kept:a,removed:n}),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 o(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 n(e){let t=Array.from(e.querySelectorAll("[id]"));return e.getAttribute?.("id")&&t.push(e),t}function a(e,t,r,o){for(let n of o){let o=n.getAttribute("id");if(t.has(o)){let t=n;for(;t;){let n=e.get(t);if(n??(n=new Set,e.set(t,n)),n.add(o),t===r)break;t=t.parentElement}}}}function s(e,t){let r=n(e),o=n(t),s=function(e,t){let r=new Set,o=new Map;for(let{id:t,tagName:n}of e)o.has(t)?r.add(t):o.set(t,n);let n=new Set;for(let{id:e,tagName:a}of t)n.has(e)?r.add(e):o.get(e)===a&&n.add(e);for(let e of r)n.delete(e);return n}(r,o),i=new Map;return a(i,s,e,r),a(i,s,t.__idiomorphRoot||t,o),{persistentIds:s,idMap:i}}return function(t,n,a){let{persistentIds:i,idMap:l}=s(t,n),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:n,config:d,morphStyle:c,ignoreActive:d.ignoreActive,ignoreActiveValue:d.ignoreActiveValue,restoreFocus:d.restoreFocus,idMap:l,persistentIds:i,pantry:r(),activeElementAndParents:o(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 o=r.querySelectorAll(e);for(let e=0;e<o.length;e++)t.push(o[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(o){if(null==o)return document.createElement("div");if("string"==typeof o)return r(function(t){let r=new DOMParser,o=t.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(o.match(/<\/html>/)||o.match(/<\/head>/)||o.match(/<\/body>/)){let n=r.parseFromString(t,"text/html");if(o.match(/<\/html>/))return e.add(n),n;{let t=n.firstChild;return t&&e.add(t),t}}{let o=r.parseFromString("<body><template>"+t+"</template></body>","text/html").body.querySelector("template").content;return e.add(o),o}}(o));if(e.has(o))return o;if(o instanceof Node){if(o.parentNode)return new t(o);{let e=document.createElement("div");return e.append(o),e}}{let e=document.createElement("div");for(let t of[...o])e.append(t);return e}}}}();return{morph:function(e,t,o={}){e=i(e);let a=l(t),d=s(e,a,o),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:o,selectionStart:n,selectionEnd:a}=r,s=t();return o&&o!==document.activeElement?.getAttribute("id")&&(r=e.target.querySelector(`[id="${o}"]`),r?.focus()),r&&!r.selectionEnd&&a&&r.setSelectionRange(n,a),s}(d,()=>n(d,e,a,t=>"innerHTML"===t.morphStyle?(r(t,e,a),Array.from(e.childNodes)):function(e,t,o){let n=l(t);return r(e,n,o,t,t.nextSibling),Array.from(n.childNodes)}(t,e,a)));return d.pantry.remove(),c},defaults:t}}();let as=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;ns.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement){if(t instanceof HTMLElement&&t.hasAttribute("data-persona-reuse")&&e.id===t.id)return!1;if(o){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}}}}})},ss={index:-1,draft:""},is=new WeakMap;function ls(e){if("string"==typeof e)return e.length;if(!e)return 0;if("object"!=typeof e)return JSON.stringify(e)?.length??0;let t=is.get(e);return void 0===t&&(t=JSON.stringify(e)?.length??0,is.set(e,t)),t}function ds(e){return"assistant"===e.role&&"tool"!==e.variant&&"reasoning"!==e.variant&&("approval"===e.variant||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length))}function cs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ps(e,t){return cs(e)-e.scrollTop<=t}function us(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 hs="none",ms="none",gs=120,fs=1800,ys="none",bs=["pre","code","a","script","style"],vs=e=>({type:e?.type??hs,placeholder:e?.placeholder??ms,speed:e?.speed??gs,duration:e?.duration??fs,buffer:e?.buffer??ys}),ws=[{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"}],xs=new Map;for(let e of ws)xs.set(e.name,e);let Cs=["wipe","glyph-cycle"],Ss=e=>{xs.set(e.name,e)},ks=(e,t)=>"none"===e?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:xs.get(e)??null,As=(e,t,r,o,n)=>{if(!n)return e;if(r?.bufferContent)return r.bufferContent(e,o);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},Ms=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},Is=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},Ts=/\s/,Es=(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},Ls=(e,t,r)=>{let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(Ts.test(a[i])){let e=i;for(;e<a.length&&Ts.test(a[e]);)e+=1;s.appendChild(o.createTextNode(a.slice(i,e))),i=e}else{let e=o.createElement("span");e.className="persona-stream-word-group";let n=i;for(;n<a.length&&!Ts.test(a[n]);)e.appendChild(Ms(o,a[n],t,r.value)),r.value+=1,n+=1;s.appendChild(e),i=n}n.replaceChild(s,e)},Ps=(e,t,r)=>{let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let e of i)e&&(/^\s+$/.test(e)?s.appendChild(o.createTextNode(e)):(s.appendChild(Is(o,e,t,r.value)),r.value+=1));n.replaceChild(s,e)},Bs=(e,t,r,o)=>{if(!e||typeof document>"u")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set((o?.skipTags??bs).map(e=>e.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],l=s.nextNode();for(;l;)Es(l,a)||i.push(l),l=s.nextNode();let d={value:o?.startIndex??0},c="char"===t?Ls:Ps;for(let e of i)c(e,r,d);return n.innerHTML},Ns=(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},Rs=(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},$s=new WeakMap,Hs=new WeakMap,Ws=e=>{let t=Hs.get(e);if(t){for(let e of t.values())"function"==typeof e&&e();t.clear()}},Ds=(e,t)=>{((e,t)=>{if(!e.styles)return;let r=$s.get(t);if(r||(r=new Set,$s.set(t,r)),r.has(e.name)){let o=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${o}"]`))return;r.delete(e.name)}r.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)})(e,t),((e,t)=>{if(!e.onAttach)return;let r=Hs.get(t);if(r||(r=new Map,Hs.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)})(e,t)},{setLoader:Fs,load:Os}=U({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),zs=Fs,qs=Os;function js(e,t=1e5){let r=e.style.position,o=e.style.zIndex,n=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=o,e.style.isolation=n}}let _s=0,Us=null;function Vs(e=document){if(_s++,1===_s){let t=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Us={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,_s=Math.max(0,_s-1),0===_s&&Us)){let t=e.body,r=e.defaultView??window;t.style.overflow=Us.originalOverflow,t.style.position=Us.originalPosition,t.style.top=Us.originalTop,t.style.width=Us.originalWidth,r.scrollTo(0,Us.scrollY),Us=null}}}let Ks="right",Js="420px",Gs=!0,Xs="resize",Qs="100dvh",Ys=e=>"docked"===(e?.launcher?.mountMode??"floating"),Zs=e=>"composer-bar"===(e?.launcher?.mountMode??"floating"),ei=e=>{let t=e?.launcher?.dock,r=T(e).dockWidth?t?.width:Aa(ja(e),"components.panel.width");return{side:t?.side??Ks,width:r??Js,animate:t?.animate??Gs,reveal:t?.reveal??Xs,maxHeight:t?.maxHeight??Qs}},ti=e=>"followUp"===e?"follow-up":e,ri=(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 o=e.prompt?.trim()||r;return{id:e.id?.trim()||o||`suggestion-${t}`,label:r,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},oi=new WeakSet,ni=e=>{let{item:t,index:r,surface:o,source:n,variant:a,streaming:s,config:i,plugins:l,chipsConfig:d,session:c,getTextarea:p,eventTarget:u,submitPrompt:h}=e,f="followUp"===o,y=t.behavior,b=()=>{if(c.isStreaming())return;let e={suggestion:{...t},surface:o,source:n,behavior:y},r=u.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(f&&u.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!r)return;for(let e of l)if(!1===e.onSuggestionSelect?.({suggestion:{...t},surface:o,source:n,variant:a,config:i}))return;let s=p();"fill"===y?(s.value=t.prompt,s.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),s.focus()):h?h(t.prompt):(s.value="",c.sendMessage(t.prompt))},v=()=>{let e=q("button",`persona-suggestion persona-suggestion--${a}`);if(e.type="button",e.disabled=s,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=y,"chip"===a&&(d?.fontWeight&&(e.style.fontWeight=d.fontWeight),d?.paddingX&&(e.style.paddingLeft=d.paddingX,e.style.paddingRight=d.paddingX),d?.paddingY&&(e.style.paddingTop=d.paddingY,e.style.paddingBottom=d.paddingY)),t.icon){let r=se(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 r=q("span","persona-suggestion__copy");if(r.appendChild(j("span",{className:"persona-suggestion__label",text:t.label})),t.description&&"chip"!==a&&r.appendChild(j("span",{className:"persona-suggestion__description",text:t.description})),e.appendChild(r),"chip"!==a){let t=g(m.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 l)if(e.renderSuggestion&&(w=e.renderSuggestion({suggestion:{...t},index:r,surface:o,source:n,variant:a,streaming:s,config:i,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",s?"true":"false"),w},ai=e=>{let t=[],r=[],o=null,n=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(n=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,o=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),s=o<=4,i=o>=t-4,l=r?!i:!s,d=r?!s:!i;e.toggleAttribute("data-scroll-left",l),e.toggleAttribute("data-scroll-right",d)},i=()=>{null!==n||"function"!=typeof requestAnimationFrame?"function"!=typeof requestAnimationFrame&&s():n=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!==n&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(n),n=null},render:(n,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";!oi.has(v)&&!0===v.debug&&"chip"!==f&&void 0!==v.suggestions?.[C]?.overflow&&(oi.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(ri).filter(e=>null!==e).map(e=>({...e,behavior:e.behavior??y})),k=S(n??[]);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,o=null,void a();if(!g&&(c??l.getMessages()).some(e=>"user"===e.role))return e.hidden=!0,void(o=null);e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=ti(m),e.dataset.variant=f,e.dataset.overflow=b;let M=document.createDocumentFragment(),I=l.isStreaming();A.forEach((o,n)=>{let a=ni({item:o,index:n,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!==o&&(o=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})))}}},si={"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"},ii={x:[1.4,1.05]},li="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",di=(e,t,r={})=>{let{iconSize:o,iconText:n}=r,[a,s]=ii[t]??[1,1.5],i=!o;e.classList.toggle("persona-header-control--glyph",i),e.classList.toggle("persona-header-control--sparse",i&&1!==a);let l=se(t,`${Math.round((parseFloat(o??"")||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)):n&&(e.textContent=n)},ci=e=>{let{ariaLabel:t,tooltip:r=!0,tooltipHint:o,iconName:n,iconText:a,wrapperClassName:s=li,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=q("div",s),w=!(!p&&!u),x=j("button",{className:_("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||hi.actionIconColor,backgroundColor:c,border:w?`${p||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:h,paddingLeft:m,paddingRight:m,paddingTop:g,paddingBottom:g}});return n?di(x,n,{iconSize:l,iconText:a}):a&&(x.textContent=a),v.appendChild(x),Xo({anchor:x,trigger:v,text:()=>x.getAttribute("aria-label")??t,hint:o,enabled:r}),{button:x,wrapper:v}},pi=(e,t={})=>{let{showClose:r=!0,wrapperClassName:o=li,buttonSize:n,iconSize:a}=t,s=e?.launcher??{},i=s.closeButtonTooltipText??"Close chat",l=s.closeButtonShowTooltip??!0,{button:d,wrapper:c}=ci({ariaLabel:i,tooltip:l,iconName:s.closeButtonIconName??"x",iconText:s.closeButtonIconText??"×",wrapperClassName:o,size:n??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}},ui=(e,t={})=>{let{wrapperClassName:r="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",buttonSize:o,iconSize:n}=t,a=(e?.launcher??{}).clearChat??{},s=a.tooltipText??"Clear chat",i=a.showTooltip??!0,{button:l,wrapper:d}=ci({ariaLabel:s,tooltip:i,iconName:a.iconName??"refresh-cw",wrapperClassName:r,size:o??a.size,iconSize:n,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}},hi={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)"},mi={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)"},gi={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)"},fi=e=>{let{config:t,showClose:r=!0}=e,o=j("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:hi.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)))"}}),n=t?.launcher??{},a=n.headerIconSize??"40px",s=n.closeButtonPlacement??"inline",i=n.headerIconHidden??!1,l=n.headerIconName,d=j("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(l){let e=parseFloat(a)||24,r=se(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=q("img");e.src=t.launcher.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=a,e.style.width=a,d.replaceChildren(e)}else d.textContent=t?.launcher?.agentIconText??"💬";let c=q("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=j("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:hi.titleColor,...mi}}),u=j("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:hi.subtitleColor,...gi}});c.append(p,u),i?o.append(c):o.append(d,c);let h=n.clearChat??{},m=h.enabled??!0,g=h.placement??"inline",f=null,y=null;if(m){let e=ui(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&&o.appendChild(y)}let{button:b,wrapper:v}=pi(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&&o.appendChild(v),{header:o,iconHolder:d,headerTitle:p,headerSubtitle:u,closeButton:b,closeButtonWrapper:v,clearChatButton:f,clearChatButtonWrapper:y}},yi=(e,t,r)=>{let o=r?.launcher??{},n=o.closeButtonPlacement??"inline",a=o.clearChat?.placement??"inline";e.appendChild(t.header),"top-right"===n&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&"top-right"===a&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function bi(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a,onOpenChange:s}=e,i=q("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"===n?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=se(e.icon,16,"currentColor",1.5);r&&t.appendChild(r)}let o=document.createElement("span");o.textContent=e.label,t.appendChild(o),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=o.getBoundingClientRect();i.style.top=`${e.bottom+4}px`,"bottom-right"===n?(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)&&!o.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 vi(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,chromeless:s,onClick:i,aria:l}=e,d=q("button",_(!s&&"persona-icon-btn",a));d.type="button",d.setAttribute("aria-label",r),d.title=r;let c=se(t,o??16,"currentColor",n??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 wi(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:l}=e,d="persona-label-btn";"default"!==o&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+n,s&&(d+=" "+s);let c=q("button",d);if(c.type="button",c.setAttribute("aria-label",r),t){let e=se(t,a??14,"currentColor",2);e&&c.appendChild(e)}let p=q("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 xi(e){let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:l}=e,d=q("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=q("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let p=se(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=bi({items:o,onSelect:e=>{d.setAttribute("aria-expanded","false"),n(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 Ci=e=>{let t=fi({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},Si=e=>{let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=t?.launcher??{},i=q("div","persona-flex persona-items-center persona-justify-between");i.setAttribute("data-persona-theme-zone","header"),i.style.minHeight=hi.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=n?.titleMenu;if(c){let e=xi({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}}))},o=c.onSelect(t);o instanceof Promise?o.then(r,()=>{}):r(o)},hover:c.hover,className:""});l=e.element,l.style.color=hi.titleColor,d=l.querySelector(".persona-combo-btn-label")??l}else{if(l=q("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=q("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=hi.titleColor,Object.assign(d.style,mi),d.textContent=s.title??"Chat Assistant",l.appendChild(d),n?.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let e=n.onTitleClick;l.addEventListener("click",t=>{t.target.closest("button")||e()}),l.addEventListener("keydown",t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),e())})}let e=n?.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}=pi(t,{showClose:r,wrapperClassName:p});o&&u.addEventListener("click",o);let m=q("div","persona-flex persona-items-center persona-gap-1");c||function(e,t,r){if(t?.length)for(let o of t){let{button:t,wrapper:n}=ci({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Za(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(t.setAttribute("data-persona-header-action",o.id),o.shortcut){let e=es(o.shortcut);e&&t.setAttribute("aria-keyshortcuts",e)}if(o.menuItems?.length){let e=bi({items:o.menuItems,onSelect:e=>r?.(e),anchor:n,position:"bottom-right"});n.appendChild(e.element),t.addEventListener("click",t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener("click",()=>r?.(o.id));e.appendChild(n)}}(m,n?.trailingActions,n?.onAction??a);let g=s.clearChat??{},f=null,y=null;if(g.enabled??1){let e=g.placement??"inline",r=ui(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=q("div");b.style.display="none";let v=q("span");return v.style.display="none",{header:i,iconHolder:b,headerTitle:d,headerSubtitle:v,closeButton:u,closeButtonWrapper:h,clearChatButton:f,clearChatButtonWrapper:y}},ki={default:Ci,minimal:Si},Ai=e=>ki[e]??ki.default,Mi=(e,t,r)=>{if(t?.render){let o=t.render({config:e,onClose:r?.onClose,onClearChat:r?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),n=q("div");n.style.display="none";let a=q("span"),s=q("span"),i=q("button");i.style.display="none";let l=q("div");return l.style.display="none",{header:o,iconHolder:n,headerTitle:a,headerSubtitle:s,closeButton:i,closeButtonWrapper:l,clearChatButton:null,clearChatButtonWrapper:null}}let o=Ai(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&&(o.iconHolder.style.display="none"),!1===t.showTitle&&(o.headerTitle.style.display="none"),!1===t.showSubtitle&&(o.headerSubtitle.style.display="none"),!1===t.showCloseButton&&(o.closeButton.style.display="none"),!1===t.showClearChat&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o},Ii=e=>{let{config:t}=e,r=j("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=fn(),n=j("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""}}),{textarea:a,attachAutoResize:s}=cn(t);s();let i=un(t),l=hn(t),d=mn(t),c=gn(t),p=j("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(p),d&&(d.previewsContainer.style.gap="8px",p.append(d.previewsContainer),n.append(d.input)),n.append(a);let u=j("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=j("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),m=j("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return d&&h.append(d.wrapper),l&&m.append(l.wrapper),m.append(i.wrapper),u.append(h,m),n.append(u),n.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(o,c,n):r.append(o,n,c),{footer:r,suggestions:o,composerForm:n,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}},Ti=()=>{let e=j("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=q("span","persona-pill-peek__icon"),r=g(m.MessageSquare,16,"currentColor",1.5);r&&t.appendChild(r);let o=q("span","persona-pill-peek__text"),n=q("span","persona-pill-peek__caret"),a=g(m.ChevronUp,16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},Ei=e=>{let{config:t}=e,r=j("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=fn(),n=gn(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=cn(t,{defaultMaxLines:5});s();let i=un(t),l=hn(t),d=mn(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=j("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),p=j("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});d&&p.append(d.wrapper);let u=j("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=j("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(h),d&&h.append(d.previewsContainer),r.append(o,c,n);let m=c;return{footer:r,suggestions:o,composerForm:c,header:h,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:n,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 Li(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let r=j("span",{className:_("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 o=se(e.iconName??"at-sign",13,"currentColor",2);if(o){let e=q("span","persona-mention-token-icon");e.appendChild(o),r.appendChild(e)}return r.appendChild(j("span",{className:"persona-mention-token-label",text:`@${e.label}`})),r}let Pi=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(":"))},Bi=()=>{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 o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let n=document.createElement("span");return n.className="persona-sr-only",n.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(o),e.appendChild(n),e},Ni=(e,t,r)=>{let o={config:r??{},streaming:!0,location:e,defaultRenderer:Bi};if(t){let e=t(o);if(null!==e)return e}return Bi()},Ri=(e,t,r="div")=>{let o=q(r,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return o.textContent=t.format?t.format(n):n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},$i=(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},Hi={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"}},Wi=e=>`custom:${e}`,Di=(e,t)=>"user"!==t&&"assistant"!==t?[]:(e?.custom??[]).filter(e=>(e.roles??["assistant"]).includes(t)),Fi=(e,t,r,o)=>{let n=t.showCopy??!0,a=t.showUpvote??!1,s=t.showDownvote??!1,i=t.showReadAloud??!1,l=(t.showRegenerate??!1)&&!0===o?.canRegenerate,d=(t.showEdit??!1)&&!0===o?.canEdit,c=(t.showQuote??!1)&&!1!==o?.canQuote,p=Di(t,e.role);if(!(n||a||s||i||l||d||c||0!==p.length)){let t=q("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=q("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 o=vi({icon:e,label:t,size:14,className:"persona-message-action-btn",chromeless:!0});return o.setAttribute("data-action",r),o};n&&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,Wi(e.id)));return g},Oi=(e,t,r,o,n,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=$i(e.role,i),g=q("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=ka(a?.widgetConfig?.future).components.message,y=a?.widgetConfig?.theme?.components?.message;((e,t,r="bubble",o)=>{if(!o)return;let n="user"===t?"user":"assistant",a=Hi[r??"bubble"]??Hi.bubble;o.padding&&(e.style.padding=`var(--persona-message-${n}-padding, ${a.padding})`),o.fontSize&&(e.style.fontSize=`var(--persona-message-${n}-font-size, ${a.fontSize})`),o.lineHeight&&(e.style.lineHeight=`var(--persona-message-${n}-line-height, ${a.lineHeight})`),o.fontFamily&&(e.style.fontFamily=`var(--persona-message-${n}-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=vs(a?.widgetConfig?.features?.streamAnimation),C=a?.widgetConfig?.features?.streamAnimation?.plugins,S="assistant"===e.role&&"none"!==x.type?ks(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?As(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?Bs(r,"char",e.id,{skipTags:S.skipTags}):A&&"word"===S?.wrap?Bs(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,o)=>{let n=Math.random().toString(36).slice(2,8),a=e=>`${n}:${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 o of e)"text"===o.kind?r.appendChild(document.createTextNode(o.text)):r.appendChild(Li(o.ref,{readonly:!0,render:t}));return r})(t,o));e.innerHTML=s;let i=RegExp(`${n}:(\\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 n=t[Number(e[1])],a=r.splitText(e.index);a.data=a.data.slice(e[0].length),"mention"===n?.kind&&a.parentNode?.insertBefore(Li(n.ref,{readonly:!0,render:o}),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=Ns(),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=Ri(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 o=q("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r?.())};return e.forEach((e,t)=>{let r=q("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;n+=1,r.addEventListener("error",()=>{a||(a=!0,n=Math.max(0,n-1),r.remove(),0===n&&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,o.appendChild(r)):(a=!0,n=Math.max(0,n-1),r.remove())}),0===n?(s(),null):o}catch{return r?.(),null}})(b,!w&&!!v,()=>{w&&E&&(E.style.display="")});e?g.appendChild(e):w&&E&&(E.style.display="")}let L=(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(L.length>0){let e=(e=>{if(0===e.length)return null;try{let t=q("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(e=>{if(!Pi(e.audio))return;let o=q("audio");o.controls=!0,o.preload="metadata",o.src=e.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth="320px",t.appendChild(o),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(L);e&&g.appendChild(e)}let P=(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(P.length>0){let e=(e=>{if(0===e.length)return null;try{let t=q("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(e=>{if(!Pi(e.video))return;let o=q("video");o.controls=!0,o.preload="metadata",o.src=e.video,o.style.display="block",o.style.width="100%",o.style.maxWidth="320px",o.style.maxHeight="320px",o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),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=>"file"===e.type&&"string"==typeof e.data&&e.data.trim().length>0):[])(e);if(B.length>0){let e=(e=>{if(0===e.length)return null;try{let t=q("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(e=>{if(!Pi(e.data))return;let o=q("a");o.href=e.data,o.download=e.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=e.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(B);e&&g.appendChild(e)}let N=e.contentSegments?.length?null:(e=>{if(!e||0===e.length)return null;let t=j("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let r of e){let e=j("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:r.label}}),o=q("span","persona-mention-chip-icon"),n=se(r.iconName??"at-sign",13,"currentColor",2);n&&o.appendChild(n),e.appendChild(o),e.appendChild(j("span",{className:"persona-mention-chip-label",text:r.label})),t.appendChild(e)}return t})(e.contextMentions);if(N&&g.appendChild(N),g.appendChild(M),p&&"below"===h&&e.createdAt){let t=Ri(e,d);t.classList.add("persona-mt-1"),g.appendChild(t)}let R="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 o=t?.[e];return(void 0===o?r:o)||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(Rs());else if(t)g.appendChild(Rs());else{let e=Ni("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);e&&g.appendChild(e)}}R&&e.stopReason&&!e.streaming&&(v||(M.style.display="none"),g.appendChild(((e,t)=>{let r=q("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,R)));let $="assistant"===e.role&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&!1!==o?.enabled,H=a?.actionEligibility,W="user"===e.role&&!e.streaming&&!1!==o?.enabled&&(!0===o?.showEdit&&!0===H?.canEdit||!0===o?.showQuote&&!0===H?.canQuote||Di(o,"user").length>0);if(($||W)&&o){let t=Fi(e,W?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,0,H);g.appendChild(t)}if(!c||"system"===e.role)return g;let D=q("div","persona-message-with-avatar persona-flex persona-gap-2 "+("user"===e.role?"persona-flex-row-reverse":"")),F=((e,t)=>{let r=q("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o="user"===t?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let e=q("img");e.src=o,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=o,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?D.append(g,F):D.append(F,g),D},zi=(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)},qi=(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=se(t.name,40);if(!r)return void(e.hidden=!0);e.appendChild(r)}else"image"===t.type?e.appendChild(j("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(j("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1}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")},ji="data-persona-welcome-overlay",_i="persona-welcome-overlay-active",Ui=new WeakMap,Vi=(e,t,r)=>{r.setAttribute("data-persona-welcome-plugin",""),t.appendChild(r),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(ji,""),e.classList.contains(_i)||(Ui.set(e,e.scrollTop),e.classList.add(_i),e.scrollTop=0)},Ki=(e,t,r)=>{r&&r!==t&&r.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(ji),e.classList.contains(_i)&&(e.classList.remove(_i),e.scrollTop=Ui.get(e)??e.scrollTop,Ui.delete(e))},Ji=(e,t,r)=>{if(e.replaceChildren(),!t)return void(e.hidden=!0);let o=r?.layout?.messages?.layout??"bubble",n=j("div",{className:$i("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:"flat"===o?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(j("div",{className:"persona-flex"},n)),e.hidden=!1},Gi=()=>typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Xi=(e,t)=>{if(Gi()||"function"!=typeof e.animate||!e.isConnected)return t(null),null;let r=e.getBoundingClientRect(),o=e.parentElement,n=0,a=0,s=0;if(o){let t=getComputedStyle(o);n=parseFloat(t.rowGap)||0;let i=e.previousElementSibling,l=e.nextElementSibling,d=o.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-o.scrollTop;a=Math.max(0,i?r.top-i.getBoundingClientRect().bottom-n:r.top-d),s=Math.max(0,l?l.getBoundingClientRect().top-r.bottom-n: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:-n+"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},Qi=(e,t,r,o=260)=>{if(t<=1||Gi()||"function"!=typeof e.animate||!e.isConnected)return null;let n="drop"===r?-t:t;return e.animate([{transform:`translateY(${n}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})},Yi=new WeakSet,Zi=(e,t)=>!!e&&void 0!==e[t],el=(e,t=!0===e?.launcher?.fullHeight&&!e.launcher.sidebarMode&&"docked"!==e.launcher.mountMode)=>{let r=e?.welcome,o=e?.copy,n=!0===e?.future?.v5Defaults,a=r?.layout??(n?"centered":"top"),s=Zi(r,"variant")?r.variant:!1===o?.showWelcomeCard?"none":"card",i="hero"!==s||n||void 0!==r?.layout?Zi(r,"dismiss")?r.dismiss:n||"hero"===s?"on-first-message":"never":"on-first-message",l=[];Zi(r,"title")&&Zi(o,"welcomeTitle")&&l.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Zi(r,"subtitle")&&Zi(o,"welcomeSubtitle")&&l.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Zi(r,"variant")&&Zi(o,"showWelcomeCard")&&l.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),"hero"===s&&Zi(r,"message")&&l.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!n&&void 0===r?.layout&&"hero"===s&&Zi(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!==Ja(r?.anchorComposerTop);return Zi(r,"anchorComposerTop")&&!c&&l.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),"center"!==d&&(Zi(r,"anchorComposerTop")||Zi(r,"composerGap"))&&l.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),((e,t)=>{e&&!0===e.debug&&t.length&&(Yi.has(e)||(Yi.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))})(e,l),{title:Zi(r,"title")?r.title:o?.welcomeTitle??(n?"What can I help with?":"Hello 👋"),kicker:r?.kicker??"",subtitle:Zi(r,"subtitle")?r.subtitle:o?.welcomeSubtitle??(n?"":"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"}},tl=(e,t)=>"none"!==e.variant&&("never"===e.dismiss||!(t??[]).some(e=>"user"===e.role)),rl="var(--persona-components-panel-height)",ol=e=>{let t=T(e),r=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0;return{width:r??"var(--persona-components-panel-width)",maxWidth:r??"var(--persona-components-panel-maxWidth)",height:0===o?`max(200px, ${rl})`:`max(200px, calc(${rl} - ${o}px))`,maxHeight:"var(--persona-components-panel-maxHeight)"}},nl="16px",al="10px",sl="14px",il=e=>{let t=j("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":ti(e)}});return t.hidden=!0,t},ll=(e,t)=>{let r=((e,t,r={})=>{let o=j("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let n=q("p","persona-welcome-kicker");n.hidden=!0;let a=q("h2","persona-welcome-title"),s=q("p","persona-welcome-subtitle"),i=j("div",{className:"persona-welcome-head-text"},n,a),l=j("div",{className:"persona-welcome-title-row"},o,i);return{host:j("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:r.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},l,s,t),iconHolder:o,kicker:n,title:a,subtitle:s,starterSuggestions:t}})(0,il("starter"),{flatShadow:Ys(e)}),o=el(e);qi(r,o),zi(t,r.host,tl(o,e?.initialMessages));let n=(()=>{let e=j("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e})();return Ji(n,o.message,e),{welcome:r,greetingHost:n}},dl=(e,t)=>{let r=q("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 o=e=>{let t=e.launcher??{},o=Ys(e),n="circle"===ia(e);n?(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||o||n?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,o=se(t.agentIconName,.6*r,"var(--persona-text-inverse, #ffffff)",1.5);o?(l.appendChild(o),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||n)c.style.display="none";else if(c.style.display=o?"none":"",c.innerHTML="",t.callToActionIconName){let o=Math.max((parseFloat(e)||24)-r,8),n=se(t.callToActionIconName,o,"currentColor",1.5);n?c.appendChild(n):c.textContent=t.callToActionIconText??"↗"}else c.textContent=t.callToActionIconText??"↗"}let p=t.position&&si[t.position]?si[t.position]:si["bottom-right"];r.className=o?"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}`,o||(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,o?(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&&o(e),{element:r,update:o,destroy:()=>{r.removeEventListener("click",t),r.remove()}}},cl=new Set,pl=e=>{let t=e?.persistState;return`${("object"==typeof t?t?.keyPrefix:void 0)??"persona-"}teaser-dismissed`},ul=(e,t)=>{let r=q("div","persona-launcher-surface");r.setAttribute("data-persona-launcher-surface","true");let o=e??{},n=null,a=null,s=null,i=null,l=null,d=!1,c=!1,p=!1,u=!1,h=()=>"once"===(n?.frequency??"once")&&!1!==o.persistState,m=()=>{null!==l&&(clearTimeout(l),l=null)},g=e=>{m(),p=!0,a&&d&&(d=!1,a.hidden=!0),((e,t)=>{if(cl.add(e),t)try{window.localStorage.setItem(e,"1")}catch{}})(pl(o),e&&h())},f=e=>{n&&!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=dl(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=o.launcher?.position??"bottom-right",t=si[e]??si["bottom-right"];a?(r.className=_("persona-launcher-surface",t),r.setAttribute("data-teaser",e),r.style.zIndex=String(o.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&&!Ys(e??{})?t:null})(e);n=t,t?(a||(i=j("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),i.addEventListener("click",b),s=j("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"×"}),s.addEventListener("click",v),a=j("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"),n&&a&&(p||c||u||((e,t)=>{if(cl.has(e))return!0;if(!t)return!1;try{return"1"===window.localStorage.getItem(e)}catch{return!1}})(pl(o),h())||(m(),l=setTimeout(y,Math.max(0,n.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=>{o=e,w.update(e),S(e),C()},destroy:()=>{x(),w.destroy(),r.remove()}}},hl=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=(e=>{let t=e?.launcher?.enabled??!0,r=Ys(e);if(Zs(e)){let t=e?.launcher?.composerBar??{},r=q("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 o=q("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");o.style.width="100%",r.appendChild(o);let n=q("div","persona-widget-pill-root");return n.setAttribute("data-persona-composer-bar",""),n.dataset.state="collapsed",n.dataset.expandedSize=t.expandedSize??"anchored",n.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:r,panel:o,pillRoot:n}}if(r){let e=q("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),t=q("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=q("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),r=q("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),o=T(e),n=o.launcherWidth||o.legacyLauncherWidth||void 0!==e?.theme?.components?.panel?.width?ol(e).width:"100%";return t.style.width=n,r.style.width="100%",t.appendChild(r),{wrapper:t,panel:r}}let o=e?.launcher??{},n=o.position&&si[o.position]?si[o.position]:si["bottom-right"],a=q("div",`persona-widget-wrapper persona-fixed ${n} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let s=q("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=ol(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(Zs(e))return((e,t)=>{let r=q("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:o,wrapper:n}=pi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:nl,iconSize:al});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=null,s=null;if(e?.launcher?.clearChat?.enabled??1){let t=ui(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:nl,iconSize:sl});a=t.button,s=t.wrapper,s.style.position="absolute",s.style.top="8px",s.style.right="32px",s.style.zIndex="10"}let i=j("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=j("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});l.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:c}=ll(e,l),{host:p,title:u,subtitle:h}=d,m=d.starterSuggestions,g=q("div","persona-widget-messages persona-flex persona-flex-col");g.style.gap="var(--persona-components-message-gap, 12px)";let f=il("followUp"),y=Va(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=j("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),v=Ei({config:e}),{root:w,textNode:x}=Ti();return r.append(i,n,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:o,closeButtonWrapper:n,clearChatButton:a,clearChatButtonWrapper:s,iconHolder:q("span"),headerTitle:q("span"),headerSubtitle:q("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=j("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,n=!1!==e?.layout?.showHeader,a=o?Mi(e,o,{showClose:t}):fi({config:e,showClose:t}),s=j("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});s.style.setProperty("scrollbar-gutter","stable");let{welcome:i,greetingHost:l}=ll(e,s),{host:d,title:c,subtitle:p}=i,u=i.starterSuggestions,h=q("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let m=il("followUp"),g=Va(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=Ii({config:e}),y=!1!==e?.layout?.showFooter;n||(a.header.style.display="none"),yi(r,a,e),r.append(s);let b=j("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return 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:o,pillRoot:n},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}}},ml=({config:e,plugins:t,onToggle:r})=>{let o=t.find(e=>e.renderLauncher);if(o?.renderLauncher){let t=o.renderLauncher({config:e,defaultRenderer:()=>dl(e,r).element,onToggle:r});if(t)return{instance:null,element:t}}let n=ul(e,r);return{instance:n,element:n.element}},gl=(e,t,r)=>{let o=r;for(let r of t){let t=q("span","persona-tool-char");t.style.setProperty("--char-index",String(o)),t.textContent=" "===r?" ":r,e.appendChild(t),o++}return o},fl=(e,t,r)=>{me(e,t,{stateSet:r,previewKind:"reasoning",iconColor:"currentColor"})},yl=(e,t,r=new Set)=>{t=ge(t,"reasoning");let o=e.reasoning,n=le("persona-reasoning-bubble",e.id);if(!o)return be(n,e,t,"reasoning");let a=t?.features?.reasoningDisplay??{},s=a.expandable??N.expandable,i=s&&r.has(e.id),l="complete"!==o.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??N.previewMaxLines),c=de({expandable:s,expanded:i,bubbleType:"reasoning"}),p=q("div","persona-flex persona-flex-col persona-text-left"),u=q("span","persona-text-xs persona-text-persona-primary"),h="row"===fe(t,"reasoning"),m=h&&!l?`Thought for ${ye(o.durationMs??(void 0!==o.completedAt&&void 0!==o.startedAt?o.completedAt-o.startedAt:void 0))}`:"Thinking...",g=t?.reasoning??{},f=String(o.startedAt??Date.now()),y=()=>{let e=q("span","");return e.setAttribute("data-tool-elapsed",f),e.textContent=lr(o),e},b=g.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:m,previewText:d,isActive:l,config:t??{},elapsed:lr(o),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=q("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,o=(void 0===e.durationMs?Math.max(0,t-r):e.durationMs)/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`})(e):"pending"===e.status?"Waiting":"")(o),h||p.appendChild(v);let w=a.loadingAnimation??N.loadingAnimation,x=g.activeTextTemplate,C=g.completeTextTemplate,S=l?x:C,k=b instanceof HTMLElement,A=(e,t)=>{u.textContent="";let r=cr(e,""),n=0;for(let e of r){let r=e.styles.length>0?(()=>{let t=q("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?lr(o):e.text;t?n=gl(r,a,n):r.appendChild(document.createTextNode(a))}}};if(!k&&S)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`),A(S,!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)),A(S,!0))}else A(S,!1);else if(!k&&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="",gl(u,t,0)}"complete"===o.status&&!h&&(u.style.display="none")}else k||("complete"!==o.status||h?u.style.display="":u.style.display="none");if(a.iconName&&!k){let e=q("span","persona-reasoning-header-icon"),t=se(a.iconName,16,"currentColor",2);t&&(e.appendChild(t),c.appendChild(e))}let M="currentColor",I=pe(c,p,{expandable:s,expanded:i,iconColor:M,metaGap:!1}),T=ue({bubble:n,previewKind:"reasoning",expanded:i,isActive:l,previewText:d,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:d,isActive:l,config:t??{}})});if(!s)return n.append(c,T),be(n,e,t,"reasoning");let E=q("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");E.style.display=i?"":"none";let L=o.chunks.join(""),P=q("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return P.textContent=L||("complete"===o.status?"No additional context was shared.":"Waiting for details…"),E.appendChild(P),he({expanded:i,header:c,toggleIcon:I,content:E,collapsedPreview:T,iconColor:M}),n.append(c,T,E),be(n,e,t,"reasoning")},bl=e=>{if(null==e)return!0;if("string"==typeof e){if(!e.trim())return!0;try{return bl(JSON.parse(e))}catch{return!1}}return"object"==typeof e&&0===Object.keys(e).length},vl=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}},wl=new WeakMap;async function xl(e){let t=e.closest("[data-persona-tool-detail]"),r=t?.querySelector("pre");if(!r)return;let o=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(wl.get(e));try{await navigator.clipboard.writeText(r.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let t=se("check",14,"currentColor",2);t&&e.replaceChildren(t)}catch{e.setAttribute("aria-label","Copy failed — try again"),e.title="Copy failed — try again"}wl.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",o),e.title=o;let t=se("copy",14,"currentColor",1.7);t&&e.replaceChildren(t),wl.delete(e)},1800))}let Cl=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),Sl=(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)"},kl=(e,t)=>{let r=e.toolCall,o=t?.features?.toolCallDisplay,n=o?.collapsedMode??B.collapsedMode,a=!1===r?.success?r.error||"Tool failed":((e,t)=>{let r=e.toolCall;if(!r)return"";let o=(r.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(-t).join("\n");let n=ar(r.args).trim();return n?n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join("\n"):""})(e,o?.previewMaxLines??B.previewMaxLines),s=r?.interrupted?`${r.name?.trim()||"Tool"} · Interrupted`:r?"row"===fe(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"===n?d=r.name?.trim()||s:"tool-preview"===n&&a&&(d=a),i&&l.activeTextTemplate?d=dr(r,l.activeTextTemplate,d):!i&&!r.interrupted&&l.completeTextTemplate&&(d=dr(r,l.completeTextTemplate,d)),r.interrupted?d.includes(" · Interrupted")||(d+=" · Interrupted"):!1===r.success?d+=" · Failed":r.superseded&&(d+=" · Approved, ran again below"),{summary:d,previewText:a,isActive:i}},Al=(e,t,r,o)=>{me(e,t,{stateSet:r,previewKind:"tool",iconColor:Cl(o?.toolCall??{},t.classList.contains("persona-activity-row"))})},Ml=(e,t,r=new Set)=>{t=ge(t,"tool");let o=e.toolCall,n=t?.toolCall??{},a=le("persona-tool-bubble",e.id);if(n.backgroundColor&&(a.style.backgroundColor=n.backgroundColor),n.borderColor&&(a.style.borderColor=n.borderColor),n.borderWidth&&(a.style.borderWidth=n.borderWidth),n.borderRadius&&(a.style.borderRadius=n.borderRadius),a.style.boxShadow=void 0===n.shadow?"var(--persona-tool-bubble-shadow)":""===n.shadow.trim()?"none":n.shadow,!o)return be(a,e,t,"tool");let s=t?.features?.toolCallDisplay??{},i=s.expandable??B.expandable,l=i&&r.has(e.id),{summary:d,previewText:c,isActive:p}=kl(e,t),u=de({expandable:i,expanded:l,bubbleType:"tool"});n.headerBackgroundColor&&(u.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(u.style.paddingLeft=n.headerPaddingX,u.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(u.style.paddingTop=n.headerPaddingY,u.style.paddingBottom=n.headerPaddingY);let h=q("div","persona-flex persona-flex-col persona-text-left"),m=q("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(m.style.color=n.headerTextColor);let g=String(o.startedAt??Date.now()),f=()=>{let e=q("span","");return p&&e.setAttribute("data-tool-elapsed",g),e.textContent=ir(o),e},y=n.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:d,previewText:c,collapsedMode:s.collapsedMode??B.collapsedMode,isActive:p,config:t??{},elapsed:ir(o),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??B.loadingAnimation,v=n.activeTextTemplate,w=o.interrupted?void 0:n.completeTextTemplate,x=p?v:w,C=(e,t)=>{m.textContent="";let r=o.name?.trim()||"tool",n=cr(e,r),a=0;for(let e of n){let r=e.styles.length>0?(()=>{let t=q("span",e.styles.map(e=>`persona-tool-text-${e}`).join(" "));return m.appendChild(t),t})():m;if(e.isDuration&&p)r.appendChild(f());else{let n=e.isDuration?ir(o):e.text;t?a=gl(r,n,a):r.appendChild(document.createTextNode(n))}}};if(!(y instanceof HTMLElement))if(p&&"none"!==b){let e=n.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`),x&&C(x,!1);else if(m.classList.add(`persona-tool-loading-${b}`),m.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===b&&(n.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),x)C(x,!0);else{let e=m.textContent||d;m.textContent="",gl(m,e,0)}}else x&&C(x,!1);let S=Cl(n,"row"===fe(t,"tool")),k=pe(u,h,{expandable:i,expanded:l,iconColor:S,metaGap:!0}),A=ue({bubble:a,previewKind:"tool",expanded:l,isActive:p,previewText:c,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>n.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:c,isActive:p,config:t??{}})});if(!i)return a.append(u,A),be(a,e,t,"tool");let M=q("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(M.style.display=l?"":"none",n.contentBackgroundColor&&(M.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(M.style.color=n.contentTextColor),n.contentPaddingX&&(M.style.paddingLeft=n.contentPaddingX,M.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(M.style.paddingTop=n.contentPaddingY,M.style.paddingBottom=n.contentPaddingY),!0===t.future?.v5Defaults)!function(e,t,r){let o=t.toolCall;if(!o)return;let n=r.toolCall??{},a=(t,r)=>{let o=j("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":t.toLowerCase()},style:{backgroundColor:n.codeBlockBackgroundColor,borderColor:n.codeBlockBorderColor,borderWidth:n.codeBlockBorderColor?"1px":void 0}}),a=j("div",{className:"persona-tool-detail-label",text:t,style:{color:n.labelTextColor}}),s=ar(r),i=j("pre",{className:"persona-tool-detail-value"+(vl(r)?" persona-tool-detail-code":""),text:s,attrs:s.length>420||s.split("\n").length>7?{tabindex:"0","aria-label":`${t} content`}:{},style:{color:n.codeBlockTextColor??n.contentTextColor}}),l=j("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${t.toLowerCase()}`,title:`Copy ${t.toLowerCase()}`}}),d=se("copy",14,"currentColor",1.7);d&&l.appendChild(d),o.append(a,i,l),e.appendChild(o)};bl(o.args)||a("Request",o.args);let s="complete"===o.status&&void 0!==o.result?o.result:o.chunks?.join("");void 0!==s&&("string"!=typeof s||s.trim())&&a("Response",s),!1===o.success&&e.appendChild(j("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}(M,e,t);else{if(o.name){let e=q("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?e.style.color=n.contentTextColor:n.headerTextColor&&(e.style.color=n.headerTextColor),e.textContent=o.name,M.appendChild(e)}if(void 0!==o.args){let e=q("div","persona-space-y-1"),t=q("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(t.style.color=n.labelTextColor),t.textContent="Arguments";let r=q("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",Sl(r,n),r.textContent=ar(o.args),e.append(t,r),M.appendChild(e)}if(o.chunks&&o.chunks.length){let e=q("div","persona-space-y-1"),t=q("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(t.style.color=n.labelTextColor),t.textContent="Activity";let r=q("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",Sl(r,n),r.textContent=o.chunks.join(""),e.append(t,r),M.appendChild(e)}if(!1===o.success&&M.appendChild(j("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),"complete"===o.status&&void 0!==o.result){let e=q("div","persona-space-y-1"),t=q("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(t.style.color=n.labelTextColor),t.textContent="Result";let r=q("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",Sl(r,n),r.textContent=ar(o.result),e.append(t,r),M.appendChild(e)}if("complete"===o.status&&"number"==typeof o.duration){let e=q("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(e.style.color=n.contentTextColor),e.textContent=`Duration: ${o.duration}ms`,M.appendChild(e)}}return he({expanded:l,header:u,toggleIcon:k,content:M,collapsedPreview:A,iconColor:S}),a.append(u,A,M),be(a,e,t,"tool")},{setLoader:Il,load:Tl,provide:El,getSync:Ll}=U({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),Pl=Il,Bl=Tl,Nl=Ll,{setLoader:Rl,load:$l}=U({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),Hl=Rl,Wl=$l,Dl=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)})}},Fl=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:Ol,load:zl,provide:ql,getSync:jl}=U({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),_l=null,Ul=new Set,Vl=e=>{if(_l)return _l;_l=e,e.initArtifactsUi({componentRegistry:Dl});for(let t of Fl)Dl.has(t)||Dl.register(t,"PersonaArtifactCard"===t?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Pe();t?e.__provideMarkdownParsers(t):Le(()=>{let t=Pe();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>G());let r=[...Ul];Ul.clear();for(let e of r)try{e()}catch{}return e},Kl=Ol,Jl=()=>zl().then(Vl),Gl=()=>{if(_l)return _l;let e=jl();return e?Vl(e):null},Xl=e=>_l?()=>{}:(Ul.add(e),()=>{Ul.delete(e)});function Ql(e){return!0===e?.features?.artifacts?.enabled}function Yl(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"),!Ql(t))return;let r=t.features?.artifacts?.layout,o=r?.paneBorder?.trim(),n=r?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):n&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",n))}let Zl=["panel","seamless","detached"];function ed(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Zl.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function td(e){return!(!e||!Ql(e))&&"detached"===ed(e)}function rd(e,t){if(!Ql(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 Yl(e,t);let r=t.features?.artifacts?.layout,o="detached"===ed(t)?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",r?.splitGap??o),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 n=r?.paneBackground?.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):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 o=t?.trim();o?e.style.setProperty(r,o):e.style.removeProperty(r)}Yl(e,t)}function od(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"),!Ql(t))return;let r=t.features?.artifacts?.layout,o=ed(t);e.classList.add(`persona-artifact-appearance-${o}`);let n=r?.paneBorderRadius?.trim();n&&e.style.setProperty("--persona-artifact-pane-radius",n);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 nd=new Set(["__proto__","prototype","constructor"]),ad=new Set(["collapsed","card","panel","inline"]),sd=new Set(["markdown","component"]),id=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,ld=e=>"object"==typeof e&&!!e&&!Array.isArray(e),dd=e=>!nd.has(e),cd=e=>"string"==typeof e&&ad.has(e),pd=e=>Object.keys(e).length>0;function ud(e,t,r,o){e.push({path:t,code:r,message:o})}let hd="Ignored an unsupported value.",md={kind:"mode",message:hd},gd={kind:"string",message:"Expected a CSS length string."},fd={kind:"boolean"},yd={kind:"object",message:"Expected a preference object.",children:{showToolCalls:fd,showReasoning:fd,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:hd},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:hd},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:hd},expandable:fd,grouped:fd}},reasoningDisplay:{kind:"object",children:{expandable:fd,activePreview:fd}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:md,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:md,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:sd,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:sd}}},filePreview:{kind:"object",children:{enabled:fd}},layout:{kind:"object",children:{paneWidth:gd,paneMaxWidth:gd,paneMinWidth:gd,expandedPanelWidth:gd,resizableMinWidth:gd,resizableMaxWidth:gd,expandLauncherPanelWhenOpen:fd,resizable:fd}}}}}};function bd(e,t,r,o){if(void 0!==e)switch(t.kind){case"boolean":return"boolean"==typeof e?e:ud(o,r,"invalid_type","Expected a boolean.");case"string":return"string"==typeof e?e:ud(o,r,"invalid_type",t.message);case"enum":return"string"==typeof e&&t.values.has(e)?e:ud(o,r,"invalid_value",t.message);case"mode":return cd(e)?to(e):ud(o,r,"invalid_value",t.message);case"modeMap":{if(!ld(e))return ud(o,r,"invalid_type","Expected an object.");let n="mediaType"===t.keys?void 0:t.keys,a={};for(let[t,s]of Object.entries(e)){let e=n?t:ro(t);dd(t)&&(n?n.has(t):id.test(e))?cd(s)?a[e]=to(s):ud(o,`${r}.${t}`,"invalid_value","Expected collapsed, panel, or inline."):ud(o,`${r}.${t}`,n?"unknown_key":"invalid_value",n?"Ignored an unsupported selector.":'Expected a MIME type such as "text/html" or a wildcard such as "image/*".')}return pd(a)?a:void 0}case"object":{if(t.bareMode&&cd(e))return to(e);if(!ld(e))return ud(o,r,"invalid_type",t.message??"Expected an object.");let n=Object.keys(t.children),a=e=>r?`${r}.${e}`:e;for(let t of Object.keys(e))(!dd(t)||!n.includes(t))&&ud(o,a(t),"unknown_key","Ignored because this key is not part of the persisted preference schema.");let s={};for(let r of n){let n=t.children[r],i=bd(e[r],n,a(r),o);if(n.deprecated&&void 0!==e[r]&&ud(o,a(r),"deprecated_key",n.deprecated),void 0===i)continue;let l=n.alias??r,d=s[l];s[l]=ld(d)&&ld(i)?{...d,...i}:i}return pd(s)?s:void 0}}}function vd(e){let t=[];return{preferences:(null===e?void 0:bd(e,yd,"",t))??{},issues:t}}function wd(e){if(Array.isArray(e))return e.map(wd);if(!ld(e))return e;let t={};for(let[r,o]of Object.entries(e))dd(r)&&void 0!==o&&(t[r]=wd(o));return t}function xd(e,t){let r=wd(e);for(let[e,o]of Object.entries(t)){if(!dd(e)||void 0===o)continue;let t=r[e];r[e]=ld(t)&&ld(o)?xd(t,o):wd(o)}return r}function Cd(e,t){if(void 0===t)return void 0===e?void 0:wd(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},o=t.default??r.default,n={...r.byType,...r.byKind,...t.byType,...t.byKind},a=function(e,t){if(void 0===t)return void 0===e?void 0:wd(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},o=t.default??r.default,n={...r.byMediaType,...t.byMediaType},a={...o?{default:o}:{},...pd(n)?{byMediaType:n}:{}};return pd(a)?a:void 0}(r.files,t.files),s={...o?{default:o}:{},...pd(n)?{byKind:n}:{},...void 0===a?{}:{files:a}};return pd(s)?s:void 0}function Sd(e={},t){let r=function(e){let t,r={};for(let o of e){let e=vd(o).preferences;t=Cd(t,e.artifacts?.display),r=xd(r,e)}let o=r;return o.artifacts&&(void 0===t?delete o.artifacts.display:o.artifacts.display=t),o}(t),o={...e};if(void 0!==r.showToolCalls&&(o.showToolCalls=r.showToolCalls),void 0!==r.showReasoning&&(o.showReasoning=r.showReasoning),r.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...r.toolCallDisplay}),r.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...r.reasoningDisplay}),r.artifacts){let t=e.artifacts??{},n={...t};if(void 0!==r.artifacts.display){let e=Cd(t.display,r.artifacts.display);void 0!==e&&(n.display=e)}r.artifacts.filePreview&&(n.filePreview={...t.filePreview,enabled:r.artifacts.filePreview.enabled}),r.artifacts.layout&&(n.layout={...t.layout,...r.artifacts.layout}),o.artifacts=n}return o}function kd(e){let t=e.preferences;return t&&pd(t)?{...e,features:Sd(e.features??{},[t])}:e}function Ad(e,t){let r=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let n=/^([\d.]+)/.exec(r);return n?Number(n[1]):8}let{setLoader:Md,load:Id,provide:Td,getSync:Ed}=U({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),Ld=Md,Pd=Id,Bd=Ed,Nd=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()}},Rd=e=>"object"==typeof e&&!!e&&!Array.isArray(e),$d=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),Hd=(e,t,r)=>{if(!Rd(e)||!Rd(t)||$d.has(r))return t;let o={...e};for(let n of Object.keys(t)){if(void 0===t[n]){delete o[n];continue}let a=r?`${r}.${n}`:n;o[n]=Hd(e[n],t[n],a)}return o};function Wd(e,t){let r=w(H),o=function(e,t,r){let o=t[b];if(o)return o;let n=new Set(C(e,r));for(let e of r){let r=x(t,e);"clear"===r&&n.delete(e),"explicit"===r&&n.add(e)}return[...n]}(e,t,r),n=S(function(e,t,r){let o={...e};for(let e of t){if(r.includes(e))continue;let t=e.split("."),n=o;for(let e of t.slice(0,-1)){let t=n[e];if(!v(t)){n=void 0;break}n[e]={...t},n=n[e]}n&&delete n[t[t.length-1]]}return o}(Hd(e,t,""),r,o),o);return E(z(n),((e,t)=>{let r=t[A];if(r)return{...r};let o=T(e);return M(t,"launcherWidth")&&(o.legacyLauncherWidth=void 0!==t.launcherWidth),M(t,"launcher")&&void 0===t.launcher?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(M(t.launcher,"width")&&(o.launcherWidth=void 0!==t.launcher?.width),M(t.launcher,"sidebarWidth")&&(o.sidebarWidth=void 0!==t.launcher?.sidebarWidth),M(t.launcher,"dock")&&void 0===t.launcher?.dock?o.dockWidth=!1:M(t.launcher?.dock,"width")&&(o.dockWidth=void 0!==t.launcher?.dock?.width),o)})(e,t))}let Dd=({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 o=0;for(let e=r;e<t.length;e+=1){let n=t[e];if("{"===n&&(o+=1),"}"===n&&(--o,0===o))return t.slice(r,e+1)}return null})(t);if(!r)return null;let o=JSON.parse(r);if(!o||"object"!=typeof o||!o.action)return null;let{action:n,...a}=o;return{type:String(n),payload:a,raw:o}}catch{return null}},Fd=e=>"string"==typeof e?e:null==e?"":String(e),Od={message:e=>{if("message"===e.type)return{handled:!0,displayText:Fd(e.payload.text)}},messageAndClick:(e,t)=>{if("message_and_click"!==e.type)return;let r=e.payload,o=Fd(r.element);if(o&&t.document?.querySelector){let e=t.document.querySelector(o);e?setTimeout(()=>{e.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Fd(r.text)}}},zd=e=>Array.isArray(e)?e.map(e=>String(e)):[],qd=e=>{let t=new Set(zd(e.getSessionMetadata().processedActionMessageIds));return{process:r=>{if(r.streaming||"assistant"!==r.message.role||!r.text||t.has(r.message.id))return null;let o="string"==typeof r.raw&&r.raw||"string"==typeof r.message.rawContent&&r.message.rawContent||"string"==typeof r.text&&r.text||null;!o&&"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 n=o?e.parsers.reduce((e,t)=>e||t?.({text:o,message:r.message})||null,null):null;if(!n)return null;t.add(r.message.id),(()=>{let r=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:r}))})();let a={action:n,message:r.message};e.emit("action:detected",a);for(let t of e.handlers)if(t)try{let o=t(n,{message:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{e.emit("action:resubmit",a)}});if(!o)continue;if(o.handled){let e=!1!==o.persistMessage;return{text:void 0===o.displayText?"":o.displayText,persist:e,resubmit:o.resubmit}}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",e)}return{text:"",persist:!0}},syncFromMetadata:()=>{t=new Set(zd(e.getSessionMetadata().processedActionMessageIds))}}},jd=e=>e.map(e=>({...e,streaming:!1})),_d=e=>e.map(e=>({...e,status:"complete"})),Ud=e=>`${e??"persona-"}state`,Vd=(e=Ud())=>{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 o=t();if(o)try{let t={...r,messages:r.messages?jd(r.messages):void 0,artifacts:r.artifacts?_d(r.artifacts):void 0};o.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)}}}},Kd=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)},Jd=(e,t,r)=>{let o="",n="",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(o)}catch{return s=!0,d}},m=(e,t)=>{if(i||e===d)return;let r=d;d=e,l+=1;let o={previousToken:r,token:e,source:t,revision:l};for(let e of p)e(o)},g=e=>{i||(null===e.key||e.key===o)&&m(null===e.key?null:e.newValue??null,"external")},f=(async()=>{let s=await(async(e,t)=>{let r=await Kd(e);return{storageKey:`${t}visitor:${r}`,leaseKey:`${t}visitor-init-lock:${r}`,lockName:`persona-visitor-init:${await Kd(`${e}\0${t}`)}`}})(e,t);o=s.storageKey,n=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(n);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(n)}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(o,e);function o(){clearTimeout(r),w.delete(o),window.removeEventListener("storage",a),t()}function a(e){(null===e.key||e.key===n)&&o()}w.add(o),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(o,e)}catch{s=!0}m(e,"local")},async clear(){await f;let e=u();if(e)try{e.removeItem(o)}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 o=Date.now(),a=b();if(a&&a.expiresAt>o&&a.ownerNonce!==t)await C(Math.min(a.expiresAt-o,500));else{try{r.setItem(n,JSON.stringify({ownerNonce:t,expiresAt:o+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:(o,n,a)=>o===e&&n===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:Gd,load:Xd}=U({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),Qd=Gd,Yd=Xd,{setLoader:Zd,load:ec,provide:tc,getSync:rc}=U({fallbackImport:()=>import("./history-shell")}),oc=Zd,nc=ec,ac=rc;function sc(){return null}function ic(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.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,vt.parse)(r,vt.STR|vt.OBJ),r);t&&(e=t)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function lc(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=Dl.get(e.component);if(!a){if(Fl.includes(e.component)){Jl().catch(()=>{});let e=q("div","persona-w-full");return e.setAttribute("data-persona-artifact-pending","true"),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let s={message:o,config:r,updateProps:e=>{n&&n(e)}};try{return a(e.props,s)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function dc(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 cc(e){let t=dc(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 pc(e){let t=dc(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 uc=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function hc(e){let{onSubmit:t,onDismiss:r,title:o="How satisfied are you?",subtitle:n="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:l=!0,ratingLabels:d=uc}=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=o,h.appendChild(m);let g=document.createElement("p");g.className="persona-feedback-subtitle",g.textContent=n,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 o=r<e;t.classList.toggle("selected",o),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 mc(e){let{onSubmit:t,onDismiss:r,title:o="How likely are you to recommend us?",subtitle:n="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=o,m.appendChild(g);let f=document.createElement("p");f.className="persona-feedback-subtitle",f.textContent=n,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 gc="persona-chat-history",fc="data-persona-composer-reason",yc="data-persona-composer-notice",bc={"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 vc(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 o=bc[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${o}`,{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 wc(e){if(!e)return!1;let t=e.types;return!!t&&("function"==typeof t.contains?t.contains("Files"):Array.from(t).includes("Files"))}let xc=e=>e&&"object"==typeof e?{...e}:{},Cc=e=>e.filter(e=>!Lr(e)).map(e=>({...e,streaming:!1})),Sc=(e,t,r)=>{let o=e?.markdown?Ne(e.markdown):null,n=je(e?.sanitize);e?.postprocessMessage&&n&&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!==Pe();if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:s,raw:i??a.text??""});l=n?n(t):t}else if(o){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 o=t[e],n=t[e+1];if(!Ue(o)||_e.test(o)||!_e.test(n))continue;let a=Ve(o).length;if(a<1)continue;let s=Je(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()||!Ue(e))break;let o=Ke(Ge(Ve(e),a));t[i]!==o&&(t[i]=o,r=!0)}e=i-1}return r?t.join("\n"):e})(s):s,t=o(e);l=n&&d?n(t):t}else l=He(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)),He(e.text??"")}}};function kc(e){let t=q("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=se(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=q("span","persona-drop-overlay-label");r.textContent=e.label,t.appendChild(r)}return t}let Ac=(e,t)=>{let r={...e};for(let[e,o]of Object.entries(t)){let t=r[e];r[e]=t?{...t,...o}:o}return r},Mc=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:Ac(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),Ic=(e,t,r)=>{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 o=z(t),n=new Set,s=new Set,i=function(e){let t=new Set,r=new Set,o=new Set,n=new Map,a=e=>{clearTimeout(n.get(e)),n.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&&!o.has(a.id))){if(o.add(a.id),!1===l.autoCollapseDelay)return;n.set(a.id,setTimeout(()=>{n.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 n of new Set([...t,...r,...o]))e.has(n)||(a(n),t.delete(n),r.delete(n),o.delete(n))},clear(){for(let e of n.keys())a(e);t.clear(),r.clear(),o.clear()}}}((e,t)=>{Ha.delete(e);let r=Array.from(dt.querySelectorAll("[data-message-id]")).find(t=>t.dataset.messageId===e);r&&("tool"===t?Al(e,r,n,o):fl(e,r,s))}),l=new Map,d=()=>{Uo({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};d();let c=o.features;o=kd(o);let p=Nd.getForInstance(o.plugins),h=os(e),f=[],b=!1,v=(e=>{let t=new Map,r=!1,o=()=>{if(r||!1===e()?.persistState)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return r=!0,null}};return n=>{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(),n,t);return{get:e=>{let n=a(e),s=o();if(s)try{return s.getItem(n)}catch{r=!0}return t.get(n)??null},set:(e,n)=>{let s=a(e),i=o();if(i)try{return void i.setItem(s,n)}catch{r=!0}t.set(s,n)},remove:e=>{let n=a(e);t.delete(n);let s=o();if(s)try{s.removeItem(n)}catch{r=!0}}}}})(()=>o),w=null,x=null,C=null,S=!1,k=null,A=e=>{w=e,e.initApprovalUi({webMcpToolTitle:a});let t=e.createBuiltInApprovalPlugin(l);x=t.plugin,C=t.teardown},M=()=>{if(w)return w;let e=Nl();return e?(A(e),e):(Bl().then(e=>{S||w||(A(e),k?.())}).catch(()=>{}),null)},I=!1,E=!1,L=null,P=(e,t,r,o)=>{if(!e.querySelector("[data-tv-form]"))return;let n=Bd();n?n.enhanceWithForms(e,t,r,o):Pd().then(()=>{I||E||!L||(E=!0,L())}).catch(()=>{})};o.components&&Dl.registerAll(o.components);let B,N,R=(()=>{let e=new Map,t=(t,r)=>{e.get(t)?.delete(r)};return{on:(r,o)=>(e.has(r)||e.set(r,new Set),e.get(r).add(o),()=>t(r,o)),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)}})}}})(),$=!1===o.persistState?null:o.storageAdapter??Vd(Ud("object"==typeof o.persistState?o.persistState.keyPrefix:void 0)),H=!!o.clientToken&&"function"!=typeof o.reconnectStream,W={},D=null,F=new Promise(e=>{B=e}),O=()=>{},j=new Promise(e=>{O=e}),_=!1,U=e=>{if(o.onStateLoaded)try{let t=o.onStateLoaded(e);if(t&&"object"==typeof t&&"state"in t){let{state:e,open:r}=t;return r&&(_=!0),e}return t}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}return e};if($?.load)try{let e=$.load();if(e&&"function"==typeof e.then)D=e.then(e=>U(e??{messages:[],metadata:{}}));else{let t=U(e??{messages:[],metadata:{}});t.metadata&&(W=xc(t.metadata)),t.messages?.length&&(o={...o,initialMessages:t.messages}),t.artifacts?.length&&(o={...o,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(o.onStateLoaded)try{let e=U({messages:[],metadata:{}});e.messages?.length&&(o={...o,initialMessages:e.messages})}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}D||B();let V=()=>W,K=e=>{W=e({...W})??{},li()},J=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dd],G=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Od.message,Od.messageAndClick],X=qd({parsers:J,handlers:G,getSessionMetadata:V,updateSessionMetadata:K,emit:R.emit,documentRef:typeof document<"u"?document:null});X.syncFromMetadata();let Q=o.launcher?.enabled??!0,Y=o.launcher?.autoExpand??!1,Z=o.autoFocusInput??!1,ee=Y,te=Q,re=o.layout?.header?.layout,ne=!1,ae=()=>Zs(o),ie=()=>Q||ae(),le=!ae()&&(!Q||Y),de=!1,ce=null,pe=()=>{de=!0,ce&&clearTimeout(ce),ce=setTimeout(()=>{de&&=(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),!1)},1e4)},ue=Sc(o,X,pe),he=o.features?.showReasoning??!0,me=o.features?.showToolCalls??!0,ge=o.features?.showEventStreamToggle??!1,be=o.features?.scrollToBottom??{},Se=o.features?.scrollBehavior??{},ke=()=>("object"==typeof o.persistState?o.persistState?.keyPrefix:void 0)??"persona-",Ae=`${ke()}event-stream`,Me=null,Ie=o.features?.eventStream?.maxEvents??2e3,Te=null,Be=null,Ne=null,Re=!1,$e=null,We=!1,De=null,Fe=0,Oe=(e,t)=>{Te?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},ze=(e,t)=>{Be?.processEvent(e,t),Te?Oe(e,t):Ne&&(Ne.length>=Ie&&Ne.shift(),Ne.push({type:e,payload:t}))},qe=()=>{!Te&&ge&&(Ne??=[],Wl().then(e=>{if(Re||Te||!ge)return;Me=new e.EventStreamStore(Ae),Te=new e.EventStreamBuffer(Ie,Me),Be??=new e.ThroughputTracker,Me.open().then(()=>Te?.restore()).catch(e=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",e)});let t=Ne??[];Ne=null;for(let e of t)Be?.processEvent(e.type,e.payload),Oe(e.type,e.payload)}).catch(()=>{}))};ge&&qe();let je=!1,_e=null,Ue=()=>{},Ve=()=>{},Ke=()=>{},Je=()=>{},Ge=()=>{},Xe=e=>{R.emit("message:copy",e),wa?.isClientTokenMode()&&wa.submitMessageFeedback(e.id,"copy").catch(e=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",e)}),o.messageActions?.onCopy?.(e)},Qe=e=>{R.emit("message:feedback",e),wa?.isClientTokenMode()&&wa.submitMessageFeedback(e.messageId,e.type).catch(e=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",e)}),o.messageActions?.onFeedback?.(e)};o.statusIndicator;let Ye=(e,t=o.statusIndicator??{})=>"idle"===e?t.idleText??Pr.idle:"connecting"===e?t.connectingText??Pr.connecting:"connected"===e?t.connectedText??Pr.connected:"error"===e?t.errorText??Pr.error:"paused"===e?t.pausedText??Pr.paused:"resuming"===e?t.resumingText??Pr.resuming:Pr[e];function et(e,t,r,o){if(!ae()&&("transient"===r.mode||e.classList.contains("persona-mb-2"))&&(xe(e,gt,r),we(e,r,o)),!e.hasAttribute(fc)&&!e.hasAttribute(yc))if("idle"===o&&r.idleLink){e.textContent="";let o=document.createElement("a");o.href=r.idleLink,o.target="_blank",o.rel="noopener noreferrer",o.textContent=t,o.style.color="inherit",o.style.textDecoration="none",e.appendChild(o)}else e.textContent=t}let tt=hl({config:o,showClose:ie()}),{wrapper:rt,panel:ot,pillRoot:nt}=tt.shell,st=tt.panelElements,{container:it,body:lt,messagesWrapper:dt,starterSuggestions:ct,transcriptSuggestions:pt,suggestions:ut,textarea:ht,sendButton:mt,composerForm:gt,statusText:ft,welcomeHost:yt,welcomeIconHolder:bt,greetingHost:vt,introKicker:wt,introTitle:xt,introSubtitle:Ct,closeButton:St,iconHolder:kt,headerTitle:At,headerSubtitle:Mt,header:It,footer:Tt,actionsRow:Lt}=st,Bt=st.leftActions,Nt=st.rightActions,Rt=st.sendButtonWrapper,$t=st.setSendButtonMode,Ht=st.micButton,Wt=st.micButtonWrapper,Dt=st.attachmentButton,Ft=st.attachmentButtonWrapper,Ot=st.attachmentInput,zt=st.attachmentPreviewsContainer;it.classList.add("persona-relative"),lt.classList.add("persona-relative");let _t=()=>be.label??"",Ut=()=>Se.mode??"anchor-top",Vt=()=>"follow"===Ut()||"anchor-top"===Ut()&&ws,Jt=()=>Se.anchorTopOffset??16,Xt=()=>!0===Se.pauseOnInteraction,Yt=()=>!1!==Se.showActivityWhilePinned,Zt=()=>!0===Se.announce,er=()=>Se.scrollbar??"on-scroll",tr=q("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");tr.type="button",tr.style.display="none",tr.setAttribute("data-persona-scroll-to-bottom","true");let rr=q("span","persona-flex persona-items-center"),or=q("span",""),nr=q("span","");nr.setAttribute("data-persona-scroll-to-bottom-count",""),nr.style.display="none",tr.append(rr,or,nr),it.appendChild(tr);let ar=q("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",lt.appendChild(ar);let ir=q("div","persona-sr-only");ir.setAttribute("aria-live","polite"),ir.setAttribute("aria-atomic","true"),ir.setAttribute("role","status"),ir.setAttribute("data-persona-live-region",""),Object.assign(ir.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"}),it.appendChild(ir);let lr=null,dr=null,cr=e=>{Zt()&&e&&(dr=e,null===lr&&(lr=setTimeout(()=>{lr=null,dr&&Zt()&&(ir.textContent=dr),dr=null},400)))},pr=()=>{let t=e.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(Q||Ys(o))||!0===o.launcher?.fullHeight&&!o.launcher.sidebarMode&&!Ys(o)},ur=()=>el(o,pr()),hr="empty",mr=0,gr=()=>mr||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,fr=()=>{let e="none"===Tt.style.display?0:Tt.offsetHeight;tr.style.bottom=`${e+gr()+12}px`};fr();let yr=()=>{oo||(Tt.style.marginBottom=mr>0?`${mr}px`:"")},br=()=>{let t=Ka(o,ae()),r=ur();e.setAttribute("data-persona-welcome-fullscreen",String(pr())),e.setAttribute("data-persona-welcome-layout",r.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom");let n="none"===Tt.style.display?0:Tt.offsetHeight,a="center"===r.anchor&&"empty"===hr?Ja(r.anchorComposerTop)??Ja("44%"):null,s=null!==a&&"centered"===r.layout&&void 0===o.welcome?.anchor&&void 0===o.welcome?.anchorComposerTop,i=s?getComputedStyle(lt):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=s?lt.getBoundingClientRect().top-it.getBoundingClientRect().top:0,u=!s||yt.hidden?0:(yt.querySelector("[data-persona-welcome-plugin]")??yt).offsetHeight,h=null===a||ae()?0:s?Math.max(0,Math.round((it.clientHeight-p-u-c-n)/2)):(e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight))({columnHeight:it.clientHeight,footerHeight:n,fraction:a});e.style.setProperty("--persona-composer-overlay-height",`${n}px`),e.style.setProperty("--persona-composer-lift",`${"overlay"===t?h:0}px`),mr="block"===t?h:0,yr(),fr()},vr=()=>{let e=!!_t();tr.setAttribute("aria-label",_t()||"Jump to latest"),tr.title=_t(),tr.setAttribute("data-persona-scroll-to-bottom-has-label",e?"true":"false"),rr.innerHTML="";let t=se(be.iconName??"arrow-down","14px","currentColor",2);t?(rr.appendChild(t),rr.style.display=""):rr.style.display="none",or.textContent=_t(),or.style.display=e?"":"none"};vr();let wr=null,xr=null,Cr=Wo();Cr.subscribe(e=>{try{it.dispatchEvent(new CustomEvent("persona:composer:state",{detail:e,bubbles:!0,composed:!0}))}catch{}});let kr=()=>{Cr.setText(ht?.value??"")},Mr=()=>{Cr.setMentionRefs(xr?.getMentionRefs()??[])},Ir=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}),Tr=e=>{let t=Object.freeze(e.map(Ir));Cr.setAttachments(t);try{o.attachments?.onChange?.(t)}catch(e){console.error("[AgentWidget] attachments.onChange failed:",e)}_l()};Cr.setSelectedModelId(o.composer?.selectedModelId);let Er=()=>o.composer?.modes??[],Lr=()=>function(e,t){return e?.length?e.filter(e=>!jn(e.groupId,t)&&!function(e,t){return!!e&&"hidden"===t?.find(t=>t.id===e)?.chipVisibility}(e.groupId,t)):[]}(Er(),o.composer?.modeGroups);{let e=_n(o.composer?.defaultActiveModeIds??[],Er());e.length&&Cr.setActiveModeIds(e)}function Nr(e){if(Cr.getState().selectedModelId!==e){Cr.setSelectedModelId(e),Hr?.repaint();try{o.composer?.onModelChange?.(e)}catch(e){console.error("[AgentWidget] composer.onModelChange failed:",e)}}}function Rr(e){Cr.setActiveModeIds(e),Dr?.render(e,Lr()),Or.forEach(e=>e.repaint()),yo?.resolve(),Sd(),Io()}function $r(e){Rr(function(e,t,r,o){let n=r.find(e=>e.id===t);if(!n)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)(n,o)){let e=r.filter(e=>e.groupId===n.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,Er(),o.composer?.modeGroups))}let Hr=null,Wr=null,Dr=null,Or=new Map,zr=null;function qr(e){Cr.setQuote(e),zr?.render(Cr.getState().quote),Io(),gi()}let jr=!1;function _r(){let e=o.composer?.streamingSubmitBehavior??"block";return"interrupt"===e?o.clientToken?"interrupt":(!jr&&!0===o.debug&&(jr=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block"):e}let Kr=null;function Jr(e){Cr.setPendingSubmission(e),Kr?.render(Cr.getState().pendingSubmission),Io()}let Gr=()=>{let e=[],t=Cr.getState().activeModeIds,r=new Set;if(Er().forEach((n,a)=>{if(jn(n.groupId,o.composer?.modeGroups)){let t=n.groupId;if(r.has(t))return;r.add(t);let s=(e=>{let t=Or.get(e);if(t)return t;let r=Un({groupId:e,getGroup:()=>o.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>Er().filter(t=>t.groupId===e),getActiveIds:()=>Cr.getState().activeModeIds,onSelect:e=>$r(e)});return Or.set(e,r),r})(t);s.action.order=zn(a),s.action.label=o.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(s.action)}else e.push({id:On(n.id),kind:"button",placement:"start",order:zn(a),presentation:n.presentation??"auto",label:n.label,shortLabel:n.shortLabel,iconName:n.iconName,pressed:t.includes(n.id),onSelect:()=>$r(n.id)})}),o.composer?.models?.length&&!p.some(e=>e.renderComposer)){let t=o.composer?.modelPicker?.presentation??"native";(!Hr||Wr!==t)&&(Wr=t,Hr=$n({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Cr.getState().selectedModelId,onSelect:e=>Nr(e),presentation:t,getSuffix:()=>o.composer?.modelPicker?.suffix})),e.push(Hr.action)}return e},Xr=null,Qr=p.find(e=>e.renderHeader);if(Qr?.renderHeader){let e=Qr.renderHeader({config:o,defaultRenderer:()=>{let e=fi({config:o,showClose:ie()});return yi(it,e,o),e.header},onClose:()=>Fl(!1,"user")});e&&It&&(It.replaceWith(e),It=e,tt.header.element=e)}let Yr=()=>{$e&&(lt.style.display="none",Tt.parentNode?.insertBefore($e.element,Tt),$e.update())},Zr=()=>{if(!Te)return void qe();if(We=!0,$e?Yr():Wl().then(e=>{!$e&&We&&Te&&($e=e.createEventStreamView({buffer:Te,getFullHistory:()=>Te.getAllFromStore(),onClose:()=>eo(),config:o,plugins:p,getThroughput:()=>Be?.getMetric()??{status:"idle"},renderIconByName:se}),Yr())}).catch(()=>{eo()}),to){to.style.boxShadow=`inset 0 0 0 1.5px ${hi.actionIconColor}`;let e=o.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&to.classList.add(e))}let e=()=>{if(!We)return;let t=Date.now();t-Fe>=200&&($e?.update(),Fe=t),De=requestAnimationFrame(e)};Fe=0,De=requestAnimationFrame(e),Ni(),R.emit("eventStream:opened",{timestamp:Date.now()})},eo=()=>{if(We){if(We=!1,$e&&$e.element.remove(),lt.style.display="",to){to.style.boxShadow="";let e=o.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&to.classList.remove(e))}null!==De&&(cancelAnimationFrame(De),De=null),Ni(),R.emit("eventStream:closed",{timestamp:Date.now()})}},to=null;if(ge){let e=o.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:"");to=q("button",t),to.style.width="28px",to.style.height="28px",to.style.color=hi.actionIconColor,to.type="button",to.setAttribute("aria-label","Event Stream"),to.title="Event Stream";let r=g(m.Activity,"18px","currentColor",1.5);r&&to.appendChild(r);let n=st.clearChatButtonWrapper,a=st.closeButtonWrapper,s=n||a;s&&s.parentNode===It?It.insertBefore(to,s):It.appendChild(to),to.addEventListener("click",()=>{We?eo():Zr()})}let ro=e=>{let t=o.attachments;if(!t?.enabled)return;let r=e.querySelector("[data-persona-composer-attachment-previews]")??e.querySelector(".persona-attachment-previews");if(!r){r=q("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=q("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Ar).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label",t.buttonTooltipText??"Attach files"),e.appendChild(r)}},oo=!1,ao=e=>{let t=p.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let r=o.composer,n=!!b&&wa.isStreaming();return t.renderComposer({config:o,defaultRenderer:e,requestRender:()=>pu(),storage:v(t.id),onSubmit:e=>{wa&&!wa.isStreaming()&&ep(e.trim(),{consumeDraft:!1})},streaming:n,disabled:n,openAttachmentPicker:()=>{zl()||Ot?.click()},models:r?.models,selectedModelId:Cr.getState().selectedModelId??r?.selectedModelId,onModelChange:e=>Nr(e),onVoiceToggle:!0===o.voiceRecognition?.enabled?()=>{Xr?.()}:void 0})},so=ao(()=>Ii({config:o}).footer);so&&(tt.replaceComposer(so),Tt=tt.composer.footer,oo=!0);let co=null;function po(){let e=ht;if(!e)return;let t=o.composer?.inputAttributes,r=t?.ariaLabel||e instanceof HTMLTextAreaElement?null:e.getAttribute("aria-label");nn(e,t),r&&e.setAttribute("aria-label",r),on(e,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:en(e)}),Zo(e,Yo(o.composer?.maxLines,ae()?5:3))}let uo=e=>{co=Oo(e,{debug:!0===o.debug}),co&&(e=>{gt=e.form,ht=e.input,Rt=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(mt=e.sendButton),e.micButton&&(Ht=e.micButton,Wt=e.micButton.parentElement),e.found.status&&(ft=e.found.status),e.found.suggestions&&(ut=e.found.suggestions),e.attachmentButton&&(Dt=e.attachmentButton,Ft=e.attachmentButton.parentElement),Ot=e.attachmentInput??null,zt=e.attachmentPreviews??null,e.found.actionsRow&&(Lt=e.found.actionsRow),Bt=e.found.actionsStart,Nt=e.found.actionsEnd})(co),po()};ro(Tt),uo(Tt),kr();let ho=Va(o,ae());ho&&(dt.style.maxWidth=ho,dt.style.marginLeft="auto",dt.style.marginRight="auto",dt.style.width="100%",vt.style.maxWidth=ho,vt.style.marginLeft="auto",vt.style.marginRight="auto",vt.style.width="100%",ct.style.maxWidth=ho,pt.style.maxWidth=ho,pt.style.marginLeft="auto",pt.style.marginRight="auto",pt.style.width="100%");let mo=()=>{let e=Va(o,ae());if(e&&!ae())for(let t of[gt,ut,zt,ft])t&&(t.style.maxWidth=e,t.style.marginLeft="auto",t.style.marginRight="auto",t.style.width="100%")};mo();let go=()=>{o.attachments?.enabled&&Ot&&zt&&(wr?wr.remountPreviews(zt):(wr=$o.fromConfig(o.attachments,Tr),wr.setPreviewsContainer(zt)),co?.addListener(Ot,"change",e=>{let t=e.target;wr?.handleFileSelect(t.files),t.value=""}),it.querySelector(".persona-attachment-drop-overlay")||it.appendChild(kc(o.attachments.dropOverlay)))};go();let fo=()=>{if(!o.contextMentions?.enabled||!ht)return;let e=Vr();if(!e){let e=ht;return void Ur().then(()=>{!xr&&ht===e&&e.isConnected&&(fo(),yo?.resolve())},()=>{})}let t=co?.header??null,r=t?Dn(t):void 0;if(xr=e.createContextMentionOrchestrator({deps:{loadContextMentions:ta,loadContextMentionsInline:aa,renderLucideIcon:se,createMentionButton:sa},config:o,textarea:ht,anchor:gt??ht,getMessages:()=>wa.getMessages(),liveRegionHost:it,chipRow:r}),xr&&!r){let e=ht;e.parentElement?.insertBefore(xr.contextRow,e)}};fo();let yo=null,wo={getState:()=>Cr.getState(),getValue:()=>ht?.value??"",setValue:e=>{ht&&(ht.value=e,ht.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})))}(co?.form??null)},openAttachmentPicker:()=>{zl()||Ot?.click()},toggleVoice:()=>{Xr?.()},requestRender:()=>yo?.resolve()},xo=()=>{let e=[];return(xr?.affordanceButtons??[]).forEach((t,r)=>{e.push({id:`core:mention-${r}`,placement:"start",order:100+r,element:t,managed:!0})}),Ft&&e.push({id:"core:attachment",placement:"start",order:200,element:Ft}),Wt&&e.push({id:"core:mic",placement:"end",order:800,element:Wt}),Rt&&e.push({id:"core:send",placement:"end",order:Cn,element:Rt}),e},Co=()=>{yo?.destroy(),yo=Bn({getBindings:()=>co,collect:()=>({builtIns:xo(),configActions:[...Gr(),...o.composer?.actions??[]],plugins:p,contributionContext:{config:o,getState:()=>Cr.getState(),requestRender:()=>yo?.resolve()},debug:!0===o.debug}),actionContext:wo,getState:()=>Cr.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(e,t)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),yo.resolve()};Co();let So=()=>{if(Dr?.destroy(),Dr=null,!Lr().length)return;let e=co?.header;e&&(Dr=Fn({row:Dn(e),onRemove:e=>$r(e),initialIds:Cr.getState().activeModeIds}),Dr.render(Cr.getState().activeModeIds,Lr()))};So();let ko=()=>{zr?.destroy(),zr=null,Kr?.destroy(),Kr=null;let e=co?.header;e&&(zr=Vn({onDismiss:()=>qr(void 0)}),e.appendChild(zr.element),zr.render(Cr.getState().quote),"defer-one"===_r()&&(Kr=Kn({onEdit:()=>function(){let e=Cr.getState().pendingSubmission;e&&(Jr(void 0),ht&&(ht.value=e.text,ht.dispatchEvent(new Event("input",{bubbles:!0})),kr()),e.options.selectedModelId&&(Cr.setSelectedModelId(e.options.selectedModelId),Hr?.repaint()),e.options.activeModeIds?.length&&Rr(e.options.activeModeIds),e.options.quote&&qr(e.options.quote),ht?.focus())}(),onRemove:()=>Jr(void 0)}),e.appendChild(Kr.element),Kr.render(Cr.getState().pendingSubmission)))};ko();let Ao=function(){let e=!1;return{observe:(t,r)=>r?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}(),Mo=()=>{let e=co?.header?.querySelector(Hn);if(e)return e.childElementCount>0;let t=Cr.getState();return t.mentionRefs.length>0||_n(t.activeModeIds,Lr()).length>0};function Io(){let e=Cr.getState(),t=Ao.observe(function(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let r=t.getComputedStyle(e),o=Number.parseFloat(r.lineHeight),n=Number.parseFloat(r.fontSize),a=Number.isFinite(o)&&o>0?o:Number.isFinite(n)&&n>0?1.4*n:0;if(!a)return!1;let s=(Number.parseFloat(r.paddingTop)||0)+(Number.parseFloat(r.paddingBottom)||0);return e.scrollHeight-s>1.5*a}(ht),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:Mo(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission}))}function To(){"single-row"!==o.composer?.layout||ae()?Tt.removeAttribute("data-persona-composer-layout"):Tt.setAttribute("data-persona-composer-layout","single-row")}To(),Cr.subscribe(()=>{yo?.sync(),_l(),Ul(),Io(),gi()}),Ul();let Eo=!1;(()=>{let e=o.layout?.slots??{};(e=>{if(Eo||!0!==o.debug)return;let t=["messages","composer"].filter(t=>e[t]);t.length&&(Eo=!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 lt.querySelector("[data-persona-intro-card]");case"messages":return dt;case"footer-top":return ut;case"composer":return gt;case"footer-bottom":return ft;default:return null}},r=(e,t)=>{switch(e){case"header-left":case"header-center":case"header-right":if("header-left"===e)It.insertBefore(t,It.firstChild);else if("header-right"===e)It.appendChild(t);else{let e=It.querySelector(".persona-flex-col");e?e.parentNode?.insertBefore(t,e.nextSibling):It.appendChild(t)}break;case"body-top":{let e=lt.querySelector("[data-persona-intro-card]");e?e.replaceWith(t):lt.insertBefore(t,lt.firstChild);break}case"body-bottom":lt.appendChild(t);break;case"footer-top":ut.replaceWith(t);break;case"footer-bottom":ft.replaceWith(t)}};for(let[n,a]of Object.entries(e))if(a)try{let e=a({config:o,defaultContent:()=>t(n)});e&&r(n,e)}catch(e){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${n}":`,e)}})(),dt.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(),xl(r))});let Lo=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 a=r.getAttribute("data-message-id");if(!a)return;Ts(),Ri();let d=t.getAttribute("data-bubble-type");if(r.classList.contains("persona-activity-row")){i.manual(a);let e=r.parentElement?.closest("[data-persona-tool-group]");e?.dataset.messageId&&i.manual(e.dataset.messageId)}if("reasoning"===d)s.has(a)?s.delete(a):s.add(a),fl(a,r,s);else if("tool"===d)n.has(a)?n.delete(a):n.add(a),Al(a,r,n,o);else if("approval"===d&&w){let e="expanded"===((!1===o.approval?void 0:o.approval)?.detailsDisplay??"collapsed"),t=l.get(a)??e;l.set(a,!t),w.updateApprovalDetailsUI(a,r,o,l)}Ha.delete(a)};dt.addEventListener("pointerdown",e=>{e.target.closest('button[data-expand-header="true"]')&&(e.preventDefault(),Lo(e))}),dt.addEventListener("click",e=>{0===e.detail&&e.target.closest(".persona-activity-row")&&Lo(e)}),dt.addEventListener("keydown",e=>{let t=e.target;("Enter"===e.key||" "===e.key)&&t.closest('button[data-expand-header="true"]')&&(e.preventDefault(),Lo(e))}),dt.addEventListener("copy",e=>{let{clipboardData:t}=e;if(!t)return;let r=dt.getRootNode(),o="function"==typeof r.getSelection?r.getSelection():window.getSelection();if(!o||o.isCollapsed)return;let n=o.toString(),a=(e=>e.replace(/^\n+/,"").replace(/\s+$/,""))(n);a&&a!==n&&(t.setData("text/plain",a),e.preventDefault())});let Bo=new Map,No=null,Ro="idle",Ho={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading…"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Do=()=>{dt.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:o}=Ho[t];e.setAttribute("aria-label",o),e.title=o,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 n=se(r,14,"currentColor",2);n&&(e.innerHTML="",e.appendChild(n))})(e,t&&t===No?Ro:"idle")})};dt.addEventListener("click",e=>{let t=e.target.closest(".persona-message-action-btn[data-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.closest("[data-actions-for]");if(!r)return;let n=r.getAttribute("data-actions-for");if(!n)return;let a=t.getAttribute("data-action");if("copy"===a){let e=wa.getMessages().find(e=>e.id===n);if(e&&Xe){let r=e.content||"";navigator.clipboard.writeText(r).then(()=>{t.classList.add("persona-message-action-success");let e=g(m.Check,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e)),setTimeout(()=>{t.classList.remove("persona-message-action-success");let e=g(m.Copy,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e))},2e3)}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",e)}),Xe(e)}}else if("read-aloud"===a)wa.toggleReadAloud(n);else if("upvote"===a||"downvote"===a){let e="upvote"===a?"thumbs-up":"thumbs-down";if((Bo.get(n)??null)===a){Bo.delete(n),t.classList.remove("persona-message-action-active");let r=se(e,14,"currentColor",2);r&&(t.innerHTML="",t.appendChild(r))}else{let o="upvote"===a?"downvote":"upvote",s=r.querySelector(`[data-action="${o}"]`);if(s){s.classList.remove("persona-message-action-active");let e=se("upvote"===o?"thumbs-up":"thumbs-down",14,"currentColor",2);e&&(s.innerHTML="",s.appendChild(e))}Bo.set(n,a),t.classList.add("persona-message-action-active");let i=se(e,14,"currentColor",2);i&&(i.setAttribute("fill","currentColor"),t.innerHTML="",t.appendChild(i)),t.classList.remove("persona-message-action-pop"),t.offsetWidth,t.classList.add("persona-message-action-pop");let l=wa.getMessages().find(e=>e.id===n);l&&Qe&&Qe({type:a,messageId:l.id,message:l})}}else if("regenerate"===a)Fo?.regenerate(n);else if("edit"===a)Fo?.edit(n);else if("quote"===a)Fo?.quote(n);else if(a?.startsWith("custom:")){let e=a.slice(7),r=o.messageActions?.custom?.find(t=>t.id===e),s=wa.getMessages().find(e=>e.id===n);if(!r||!s)return;try{r.onSelect(s)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let Fo=null;dt.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 o=r.getAttribute("data-message-id");if(!o)return;let n=t.getAttribute("data-approval-action");if(!n)return;let a="approve"===n?"approved":"denied",s=wa.getMessages().find(e=>e.id===o);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"}),u(s.approval)?wa.resolveWebMcpApproval(o,a):wa.resolveApproval(s.approval,a)});let zo=null,qo=!1,jo=null,_o=()=>{},Vo="none",Ko=null,Jo={artifacts:[],selectedId:null},Go=!1,Qo=!1,tn=!1,dn=!1,cn=()=>dn||Jo.artifacts.some(e=>"panel"===no(o.features?.artifacts,e)),un=()=>Jo.artifacts.length>0&&!Go&&cn(),mn={current:null},gn=(e,t)=>{let r=wa.getArtifactById(t),o=r?.markdown,n=r?.title||"artifact",a=r?.file,s=r?.artifactType??"markdown";if(!o){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);o=t?.props?.markdown,n=t?.props?.title||n,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:o,title:n,file:a,artifactType:s}};dt.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===o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:r}))return;let{markdown:n,title:a,file:s}=gn(t,r);if(!n)return;let i=Gl();i&&i.triggerArtifactDownload(i.downloadInfoFor({title:a,markdown:n,file:s}))}),dt.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]"),a=n?null:t.closest("[data-open-artifact]"),s=n?n.getAttribute("data-artifact-inline"):a?.getAttribute("data-open-artifact")??null,i=(n?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(e=>e.id===r);if(!i)return;let{markdown:l,title:d,file:c,artifactType:p}=gn(t,s??""),u={artifactId:s,title:d,artifactType:p,markdown:l,file:c};try{Promise.resolve(i.onClick(u)).catch(()=>{})}catch{}}),dt.addEventListener("click",e=>{let t=e.target.closest("[data-copy-artifact]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-copy-artifact");if(!r)return;let o=wa.getArtifactById(r),n=Gl();if(!n)return;let a="";if(o)a=n.artifactCopyText(o);else{let{markdown:e,file:o,artifactType:s}=gn(t,r);"markdown"===s&&(a=n.artifactCopyText({id:r,artifactType:"markdown",status:"complete",markdown:e??"",...o?{file:o}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=g(m.Check,16,"currentColor",2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=g(m.Copy,16,"currentColor",2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),dt.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!==o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:r})&&(Go=!1,dn=!0,Qo=!0,tn=!0,wa.selectArtifact(r),Yn())}),dt.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!==o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:n})&&(e.preventDefault(),e.stopPropagation(),Go=!1,dn=!0,wa.selectArtifact(n),Yn())}),dt.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 fn=st.composerOverlay,yn=e=>{Ur().catch(()=>{}),qt(e,o,fn)},bn=null,vn={mount:e,overlay:fn,sessionRef:mn,config:()=>o},wn=!1,xn=e=>t=>{let r=t.target,o=r?.closest?.("[data-persona-ask-sheet-for]");if(!o||!("click"===e?r?.closest("[data-ask-user-action]"):"Enter"===t.key&&r?.matches?.('[data-ask-free-text-input="true"]')))return;let n=r=>{bn??=r.createAskUserSheetHandlers(vn),bn[e](t)},a=Vr();a?n(a):wn||(wn=!0,Ur().then(e=>{wn=!1,o.isConnected&&n(e)},()=>{wn=!1}))};fn.addEventListener("click",xn("click")),fn.addEventListener("keydown",xn("keydown"));let Sn=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=fn.querySelector("[data-persona-ask-sheet-for]");if(!r||"rows"!==r.getAttribute("data-ask-layout")||"true"===r.getAttribute("data-multi-select"))return;let o=Number(e.key),n=r.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[o-1];n&&(e.preventDefault(),n.click())};document.addEventListener("keydown",Sn);let kn=null,An=null,Mn=null,In=null,Tn=()=>{},En=!1,Ln="",Pn="";function Nn(){In?.(),In=null}let Rn=()=>{if(!kn||!An)return;let t=e.classList.contains("persona-artifact-welded-split"),r=e.ownerDocument.defaultView??window,o=r.innerWidth<=640;if(!t||e.classList.contains("persona-artifact-narrow-host")||o)return An.style.removeProperty("position"),An.style.removeProperty("left"),An.style.removeProperty("top"),An.style.removeProperty("bottom"),An.style.removeProperty("width"),void An.style.removeProperty("z-index");let n=kn.firstElementChild;if(!n||n===An)return;An.style.position="absolute",An.style.top="0",An.style.bottom="0",An.style.width="10px",An.style.zIndex="5";let a=Ad(kn,r),s=n.offsetWidth+a/2-5;An.style.left=`${Math.max(0,s)}px`},Wn=()=>{},qn=()=>{let t=e.ownerDocument.defaultView??window,r=o.launcher?.mobileFullscreen??!0,n=o.launcher?.mobileBreakpoint??640;return!(!r||t.innerWidth>n)&&(Q||Ys(o))},Xn=()=>!Ql(o)||!un()||e.classList.contains("persona-artifact-narrow-host")||qn()||(e.ownerDocument.defaultView??window).innerWidth<641?"none":td(o)?"detached":"welded",Yn=()=>{if(!zo||!Ql(o))return;rd(e,o),od(e,o),Wn();let t=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,r=ot.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",r>0&&r<=t);let n=un();zo.setVisible(n),zo.update(Jo),Go?(zo.setMobileOpen(!1),zo.element.classList.add("persona-hidden"),zo.backdrop?.classList.add("persona-hidden"),Qo=!1,tn=!1):Jo.artifacts.length>0&&cn()?(zo.element.classList.remove("persona-hidden"),zo.setMobileOpen(!0)):(zo.setMobileOpen(!1),zo.element.classList.add("persona-hidden"),zo.backdrop?.classList.add("persona-hidden"),Qo=!1,tn=!1);let a=!0===o.features?.artifacts?.layout?.showExpandToggle;if(zo.setExpandToggleVisible(a),zo.setCopyButtonVisible(!0===o.features?.artifacts?.layout?.showCopyButton),zo.setRefreshButtonVisible("function"==typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh),zo.setCustomActions(o.features?.artifacts?.toolbarActions??[]),zo.setTabFade(o.features?.artifacts?.layout?.tabFade),zo.setRenderTabBar(o.features?.artifacts?.renderTabBar),!a&&!tn&&(Qo=!1),Qo!==En){let e=zo.element;Qo?(Ln=e.style.width,Pn=e.style.maxWidth,e.style.removeProperty("width"),e.style.removeProperty("max-width")):(Ln&&(e.style.width=Ln),Pn&&(e.style.maxWidth=Pn),Ln="",Pn=""),En=Qo}e.classList.toggle("persona-artifact-expanded",Qo),zo.setExpanded(Qo);let s=Xn();s!==Vo&&(Vo=s,_o()),Tn()};if(Ql(o)){ot.style.position="relative";let t=q("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),r=q("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");t.appendChild(it),kn=r,r.appendChild(t),ot.appendChild(r);let n=e=>{qo||zo||(zo=e.createArtifactPane(o,{onSelect:e=>mn.current?.selectArtifact(e),onDismiss:()=>{Go=!0,Yn()},onToggleExpand:()=>{let e=!Qo,t=Jo.selectedId??Jo.artifacts[Jo.artifacts.length-1]?.id??null;!0!==o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:t,expanded:e})&&(Qo=e,e||(tn=!1),Yn())}}),zo.element.classList.add("persona-hidden"),r.appendChild(zo.element),zo.backdrop&&ot.appendChild(zo.backdrop),Tn(),Yn())},a=Gl();a?n(a):(Xl(()=>{let e=Gl();e&&n(e)}),Jl().catch(()=>{})),Tn=()=>{if(kn&&zo)if(!0!==o.features?.artifacts?.layout?.resizable)Mn?.(),Mn=null,Nn(),An&&=(An.remove(),null),zo.element.style.removeProperty("width"),zo.element.style.removeProperty("maxWidth");else{if(!An){let t=q("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");t.setAttribute("role","separator"),t.setAttribute("aria-orientation","vertical"),t.setAttribute("aria-label","Resize artifacts panel"),t.tabIndex=0;let r=e.ownerDocument,n=r.defaultView??window,a=a=>{if(!zo||0!==a.button||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||n.innerWidth<=640)return;a.preventDefault(),Nn();let s=a.clientX,i=zo.element.getBoundingClientRect().width,l=o.features?.artifacts?.layout,d=r=>{let o=kn.getBoundingClientRect().width,a=e.classList.contains("persona-artifact-welded-split"),d=Ad(kn,n),c=a?0:t.getBoundingClientRect().width||6,p=function(e,t,r,o,n,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}(n),l=function(e,t,r,o){let n=e-o-2*t-r;return Math.max(0,n)}(t,r,o,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-s),o,d,c,l?.resizableMinWidth,l?.resizableMaxWidth,(()=>{let e=oc?.railShell?oc.railHost:null,t=e?.isConnected?e:null,r=t?t.getBoundingClientRect().width:0;return r<=0?200:r+360})());zo.element.style.width=`${p}px`,zo.element.style.maxWidth="none",Rn()},c=()=>{r.removeEventListener("pointermove",d),r.removeEventListener("pointerup",c),r.removeEventListener("pointercancel",c),In=null;try{t.releasePointerCapture(a.pointerId)}catch{}};In=c,r.addEventListener("pointermove",d),r.addEventListener("pointerup",c),r.addEventListener("pointercancel",c);try{t.setPointerCapture(a.pointerId)}catch{}};t.addEventListener("pointerdown",a),An=t,kn.insertBefore(t,zo.element),Mn=()=>{t.removeEventListener("pointerdown",a)}}if(An){let e=un();An.classList.toggle("persona-hidden",!e),Rn()}}},Wn=()=>{if(!Q||!zo||o.launcher?.sidebarMode||Ys(o)&&"emerge"===ei(o).reveal)return;let t=e.ownerDocument.defaultView??window,r=o.launcher?.mobileFullscreen??!0,n=o.launcher?.mobileBreakpoint??640;if(r&&t.innerWidth<=n||!function(e,t){return!(!t||!Ql(e))&&!1!==e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen}(o,Q))return;let a=ol(o).width,s=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";un()?(ot.style.width=s,ot.style.maxWidth=s):(ot.style.width=a,ot.style.maxWidth=a)},typeof ResizeObserver<"u"&&(jo=new ResizeObserver(()=>{Yn()}),jo.observe(ot))}else ot.appendChild(it);ae()&&nt&&(st.peekBanner&&nt.appendChild(st.peekBanner),nt.appendChild(Tt)),e.appendChild(rt),nt&&e.appendChild(nt);let Zn=()=>{let t=qn()||ae()&&"fullscreen"===o.launcher?.composerBar?.expandedSize||!0===o.launcher?.fullHeight&&!o.launcher?.sidebarMode&&!Ys(o);if(dt.style.gap=t?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",dt.style.setProperty("--persona-transcript-gap",dt.style.gap),ae()){ot.style.width="100%",ot.style.maxWidth="100%";let e=o.launcher?.composerBar??{},t="expanded"===rt.dataset.state,r=e.expandedSize??"anchored";if(!t||"fullscreen"===r)return it.style.background="",it.style.border="",it.style.borderRadius="",it.style.overflow="",void(it.style.boxShadow="");let n=o.theme?.components?.panel,a=ja(o),s=(e,t)=>null==e||""===e?t:Aa(a,e)??e;return it.style.background="var(--persona-surface, #ffffff)",it.style.border=s(n?.border,"1px solid var(--persona-border)"),it.style.borderRadius=s(n?.borderRadius,"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))"),it.style.boxShadow=s(n?.shadow,"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))"),void(it.style.overflow="hidden")}let r=Ys(o),n=o.launcher?.sidebarMode??!1,a=r||n||(o.launcher?.fullHeight??!1),s=!1===o.launcher?.enabled,i=!0===o.launcher?.detachedPanel,l=o.theme?.components?.panel,d=o.darkTheme?.components?.panel,c="dark"===qa(o)?y(l??{},d??{}):l,p=ja(o),u=(e,t)=>null==e||""===e?t:Aa(p,e)??e,h=e.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,g=o.launcher?.mobileBreakpoint??640,f=h.innerWidth<=g,b=m&&f&&Q,v=r&&m&&f,w=o.launcher?.position??"bottom-left",x="bottom-left"===w||"top-left"===w,C=o.launcher?.zIndex??1e5,S=(e,t,r)=>`var(--persona-components-panel-modes-${e}-${t}, ${r})`,k=c?.modes?.floating,A=u(k?.border??c?.border,S("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),M=u(k?.shadow??c?.shadow,S("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),I=u(k?.borderRadius??c?.borderRadius,S("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),E=i&&!b&&!v,L=b||v?"mobile":E?"floating":r?"docked":n?"sidebar":s?"inline":"floating",P=c?.modes?.[L];E?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let B=E?A:n||b?"none":A,N=E?M:b?"none":n?x?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":s?"none":M;r&&!b&&!E&&(N="none",B="none");let R=E?I:n||b?"0":I,$=u(P?.border??c?.border,S(L,"border",B)),H=u(P?.shadow??c?.shadow,S(L,"shadow",N)),W=u(P?.borderRadius??c?.borderRadius,S(L,"borderRadius",R)),D=Xn(),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"===o.features?.artifacts?.layout?.chatSurface?"flush":"card")&&Ql(o)&&td(o)&&s&&!r;e.classList.toggle("persona-artifact-chat-flush",q);let j=F||q?"none":H,_=F?A:O?"none":$,U=F?I:W;q&&(_="none",U="0");let V=null!=P?.borderRadius&&""!==P.borderRadius||null!=c?.borderRadius&&""!==c.borderRadius,K=q&&!V?"0":W,J=lt.scrollTop;e.style.cssText="",rt.style.cssText="",ot.style.cssText="",it.style.cssText="",lt.style.cssText="",oo||(Tt.style.cssText=""),We&&(lt.style.display="none"),(a||s)&&(e.style.minWidth="0");let G=()=>{J<=0||(lt.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(lt.scrollTop===J)return;let e=lt.scrollHeight-lt.clientHeight;e<=0||(lt.scrollTop=Math.min(J,e))})};if(b)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: ${C} !important;\n background-color: var(--persona-surface, #ffffff) !important;\n `,ot.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 ",it.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 ",lt.style.flex="1 1 0%",lt.style.minHeight="0",lt.style.overflowY="auto",Tt.style.flexShrink="0",yr(),ne=!0,void G();let X=ol(o);if(n||r){if(r)if("emerge"!==ei(o).reveal||i)ot.style.width="100%",ot.style.maxWidth="100%";else{let e=ei(o).width;ot.style.width=e,ot.style.maxWidth=e}}else s&&a?(ot.style.width="100%",ot.style.maxWidth="100%"):(ot.style.width=X.width,ot.style.maxWidth=X.maxWidth);if(Wn(),ot.style.boxShadow=j,ot.style.borderRadius=K,F?ot.style.border="none":O&&(ot.style.border=$),it.style.border=_,it.style.borderRadius=U,it.style.boxShadow=F&&!q?z:"",q&&(it.style.background="transparent",lt.style.background="transparent",Tt.style.background="transparent",Tt.style.borderTop="none"),O){let e=o.features?.artifacts?.layout;Ko=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||W}else Ko=null;let Y=null!=P?.border||null!=c?.border;if(r&&!b&&!E&&!F&&!O&&!Y&&(it.style.border="none","right"===ei(o).side?it.style.borderLeft="1px solid var(--persona-border)":it.style.borderRight="1px solid var(--persona-border)"),r&&!b&&O&&!Y&&("right"===ei(o).side?ot.style.borderLeft="1px solid var(--persona-border)":ot.style.borderRight="1px solid var(--persona-border)"),a&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",s&&(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%",s&&(rt.style.overflow="hidden"),ot.style.display="flex",ot.style.flexDirection="column",ot.style.flex="1 1 0%",ot.style.minHeight="0",ot.style.maxHeight="100%",ot.style.height="100%",F||(ot.style.overflow="hidden"),it.style.display="flex",it.style.flexDirection="column",it.style.flex="1 1 0%",it.style.minHeight="0",it.style.maxHeight="100%",it.style.overflow="hidden",lt.style.flex="1 1 0%",lt.style.minHeight="0",lt.style.overflowY="auto",Tt.style.flexShrink="0"),s&&(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&&!s&&!r&&(si[w]??si["bottom-right"]).split(" ").forEach(e=>rt.classList.add(e)),n){let e=T(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":Aa(ja(o),"components.panel.width")??"420px";rt.style.cssText=i?`\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: ${C} !important;\n ${x?"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: ${C} !important;\n ${x?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}\n `,ot.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: ${K} !important;\n ${F?"border: none !important;":O?`border: ${$} !important;`:""}\n `,ot.style.setProperty("width","100%","important"),ot.style.setProperty("max-width","100%","important"),it.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 `,oo||(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(!s&&!r){let e=n?"":"padding-top: 1.25em !important;",t=n?"":`z-index: ${o.launcher?.zIndex??1e5} !important;`;rt.style.cssText+="max-height: -moz-available !important; max-height: stretch !important;"+e+t}yr(),G()},ea=()=>{e.style.setProperty("--persona-content-max-width",Va(o,ae()))},ra=!1;function oa(){o.layout?.topFade&<.scrollTop>1?lt.setAttribute("data-persona-top-fade","true"):lt.removeAttribute("data-persona-top-fade")}let na=()=>{oa();let t=Ka(o,ae());ae()&&o.composer?.placement&&!0===o.debug&&!ra&&(ra=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let r=ur();e.setAttribute("data-persona-composer-placement",t),e.setAttribute("data-persona-conversation-state",hr),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",r.composerGap??"24px"),br()},ia=()=>{if(ae())return;let t=Ys(o),r=o.launcher?.sidebarMode??!1;if(t||r||o.launcher?.fullHeight||!Q)return;let n=e.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,s=o.launcher?.mobileBreakpoint??640;if(a&&n.innerWidth<=s)return;let i=ol(o);ot.style.height=i.height,ot.style.maxHeight=i.maxHeight};Zn(),_a(e,o),rd(e,o),od(e,o),ea(),na(),_o=()=>{Zn(),ia(),_a(e,o),rd(e,o),od(e,o),ea(),na(),Ko?e.style.setProperty("--persona-artifact-welded-outer-radius",Ko):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Ve(),Ue()};let la=[];la.push(()=>{qo=!0}),la.push(()=>{f.forEach(e=>e()),h.destroy()}),la.push(()=>{document.removeEventListener("keydown",Sn)}),la.push(()=>{null!==lr&&clearTimeout(lr)});let da=null,ca=null;la.push(()=>{da?.(),da=null,ca?.(),ca=null}),jo&&la.push(()=>{jo?.disconnect(),jo=null}),la.push(()=>{Mn?.(),Mn=null,Nn(),An&&=(An.remove(),null),zo?.element.style.removeProperty("width"),zo?.element.style.removeProperty("maxWidth"),zo?.destroy()}),ge&&la.push(()=>{Re=!0,Ne=null,null!==De&&(cancelAnimationFrame(De),De=null),$e?.destroy(),$e=null,Te?.destroy(),Te=null,Me=null});let pa=null,ua=()=>{pa&&=(pa(),null),"auto"===o.colorScheme&&(pa=Ua(()=>{_a(e,o)}))};ua(),la.push(()=>{pa&&=(pa(),null)}),la.push(()=>{S=!0,C?.()}),la.push(()=>{I=!0});let ha=!1;la.push(()=>{ha=!0});let ma=(t,r)=>{let o=ks(t,r);return o||!Cs.includes(t)?o:(qs().then(o=>{if(ha)return;Ss(o.wipe),Ss(o.glyphCycle);let n=ks(t,r);n&&Ds(n,e)}).catch(()=>{}),null)},ga=o.features?.streamAnimation;if(ga?.type&&"none"!==ga.type){let t=ma(ga.type,ga.plugins);t&&Ds(t,e),la.push(()=>Ws(e))}let fa=ai(ut),ya=ai(ct),ba=ai(pt),va=[fa,ya,ba];la.push(()=>{va.forEach(e=>e.destroy())});let wa,xa=null,Ca=null,Sa=!1,ka=0,Ma=null,Ia=e=>e.reduce((e,t)=>"user"===t.role?e+1:e,0),Ta=e=>{for(let t=e.length-1;t>=0;t--)if(Kt(e[t]))return e[t].id??null;return null},Ea=!1,La=!1,Pa=!1,Ba=(e,t)=>{La||!0!==o.debug||t.enabled&&!t.expose&&(Sa||Pa&&(wa.isStreaming()||e.some(Kt)||(La=!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."))))},Na=e=>{if(!wa)return;let t=e??wa.getMessages(),r=e=>{e.render([],wa,ht,t)},n=e=>{va.forEach(t=>{t!==e&&r(t)})};Ca&&(Ia(t)>ka||Ta(t)!==Ma)&&(Ca=null);let a=Qt(o);Ba(t,a);let s=a.enabled?Gt(t):null,i=Ca??s,l=Ca?"host":"agent";if(i){let e=o.suggestions?.followUps,r=e?.placement??(e?"auto":"composer"),a="after-message"===("auto"===r?ae()?"composer":"after-message":r)?ba:fa;return n(a),void a.render(i,wa,ht,t,o.suggestionChipsConfig,{source:l,surface:"followUp",variant:e?.variant??"chip",behavior:e?.behavior??"send",overflow:e?.overflow??"wrap",maxItems:e?.maxItems??4,config:o,plugins:p,submitPrompt:Zc})}if(t.some(e=>"user"===e.role))return void va.forEach(r);let d=!0===o.future?.v5Defaults,c=pr(),u=o.suggestions?.starters??(d?{}:void 0);if(u){let e=tl(ur(),t),a=u.placement??"auto",s="auto"===a?e?"welcome":"composer":a;if("welcome"===s&&!e)return Ea||!0!==o.debug||(Ea=!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"===s?ya:fa;n(i),i.render(u.items??o.suggestionChips,wa,ht,t,o.suggestionChipsConfig,{surface:"starter",variant:u.variant??(d&&!c?"chip":"card"),behavior:u.behavior??"send",overflow:u.overflow??"wrap",maxItems:u.maxItems??(d&&!c?3:4),config:o,plugins:p,submitPrompt:Zc})}else n(fa),fa.render(o.suggestionChips,wa,ht,t,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:p,submitPrompt:Zc})},Ra=()=>{Ca&&(Ca=null,Na())},$a=!1,Ha=new Map,Wa=new Set,Da=new Map,Fa=new Map,Oa=new Map,za=new Map,Ga=null,Xa=null;function Qa(){if(!Ga)return;let e=Ga;Ga=null,Xa?.destroy(),Xa=null,Ha.delete(e),it.querySelector(`#wrapper-${e}`)?.removeAttribute("data-preserve-runtime"),wa&&wl(dt,wa.getMessages(),ue)}let Ya=0,Za=null!==Pe(),es=function(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>!!t&&(t=!1,!0),resume:()=>!t&&(t=!0,!0)}}(),ts=0,rs=null,ns=!1,is=!1,hs=0,ms=null,gs=null,fs=!1,ys=!1,bs=null,ws=!0,xs=!1,Ms=null,Is=!1,Ts=()=>{Is=!0,$s()},Es=null,Ls=null,Ps=()=>{e.setAttribute("data-persona-scrollbar",er()),"on-scroll"!==er()&&(null!==Ls&&clearTimeout(Ls),Ls=null,lt.removeAttribute("data-persona-scrollbar-visible"))},$s=()=>{"on-scroll"===er()&&(lt.setAttribute("data-persona-scrollbar-visible",""),null!==Ls&&clearTimeout(Ls),Ls=setTimeout(()=>{Ls=null,ps(lt,24)&<.removeAttribute("data-persona-scrollbar-visible")},1e3))};Ps(),la.push(()=>{null!==Ls&&clearTimeout(Ls)});let Hs=new Map,Fs=!1,Os=null,zs={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Io();let _s=o.voiceRecognition?.autoResume??!1,Us=()=>wa.isVoiceActive()||wa.isBargeInActive(),Ks=!1,Js=e=>{R.emit("voice:state",{active:zs.active,source:e,timestamp:Date.now()})},Gs=()=>{K(e=>({...e,voiceState:{active:zs.active,timestamp:Date.now(),manuallyDeactivated:zs.manuallyDeactivated}}))},Xs=e=>{Ks=!e.persisted,zs.active&&Gs()};typeof window<"u"&&(window.addEventListener("pagehide",Xs),la.push(()=>window.removeEventListener("pagehide",Xs)));let Qs=()=>wa?Cc(wa.getMessages()).filter(e=>!e.__skipPersist):[],ti=null,oi=(e,t)=>{typeof console<"u"&&console.error(e,t)},ii=(e,t)=>{let r=()=>{try{let r=e();return r&&"function"==typeof r.then?Promise.resolve(r).catch(e=>{oi(t,e)}):null}catch(e){return oi(t,e),null}},o=ti?ti.then(()=>r()??void 0):r();if(!o)return;let n=o.finally(()=>{ti===n&&(ti=null)});ti=n};function li(e){if(!$?.save)return;let t=e?Cc(e):wa?Qs():[],r=H&&wa?.getResumableHandle();r&&(W={...W,durableResume:{executionId:r.executionId,after:r.lastEventId}});let o={messages:t,metadata:W,artifacts:Jo.artifacts,selectedArtifactId:Jo.selectedId,...pi?{draft:pi}:{}};ii(()=>$.save(o),"[AgentWidget] Failed to persist state:")}let pi,ui=()=>!(!$?.save||!1===o.persistState||"object"==typeof o.persistState&&!1===o.persistState.persist?.draft),mi=function(e){let t=e.delay??500,r=null,o=!1,n=()=>{null!==r&&(clearTimeout(r),r=null)};return{schedule:()=>{o||(n(),r=setTimeout(()=>{r=null,e.write()},t))},flush:()=>{o||null===r||(n(),e.write())},cancel:n,destroy:()=>{o=!0,n()}}}({write:()=>{if(!ui())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:_c(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(pi)&&(pi=t,li())}});function gi(){ui()&&mi.schedule()}function bi(){mi.flush()}function vi(e){if(!ui())return;let t=function(e,t){if(!e||"string"!=typeof e.text)return;let r=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(e=>r.has(e.sourceId)),n=o.length===(e.mentionRefs?.length??0)&&o.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,...n?{mentionRefs:o}:{},...n&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...i?{selectedModelId:i}:{},...s.length?{activeModeIds:s}:{},...e.quote?.text?{quote:e.quote}:{}}}(e,{mentionSourceIds:(o.contextMentions?.sources??[]).map(e=>e.id),modelIds:(o.composer?.models??[]).map(e=>e.id),modes:o.composer?.modes??[]});t&&(pi=e,ht&&!ht.value&&(ht.value=t.text,ht.dispatchEvent(new Event("input",{bubbles:!0})),kr()),t.selectedModelId&&(Cr.setSelectedModelId(t.selectedModelId),Hr?.repaint()),Rr(t.activeModeIds??[]),t.quote&&qr(t.quote),mi.cancel())}function wi(){mi.cancel(),pi&&(pi=void 0,ui()&&li())}let xi=null,Ci=()=>rt.querySelector("#persona-scroll-container")||lt,Si=()=>{null!==xi&&(cancelAnimationFrame(xi),xi=null),ns=!1},ki=()=>{null!==rs&&(cancelAnimationFrame(rs),rs=null),is=!1,Si()},Ai=()=>{let e=_t()||"Jump to latest",t=$a&&Li()&&("anchor-top"!==Ut()||Yt());tr.toggleAttribute("data-persona-scroll-to-bottom-streaming",t),hs>0?(nr.textContent=String(hs),nr.style.display="",tr.setAttribute("aria-label",`${e} (${hs} new)`)):(nr.textContent="",nr.style.display="none",tr.setAttribute("aria-label",t?`${e} (response streaming below)`:e))},Ti=()=>{0!==hs&&(hs=0,Ai())},Li=()=>Vt()?!es.isFollowing():!(()=>{let e=ms?.spacerHeight??0;return e<=0?ps(lt,24):Zi(e)-lt.scrollTop-lt.clientHeight<=24})(),Pi=()=>!!wa&&wa.getMessages().length>0,Ni=()=>{if(!1===be.enabled||We||je&&"panel"===_e)return tr.parentNode&&tr.remove(),void(tr.style.display="none");tr.parentNode!==it&&it.appendChild(tr),fr();let e=cs(lt)>0&&Li()&&Pi();e?Ai():Ti(),tr.style.display=e?"":"none"},Ri=()=>{es.pause()&&(ki(),Ni())},Hi=()=>{es.resume(),Ti(),Ni()},Wi=(e=!1)=>{Vt()&&Pi()&&es.isFollowing()&&(e||$a)&&(null!==rs&&(cancelAnimationFrame(rs),rs=null),is=!0,rs=requestAnimationFrame(()=>{rs=null,is=!1,es.isFollowing()&&Fi(Ci(),e?220:140)}))},Di=(e,t,r,o=()=>!0)=>{let n=e.scrollTop,a=t(),s=a-n;if(Si(),Math.abs(s)<1)return ns=!0,e.scrollTop=a,ts=e.scrollTop,void(ns=!1);let i=performance.now();ns=!0;let l=d=>{if(!o())return void Si();let c=t();c!==a&&(a=c,s=a-n);let p=d-i,u=Math.min(p/r,1),h=(e=>1-(1-e)**3)(u);e.scrollTop=n+s*h,ts=e.scrollTop,u<1?xi=requestAnimationFrame(l):(e.scrollTop=a,ts=e.scrollTop,xi=null,ns=!1)};xi=requestAnimationFrame(l)},Fi=(e,t=500)=>{let r=cs(e)-e.scrollTop;Math.abs(r)<1?ts=e.scrollTop:Math.abs(r)>=80?(Si(),ns=!0,e.scrollTop=cs(e),ts=e.scrollTop,ns=!1):Di(e,()=>cs(e),t,()=>es.isFollowing())},ji=()=>{if(!Pi())return void Ni();let e=Ci();ns=!0,e.scrollTop=cs(e),ts=e.scrollTop,ns=!1,Ni()},_i=e=>{let t=0,r=e;for(;r&&r!==lt;)t+=r.offsetTop,r=r.offsetParent;return t},Ui=()=>function(e,t){return!(!e||e.isCollapsed)&&(t.contains(e.anchorNode)||t.contains(e.focusNode))}((()=>{let e=lt.getRootNode();return("function"==typeof e.getSelection?e.getSelection():null)??lt.ownerDocument.getSelection()})(),lt),Gi=()=>{if("last-user-turn"!==(Se.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,'\\"'),o=lt.querySelector(`[data-message-id="${r}"]`);if(!o)return!1;let n=Math.min(Math.max(0,_i(o)-Jt()),cs(lt));return ns=!0,lt.scrollTop=n,ts=lt.scrollTop,ns=!1,"follow"===Ut()&&!ps(lt,24)&&es.pause(),Ni(),!0},Yi=e=>{let t=Math.max(0,Math.round(e));ar.style.height=`${t}px`,ar.style.display=t>0?"":"none",ms&&(ms.spacerHeight=Math.max(0,e))},Zi=e=>{let t=parseFloat(getComputedStyle(lt).paddingBottom)||0,r=0;for(let e of Array.from(lt.children)){if(e===ar||0===e.offsetHeight)continue;let t=_i(e)+e.offsetHeight;t>r&&(r=t)}let o=lt.scrollHeight-e;return r>0?Math.min(r+t,o):o},rl=()=>{null!==gs&&(cancelAnimationFrame(gs),gs=null),Si(),ms=null,ar.style.height="0px",ar.style.display="none"},nl=e=>typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),il=e=>lt.querySelector(`[data-message-id="${nl(e)}"]`),ll=e=>{null!==gs&&cancelAnimationFrame(gs),gs=requestAnimationFrame(()=>{gs=null;let t=nl(e),r=lt.querySelector(`[data-message-id="${t}"]`);if(!r)return;let o=_i(r),n=Zi(ms?.spacerHeight??0),{targetScrollTop:a,spacerHeight:s}=us({anchorOffsetTop:o,topOffset:Jt(),viewportHeight:lt.clientHeight,contentHeight:n,slack:24});ms={initialSpacerHeight:s,contentHeightAtAnchor:n,spacerHeight:s},Yi(s),Di(lt,()=>r.isConnected?Math.max(0,_i(r)-Jt()):a,220)})},dl=()=>{if("anchor-top"!==Ut()||!ms||!Ms)return;let e=il(Ms);if(!e)return;Si();let t=ms.spacerHeight,r=Zi(t),{targetScrollTop:o,spacerHeight:n}=us({anchorOffsetTop:_i(e),topOffset:Jt(),viewportHeight:lt.clientHeight,contentHeight:r,slack:24});ms={initialSpacerHeight:n,contentHeightAtAnchor:r,spacerHeight:n},Yi(n),ns=!0,lt.scrollTop=o,ts=lt.scrollTop,ns=!1,Ni()},cl=e=>{if(null===bs)return!0;let t=il(bs),r=il(e);if(!t||!r)return!0;let o=_i(r)-_i(t);return Jt()+o>lt.clientHeight-96},pl=(e,t)=>{let r="user"===t?"user":"assistant",n=o.layout?.messages?.[r],a=n?.width??"content",s=n?.maxWidth??("full"===a?`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-${a}`),e.classList.toggle("persona-justify-end","user"===t),e.setAttribute("data-message-role",t),e.setAttribute("data-message-width",a),s?e.style.setProperty("--persona-message-row-max-width",s):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=(e,t,r)=>{let a=new Set;for(let e of t){let t="tool"===e.variant?"tool":"reasoning"===e.variant?"reasoning":null;if(!t||"row"!==fe(o,t))continue;let r="tool"===t?o.features?.toolCallDisplay:o.features?.reasoningDisplay;!1!==r?.expandable&&(a.add(e.id),i.observe(e,t,"tool"===t?n:s,r))}let d=document.createElement("div"),c=!o.features?.toolCallDisplay?.grouped,h=new Set;if(c)for(let t of Array.from(e.children)){let e=t.getAttribute("data-wrapper-id");e&&h.add(e)}let m=new Map,g=(()=>{let e=p.find(e=>e.renderLoadingIndicator);return e?.renderLoadingIndicator?e.renderLoadingIndicator:o.loadingIndicator?.render?o.loadingIndicator.render:void 0})(),f=new Set,y=new Map,b=new Set,v=p.some(e=>e.renderAskUserQuestion),w=[],C=[],S=!1!==o.enableComponentStreaming,k=!1!==o.approval,A=[],I=o.messageActions,T=!0===I?.showRegenerate&&!1!==I.enabled&&!0!==mn.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 io(e,r.id)?r.id:null}return null}(t):null,E=!0===I?.showEdit&&!1!==I.enabled,L=!0===I?.showQuote&&!1!==I.enabled,B=null,N=o.features?.reasoningDisplay?.completedVisibility,R=e=>"removed"===N||"removed-when-short"===N&&((e,t)=>{let r=t?.durationMs??15e3,o=t?.chars??1200;return"number"==typeof e.durationMs?e.durationMs<r:(e.chunks??[]).join("").length<o})(e,o.features?.reasoningDisplay?.shortThinkThreshold),$="removed"===o.features?.toolCallDisplay?.completedVisibility,H=e=>"reasoning"===e.variant&&"complete"===e.reasoning?.status?R(e.reasoning):$&&"tool"===e.variant&&"complete"===e.toolCall?.status&&!e.toolCall.interrupted;if(t.forEach(t=>{if(H(t))return;if(f.add(t.id),y.set(t.id,t.role),Ga===t.id&&Xa){let e=ul(t.id,t.role);return e.setAttribute("data-persona-message-edit-stub","true"),e.setAttribute("data-preserve-runtime","true"),d.appendChild(e),void(B={messageId:t.id,element:Xa.element})}let a=v&&Et(t),i=k&&"approval"===t.variant&&!!t.approval,I=!a&&"assistant"===t.role&&!t.variant&&S&&cc(t);!i&&za.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),za.delete(t.id)),!I&&Oa.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),Oa.delete(t.id));let N=Et(t)?`:${t.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:"",R={canRegenerate:T===t.id,canEdit:E&&lo(t),canQuote:L&&!t.variant&&(t.content?.trim().length??0)>0},$=`${R.canRegenerate?"r":""}${R.canEdit?"e":""}${R.canQuote?"q":""}`,W=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)??"",ls(e.toolCall?.args),e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}(t,Ya)+N+`:${$}`,D=a||i||I?null:function(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}(Ha,t.id,W);if(D){if(h.has(t.id)&&Da.get(t.id)===W){let e=document.createElement("div");e.id=`wrapper-${t.id}`,e.setAttribute("data-wrapper-id",t.id),e.setAttribute("data-persona-reuse","true"),d.appendChild(e)}else d.appendChild(D.cloneNode(!0));return c&&m.set(t.id,W),void(Et(t)&&t.toolCall?.id&&!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(b.add(t.toolCall.id),yn(t)))}let F=null,O=p.find(e=>!!("reasoning"===t.variant&&e.renderReasoning||"tool"===t.variant&&e.renderToolCall||!t.variant&&e.renderMessage)),z=o.layout?.messages;if(Et(t)&&!0===t.agentMetadata?.askUserQuestionAnswered)return Fa.delete(t.id),void e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime");if(Kt(t)&&Qt(o).enabled)return;if(Et(t)&&!1!==o.features?.askUserQuestion?.enabled){let e=p.find(e=>"function"==typeof e.renderAskUserQuestion);if(e&&mn.current){let r=Fa.get(t.id),n=r!==W,a=null;if(n){let{payload:r,complete:n}=Pt(t),s=t.id,i=()=>mn.current?.getMessages().find(e=>e.id===s);a=e.renderAskUserQuestion({message:t,payload:r,complete:n,resolve:e=>{let t=i();t&&mn.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=i();e?.agentMetadata?.awaitingLocalTool&&(mn.current?.markAskUserQuestionResolved(e),mn.current?.resolveAskUserQuestion(e,"(dismissed)"))},config:o})}if(n&&null===a&&null==r)return void(!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(b.add(t.toolCall.id),yn(t)));let s=ul(t.id,t.role);return s.setAttribute("data-ask-plugin-stub","true"),s.setAttribute("data-preserve-runtime","true"),d.appendChild(s),void w.push({messageId:t.id,fingerprint:W,bubble:a})}return void(!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(b.add(t.toolCall.id),yn(t)))}if(i){let r=M();if(!r)return void d.appendChild(ul(t.id,t.role));let n=p.find(e=>"function"==typeof e.renderApproval)??x,a=za.get(t.id)!==W,s=null;if(a&&n?.renderApproval){let e=t.id,a=(t,r)=>{let o=mn.current?.getMessages().find(t=>t.id===e);o?.approval&&(u(o.approval)?mn.current?.resolveWebMcpApproval(o.id,t):mn.current?.resolveApproval(o.approval,t,r))};s=n.renderApproval({message:t,defaultRenderer:()=>r.createApprovalBubble(t,o,l),config:o,approve:e=>a("approved",e),deny:e=>a("denied",e)})}if(!a||null!==s){let e=ul(t.id,t.role);return e.setAttribute("data-approval-plugin-stub","true"),e.setAttribute("data-preserve-runtime","true"),d.appendChild(e),void A.push({messageId:t.id,fingerprint:W,bubble:s})}e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),za.delete(t.id),F=r.createApprovalBubble(t,o,l)}else if(O)if("reasoning"===t.variant&&t.reasoning&&O.renderReasoning){if(!he)return;F=O.renderReasoning({message:t,defaultRenderer:()=>yl(t,o,s),config:o})}else if("tool"===t.variant&&t.toolCall&&O.renderToolCall){if(!me)return;F=O.renderToolCall({message:t,defaultRenderer:()=>Ml(t,o,n),config:o})}else O.renderMessage&&(F=O.renderMessage({message:t,defaultRenderer:()=>{let e=Oi(t,r,z,o.messageActions,0,{loadingIndicatorRenderer:g,widgetConfig:o,actionEligibility:R});return"user"!==t.role&&P(e,t,o,wa),e},config:o}));if(!F&&I){let n=pc(t);if(n){let a=Oa.get(t.id),s=a!==W,i=!1!==o.wrapComponentDirectiveInBubble&&!1!==Dl.getOptions(n.component)?.bubbleChrome,l=null;if(s){let a=lc(n,{config:o,message:t,transform:r});if(a&&"PersonaArtifactInline"===n.component){let r=a.hasAttribute("data-artifact-inline")?a:a.querySelector("[data-artifact-inline]"),o=r?.getAttribute("data-artifact-inline")??"",n=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(o):o,s=o?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${n}"]`)??null:null;r&&s&&s!==r&&Gl()?.hasLiveInlineArtifactBlock(s)&&(r===a?a=s:r.replaceWith(s))}if(a)if(i){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 o=document.createElement("div");o.className="persona-mb-3 persona-text-sm persona-leading-relaxed",o.innerHTML=r({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(o)}e.appendChild(a),l=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 o=document.createElement("div");o.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",o.innerHTML=r({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(o)}e.appendChild(a),l=e}}if(l||null!=a){let e=ul(t.id,t.role);return e.setAttribute("data-component-directive-stub","true"),e.setAttribute("data-preserve-runtime","true"),d.appendChild(e),void C.push({messageId:t.id,fingerprint:W,bubble:l})}}}if(!F)if("reasoning"===t.variant&&t.reasoning){if(!he)return;F=yl(t,o,s)}else if("tool"===t.variant&&t.toolCall){if(!me)return;F=Ml(t,o,n)}else if("approval"===t.variant&&t.approval){if(!1===o.approval)return;let e=M();if(!e)return;F=e.createApprovalBubble(t,o,l)}else{let e=o.layout?.messages;F=e?.renderUserMessage&&"user"===t.role?e.renderUserMessage({message:t,config:o,streaming:!!t.streaming}):e?.renderAssistantMessage&&"assistant"===t.role?e.renderAssistantMessage({message:t,config:o,streaming:!!t.streaming}):Oi(t,r,e,o.messageActions,0,{loadingIndicatorRenderer:g,widgetConfig:o,actionEligibility:R}),"user"!==t.role&&F&&P(F,t,o,wa)}let q=ul(t.id,t.role);q.appendChild(F),function(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}(Ha,t.id,W,q),d.appendChild(q),c&&m.set(t.id,W)}),st.composerOverlay&&st.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(e=>{let t=e.getAttribute("data-persona-ask-sheet-for");t&&!b.has(t)&&jt(st.composerOverlay,t)}),o.features?.toolCallDisplay?.grouped){let e=[],r=[],s="summary"===o.features.toolCallDisplay.groupedMode;t.forEach(t=>{if("tool"===t.variant&&t.toolCall&&me){if($&&"complete"===t.toolCall.status&&!t.toolCall.interrupted)return;r.push(t)}else("reasoning"!==t.variant||he&&("complete"!==t.reasoning?.status||!R(t.reasoning)))&&((r.length>1||s&&r.length>0)&&e.push(r),r=[])}),(r.length>1||s&&r.length>0)&&e.push(r),e.forEach(e=>{let t=e.map(e=>Array.from(d.children).find(t=>t instanceof HTMLElement&&t.getAttribute("data-wrapper-id")===e.id)).filter(e=>!!e);if(t.length<(s?1:2))return;let r=ul(`tool-group-${e[0].id}`,"assistant");if(r.setAttribute("data-persona-tool-group-row","true"),"collapsible"===o.features?.toolCallDisplay?.groupedMode){let s=`tool-group-${e[0].id}`,l=e.some(e=>"complete"!==e.toolCall?.status),d={...e[0],id:s,toolCall:{id:s,name:`${e.length} tools`,status:l?"running":"complete",chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>!1===e.toolCall?.success),interrupted:!l&&e.some(e=>e.toolCall?.interrupted)}};a.add(s),i.observe(d,"tool",n,o.features.toolCallDisplay);let c=d.toolCall?.interrupted?`${e.length} tools · Interrupted`:`${l?"Using":"Used"} ${e.length} tools`,p=o.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:c,config:o}),u=ve(d,o,n.has(s),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=`${e.length} ${1===e.length?"tool":"tools"}`,u=e.some(e=>e.toolCall?.interrupted)?`${p} · Interrupted`:`Called ${p}`,h=o.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:u,config:o});((e,t)=>null!=t&&("string"==typeof t?(e.textContent=t,!0):(e.appendChild(t),!0)))(c,h)||(c.textContent=u);let m=document.createElement("div");m.className="persona-tool-group-stack persona-flex persona-flex-col",m.id=`tool-group-stack-${e[0].id}`,m.setAttribute("data-persona-tool-group-stack","true"),l.appendChild(c),s||l.appendChild(m),r.appendChild(l),t[0].before(r),t.forEach((e,r)=>{if(s)return void e.remove();e.style.setProperty("--persona-message-row-max-width","100%");let o=document.createElement("div");o.className="persona-tool-group-item persona-relative",o.setAttribute("data-persona-tool-group-item","true"),r<t.length-1&&o.setAttribute("data-persona-tool-group-connector","true"),o.appendChild(e),m.appendChild(o)})})}i.prune(a),function(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}(Ha,f);let W=e=>"tool"===e.variant&&!me||"reasoning"===e.variant&&!he||H(e),D=t.some(e=>"assistant"===e.role&&e.streaming&&!W(e)),F=t.length-1;for(;F>=0&&W(t[F]);)F--;let O=F>=0?t[F]:void 0,z=F<t.length-1,q="assistant"===O?.role&&!O.streaming&&"approval"!==O.variant&&!z;if($a&&t.some(e=>"user"===e.role)&&!D&&!q){let e={config:o,streaming:!0,location:"standalone",defaultRenderer:Bi},t=p.find(e=>e.renderLoadingIndicator),r=null;if(t?.renderLoadingIndicator&&(r=t.renderLoadingIndicator(e)),null===r&&o.loadingIndicator?.render&&(r=o.loadingIndicator.render(e)),null===r&&(r=Bi()),r){let e=document.createElement("div"),t=!1!==o.loadingIndicator?.showBubble,n=o.layout?.messages?.layout??"bubble";e.className=t?$i("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),d.appendChild(a)}}if(!$a&&t.length>0){let e=t[t.length-1],r={config:o,lastMessage:e,messageCount:t.length},n=p.find(e=>e.renderIdleIndicator),a=null;if(n?.renderIdleIndicator&&(a=n.renderIdleIndicator(r)),null===a&&o.loadingIndicator?.renderIdle&&(a=o.loadingIndicator.renderIdle(r)),a){let e=document.createElement("div");e.className=!1===o.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),d.appendChild(t)}}(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)})})(d),as(e,d),Da=m;for(let t of Array.from(e.querySelectorAll(":scope > [data-persona-reuse]"))){let e=Ha.get(t.getAttribute("data-wrapper-id")??"");e?t.replaceWith(e.wrapper.cloneNode(!0)):t.remove()}if(Ze(e),B){let{messageId:t,element:r}=B,o=e.querySelector(`#wrapper-${t}`);o&&r.parentElement!==o&&(pl(o,y.get(t)??"user"),o.replaceChildren(r))}if(w.length>0)for(let{messageId:t,fingerprint:r,bubble:o}of w){let n=e.querySelector(`#wrapper-${t}`);n&&(pl(n,y.get(t)??"assistant"),null!==o&&(n.replaceChildren(o),n.setAttribute("data-bubble-fp",r),Fa.set(t,r)))}if(Fa.size>0)for(let e of Fa.keys())f.has(e)||Fa.delete(e);if(C.length>0)for(let{messageId:t,fingerprint:r,bubble:o}of C){let n=e.querySelector(`#wrapper-${t}`);n&&(pl(n,y.get(t)??"assistant"),null!==o&&(n.replaceChildren(o),n.setAttribute("data-bubble-fp",r),Oa.set(t,r)))}if(Oa.size>0)for(let e of Oa.keys())f.has(e)||Oa.delete(e);if(A.length>0)for(let{messageId:t,fingerprint:r,bubble:o}of A){let n=e.querySelector(`#wrapper-${t}`);n&&(pl(n,y.get(t)??"assistant"),null!==o&&(n.replaceChildren(o),n.setAttribute("data-bubble-fp",r),za.set(t,r)))}if(za.size>0)for(let e of za.keys())f.has(e)||za.delete(e)},bl=!1,vl=()=>{bl||(bl=!0,at().catch(()=>{}),Ee().catch(()=>{bl=!1}))},wl=(e,t,r)=>{t.length>0&&vl(),gl(e,t,r),Do()},Cl=null,Sl=()=>{if(Cl)return;let t=e=>{let t=e.composedPath();t.includes(rt)||nt&&t.includes(nt)||Fl(!1,"user")};Cl=t,(e.ownerDocument??document).addEventListener("pointerdown",t,!0)},kl=()=>{Cl&&=((e.ownerDocument??document).removeEventListener("pointerdown",Cl,!0),null)};la.push(()=>kl());let Il=null,Tl=()=>{if(Il)return;let t=e=>{"Escape"===e.key&&(e.isComposing||Fl(!1,"user"))};Il=t,(e.ownerDocument??document).addEventListener("keydown",t,!0)},El=()=>{Il&&=((e.ownerDocument??document).removeEventListener("keydown",Il,!0),null)};la.push(()=>El());let Ll=!1,Pl=new Set,Rl=()=>o.launcher?.composerBar?.peek?.streamAnimation||o.features?.streamAnimation,$l=()=>{if(!ae())return;let t=st.peekBanner,r=st.peekTextNode;if(!t||!r)return;if(le)return void t.classList.remove("persona-pill-peek--visible");let o,n=wa?.getMessages()??[];for(let e=n.length-1;e>=0;e--){let t=n[e];if("assistant"===t.role&&t.content){o=t;break}}if(!o)return void t.classList.remove("persona-pill-peek--visible");let a=o.content,s=!!o.streaming,i=Rl(),l=vs(i),d="none"===l.type?null:ma(l.type,i?.plugins),c=!0===d?.isAnimating?.(o),p=null!==d&&(s||c);p&&d&&!Pl.has(d.name)&&(Ds(d,e),Pl.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?As(a,l.buffer,d,o,s):a;if(!p||"skeleton"!==l.placeholder||!s||m&&m.trim()){let e=Math.max(0,m.length-100),n=m.length>100?m.slice(-100):m,a=He(n);if(p&&d){let s=a;("char"===d.wrap||"word"===d.wrap)&&(s=Bs(a,d.wrap,`peek-${o.id}`,{skipTags:d.skipTags,startIndex:e}));let i=document.createElement("div");if(i.innerHTML=s,d.useCaret&&n.length>0){let e=Ns(),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)}as(r,i),d.onAfterRender?.({container:r,bubble:t,messageId:o.id,message:o,speed:l.speed,duration:l.duration})}else{let e=m.length>100?`…${n}`:n;r.textContent!==e&&(r.textContent=e)}}else{let e=document.createElement("div"),t=Rs();t.classList.add("persona-pill-peek__skeleton"),e.appendChild(t),as(r,e)}let g=$a||Ll;t.classList.toggle("persona-pill-peek--visible",g)};if(ae()){let e=st.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),Fl(!0,"user")};e.addEventListener("pointerdown",t),la.push(()=>{e.removeEventListener("pointerdown",t)})}let t=()=>{Ll||(Ll=!0,$l())},r=()=>{Ll&&(Ll=!1,$l())};ot.addEventListener("pointerenter",t),ot.addEventListener("pointerleave",r),la.push(()=>{ot.removeEventListener("pointerenter",t),ot.removeEventListener("pointerleave",r)}),nt&&(nt.addEventListener("pointerenter",t),nt.addEventListener("pointerleave",r),la.push(()=>{nt.removeEventListener("pointerenter",t),nt.removeEventListener("pointerleave",r)}))}let Hl=()=>{if(le&&vl(),!ie())return;if(ae()){let e=(o.launcher?.composerBar??{}).expandedSize??"anchored",t=le?"expanded":"collapsed";return rt.dataset.state=t,rt.dataset.expandedSize=e,nt&&(nt.dataset.state=t,nt.dataset.expandedSize=e),rt.style.removeProperty("display"),rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ot.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),(e=>{let t=o.launcher?.composerBar??{},r=t.expandedSize??"anchored",n=t.bottomOffset??"16px",a=t.collapsedMaxWidth,s=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="",nt){let e=nt.style;e.bottom=n,e.width=a??""}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=s,p.maxWidth=c))})(le),it.style.display=le?"flex":"none",_o(),le?(Sl(),Tl()):(kl(),El()),void $l()}let t=Ys(o),r=e.ownerDocument.defaultView??window,n=o.launcher?.mobileBreakpoint??640,a=o.launcher?.mobileFullscreen??!0,s=r.innerWidth<=n,i=a&&s&&Q,l=ei(o).reveal;le?(rt.style.removeProperty("display"),rt.style.display=t?"flex":"",rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ot.classList.remove("persona-scale-95","persona-opacity-0"),ot.classList.add("persona-scale-100","persona-opacity-100"),_p?(_p.setPanelOpen(!0),_p.element.style.display="none"):Up&&(Up.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"),ot.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"),ot.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"),ot.classList.remove("persona-scale-100","persona-opacity-100"),ot.classList.add("persona-scale-95","persona-opacity-0")),_p?(_p.setPanelOpen(!1),_p.element.style.display=t?"none":""):Up&&(Up.style.display=t?"none":""))},Fl=(t,r="user")=>{if(!ie()||le===t)return;let n=le;le=t,Hl();let a=(()=>{let t=o.launcher?.sidebarMode??!1,r=e.ownerDocument.defaultView??window,n=o.launcher?.mobileFullscreen??!0,a=o.launcher?.mobileBreakpoint??640,s=r.innerWidth<=a,i=Ys(o)&&n&&s,l=ae()&&"fullscreen"===(o.launcher?.composerBar?.expandedSize??"fullscreen");return t||n&&s&&Q||i||l})();if(le&&a){if(!da){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&(da=js(r,o.launcher?.zIndex??1e5))}ca||=Vs(e.ownerDocument)}else le||(da?.(),da=null,ca?.(),ca=null);le&&(Gp(),Gi()||("follow"===Ut()?Wi(!0):ji()));let s={open:le,source:r,timestamp:Date.now()};le&&!n?R.emit("widget:opened",s):!le&&n&&R.emit("widget:closed",s),R.emit("widget:state",{open:le,launcherEnabled:Q,voiceActive:zs.active,streaming:wa.isStreaming()})},Ol={inputDisabled:!1,sendDisabled:!1},zl=()=>Ol.inputDisabled,ql=()=>Ce(o.voiceRecognition?.provider)&&!!wa&&(wa.isBargeInActive()||["listening","processing","speaking"].includes(wa.getVoiceStatus())),jl=()=>Ol.inputDisabled||Ol.sendDisabled;function _l(){if(!mt)return;if("streaming"===Cr.getState().phase)return void(mt.disabled=!1);let e=!!wr&&!wr.isReady();mt.disabled=jl()||e}function Ul(){if(!Rt)return;let e=Cr.getState(),t="when-text"===o.sendButton?.visibility&&"streaming"!==e.phase&&0===e.text.trim().length&&0===e.attachments.length;Rt.toggleAttribute("data-persona-send-hidden",t)}function Vl(){let e=an(o.composer?.inputDisabled),t=an(o.composer?.sendDisabled);Ol={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,a=r||n;ht&&(ht instanceof HTMLTextAreaElement?ht.disabled=n:ht.setAttribute("contenteditable",n?"false":"true"),ht.setAttribute("aria-disabled",n?"true":"false")),Dt&&(Dt.disabled=n),Ot&&(Ot.disabled=n);for(let e of xr?.affordanceButtons??[])e.querySelectorAll("button").forEach(e=>{e.disabled=n});Ht&&(Ht.disabled=n||r&&!ql()),va.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute("data-disabled",a),e instanceof HTMLButtonElement||e.setAttribute("aria-disabled",a?"true":"false")}),e.buttons.forEach(e=>{e.disabled=a})}),yd.forEach(e=>{e.toggleAttribute("data-disabled",a),e instanceof HTMLButtonElement?e.disabled=a:e.setAttribute("aria-disabled",a?"true":"false"),e.querySelectorAll("button").forEach(e=>{e.disabled=a})}),Tt.dataset.personaComposerStreaming=r?"true":"false",Tt.dataset.personaComposerInputDisabled=n?"true":"false",Tt.dataset.personaComposerSendDisabled=jl()?"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)}),_l(),function(){let e=(Ol.inputDisabled?Ol.inputReason:void 0)??(Ol.sendDisabled?Ol.sendReason:void 0);if(ae()){let t=gt??Tt;e?t.setAttribute("title",e):t.removeAttribute("title"),Tt.toggleAttribute(fc,!!e)}else if(e)ft.setAttribute("role","status"),ft.setAttribute("aria-live","polite"),ft.setAttribute(fc,""),ft.removeAttribute(yc),ft.textContent=e,we(ft,o.statusIndicator??{},"idle");else if(ft.hasAttribute(fc)&&(ft.removeAttribute("role"),ft.removeAttribute("aria-live"),ft.removeAttribute(fc),b)){let e=wa.getStatus();et(ft,Ye(e),o.statusIndicator??{},e)}}()}let Kl=e=>{Cr.setStreaming(e),$t(e?"stop":"send"),Vl()},Yl=()=>{zs.active||ht&&ht.focus()};R.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Yl(),200)});let Zl=null,ed=!1,nd=!yt.hidden,ad=null,sd=!D,id=null;la.push(()=>{id?.cancel(),id=null});let ld,dd,cd=t=>{let r=(e=>(e??[]).some(e=>"user"===e.role)?"active":"empty")(t);if(r===hr)return;hr=r,e.setAttribute("data-persona-conversation-state",r);let o=gr();br(),sd&&(id?.cancel(),id=Qi(Tt,"active"===r?o:gr(),"active"===r?"drop":"rise","centered"===ur().layout?320:260)),dl()},pd=null,ud=null,hd=null,md=!1,gd=e=>{let t=ur(),r=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??"bottom"}|${t.align??""}|${t.iconPlacement}|${t.kicker??""}|${t.title}|${t.subtitle}`;(r!==pd||t.icon!==ld)&&(pd=r,ld=t.icon,qi({host:yt,iconHolder:bt,kicker:wt,title:xt,subtitle:Ct,starterSuggestions:ct},t));let n=void 0===t.message?null:`${o.layout?.messages?.layout??"bubble"}|${t.message}`;n!==ud&&(ud=n,Ji(vt,t.message,o));let a=e??(wa?wa.getMessages():o.initialMessages);cd(a);let s=ed,i=!s&&tl(t,a),l=i!==nd;if(nd=i,hd)return ad?.cancel(),ad=null,s!==md&&(md=s,s?Ki(lt,yt,null):Vi(lt,yt,hd)),void zi(lt,yt,!s);if(l&&!i&&!s&&"on-first-message"===t.dismiss&&sd)return void(ad=Xi(yt,e=>{ad===e&&(ad=null),!nd&&!hd&&(zi(lt,yt,!1),dl()),e?.cancel()}));if(ad){if(!i&&!s)return;ad.cancel(),ad=null}let d=!yt.hidden;zi(lt,yt,i),!i&&d&&dl()},fd=[],yd=[],bd=!1,vd=null,wd=()=>{yd.length=0;let e=fd.splice(0,fd.length);for(let t of e)try{t()}catch(e){console.warn("[persona] renderWelcome cleanup threw",e)}};la.push(wd);let xd=(e,t)=>{let r=ri(e,t);if(!r)return!0===o.debug&&console.warn("[persona] renderStarter received a suggestion with no label"),q("span");let n=o.suggestions?.starters,a=ni({item:{...r,behavior:r.behavior??n?.behavior??"send"},index:t,surface:"starter",source:"config",variant:n?.variant??"card",streaming:!!b&&wa.isStreaming(),config:o,plugins:p,chipsConfig:o.suggestionChipsConfig,session:wa,getTextarea:()=>ht,eventTarget:yt,submitPrompt:Zc});return yd.push(a),a},Cd=()=>{if(bd)return;bd=!0;let e=ur();vd=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`,dd=e.icon;try{wd(),Ki(lt,yt,hd),hd=null,md=!1;let t=wa?wa.getMessages():o.initialMessages,r=tl(e,t),n=0,a=null;for(let t of p)if(t.renderWelcome&&(a=t.renderWelcome({config:e,variant:e.variant,visible:r,defaultRenderer:()=>yt,sendMessage:e=>{if(!wa||wa.isStreaming())return;let t=e.trim();t&&wa.sendMessage(t)},requestRender:()=>Cd(),renderStarter:e=>xd(e,n++),storage:v(t.id),onCleanup:e=>{fd.push(e)}}),a))break;a&&a!==yt&&(hd=a,Vi(lt,yt,a))}finally{bd=!1}gd()},Sd=()=>{gd(),oo||(ht.placeholder=function(e,t){if(t?.length&&0!==e.length)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}(Cr.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!o.sendButton?.useIcon&&!wa?.isStreaming()&&(mt.textContent=o.copy?.sendButtonLabel??"Send")),ht.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ht.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},Md=!!o.setStoredConversationId,Id=e=>K(t=>{let r={...t};return delete r[e],r}),Td=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};o.clientToken&&(o={...o,getStoredSessionId:()=>Td("sessionId"),setStoredSessionId:e=>{K(t=>({...t,sessionId:e}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Id("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Td("conversationId")),setStoredConversationId:o.setStoredConversationId??(e=>{K(t=>({...t,conversationId:e}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Id("conversationId"))});let Ld=()=>o.clientToken??null,Rd=e=>Jd(e,ke(),!1===o.persistState),$d=Ld(),Hd=$d?Rd($d):null,Fd={...Hd?{visitorStore:Hd}:{},historyBootstrapReady:!0!==o.features?.history?.enabled||ac()?F:Promise.all([F,j]).then(()=>{}),getStoredMessageCursor:()=>Td("historyMessageCursor"),setStoredMessageCursor:e=>{null===e?Id("historyMessageCursor"):K(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?K(t=>({...t,pendingDisplayProjections:e})):Id("pendingDisplayProjections")},getStoredResumableHandle:Ed,setStoredResumableHandle:e=>{e?K(t=>({...t,durableResume:e})):Id("durableResume")},shouldResumeDurableConversation:()=>H&&null!==Ed(),...Md?{}:{getStoredConversationRevision:()=>Td("conversationRevision"),setStoredConversationRevision:e=>{null===e?Id("conversationRevision"):K(t=>({...t,conversationRevision:e}))}}};if(H){let t=o.onExecutionState,r=e.ownerDocument.defaultView,n=!1,a=()=>n=!0,s=()=>n=!1;r?.addEventListener("pagehide",a),r?.addEventListener("pageshow",s),la.push(()=>{r?.removeEventListener("pagehide",a),r?.removeEventListener("pageshow",s)}),o={...o,reconnectStream:o.reconnectStream??(e=>wa.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!n)&&Fd.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let zd=()=>{let e=Ld();if(e&&Hd?.matches(e,ke(),!1===o.persistState)||!e&&!Hd)return;Hd?.destroy(),Hd=e?Rd(e):null;let t={...Fd};Hd?t.visitorStore=Hd:delete t.visitorStore,Fd=t,wa.setHistoryInternals(Fd)},jd=null,_d=e=>"user"===e.role||"approval"===e.variant||!0===e.agentMetadata?.awaitingLocalTool||Et(e),Kd=null,Gd=null,Xd=null,Qd=null,Zd=e=>{let t,r;Kd=e;for(let o=e.length-1;o>=0;--o){let n=e[o];if(!t&&"user"===n.role&&(t=n),!r&&"assistant"===n.role&&(r=n),t&&r)break}wl(dt,e,ue),Gl()?.updateInlineArtifactBlocks(dt,Jo.artifacts,{suppressTransition:$a}),jd??=setInterval(()=>{let e=dt.querySelectorAll("[data-tool-elapsed]");if(0===e.length)return clearInterval(jd),void(jd=null);let t=Date.now();e.forEach(e=>{let r=Number(e.getAttribute("data-tool-elapsed"));r&&(e.textContent=e.closest(".persona-activity-row")?ye(t-r):sr(t-r))})},100),gd(e),Na(e),Wi(!$a),(e=>{let t=new Map;e.forEach(e=>{let r=Hs.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!r&&"assistant"===e.role&&(R.emit("assistant:message",e),!ys&&("anchor-top"!==Ut()||Yt())&&Li()&&(hs+=1,Ai(),Ni(),cr(1===hs?"1 new message below.":`${hs} new messages below.`))),"assistant"===e.role&&(r?.streaming||Wa.has(e.id))&&!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}))}),Hs.clear(),t.forEach((e,t)=>{Hs.set(t,e)}),Wa.clear()})(e),0===e.length&&(rl(),ws=!0,xs=!1,Ms=null,Is=!1),!fs||ys?(fs=!0,bs=t?.id??null,Es=r?.id??null):t&&t.id!==bs?(bs=t.id,(e=>{let t=Ut();"follow"===t?(Hi(),Wi(!0)):"anchor-top"===t&&(ws=!1,xs=!0,Is=!1,Ms=e,ll(e))})(t.id)):r&&r.id!==Es&&"anchor-top"===Ut()&&(xs?ws=!1:(ws=!0,rl(),Hi(),Wi(!0))),r&&(Es=r.id),(e=>{if("anchor-top"!==Ut()||!xs||Is||Ui())return;let t=null===bs;for(let r of e)if(t){if(ds(r)){if(r.id===Ms||!cl(r.id))return;return Ms=r.id,void ll(r.id)}}else r.id===bs&&(t=!0)})(e);let o=zs.lastUserMessageId;t&&t.id!==o&&(zs.lastUserMessageId=t.id,R.emit("user:message",t)),zs.lastUserMessageWasVoice=!!t?.viaVoice,(e=>{if(!H)return li(e);Qd=e,queueMicrotask(()=>{Qd===e&&(Qd=null,li(Gd??e))})})(e),$l()},ec=()=>{null!==Xd&&(cancelAnimationFrame(Xd),Xd=null);let e=Gd;Gd=null,e&&Zd(e)},tc=()=>{null!==Xd&&cancelAnimationFrame(Xd),Xd=null,Gd=null};wa=new Po(o,{onMessagesChanged(e){(e=>{if(0===e.length)return tc(),void Zd(e);let t=Gd??Kd;$a&&t&&((e,t)=>{if(t.length<e.length)return!1;for(let r=0;r<t.length;r+=1){let o=t[r];if(o!==e[r]){if(_d(o))return!1;"assistant"===o.role&&o.streaming&&Wa.add(o.id)}}return!0})(t,e)?(Gd=e,null===Xd&&(Xd=requestAnimationFrame(()=>{Xd=null;let e=Gd;Gd=null,e&&Zd(e)}))):(ec(),Zd(e))})(e)},onStatusChanged(e){let t=o.statusIndicator??{};et(ft,(e=>"idle"===e?t.idleText??Pr.idle:"connecting"===e?t.connectingText??Pr.connecting:"connected"===e?t.connectedText??Pr.connected:"error"===e?t.errorText??Pr.error:"paused"===e?t.pausedText??Pr.paused:"resuming"===e?t.resumingText??Pr.resuming:Pr[e])(e),t,e),Ge()},onStreamingChanged(e){e||(0===wa?.getMessages().length?tc():ec()),$a=e,Kl(e),Ge(),wa&&wl(dt,wa.getMessages(),ue),e||(Wi(!0),(()=>{if(!ms||ms.spacerHeight<=0)return;let e=Zi(ms.spacerHeight),t=Math.max(0,Math.round(lt.scrollTop)+lt.clientHeight-e+24);t<ms.spacerHeight&&(Yi(t),Ni())})(),Pa=!0,wa&&Ba(wa.getMessages(),Qt(o))),Ni(),cr(e?"Responding…":"Response complete."),$l()},onVoiceStatusChanged(e){if(R.emit("voice:status",{status:e,timestamp:Date.now()}),"disconnected"!==e&&!Ce(o.voiceRecognition?.provider))return;let t=wa.getVoiceNotice();switch(t&&Gc(t,1e4),e){case"listening":if(!Fs){let e=wa.getVoiceDisclosure();e&&(Fs=!0,ae()?(Os=ht.placeholder,ht.placeholder=e,cr(e)):Gc(e,1e4))}Ep(),Mp();break;case"processing":Ep(),Ip();break;case"speaking":Ep(),Tp();break;default:"idle"===e&&wa.isBargeInActive()?(Ep(),Mp(),Ht?.setAttribute("aria-label","End voice session")):(zs.active=!1,Fs=!1,null!==Os&&(ht.placeholder=Os,Os=null),Ep(),Js("system"),Ks||Gs())}},onArtifactsState(e){Jo=e,0===e.artifacts.length&&(dn=!1),Gl()?.updateInlineArtifactBlocks(dt,e.artifacts,{suppressTransition:$a}),Yn(),li()},onHistoryStateChanged(e){Ke(e)},onHistoryNotice(e){Je(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})}},Fd),mn.current=wa,la.push(()=>wa.cancel()),la.push(()=>{wa.destroy(),Hd?.destroy(),Hd=null});let rc=null;if(wa.onReadAloudChange((e,t)=>{No=e,Ro=t,Do();let r=e??rc;e&&(rc=e);let o=r?wa.getMessages().find(e=>e.id===r)??null:null;R.emit("message:read-aloud",{messageId:r,message:o,state:t,timestamp:Date.now()}),"idle"===t&&(rc=null)}),b=!0,fs=!0,!0===o.voiceRecognition?.enabled&&Ce(o.voiceRecognition.provider))try{wa.setupVoice()}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",e)}let oc=null,ic=null,dc=!1,uc=wa.getHistoryState(),bc=()=>!0===o.features?.history?.enabled,Ac=e=>{e&&(ir.textContent="",ir.textContent=e)},Ic=()=>{f.forEach(e=>e()),f=[];let t=oc,r=t?.railCollapseShortcut();t&&r&&f.push(h.register({id:"history-rail-collapse",combo:r.combo,scope:"page"===o.features?.history?.rail?.collapseShortcutScope?"page":"widget",when:()=>je&&"rail"===_e&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of o.layout?.header?.trailingActions??[])t.shortcut&&f.push(h.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let r=e.querySelector(`[data-persona-header-action="${t.id}"]`);r?r.click():o.layout?.header?.onAction?.(t.id)}}));for(let e of p)for(let t of e.shortcuts??[])f.push(h.register({...t,id:`${e.id}:${t.id}`}))};Ic();let Tc=null,Ec=!1,Lc=()=>{if(!At)return;let e="conversation"===o.layout?.header?.titleSource,t=e&&Tc?.trim()||null;At.textContent=t??o.launcher?.title??"Chat Assistant";let r=At.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 a=r.querySelector("svg");a&&(a.style.display=n?"":"none")};Lc(),it.addEventListener("persona:title-menu-builtin",e=>{let t=e.detail?.actionId,r=wa.getActiveConversationId();r&&("delete"===t?Rc(e=>e.requestDeleteConversation(r)):"star"===t&&wa.canUpdateConversations()&&Rc(e=>e.updateHistoryConversation(r,{starred:!Ec})).catch(()=>{}))}),Ke=e=>{uc=e,oc?.historySurface?.view.setNewConversationRequired("new_conversation_required"===e.recovery),Kl(e.sendBlocked||$a),oc?.syncEarlierMessagesPill()},Je=e=>{("history_continuity_reset"===e.code||"conversation_deleted_recovered"===e.code)&&(Ha.clear(),rl(),Hi()),Ac(e.message),oc?.historySurface?.view.refresh()};let Pc={get actionManager(){return X},get activeConversationTitle(){return Tc},announceHistory:Ac,get applyRailChrome(){return Ve},set applyRailChrome(e){Ve=e},get artifactSplitRoot(){return kn},get body(){return lt},get config(){return o},get container(){return it},get conversationOpenPendingEl(){return Zl},set conversationOpenPendingEl(e){Zl=e},get conversationOpenTakeover(){return ed},set conversationOpenTakeover(e){ed=e},currentKeyPrefix:ke,destroyCallbacks:la,eventBus:R,get footer(){return Tt},get header(){return It},get historyChromeSync(){return Ge},set historyChromeSync(e){Ge=e},historyFeatureEnabled:bc,get historyInternals(){return Fd},set historyInternals(e){Fd=e},get historyPresentation(){return _e},set historyPresentation(e){_e=e},get historySessionState(){return uc},get historyVisible(){return je},set historyVisible(e){je=e},get isStreaming(){return $a},jumpToBottomInstant:ji,get lastAppliedMessages(){return Kd},set lastAppliedMessages(e){Kd=e},get launcherEnabled(){return Q},get launcherSurfaceInstance(){return _p},maybeFocusInput:Yl,messageCache:Ha,get messagesWrapper(){return dt},mount:e,get open(){return le},panel:ot,panelElements:st,get persistentMetadata(){return W},set persistentMetadata(e){W=e},plugins:p,get reapplyHistoryHostChrome(){return Ue},set reapplyHistoryHostChrome(e){Ue=e},repinAnchoredMessage:dl,resetAnchorState:rl,restoreScrollPosition:Gi,resumeAutoScroll:Hi,runStorageMutation:ii,get session(){return wa},setActiveConversationSummary:e=>{Ec=!0===e?.starred,(e=>{e!==Tc&&(Tc=e,Lc())})(e&&e.title.trim()||null),Lc()},storageAdapter:$,get suppressScrollSend(){return ys},set suppressScrollSend(e){ys=e},syncScrollToBottomButton:Ni,updateWelcome:gd,getHistoryProviderFactory:sc,historyErrors:{HistoryClientError:Br,HistoryProviderError:Fr},isDockedMountMode:Ys,renderLucideIcon:se,loadHistoryView:Yd,createHeaderIconButton:ci,attachTooltip:Xo},Bc=e=>(!oc&&!dc&&(oc=e.createHistoryShell(Pc),oc.railCollapseShortcut()&&Ic()),oc),Nc=()=>{if(oc)return Promise.resolve(oc);let e=ac();return e?Promise.resolve(Bc(e)):(ic??=nc().then(Bc,e=>{throw ic=null,e}),ic)},Rc=e=>{let t=ac(),r=oc??(t?Bc(t):null);return r?e(r):Nc().then(t=>{if(!t)throw Error("[AgentWidget] The widget was destroyed");return e(t)})},$c=()=>{oc?.syncHistoryPresentation()};la.push(()=>{dc=!0}),bc()&&Nc().catch(()=>{}).finally(O),o.clientToken&&(!0===o.features?.history?.enabled||"mount"===o.sessionInit)&&wa.initClientSession().then(()=>{let e=oc;if(e?.historyAvailable())return wa.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{oc?.syncEarlierMessagesPill()}).catch(e=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",e)});let Hc=()=>wa.warmClientSession(),Wc=e=>{let t=o.sessionInit??"input",r=co?.input??ht,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:(co?.form??gt)?.contains(n)))&&Hc()},Dc=["input","pointerdown","keyup"];Dc.forEach(t=>e.addEventListener(t,Wc));let Fc,Oc,zc=()=>{let e=Oc;Oc=void 0;try{"function"==typeof e&&e()}catch{}},qc=()=>{let t=o.clientToken&&"function"==typeof o.sessionInit?o.sessionInit:void 0;if(t!==Fc){zc(),Fc=t;try{Oc=t?.({warm:Hc,mount:e})}catch{}}};qc(),la.push(()=>{Dc.forEach(t=>e.removeEventListener(t,Wc)),zc()}),(ge||o.onSSEEvent)&&wa.setSSEEventCallback((e,t)=>{o.onSSEEvent?.(e,t),ze(e,t)});let jc=()=>{let e=o.resume??(H?Fd.getStoredResumableHandle?.():null);e&&"function"==typeof o.reconnectStream&&wa.resumeFromHandle(e)};D?D.then(e=>{if(e){if(e.metadata&&(W=xc(e.metadata),X.syncFromMetadata()),e.messages?.length){ys=!0;try{wa.hydrateMessages(e.messages)}finally{ys=!1}vl()}e.artifacts?.length&&wa.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),vi(e.draft)}}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",e)}).finally(()=>{sd=!0,B(),jc()}):(vi(N),jc());let _c=()=>{let e=ht.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>"mention"===e.kind)?e.contentSegments:void 0},Uc=!1,Vc=null,Kc=()=>{ht.value="",ht.style.height="auto",kr(),np()},Jc=null;function Gc(e,t=4e3){cr(e),!ae()&&ft&&(ft.hasAttribute(fc)||(ft.setAttribute(yc,""),ft.setAttribute("role","status"),ft.setAttribute("aria-live","polite"),ft.textContent=e,we(ft,o.statusIndicator??{},"idle"),Jc&&clearTimeout(Jc),Jc=setTimeout(()=>{if(Jc=null,ft?.hasAttribute(yc)&&(ft.removeAttribute(yc),ft.removeAttribute("role"),ft.removeAttribute("aria-live"),b)){let e=wa.getStatus();et(ft,Ye(e),o.statusIndicator??{},e)}},t)))}let Xc=(e={})=>{let t=(e.overrideText??ht?.value??"").trim();return e.resolveInlineCommand&&t?(xr?.takeInlineCommand(t)??Promise.resolve(null)).then(r=>Qc(e,t,r)):Qc(e,t,null)},Qc=(e,t,r)=>{if("action"===r?.kind)return Kc(),xr?.clear(),void Mr();let n="server"===r?.kind?r.mentions:null,a="prompt"===r?.kind?r.sendText:t,s=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:a,hasAttachments:(wr?.hasAttachments()??!1)||(s?.length??0)>0,attachmentsReady:wr?.isReady()??!0,hasMentions:xr?.hasMentions()??!1,hasServerMentions:!!n,inputDisabled:zl(),sendDisabled:jl()}))return;let i=wa.isStreaming()?_r():"block";if("defer-one"===i&&!e.pending)return Cr.getState().pendingSubmission?void Gc("One message is already queued. Edit or remove it first."):void function(e){let t=Cr.getState(),r=wr?.hasAttachments()??!1,o=r?[...wr.getContentParts()]:[];r&&e.sendText&&o.push(Sr(e.sendText)),Jr(Gn({text:e.sendText,contentParts:o.length?o:void 0,mentionRefs:[...xr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:_c(),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&&Kc(),r&&wr.clearAttachments(),xr?.clear(),Mr(),t.quote&&qr(void 0),wi(),Ao.release(),Io(),cr("Message queued. It sends when the response finishes.")}({intent:e,sendText:a,serverMentions:n});let l={text:a,mentionRefs:[...xr?.getMentionRefs()??[],...n?.refs??[]],contentSegments:"prompt"===r?.kind?void 0:_c(),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(s?.length)return[...s];if(!wr?.hasAttachments())return;let e=[...wr.getContentParts()];return l.text&&e.push(Sr(l.text)),e};l.contentParts=d();let c=()=>{Qa(),ae()&&(le||(o.launcher?.composerBar?.expandOnSubmit??1)&&Fl(!0,"auto"));let t=xr?.collectForSubmit()??null,r=((e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[r,o]=await Promise.allSettled([e.finalize(),t.finalize()]),n=[];return"fulfilled"===r.status?n.push(r.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",r.reason),"fulfilled"===o.status?n.push(o.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",o.reason),Mc(n)}}:e:t)(t,n),a=d();!1!==e.consumeDraft&&Kc();let s={selectedModelId:l.options.selectedModelId,activeModeIds:l.options.activeModeIds},c="interrupt"===i;c&&wa.cancel(),wa.sendMessage(l.text,{contentParts:a,mentions:r??void 0,contentSegments:l.contentSegments,viaVoice:l.viaVoice,composerOptions:s,...l.options.quote&&{quote:l.options.quote},...c&&{interrupt:!0}}),wr?.hasAttachments()&&wr.clearAttachments(),t&&xr?.clear(),Mr();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,o.composer?.modes);u.length!==p.length&&Rr(u),Cr.getState().quote&&qr(void 0),wi(),Ao.release(),Io()},p=o.composer?.onBeforeSend;if(!p)return void c();let u=new AbortController;Vc=u;let h=e=>{Vc=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=Qn(p,l,u.signal);if(m instanceof Promise)return Cr.setPreparing(!0),m.then(h).finally(()=>Cr.setPreparing(!1));h(m)};Fo={regenerate:function(e){if(wa.isStreaming())return;let t=io(wa.getMessages(),e);t&&(Qa(),wa.resubmitFrom(t,{reason:"retry"})&&dl())},edit:function(e){if(!0!==o.messageActions?.showEdit)return;let t=wa.getMessages().find(t=>t.id===e);t&&lo(t)&&Ga!==e&&(Qa(),Ga=e,Xa=Jn({messageId:e,initialText:t.content,onSave:t=>function(e,t){let r=Xa;Ga=null,Xa=null,r?.destroy(),Ha.delete(e),wa.resubmitFrom(e,{reason:"edit",replacement:{text:t,mentionRefs:[],options:{}}})?dl():wl(dt,wa.getMessages(),ue)}(e,t),onCancel:()=>Qa()}),Ha.delete(e),wl(dt,wa.getMessages(),ue),Xa.focus())},quote:e=>{let t=wa.getMessages().find(t=>t.id===e)?.content?.trim();t&&(qr({text:t,messageId:e}),ht?.focus())}};let Yc=async e=>{if(!Uc){Uc=!0;try{await Xc({resolveInlineCommand:!0,...e})}finally{Uc=!1}}};function Zc(e){jl()||(Kc(),ep(e,{consumeDraft:!1}))}let ep=(e,t)=>{if(Uc)return;Uc=!0;let r=()=>{Uc=!1};try{let o=Xc({...t,overrideText:e});o instanceof Promise?o.finally(r):r()}catch(e){throw r(),e}},tp=e=>{e.preventDefault(),wa.isStreaming()?(wa.cancel(),Be?.reset(),$e?.update()):Uc||Yc()},rp={...ss},op=!1,np=()=>{rp={...ss}},ap=e=>{"Escape"!==e.key||e.isComposing||e.composedPath().includes(it)&&(Vc?(Vc.abort(),Vc=null,e.preventDefault(),e.stopImmediatePropagation()):wa.isStreaming()&&(wa.cancel(),Be?.reset(),$e?.update(),np(),e.preventDefault(),e.stopImmediatePropagation()))},sp=null,ip=!1,lp=null,dp=null,cp=()=>"review"===o.voiceRecognition?.completionBehavior;function pp(e){Ht?.setAttribute("data-state",e),"recording"===e?function(){if(null!==mp)return;if("function"!=typeof requestAnimationFrame)return void bp(b?wa.getVoiceLevel()??hp:hp);let e=()=>{mp=requestAnimationFrame(e);let t=b?wa.getVoiceLevel():null;null===t?bp(hp):(fp+=.3*(t-fp),bp(fp))};mp=requestAnimationFrame(e)}():wp()}let up="--persona-voice-level",hp=.5,mp=null,gp=-1,fp=0,yp=()=>{let e=[],t=Wt??Ht?.parentElement??null;return t&&e.push(t),Tt&&e.push(Tt),e},bp=e=>{let t=Math.round(100*Math.max(0,Math.min(1,e)))/100;if(t!==gp){gp=t;for(let e of yp())e.style.setProperty(up,String(t))}},vp=()=>{gp=-1,fp=0;for(let e of yp())e.style.removeProperty(up)};function wp(){null!==mp&&(cancelAnimationFrame(mp),mp=null),vp()}let xp=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Cp=(e="user")=>{if(ip||wa.isStreaming())return;let t=xp();if(!t)return;sp=new t;let r=o.voiceRecognition??{},n=r.pauseDuration??2e3;sp.continuous=r.provider?.browser?.continuous??!0,sp.interimResults=!0,sp.lang=r.provider?.browser?.language??"en-US";let a=ht.value;sp.onresult=e=>{let t="",r="";for(let o=0;o<e.results.length;o++){let n=e.results[o],a=n[0].transcript;n.isFinal?t+=a+" ":r=a}let o=a+t+r;ht.value=o,kr(),lp&&clearTimeout(lp),(t||r)&&(lp=window.setTimeout(()=>{if(ht.value.trim()&&sp&&ip){if(Sp(),cp())return;Yc({viaVoice:!0})}},n))},sp.onerror=e=>{"no-speech"!==e.error&&Sp()},sp.onend=()=>{if(ip){let e=ht.value.trim();!cp()&&e&&e!==a.trim()&&Yc({viaVoice:!0}),Sp()}};try{if(sp.start(),ip=!0,zs.active=!0,"system"!==e&&(zs.manuallyDeactivated=!1),Js(e),Gs(),Io(),Ht){let e=o.voiceRecognition??{};dp={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"),pp("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{Sp("system")}},Sp=(e="user")=>{if(ip){if(ip=!1,lp&&=(clearTimeout(lp),null),sp){try{sp.stop()}catch{}sp=null}if(zs.active=!1,Js(e),Gs(),Io(),Ht){if(Ht.classList.remove("persona-voice-recording"),pp("idle"),dp){Ht.style.backgroundColor=dp.backgroundColor,Ht.style.color=dp.color,Ht.style.borderColor=dp.borderColor;let e=Ht.querySelector("svg");e&&e.setAttribute("stroke",dp.color||"currentColor"),dp=null}Ht.setAttribute("aria-label","Start voice recognition")}}},kp=null,Ap=e=>{let t=t=>{kp??=t.createMicStateStyles({mic:()=>Ht,config:()=>o,session:()=>wa,get original(){return dp},set original(e){dp=e},setMicState:pp,renderIcon:se,iconFallbackPx:24}),e(kp)},r=vo();r?t(r):bo().then(t,()=>{})},Mp=()=>Ap(e=>e.recording()),Ip=()=>Ap(e=>e.processing()),Tp=()=>Ap(e=>e.speaking()),Ep=()=>Ap(e=>e.reset()),Lp=()=>{if(!zl())if(Ce(o.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(()=>{zs.active=!1,zs.manuallyDeactivated=!0,Gs(),Js("user"),Ep()});wa.toggleVoice().then(()=>{zs.active=Us(),zs.manuallyDeactivated=!zs.active,Gs(),Js("user"),zs.active?Mp():Ep()})}else if(ip){let e=ht.value.trim();zs.manuallyDeactivated=!0,Gs(),Sp("user"),e&&!cp()&&Yc()}else zs.manuallyDeactivated=!1,Gs(),Cp("user")};Xr=Lp;let Pp=()=>wa.prewarmVoice(),Bp=()=>{let e=o.voiceRecognition;return!0===e?.enabled&&(e.prewarm??(!!o.clientToken&&"hover"))},Np=e=>{"hover"===Bp()&&Ht?.contains(e.target)&&Pp()},Rp=["pointerover","pointerdown","focusin"];Rp.forEach(t=>e.addEventListener(t,Np));let $p,Hp,Wp=null,Dp=()=>{let e=Hp;Hp=void 0;try{"function"==typeof e&&e()}catch{}},Fp=()=>{let t=Bp(),r="function"==typeof t&&Ht?t:void 0,o=r?Ht:null;if((r!==$p||o!==Wp)&&(Dp(),$p=r,Wp=o,r&&o))try{Hp=r({warm:Pp,micButton:o,mount:e})}catch{}};Fp(),la.push(()=>{Rp.forEach(t=>e.removeEventListener(t,Np)),Dp()}),Ht&&la.push(()=>{Ce(o.voiceRecognition?.provider)?(wa.isVoiceActive()&&wa.toggleVoice(),Ep()):Sp("system")});let Op=R.on("assistant:complete",()=>{Cr.getState().pendingSubmission&&setTimeout(()=>{wa.isStreaming()||function(){let e=Cr.getState().pendingSubmission;e&&(Jr(void 0),ep(e.text,{consumeDraft:!1,pending:e}))}()},0)});la.push(Op);let zp=R.on("assistant:complete",()=>{_s&&(zs.active||zs.manuallyDeactivated||("assistant"!==_s||zs.lastUserMessageWasVoice)&&setTimeout(()=>{!zs.active&&!zs.manuallyDeactivated&&(Ce(o.voiceRecognition?.provider)?wa.toggleVoice().then(()=>{zs.active=wa.isVoiceActive(),Js("auto"),wa.isVoiceActive()&&Mp()}):Cp("auto"))},600))});la.push(zp);let qp=R.on("action:resubmit",()=>{setTimeout(()=>{wa&&!wa.isStreaming()&&wa.continueConversation()},100)});la.push(qp);let jp=()=>{Fl(!le,"user")},_p=null,Up=null;if(Q&&!ae()){let{instance:e,element:t}=ml({config:o,plugins:p,onToggle:jp});_p=e,e||(Up=t)}_p?e.appendChild(_p.element):Up&&e.appendChild(Up),Hl(),Na(),Sd(),Cd(),Kl(wa.isStreaming()),Gi()||("follow"===Ut()?Wi(!0):ji()),(()=>{if(!1===o.voiceRecognition?.enabled)return;let e=xc(W.voiceState),t=!!e.active,r=Number(e.timestamp??0);zs.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-r<3e4&&setTimeout(()=>{zs.active||(zs.manuallyDeactivated=!1,Ce(o.voiceRecognition?.provider)?wa.toggleVoice().then(()=>{zs.active=Us(),Js("restore"),zs.active?Mp():(Gs(),Gc("Tap the mic to resume your voice call",1e4))}):Cp("restore"))},Ce(o.voiceRecognition?.provider)?0:1e3)})(),Z&&(!Q||ae()?setTimeout(()=>Yl(),0):le&&setTimeout(()=>Yl(),200));let Vp=null,Kp=()=>{Vp&&(Vp.disconnect(),Vp.observe(Tt),Vp.observe(it),Vp.observe(yt))},Jp=pr(),Gp=()=>{if(ae())return fr(),void Hl();let t=Ys(o),r=o.launcher?.sidebarMode??!1,n=e.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,s=o.launcher?.mobileBreakpoint??640,i=n.innerWidth<=s,l=a&&i&&Q;try{if(l)return _o(),void(Vo=Xn());let e=!1;ne&&(ne=!1,_o(),e=!0);let n=Xn();if(!e&&n!==Vo&&(_o(),e=!0),Vo=n,e&&Tn(),!Q&&!t)return ot.style.height="",void(ot.style.width="");if(!r&&!t){let e=ol(o);ot.style.width=e.width,ot.style.maxWidth=e.maxWidth}Wn(),ia()}finally{fr(),br();let t=pr();if(t!==Jp&&(Jp=t,gd(),Na()),Hl(),le&&Q){let t=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),r=o.launcher?.sidebarMode??!1,n=o.launcher?.mobileFullscreen??!0,a=Ys(o)&&n&&t,s=r||n&&t&&Q||a;if(s&&!ca){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&!da&&(da=js(r,o.launcher?.zIndex??1e5)),ca=Vs(e.ownerDocument)}else s||(da?.(),da=null,ca?.(),ca=null)}}};Gp();let Xp=e.ownerDocument.defaultView??window;if(Xp.addEventListener("resize",Gp),la.push(()=>Xp.removeEventListener("resize",Gp)),typeof ResizeObserver<"u"){Vp=new ResizeObserver(()=>{br()}),Kp(),la.push(()=>{Vp?.disconnect(),Vp=null});let e=new ResizeObserver(()=>{$c()});e.observe(it),la.push(()=>e.disconnect())}Xp.addEventListener("resize",$c),la.push(()=>Xp.removeEventListener("resize",$c)),ts=lt.scrollTop;let Qp=cs(lt),Yp=()=>{oa();let e=lt.scrollTop,t=cs(lt),r=t<Qp;if(Qp=t,!Vt())return ts=e,void Ni();let{action:o,nextLastScrollTop:n}=function(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:l=!0,resumeRequiresDownwardScroll:d=!1}=e,c=r-o;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:r}:!t&&n&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:r}:t&&i&&c<0||t&&l&&!n?{action:"pause",delta:c,nextLastScrollTop:r}:{action:"none",delta:c,nextLastScrollTop:r}}({following:es.isFollowing(),currentScrollTop:e,lastScrollTop:ts,nearBottom:ps(lt,24),userScrollThreshold:4,isAutoScrolling:ns||is||r,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});ts=n,"resume"===o?Ui()||Hi():"pause"===o&&Ri()};if(lt.addEventListener("scroll",Yp,{passive:!0}),la.push(()=>lt.removeEventListener("scroll",Yp)),typeof ResizeObserver<"u"){let e=new ResizeObserver(()=>{(()=>{if(Vt()){if(!es.isFollowing()||ps(lt,1))return;Wi(!$a)}else{if(ms&&ms.initialSpacerHeight>0){let e=lt.scrollHeight-ms.spacerHeight,t=function(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}({initialSpacerHeight:ms.initialSpacerHeight,contentHeightAtAnchor:ms.contentHeightAtAnchor,currentContentHeight:e});t!==ms.spacerHeight&&Yi(t)}Ni()}})(),Ze(dt)});e.observe(dt),e.observe(lt),la.push(()=>e.disconnect())}let Zp=()=>{Vt()&&es.isFollowing()&&Ui()&&Ri()},eu=lt.ownerDocument;eu.addEventListener("selectionchange",Zp),la.push(()=>{eu.removeEventListener("selectionchange",Zp)});let tu=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),ru=e=>{tu.has(e.key)&&(Ts(),Xt()&&Vt()&&es.isFollowing()&&Ri())},ou=e=>{e.target?.closest("a, button, [tabindex], input, textarea, select")&&(Ts(),Xt()&&Vt()&&es.isFollowing()&&Ri())};lt.addEventListener("keydown",ru),lt.addEventListener("focusin",ou),la.push(()=>{lt.removeEventListener("keydown",ru),lt.removeEventListener("focusin",ou)});let nu=e=>{if(0!==e.deltaY&&Ts(),!Vt())return;let t=function(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}({following:es.isFollowing(),deltaY:e.deltaY,nearBottom:ps(lt,24),resumeWhenNearBottom:!0});"pause"===t?Ri():"resume"===t&&!Ui()&&Hi()};lt.addEventListener("wheel",nu,{passive:!0}),lt.addEventListener("touchmove",Ts,{passive:!0}),lt.addEventListener("pointerdown",Ts,{passive:!0}),la.push(()=>{lt.removeEventListener("touchmove",Ts),lt.removeEventListener("pointerdown",Ts)}),la.push(()=>lt.removeEventListener("wheel",nu)),tr.addEventListener("click",()=>{rl(),lt.scrollTop=lt.scrollHeight,ts=lt.scrollTop,Hi(),Wi(!0),Ni()}),la.push(()=>tr.remove()),la.push(()=>{ki(),rl()});let au=()=>{St&&(xa&&=(St.removeEventListener("click",xa),null),ie()?(St.style.display="",xa=()=>{Fl(!1,"user")},St.addEventListener("click",xa)):St.style.display="none")};au(),(()=>{let{clearChatButton:e}=st;e&&e.addEventListener("click",()=>{let e=oc;if(e?.historyAvailable())return void e.startNewConversation({focusComposer:!0}).catch(e=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",e)});wa.clearMessages(),o.layout?.topFade&&(lt.scrollTop=0),lt.removeAttribute("data-persona-top-fade"),Ha.clear(),Hi(),jt(st.composerOverlay);try{localStorage.removeItem(gc),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${gc}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==gc)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.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),$?.clear&&ii(()=>$.clear(),"[AgentWidget] Failed to clear storage adapter:"),W={},X.syncFromMetadata(),wr?.clearAttachments(),wi(),Jr(void 0),qr(void 0),Qa(),Te?.clear(),Be?.reset(),$e?.update()})})();let su=[["keydown",e=>{if(ht&&!zl()&&(e.isComposing||!xr?.handleKeydown(e))){if(!(!1===o.features?.composerHistory||"ArrowUp"!==e.key&&"ArrowDown"!==e.key||e.shiftKey||e.metaKey||e.ctrlKey||e.altKey||e.isComposing)){let t=0===ht.selectionStart&&0===ht.selectionEnd,r=function(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=-1!==a.index;if(0===r.length)return{handled:!1,state:a};if("up"===t){if(!s&&!n)return{handled:!1,state:a};if(!s){let e=r.length-1;return{handled:!0,value:r[e],state:{index:e,draft:o}}}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:ht.value,atStart:t,state:rp});if(rp=r.state,r.handled)return e.preventDefault(),void(void 0!==r.value&&(e=>{if(!ht)return;op=!0,ht.value=e,ht.dispatchEvent(new Event("input",{bubbles:!0})),op=!1;let t=ht.value.length;ht.setSelectionRange(t,t)})(r.value))}if(rn(e,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:en(ht)}))if(wa.isStreaming()){if(e.preventDefault(),"block"===_r()||Uc||jl())return;np(),Yc()}else Uc||jl()?e.preventDefault():(np(),e.preventDefault(),mt.click())}}],["input",e=>{op||(e.isComposing||xr?.handleInput(e.inputType??void 0),np())}],["input",kr],["input",Mr],["keyup",Mr],["paste",async e=>{if(!0!==o.attachments?.enabled||!wr||zl())return;let t=vc(e.clipboardData);0!==t.length&&(e.preventDefault(),await wr.handleFiles(t))}],["focus",()=>xr?.prefetch()]],iu=e=>{if(e)for(let[t,r]of su)co?.addListener(e,t,r)},lu=()=>{co&&(co.addListener(co.form,"submit",tp),co.addListener(co.footer,"click",Mr),iu(ht),Ht&&co.addListener(Ht,"click",Lp),Fp())};lu();let du=()=>{xr?.onComposerSwap((e,t)=>{(e=>{if(e)for(let[t,r]of su)co?.removeListener(e,t,r)})(t),ht=e,co&&(co.input=e),iu(e),po(),Vl(),kr()})};du();let cu=!1;function pu(){if(!cu){cu=!0;try{let e=ht?.value??"",t=Tt.ownerDocument??document,r=!!ht&&t.activeElement===ht;wp(),co?.destroy(),co=null,xr?.destroy(),xr=null;let n=null,a=()=>(n=ae()?Ei({config:o}):Ii({config:o}),n.footer),s=ao(a)??a();tt.replaceComposer(s),Tt=tt.composer.footer;let i=null!==n&&s===n.footer;oo=!i,$t=i?n.setSendButtonMode:()=>{},ro(Tt),uo(Tt),mo(),go(),fo(),du(),Co(),So(),ko(),lu();let l=va.indexOf(fa);if(fa.destroy(),fa=ai(ut),l>=0&&(va[l]=fa),ht&&(ht.value=e),kr(),Mr(),Sd(),Na(),Kl(wa.isStreaming()),"transient"===o.statusIndicator?.mode&&!ae()){let e=wa.getStatus();et(ft,Ye(e),o.statusIndicator,e)}zs.active&&pp("recording"),_o(),Kp(),fr(),Io(),Ul(),r&&ht?.focus()}finally{cu=!1}}}let uu=e.ownerDocument??document;uu.addEventListener("keydown",ap,!0);let hu=()=>{bi()},mu=()=>{"hidden"===uu.visibilityState&&bi()};typeof window<"u"&&(window.addEventListener("pagehide",hu),uu.addEventListener("visibilitychange",mu),la.push(()=>{window.removeEventListener("pagehide",hu),uu.removeEventListener("visibilitychange",mu)}));let gu="persona-attachment-drop-active",fu=0,yu=()=>{fu=0,it.classList.remove(gu)},bu=()=>!0===o.attachments?.enabled&&null!==wr&&!zl(),vu=e=>{wc(e.dataTransfer)&&bu()&&(fu++,1===fu&&it.classList.add(gu))},wu=e=>{wc(e.dataTransfer)&&bu()&&(fu--,fu<=0&&yu())},xu=e=>{wc(e.dataTransfer)&&bu()&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},Cu=e=>{if(!wc(e.dataTransfer)||!bu())return;e.preventDefault(),e.stopPropagation(),yu();let t=Array.from(e.dataTransfer.files??[]);0!==t.length&&wr.handleFiles(t)};it.addEventListener("dragenter",vu,!0),it.addEventListener("dragleave",wu,!0),e.addEventListener("dragover",xu,!0),e.addEventListener("drop",Cu,!0);let Su=e.ownerDocument,ku=e=>{bu()&&e.preventDefault()},Au=e=>{bu()&&e.preventDefault()};Su.addEventListener("dragover",ku),Su.addEventListener("drop",Au),la.push(()=>{co?.destroy(),co=null,wp(),yo?.destroy(),yo=null,Dr?.destroy(),Dr=null,zr?.destroy(),zr=null,Kr?.destroy(),Kr=null,Hr=null,Wr=null,bi(),mi.destroy(),Jc&&clearTimeout(Jc),Qa(),Vc?.abort(),Vc=null,wr?.destroy(),wr=null,Cr.destroy(),uu.removeEventListener("keydown",ap,!0),xr?.destroy()}),la.push(()=>{it.removeEventListener("dragenter",vu,!0),it.removeEventListener("dragleave",wu,!0),e.removeEventListener("dragover",xu,!0),e.removeEventListener("drop",Cu,!0),Su.removeEventListener("dragover",ku),Su.removeEventListener("drop",Au),yu()}),la.push(()=>{wa.cancel()}),_p?la.push(()=>{_p?.destroy()}):Up&&la.push(()=>{Up?.remove()});let Mu={update(t){let r=!0===o.future?.v5Defaults,n=o.toolCall,a=o.messageActions,s=o.layout?.messages,i=o.colorScheme,l=o.loadingIndicator,u=o.iterationDisplay,h=o.features?.showReasoning,f=o.features?.showToolCalls,y=o.features?.toolCallDisplay,b=o.features?.reasoningDisplay,v=o.features?.streamAnimation?.type,w=!0===o.features?.history?.enabled,x=o.features?.history?.provider,C=o.getIdentityProof,S=o.clientToken,k=o.contextMentions;o=Wd({...o,features:c},t),c=o.features,o=kd(o),d(),Zn(),_a(e,o),rd(e,o),od(e,o),Ve(),Yn(),o.colorScheme!==i&&ua();let A=Nd.getForInstance(o.plugins);p.length=0,p.push(...A),Ic(),Q=o.launcher?.enabled??!0,Y=o.launcher?.autoExpand??!1,he=o.features?.showReasoning??!0,me=o.features?.showToolCalls??!0,be=o.features?.scrollToBottom??{};let M=Ut();Se=o.features?.scrollBehavior??{},M!==Ut()&&(rl(),Hi()),Ps(),vr(),Ni();let I=ge;if(ge=o.features?.showEventStreamToggle??!1,ge&&!I){if(Te||(qe(),wa.setSSEEventCallback((e,t)=>{o.onSSEEvent?.(e,t),ze(e,t)})),!to&&It){let e=o.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:"");to=q("button",t),to.style.width="28px",to.style.height="28px",to.style.color=hi.actionIconColor,to.type="button",to.setAttribute("aria-label","Event Stream"),to.title="Event Stream";let r=g(m.Activity,"18px","currentColor",1.5);r&&to.appendChild(r);let n=st.clearChatButtonWrapper,a=st.closeButtonWrapper,s=n||a;s&&s.parentNode===It?It.insertBefore(to,s):It.appendChild(to),to.addEventListener("click",()=>{We?eo():Zr()})}}else!ge&&I&&(eo(),to&&=(to.remove(),null),Te?.clear(),Me?.destroy(),Te=null,Me=null,Be?.reset(),Be=null,Ne=null);if(!1===o.launcher?.enabled&&_p&&(_p.destroy(),_p=null),!1===o.launcher?.enabled&&Up&&(Up.remove(),Up=null),!1!==o.launcher?.enabled&&!_p&&!Up){let{instance:t,element:r}=ml({config:o,plugins:p,onToggle:jp});_p=t,t||(Up=r),e.appendChild(r)}_p&&_p.update(o),Lc(),Mt&&void 0!==o.launcher?.subtitle&&(Mt.textContent=o.launcher.subtitle);let T=o.layout?.header;if(T?.layout!==re&&It){let e=T?Mi(o,T,{showClose:ie(),onClose:()=>Fl(!1,"user")}):fi({config:o,showClose:ie(),onClose:()=>Fl(!1,"user")});tt.replaceHeader(e),It=tt.header.element,kt=tt.header.iconHolder,At=tt.header.headerTitle,Mt=tt.header.headerSubtitle,St=tt.header.closeButton,re=T?.layout,Lc()}else if(T){if(kt&&(kt.style.display=!1===T.showIcon?"none":""),At&&(At.style.display=!1===T.showTitle?"none":""),Mt&&(Mt.style.display=!1===T.showSubtitle?"none":""),St){let e=ie()&&!1!==T.showCloseButton;St.style.display=e?"":"none"}if(st.clearChatButtonWrapper){let e=T.showClearChat;if(void 0!==e){st.clearChatButtonWrapper.style.display=e?"":"none";let{closeButtonWrapper:t}=st;t&&!t.classList.contains("persona-absolute")&&(e?t.classList.remove("persona-ml-auto"):t.classList.add("persona-ml-auto"))}}}let E=!1!==o.layout?.showHeader;It&&(It.style.display=E?"":"none");let L=!1!==o.layout?.showFooter;Tt&&(Tt.style.display=L?"":"none"),fr(),Ni(),Q===te?Y!==ee&&Fl(Y,"auto"):Q?Fl(Y,"auto"):(le=!0,Hl()),ee=Y,te=Q,Gp(),au();let P=JSON.stringify(o.toolCall)!==JSON.stringify(n),B=JSON.stringify(o.messageActions)!==JSON.stringify(a),N=JSON.stringify(o.layout?.messages)!==JSON.stringify(s),$=o.loadingIndicator?.render!==l?.render||o.loadingIndicator?.renderIdle!==l?.renderIdle||o.loadingIndicator?.showBubble!==l?.showBubble,H=o.iterationDisplay!==u,W=(o.features?.showReasoning??!0)!==(h??!0)||(o.features?.showToolCalls??!0)!==(f??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(y)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(b);(!0===o.future?.v5Defaults!==r||P||B||N||$||H||W)&&wa&&(Ya++,wl(dt,wa.getMessages(),ue));let D=o.features?.streamAnimation?.type;if(D!==v&&D&&"none"!==D){let t=ma(D,o.features?.streamAnimation?.plugins);t&&Ds(t,e)}let F=o.launcher??{},O=F.headerIconHidden??!1,z=o.layout?.header?.showIcon,j=O||!1===z,_=F.headerIconName,U=F.headerIconSize??"40px";if(kt){let e=It,t=e?.querySelector(".persona-flex-col");if(j)kt.style.display="none",e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(kt.style.display="",kt.style.height=U,kt.style.width=U,e&&t&&(e.contains(kt)?kt.nextSibling!==t&&(kt.remove(),e.insertBefore(kt,t)):e.insertBefore(kt,t)),_){let e=parseFloat(U)||24,t=se(_,.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))`,kt.replaceChildren(t)):kt.textContent=F.agentIconText??"💬"}else if(F.iconUrl){let e=kt.querySelector("img");if(e)e.src=F.iconUrl,e.style.height=U,e.style.width=U;else{let e=document.createElement("img");e.src=F.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=U,e.style.width=U,kt.replaceChildren(e)}}else{let e=kt.querySelector("svg"),t=kt.querySelector("img");(e||t)&&kt.replaceChildren(),kt.textContent=F.agentIconText??"💬"}let r=kt.querySelector("img");r&&(r.style.height=U,r.style.width=U)}}let J=o.layout?.header?.showTitle,G=o.layout?.header?.showSubtitle;if(At&&(At.style.display=!1===J?"none":""),Mt&&(Mt.style.display=!1===G?"none":""),St){let e=ie()&&!1!==o.layout?.header?.showCloseButton;if(St.style.display=e?"":"none",!ae()){let e=F.closeButtonSize??"";St.style.height=e,St.style.width=e,St.style.minWidth=e,St.style.minHeight=e}let t=F.closeButtonPlacement??"inline",{closeButtonWrapper:r}=st,n="top-right"===t,a=r?.classList.contains("persona-absolute");if(r&&n!==a)if(r.remove(),n){r.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let e=oc?.railColumn??it;e.style.position="relative",e.appendChild(r)}else{let e=F.clearChat?.placement??"inline";r.className=(F.clearChat?.enabled??1)&&"inline"===e?"":"persona-ml-auto",It&&It.appendChild(r)}if(St.style.color=F.closeButtonColor||hi.actionIconColor,F.closeButtonBackgroundColor?(St.style.backgroundColor=F.closeButtonBackgroundColor,St.classList.remove("hover:persona-bg-gray-100")):(St.style.backgroundColor="",St.classList.add("hover:persona-bg-gray-100")),F.closeButtonBorderWidth||F.closeButtonBorderColor){let e=F.closeButtonBorderWidth||"0px",t=F.closeButtonBorderColor||"transparent";St.style.border=`${e} solid ${t}`,St.classList.remove("persona-border-none")}else St.style.border="",St.classList.add("persona-border-none");F.closeButtonBorderRadius?(St.style.borderRadius=F.closeButtonBorderRadius,St.classList.remove("persona-rounded-full")):(St.style.borderRadius="",St.classList.add("persona-rounded-full")),F.closeButtonPaddingX?(St.style.paddingLeft=F.closeButtonPaddingX,St.style.paddingRight=F.closeButtonPaddingX):(St.style.paddingLeft="",St.style.paddingRight=""),F.closeButtonPaddingY?(St.style.paddingTop=F.closeButtonPaddingY,St.style.paddingBottom=F.closeButtonPaddingY):(St.style.paddingTop="",St.style.paddingBottom=""),di(St,F.closeButtonIconName??"x",{iconSize:ae()?al:void 0,iconText:F.closeButtonIconText??"×"});let s=F.closeButtonTooltipText??"Close chat",i=F.closeButtonShowTooltip??!0;St.setAttribute("aria-label",s),r&&Xo({anchor:St,trigger:r,text:()=>St?.getAttribute("aria-label")??s,enabled:i})}let{clearChatButton:Z,clearChatButtonWrapper:oe}=st;if(Z){let e=F.clearChat??{},t=e.enabled??!0,r=o.layout?.header?.showClearChat,n=void 0===r?t:r,a=e.placement??"inline";if(oe){oe.style.display=n?"":"none";let{closeButtonWrapper:e}=st;!ae()&&e&&!e.classList.contains("persona-absolute")&&(n?e.classList.remove("persona-ml-auto"):e.classList.add("persona-ml-auto"));let t="top-right"===a,r=oe.classList.contains("persona-absolute");if(!ae()&&t!==r&&n){if(oe.remove(),t){oe.className="persona-absolute persona-top-4 persona-z-50",oe.style.right="48px";let e=oc?.railColumn??it;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=st.closeButtonWrapper;It&&e&&e.parentElement===It?It.insertBefore(oe,e):It&&It.appendChild(oe)}let e=st.closeButtonWrapper;e&&!e.classList.contains("persona-absolute")&&(t?e.classList.add("persona-ml-auto"):e.classList.remove("persona-ml-auto"))}}if(n){if(!ae()){let t=e.size??"";Z.style.height=t,Z.style.width=t,Z.style.minWidth=t,Z.style.minHeight=t}let t=e.iconColor??"";if(Z.style.color=t||hi.actionIconColor,di(Z,e.iconName??"refresh-cw",{iconSize:ae()?sl:void 0}),e.backgroundColor?(Z.style.backgroundColor=e.backgroundColor,Z.classList.remove("hover:persona-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:persona-bg-gray-100")),e.borderWidth||e.borderColor){let t=e.borderWidth||"0px",r=e.borderColor||"transparent";Z.style.border=`${t} solid ${r}`,Z.classList.remove("persona-border-none")}else Z.style.border="",Z.classList.add("persona-border-none");e.borderRadius?(Z.style.borderRadius=e.borderRadius,Z.classList.remove("persona-rounded-full")):(Z.style.borderRadius="",Z.classList.add("persona-rounded-full")),e.paddingX?(Z.style.paddingLeft=e.paddingX,Z.style.paddingRight=e.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),e.paddingY?(Z.style.paddingTop=e.paddingY,Z.style.paddingBottom=e.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let r=e.tooltipText??"Clear chat",o=e.showTooltip??!0;Z.setAttribute("aria-label",r),oe&&Xo({anchor:Z,trigger:oe,text:()=>Z?.getAttribute("aria-label")??r,enabled:o})}}let ne=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dd],de=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Od.message,Od.messageAndClick];X=qd({parsers:ne,handlers:de,getSessionMetadata:V,updateSessionMetadata:K,emit:R.emit,documentRef:typeof document<"u"?document:null}),ue=Sc(o,X,pe),zd(),wa.updateConfig(o),qc(),(!0===o.features?.history?.enabled!==w||o.features?.history?.provider!==x||o.getIdentityProof!==C||o.clientToken!==S)&&(oc?.closeHistory({restoreFocus:!1}),oc?.installHistoryProvider()),oc?.syncHistoryChromeImpl(),$c(),bc()&&!oc&&Nc().catch(()=>{}),wl(dt,wa.getMessages(),ue),Na(),Sd(),(()=>{let e=ur();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`!==vd||e.icon!==dd)&&Cd()})(),Kl(wa.isStreaming()),k!==o.contextMentions&&pu();let ce=!0===o.voiceRecognition?.enabled,fe=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),ye=Ce(o.voiceRecognition?.provider);if(ce&&(fe||ye))if(Ht&&Wt){let e=o.voiceRecognition??{},t=o.sendButton??{},r=e.iconName??"mic",n=e.iconSize,a=parseFloat(n??"")||24;Ht.classList.add(sn),Ht.classList.toggle(ln,!n),Ht.style.width=n??"",Ht.style.height=n??"",Ht.style.minWidth=n??"",Ht.style.minHeight=n??"";let s=e.iconColor??t.textColor;Ht.innerHTML="";let i=se(r,a,s||"currentColor",1.5);i?Ht.appendChild(i):Ht.textContent="🎤";let l=e.backgroundColor??t.backgroundColor;Ht.style.backgroundColor=l||"",Ht.style.color=s||"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),Wt&&Xo({anchor:Ht,trigger:Wt,text:()=>Ht?.getAttribute("aria-label")??d,enabled:c}),Wt.style.display="",Ht.disabled=zl()||wa.isStreaming()&&!ql()}else{let e=hn(o);if(e){Ht=e.button,Wt=e.wrapper;let t=Rt&&Rt.parentElement===Nt?Rt:null;Nt?Nt.insertBefore(Wt,t):gt?.appendChild(Wt),co&&(co.micButton=Ht),co?.addListener(Ht,"click",Lp),Ht.disabled=zl()||wa.isStreaming()&&!ql()}}else Ht&&Wt&&(Wt.style.display="none",Ce(o.voiceRecognition?.provider)?wa.isVoiceActive()&&wa.toggleVoice():ip&&Sp());if(Fp(),!0===o.attachments?.enabled){if(Ft&&Dt){Ft.style.display="";let e=o.attachments??{};Ot&&(Ot.accept=(e.allowedTypes??Ar).join(","),Ot.multiple=(e.maxFiles??4)>1),wr&&wr.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}else{let e=o.attachments??{};zt||(zt=q("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),zt.style.display="none",(ht.parentElement??gt).insertBefore(zt,ht)),Ot||(Ot=document.createElement("input"),Ot.type="file",Ot.accept=(e.allowedTypes??Ar).join(","),Ot.multiple=(e.maxFiles??4)>1,Ot.style.display="none",Ot.setAttribute("aria-label","Attach files"),(ht.parentElement??gt).insertBefore(Ot,ht)),Ft=q("div","persona-send-button-wrapper"),Dt=q("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${sn} ${ln}`),Dt.type="button",Dt.setAttribute("aria-label",e.buttonTooltipText??"Attach file");let t=e.buttonIconName??"paperclip";Dt.style.fontSize="18px",Dt.style.lineHeight="1";let r=se(t,24,"currentColor",1.5);r?Dt.appendChild(r):Dt.textContent="📎",Dt.addEventListener("click",e=>{e.preventDefault(),Ot?.click()}),Ft.appendChild(Dt);let n=e.buttonTooltipText??"Attach file";Xo({anchor:Dt,trigger:Ft,text:()=>Dt?.getAttribute("aria-label")??n}),Bt?Bt.append(Ft):gt.appendChild(Ft),co&&(co.attachmentButton=Dt,co.attachmentInput=Ot??void 0,co.attachmentPreviews=zt??void 0),!wr&&Ot&&zt&&(wr=$o.fromConfig(e,Tr),wr.setPreviewsContainer(zt),co?.addListener(Ot,"change",async()=>{wr&&Ot?.files&&(await wr.handleFileSelect(Ot.files),Ot.value="")}))}if(it.querySelector(".persona-attachment-drop-overlay")?.remove(),it.appendChild(kc(o.attachments?.dropOverlay)),Dt){let e=o.attachments??{},t=e.buttonTooltipText??"Attach file";Dt.setAttribute("aria-label",t),Dt.textContent="";let r=se(e.buttonIconName??"paperclip",24,"currentColor",1.5);r?Dt.appendChild(r):Dt.textContent="📎",Ft&&Xo({anchor:Dt,trigger:Ft,text:()=>Dt?.getAttribute("aria-label")??t})}}else Ft&&(Ft.style.display="none"),wr&&wr.clearAttachments(),it.querySelector(".persona-attachment-drop-overlay")?.remove();let ve=o.sendButton??{},ke=ve.useIcon??!1,Ae=ve.iconText??"↑",Ie=ve.iconName,Ee=ve.tooltipText??"Send message",Le=ve.showTooltip??!1,Pe=ve.size,Re=parseFloat(Pe??"")||40,$e=ve.backgroundColor,He=ve.textColor;if(ke){if(mt.style.width=Pe??"",mt.style.height=Pe??"",mt.style.minWidth=Pe??"",mt.style.minHeight=Pe??"",mt.style.fontSize="18px",mt.style.lineHeight="1",mt.style.color=He||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!wa.isStreaming())if(mt.innerHTML="",Ie){let e=parseFloat(ve.iconSize??"")||Math.round(.5*Re),t=He?.trim()||"currentColor",r=ve.iconStrokeWidth??2,o=se(Ie,e,t,r),n=se(ve.stopIconName??"square",e,t,r);o&&n?mt.appendChild(pn(o,n)):o?mt.appendChild(o):mt.textContent=Ae}else mt.textContent=Ae;mt.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${sn}`,$e?(mt.style.backgroundColor=$e,mt.classList.remove("persona-bg-persona-primary")):(mt.style.backgroundColor="",mt.classList.add("persona-bg-persona-primary"))}else mt.textContent=o.copy?.sendButtonLabel??"Send",mt.style.width="",mt.style.height="",mt.style.minWidth="",mt.style.minHeight="",mt.style.fontSize="",mt.style.lineHeight="",mt.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?(mt.style.backgroundColor=$e,mt.classList.remove("persona-bg-persona-accent")):mt.classList.add("persona-bg-persona-accent"),He?mt.style.color=He:mt.classList.add("persona-text-white");ve.borderWidth?(mt.style.borderWidth=ve.borderWidth,mt.style.borderStyle="solid"):(mt.style.borderWidth="",mt.style.borderStyle=""),ve.borderColor?mt.style.borderColor=ve.borderColor:mt.style.borderColor="",ve.paddingX?(mt.style.paddingLeft=ve.paddingX,mt.style.paddingRight=ve.paddingX):(mt.style.paddingLeft="",mt.style.paddingRight=""),ve.paddingY?(mt.style.paddingTop=ve.paddingY,mt.style.paddingBottom=ve.paddingY):(mt.style.paddingTop="",mt.style.paddingBottom=""),wa.isStreaming()||mt.setAttribute("aria-label",Ee),Ul(),Rt&&Xo({anchor:mt,trigger:Rt,text:()=>mt.getAttribute("aria-label")??Ee,enabled:Le}),To(),na();let De=_n(Cr.getState().activeModeIds,o.composer?.modes);Cr.setActiveModeIds(De),Lr().length>0!=!!Dr&&So(),Dr?.render(De,Lr());for(let e of[...Or.keys()])jn(e,o.composer?.modeGroups)||Or.delete(e);Or.forEach(e=>e.repaint()),Hr?.repaint(),yo?.resolve();let Fe=Va(o,ae());if(ea(),Fe){dt.style.maxWidth=Fe,dt.style.marginLeft="auto",dt.style.marginRight="auto",dt.style.width="100%",vt.style.maxWidth=Fe,vt.style.marginLeft="auto",vt.style.marginRight="auto",vt.style.width="100%";for(let e of[gt,ut,zt,ft])e&&(e.style.maxWidth=Fe,e.style.marginLeft="auto",e.style.marginRight="auto",e.style.width="100%")}else{dt.style.maxWidth="",dt.style.marginLeft="",dt.style.marginRight="",dt.style.width="",vt.style.maxWidth="",vt.style.marginLeft="",vt.style.marginRight="",vt.style.width="";for(let e of[gt,ut,zt,ft])e&&(e.style.maxWidth="",e.style.marginLeft="",e.style.marginRight="",e.style.width="")}let Oe=o.statusIndicator??{};if(xe(ft,gt,Oe),we(ft,Oe,wa?.getStatus()??"idle"),wa){let e=wa.getStatus();et(ft,(e=>"idle"===e?Oe.idleText??Pr.idle:"connecting"===e?Oe.connectingText??Pr.connecting:"connected"===e?Oe.connectedText??Pr.connected:"error"===e?Oe.errorText??Pr.error:"paused"===e?Oe.pausedText??Pr.paused:"resuming"===e?Oe.resumingText??Pr.resuming:Pr[e])(e),Oe,e)}ft.classList.remove("persona-text-left","persona-text-center","persona-text-right");let je="left"===Oe.align?"persona-text-left":"center"===Oe.align?"persona-text-center":"persona-text-right";ft.classList.add(je),po(),Vl(),Io(),Ue()},open(){ie()&&Fl(!0,"api")},close(){ie()&&Fl(!1,"api")},toggle(){ie()&&Fl(!le,"api")},reconnect(){wa.reconnectNow()},clearChat(){Go=!1,i.clear(),n.clear(),s.clear(),l.clear(),wa.clearMessages(),o.layout?.topFade&&(lt.scrollTop=0),lt.removeAttribute("data-persona-top-fade"),Ha.clear(),Hi();try{localStorage.removeItem(gc),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${gc}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==gc)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.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),$?.clear&&ii(()=>$.clear(),"[AgentWidget] Failed to clear storage adapter:"),W={},X.syncFromMetadata(),wr?.clearAttachments(),wi(),Jr(void 0),qr(void 0),Qa(),Te?.clear(),Be?.reset(),$e?.update()},setMessage:e=>!(!ht||wa.isStreaming()||zl()||(!le&&ie()&&Fl(!0,"system"),ht.value=e,ht.dispatchEvent(new Event("input",{bubbles:!0})),0)),submitMessage(e){if(wa.isStreaming()||jl())return!1;let t=e?.trim()||ht.value.trim();return!!t&&(!le&&ie()&&Fl(!0,"system"),ht.value="",ht.style.height="auto",kr(),ep(t,{consumeDraft:!1}),!0)},getComposerState:()=>Cr.getState(),setQuote(e){let t=e?.text?.trim();t&&qr({...e,text:t})},clearQuote(){qr(void 0)},startVoiceRecognition:()=>!wa.isStreaming()&&(Ce(o.voiceRecognition?.provider)?(wa.isVoiceActive()||wa.isBargeInActive()||(!le&&ie()&&Fl(!0,"system"),zs.manuallyDeactivated=!1,Gs(),wa.toggleVoice().then(()=>{zs.active=Us(),Gs(),Js("user"),zs.active&&Mp()})),!0):!!ip||!!xp()&&(!le&&ie()&&Fl(!0,"system"),zs.manuallyDeactivated=!1,Gs(),Cp("user"),!0)),stopVoiceRecognition:()=>Ce(o.voiceRecognition?.provider)?!(!wa.isVoiceActive()&&!wa.isBargeInActive()||((wa.isBargeInActive()?wa.deactivateBargeIn():wa.toggleVoice()).then(()=>{zs.active=!1,zs.manuallyDeactivated=!0,Gs(),Js("user"),Ep()}),0)):!!ip&&(zs.manuallyDeactivated=!0,Gs(),Sp("user"),!0),injectMessage:e=>(!le&&ie()&&Fl(!0,"system"),wa.injectMessage(e)),injectAssistantMessage(e){!le&&ie()&&Fl(!0,"system");let t=wa.injectAssistantMessage(e);return de&&(de=!1,ce&&=(clearTimeout(ce),null),setTimeout(()=>{wa&&!wa.isStreaming()&&wa.continueConversation()},100)),t},injectUserMessage:e=>(!le&&ie()&&Fl(!0,"system"),wa.injectUserMessage(e)),injectSystemMessage:e=>(!le&&ie()&&Fl(!0,"system"),wa.injectSystemMessage(e)),injectMessageBatch:e=>(!le&&ie()&&Fl(!0,"system"),wa.injectMessageBatch(e)),injectComponentDirective:e=>(!le&&ie()&&Fl(!0,"system"),wa.injectComponentDirective(e)),injectTestMessage(e){!le&&ie()&&Fl(!0,"system"),wa.injectTestEvent(e)},connectStream:async(e,t)=>wa.connectStream(e,t),__pushEventStreamEvent(e){ge&&(qe(),ze(e.type,e.payload))},showEventStream(){ge&&Zr()},hideEventStream(){We&&eo()},isEventStreamVisible:()=>We,listConversations:e=>wa.listConversations(e),getActiveConversationId:()=>wa.getActiveConversationId(),openConversation:(e,t)=>Rc(r=>r.openHistoryConversation(e,{focusComposer:!0===t?.focus})),startNewConversation:e=>Rc(t=>t.startNewConversation({focusComposer:!0===e?.focus})),warmSession(){Hc()},deleteConversation:e=>Rc(t=>t.deleteHistoryConversation(e)),renameConversation:(e,t)=>Rc(r=>r.updateHistoryConversation(e,{title:t})),setConversationStarred:(e,t)=>Rc(r=>r.updateHistoryConversation(e,{starred:t})),clearConversationHistory:e=>Rc(t=>t.clearConversationHistory(e)),resetHistoryIdentity:()=>Rc(e=>e.resetHistoryIdentity()),async getVisitorToken(){let e=Hd;if(!e)return null;let t=await e.get();return e===Hd?t:null},getHistoryIdentityStatus(){let e=oc?.historyProvider;return e?e.getIdentityStatus():bc()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory:e=>bc()?Rc(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...void 0===e?.focus?{}:{focus:e.focus}})):Promise.resolve(),hideHistory(e){oc?.closeHistory(void 0===e?.restoreFocus?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible:()=>je,showArtifacts(){Ql(o)&&(Go=!1,dn=!0,Yn(),zo?.setMobileOpen(!0))},hideArtifacts(){Ql(o)&&(Go=!0,Yn())},upsertArtifact:e=>Ql(o)?("panel"===no(o.features?.artifacts,{artifactType:e.artifactType,..."markdown"===e.artifactType&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})&&(Go=!1,dn=!0),wa.upsertArtifact(e)):null,selectArtifact(e){Ql(o)&&wa.selectArtifact(e)},clearArtifacts(){Ql(o)&&wa.clearArtifacts()},getArtifacts:()=>wa?.getArtifacts()??[],getSelectedArtifactId:()=>wa?.getSelectedArtifactId()??null,focusInput:()=>!(Q&&!le&&!ae()||!ht||(ht.focus(),0)),async resolveApproval(e,t,r){let o=wa.getMessages().find(t=>"approval"===t.variant&&t.approval?.id===e);if(!o?.approval)throw Error(`Approval not found: ${e}`);if(!u(o.approval))return wa.resolveApproval(o.approval,t,r);wa.resolveWebMcpApproval(o.id,t)},setFollowUpSuggestions(e){(e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length)return void Ra();let r=wa?wa.getMessages():[];Ca=t,Sa=!0,ka=Ia(r),Ma=Ta(r),Na(r)})(e)},clearFollowUpSuggestions(){Ra()},getMessages:()=>wa.getMessages(),getStatus:()=>wa.getStatus(),getPersistentMetadata:()=>({...W}),updatePersistentMetadata(e){K(e)},on:(e,t)=>R.on(e,t),off(e,t){R.off(e,t)},isOpen:()=>ie()&&le,isVoiceActive:()=>zs.active,toggleReadAloud(e){wa.toggleReadAloud(e)},stopReadAloud(){wa.stopSpeaking()},getReadAloudState:e=>wa.getReadAloudState(e),onReadAloudChange:e=>wa.onReadAloudChange(e),getState:()=>({open:ie()&&le,launcherEnabled:Q,voiceActive:zs.active,streaming:wa.isStreaming()}),showCSATFeedback(e){!le&&ie()&&Fl(!0,"system");let t=dt.querySelector(".persona-feedback-container");t&&t.remove();let r=hc({onSubmit:async(t,r)=>{wa.isClientTokenMode()&&await wa.submitCSATFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e});dt.appendChild(r),r.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(e){!le&&ie()&&Fl(!0,"system");let t=dt.querySelector(".persona-feedback-container");t&&t.remove();let r=mc({onSubmit:async(t,r)=>{wa.isClientTokenMode()&&await wa.submitNPSFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e});dt.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(){ec(),null!=jd&&(clearInterval(jd),jd=null),i.clear(),n.clear(),s.clear(),l.clear(),la.forEach(e=>e()),rt.remove(),nt?.remove(),_p?.destroy(),Up?.remove(),xa&&St.removeEventListener("click",xa)}};if((r?.debugTools||o.debug)&&typeof window<"u"){let e=window.AgentWidgetBrowser,t={controller:Mu,getMessages:Mu.getMessages,getStatus:Mu.getStatus,getMetadata:Mu.getPersistentMetadata,updateMetadata:Mu.updatePersistentMetadata,clearHistory:()=>Mu.clearChat(),setVoiceActive:e=>e?Mu.startVoiceRecognition():Mu.stopVoiceRecognition()};window.AgentWidgetBrowser=t,la.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)&&Mu.focusInput()};if(window.addEventListener("persona:focusInput",r),la.push(()=>{window.removeEventListener("persona:focusInput",r)}),ge){let e=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Mu.showEventStream()},r=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Mu.hideEventStream()};window.addEventListener("persona:showEventStream",e),window.addEventListener("persona:hideEventStream",r),la.push(()=>{window.removeEventListener("persona:showEventStream",e),window.removeEventListener("persona:hideEventStream",r)})}let o=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Mu.showHistory()},n=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Mu.hideHistory()};window.addEventListener("persona:showHistory",o),window.addEventListener("persona:hideHistory",n),la.push(()=>{window.removeEventListener("persona:showHistory",o),window.removeEventListener("persona:hideHistory",n)});let a=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Mu.showArtifacts()},s=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Mu.hideArtifacts()},i=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==t||r?.artifact&&Mu.upsertArtifact(r.artifact)},l=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==t||"string"==typeof r?.id&&Mu.selectArtifact(r.id)},d=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Mu.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),la.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 Iu=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}(o.persistState);if(Iu&&ie()){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}}(Iu.storage),r=`${Iu.keyPrefix}widget-open`,o=`${Iu.keyPrefix}widget-voice`,n=`${Iu.keyPrefix}widget-voice-mode`;if(t){let a=Iu.persist?.openState&&"true"===t.getItem(r),s=Iu.persist?.voiceState&&"true"===t.getItem(o),i=Iu.persist?.voiceState&&"true"===t.getItem(n);if(a&&(_p?.setPanelOpen(!0,"auto"),setTimeout(()=>{Mu.open(),setTimeout(()=>{if(s||i)Mu.startVoiceRecognition();else if(Iu.persist?.focusInput){let t=e.querySelector("textarea");t&&t.focus()}},100)},0)),Iu.persist?.openState&&(R.on("widget:opened",()=>{t.setItem(r,"true")}),R.on("widget:closed",()=>{t.setItem(r,"false")})),Iu.persist?.voiceState&&(R.on("voice:state",e=>{t.setItem(o,e.active?"true":"false")}),R.on("user:message",e=>{t.setItem(n,e.viaVoice?"true":"false")})),Iu.clearOnChatClear){let e=()=>{t.removeItem(r),t.removeItem(o),t.removeItem(n)},a=()=>e();window.addEventListener("persona:clear-chat",a),la.push(()=>{window.removeEventListener("persona:clear-chat",a)})}}}if(_&&ie()&&(_p?.setPanelOpen(!0,"auto"),setTimeout(()=>{Mu.open()},0)),$l(),!Za){let e=Le(()=>{wa&&(Ya++,Ha.clear(),wl(dt,wa.getMessages(),ue))});la.push(e)}k=()=>{wa&&(Ya++,Ha.clear(),wl(dt,wa.getMessages(),ue))},wa.getMessages().length>0&&vl(),L=()=>{wa&&(Ya++,Ha.clear(),wl(dt,wa.getMessages(),ue))};let Tu=oe(()=>{wa&&(Ya++,Ha.clear(),wl(dt,wa.getMessages(),ue))});la.push(Tu);let Eu=Xl(()=>{wa&&(Ya++,Ha.clear(),wl(dt,wa.getMessages(),ue),Gl()?.updateInlineArtifactBlocks(dt,Jo.artifacts,{suppressTransition:!0}),Yn())});return la.push(Eu),Mu},Tc=(e,t)=>{let r=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(o)return Math.max(0,parseFloat(o[1]));let n=/^(\d+(?:\.\d+)?)%$/i.exec(r);return n?Math.max(0,t*parseFloat(n[1])/100):420},Ec=(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"},Lc=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=""},Pc=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Lc(e)},Bc=e=>{e.style.transition=""},Nc=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=""},Rc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},$c=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Hc=(e,t,r,o)=>{t?(e.style.boxSizing="border-box",e.style.padding=r,e.style.background=o):(e.style.padding="",e.style.background="",e.style.boxSizing="")},Wc=(e,t)=>Ys(t)?((e,t)=>{let{ownerDocument:r}=e,o=e.parentElement;if(!o)throw Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if("BODY"===n||"HTML"===n)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),o.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=ja(e),r=t.components?.panel,o=(e,r)=>null==e||""===e?r:Aa(t,e)??e;return{inset:o(r?.inset,da),canvasBackground:o(r?.canvasBackground,ca)}})(t):null};g();let f=()=>{((e,t,r,o,n,a,s,i)=>{let l=ei(a),d="push"===l.reveal,c=null!=i,p=i?.inset??"",u=i?.canvasBackground??"";((e,t,r,o,n)=>{n?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,o),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(o))})(e,t,r,o,d),((e,t,r,o,n,a)=>{let s=a?t:e;"left"===n?s.firstElementChild!==o&&s.replaceChildren(o,r):s.lastElementChild!==o&&s.replaceChildren(r,o)})(e,t,r,o,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",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.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"),Nc(t),Bc(o),Pc(o),Rc(r),$c(n,o),Hc(o,!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",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(a?.launcher?.zIndex??1e5),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.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"),Pc(o),((e,t)=>{!1===t?e.style.maxHeight="":(e.style.maxHeight="100vh",e.style.maxHeight=t)})(o,l.maxHeight),Hc(o,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",Nc(t),Bc(o),Rc(r),$c(n,o);let a=l.animate?"transform 180ms ease":"none",i="right"===l.side?"translateX(100%)":"translateX(-100%)",d=s?"translateX(0)":i;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=l.width,o.style.maxWidth=l.width,o.style.minWidth=l.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=a,o.style.transform=d,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2","right"===l.side?(o.style.right="0",o.style.left=""):(o.style.left="0",o.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",Bc(o),Lc(o),$c(n,o);let a=Tc(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`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=l.width,o.style.minWidth=l.width,o.style.maxWidth=l.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Nc(t),Lc(o),Rc(r),$c(n,o);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(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${i}`,o.style.width=i,o.style.maxWidth=i,o.style.minWidth=i,o.style.minHeight="0",((e,t)=>{!1===t?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")})(o,l.maxHeight),o.style.overflow=a||u?"hidden":"visible",o.style.transition=d,a){o.style.alignItems="right"===l.side?"flex-start":"flex-end";let t=c?`calc(${Tc(l.width,e.clientWidth)}px - (2 * ${p}))`:l.width;n.style.width=t,n.style.minWidth=t,n.style.maxWidth=t,n.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=Ua(()=>{g(),f()}))},v=!1,w=()=>{f(),h(),"push"===ei(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 o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(o);let n=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.remove(),n&&!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,ei(t)))},x=s.ownerDocument.defaultView,C=()=>{w()};return x?.addEventListener("resize",C),"push"===ei(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(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}})(e,t):((e,t)=>{let r=e.ownerDocument.createElement("div");return Ec(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(e){Ec(r,e)},destroy(){r.remove()}}})(e,t),Dc=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let r=t.head.querySelector("link[data-persona]");if(!r)return;let o=r.cloneNode(!0);e.insertBefore(o,e.firstChild)},Fc=[],Oc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),zc=new Set(["button","a","input","select","textarea","details","summary"]),qc=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),jc=/\b(product|card|item|listing|result)\b/i,_c=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i;function Uc(e){let t="string"==typeof e.className?e.className:"";if(jc.test(t)||e.id&&jc.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&jc.test(r.value))return!0}return!1}function Vc(e){return _c.test((e.textContent??"").trim())}function Kc(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 Jc(e){let t=e.match(_c);return t?t[0]:null}function Gc(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 Xc(e){return Uc(e)&&Vc(e)&&(Kc(e)||function(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}(e))?5200:0}function Qc(e){return!Uc(e)||Vc(e)||!Kc(e)||(e.textContent??"").trim().length<20||!e.querySelector("h1, h2, h3, h4, h5, h6, .title")&&!e.querySelector(".snippet, .description, p")?0:2800}let Yc=[{id:"commerce-card",scoreElement:e=>Xc(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||_c.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(0===Xc(e))return null;let{title:r,href:o}=Gc(e),n=Jc((e.textContent??"").trim())??Jc(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[o&&r?`[${r}](${o})${n?`: ${n}`:""}`:r?`${r}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join("\n")}},{id:"result-card",scoreElement:e=>Qc(e),formatSummary(e,t){if(0===Qc(e))return null;let{title:r,href:o}=Gc(e);return[o&&r?`[${r}](${o})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join("\n")}}];function Zc(e){return typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}let ep=["data-testid","data-product","data-action","data-id","data-name","data-type"];function tp(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||zc.has(t)||r&&qc.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||"true"===e.getAttribute("contenteditable")?"clickable":"static"}function rp(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 op(e){let t={},r=e.id;r&&(t.id=r);let o=e.getAttribute("href");o&&(t.href=o);let n=e.getAttribute("aria-label");n&&(t["aria-label"]=n);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 o=e.attributes[r];o.name.startsWith("data-")&&(t[o.name]=o.value)}return t}function np(e){let t=e.tagName.toLowerCase();if(e.id){let t=`#${Zc(e.id)}`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}for(let r of ep){let o=e.getAttribute(r);if(o){let n=`${t}[${r}="${Zc(o)}"]`;try{if(1===e.ownerDocument.querySelectorAll(n).length)return n}catch{}}}let r=Array.from(e.classList).filter(e=>e&&!e.startsWith("persona-")).slice(0,3);if(r.length>0){let o=`${t}.${r.map(e=>Zc(e)).join(".")}`;try{if(1===e.ownerDocument.querySelectorAll(o).length)return o}catch{}let n=e.parentElement;if(n){let r=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0){let t=`${o}:nth-of-type(${r+1})`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}}}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function ap(e,t){let r=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:np(e),tagName:r,text:o,role:e.getAttribute("role"),interactivity:tp(e),attributes:op(e)}}function sp(e,t,r,o){let n=function(e){return"static"===e?100:3e3}(t.interactivity),a=null;for(let s of r){let r=s.scoreElement(e,t,o);r>0&&(n+=r,s.formatSummary&&!a&&(a=s))}return{score:n,formattingRule:a}}function ip(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 lp={components:{panel:{borderRadius:"0",shadow:"none"}}},dp={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:P},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"]}},cp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:lp}},pp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:lp}},up={shop:dp,minimal:cp,fullscreen:pp},hp=typeof document<"u"?document.currentScript?.src??null:null,mp=(e,t=`host ${e} alongside it`)=>()=>{let r=hp?.replace(/index\.global\.js($|\?)/,`${e}$1`);return r&&r!==hp?import(r):Promise.reject(Error(`Could not derive the ${e} URL from the widget script URL (${hp??"unavailable"}). Self-hosted deployments that rename index.global.js should ${t}.`))};return(e=>{s=e})(mp("webmcp-polyfill.js","install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp")),Te(mp("markdown-parsers.js")),nt(mp("client-stream.js")),wr(mp("client-history.js")),_r(mp("ui-extras.js")),Qr(mp("session-actions.js")),oc(mp("history-shell.js")),(e=>{xo=e})(mp("runtype-tts.js","host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly")),ea(mp("context-mentions.js")),na(mp("context-mentions-inline.js")),Qd(mp("history-view.js")),zs(mp("animations-extra.js","host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin")),Pl(mp("approval-ui.js")),yo(mp("voice-runtime.js")),ht(mp("voice-client-tools.js")),Kl(mp("artifacts-ui.js")),Ld(mp("forms-ui.js")),J(mp("icons-extra.js","host icons-extra.js alongside it, or register the icons they use via registerIcons()")),dt(mp("webmcp-runtime.js")),Ao(mp("session-reconnect.js")),Hl(mp("event-stream-view.js")),e.ASK_USER_QUESTION_CLIENT_TOOL=Zt,e.ASK_USER_QUESTION_PARAMETERS_SCHEMA=Yt,e.ASK_USER_QUESTION_TOOL_NAME=wt,e.AgentWidgetClient=Dr,e.AgentWidgetSession=Po,e.AttachmentManager=$o,e.BrowserSpeechEngine=po,e.DEFAULT_COMPONENTS=Sa,e.DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH="440px",e.DEFAULT_FLOATING_LAUNCHER_WIDTH=P,e.DEFAULT_PALETTE=ya,e.DEFAULT_SEMANTIC=wa,e.DEFAULT_WIDGET_CONFIG=F,e.HistoryProviderError=Fr,e.PRESETS=up,e.PRESET_FULLSCREEN=pp,e.PRESET_MINIMAL=cp,e.PRESET_SHOP=dp,e.ReadAloudController=uo,e.SUGGEST_REPLIES_CLIENT_TOOL=Vt,e.SUGGEST_REPLIES_PARAMETERS_SCHEMA=Ut,e.SUGGEST_REPLIES_TOOL_NAME=_t,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=fr,e.WEBMCP_TOOL_PREFIX=r,e.applyFeaturePreferences=Sd,e.applyThemeVariables=_a,e.attachHeaderToContainer=yi,e.buildComposer=Ii,e.buildDefaultHeader=Ci,e.buildHeader=fi,e.buildHeaderWithLayout=Mi,e.buildMinimalHeader=Si,e.builtInClientToolsForDispatch=er,e.canonicalArtifactDisplayMode=to,e.collectEnrichedPageContext=function(e={}){let t=function(e){let t=e.options??{},r=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",n=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??Yc;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:o,maxTextLength:n,visibleOnly:a,root:s,rules:d}}(e),r=t.root??document.body;return r?"simple"===t.mode?function(e,t){let r=[],o=new Set,n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=n.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let t=a,s=t.tagName.toLowerCase();if(Oc.has(s)){a=n.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){a=n.nextNode();continue}}catch{}if(e.visibleOnly&&!rp(t)){a=n.nextNode();continue}let i=ap(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=n.nextNode();continue}o.has(i.selector)||(o.add(i.selector),r.push(i))}a=n.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},o=new Set,n=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&n.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let t=i,l=t.tagName.toLowerCase();if(Oc.has(l)){i=s.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!rp(t)){i=s.nextNode();continue}let d=ap(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||o.has(d.selector)){i=s.nextNode();continue}o.add(d.selector);let{score:u,formattingRule:h}=sp(t,d,e.rules,r);n.push({el:t,domIndex:a,enriched:d,score:u,formattingRule:h}),a+=1}i=s.nextNode()}n.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),o=+("static"===t.enriched.interactivity);return r===o?t.score===e.score?e.domIndex-t.domIndex:t.score-e.score:r-o});let l=[];for(let t of n){if(l.length>=e.maxElements)break;ip(l,t)||l.push(t)}return l.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),o=+("static"===t.enriched.interactivity);return r===o?1===r&&t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex:r-o}),l.map(e=>{let t;if(e.formattingRule?.formatSummary){let o=e.formattingRule.formatSummary(e.el,e.enriched,r);o&&(t=o)}let o={...e.enriched};return t&&(o.formattedSummary=t),o})}(t,r):[]},e.componentRegistry=Dl,e.createActionManager=qd,e.createAgentExperience=Ic,e.createAskUserQuestionBubble=(e,t)=>{let r=q("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 o=Lt(t);Nt(r,o);let n=q("span","persona-ask-stub-label"),{complete:a}=Pt(e);return n.textContent=a?"Awaiting your response…":"Preparing options…",r.appendChild(n),r},e.createBubbleWithLayout=(e,t,r,o,n,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}):Oi(e,t,r,o,0,a)},e.createCSATFeedback=hc,e.createComboButton=xi,e.createComponentMiddleware=function(){let e=ic();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}},e.createComponentStreamParser=ic,e.createDefaultSanitizer=qe,e.createDirectivePostprocessor=e=>{let t=Ne(e);return e=>{let r=[],o=Fe(e,r),n=t(o);return r.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=`<div class="persona-form-directive" data-tv-form="${We(t)}"></div>`;n=n.replace(r,o)}),n}},e.createDropdownMenu=bi,e.createFlexibleJsonStreamParser=e=>{let t=null,r=0,o=e||(e=>{if(!e||"object"!=typeof e)return null;let t=e=>"string"==typeof e?nr(e):null;if(e.component&&"string"==typeof e.component)return"string"==typeof e.text?nr(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 n=e.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(e.length<=r)return null===t?null:{text:t,raw:e};try{let r=(0,vt.parse)(e,vt.STR|vt.OBJ),n=o(r);null!==n&&(t=n)}catch{}return r=e.length,{text:t||"",raw:e}},close:()=>{}}},e.createIconButton=vi,e.createImagePart=function(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}},e.createJsonStreamParser=mr,e.createLabelButton=wi,e.createLocalStorageAdapter=Vd,e.createMarkdownProcessor=Be,e.createMarkdownProcessorFromConfig=Ne,e.createMessageActions=Fi,e.createNPSFeedback=mc,e.createPlainTextParser=ur,e.createRegexJsonParser=hr,e.createSplitButton=function(e){let{label:t,icon:r,iconSize:o,iconOnly:n,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=q("div","persona-split-btn"+(u?" "+u:"")),f={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:i},y=n&&r?vi({...f,icon:r,size:o??14}):wi({...f,icon:r,iconSize:o??14}),b=vi({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=bi({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=Oi,e.createTextPart=Sr,e.createTheme=La,e.createThemeObserver=Ua,e.createToggleGroup=function(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=q("div","persona-toggle-group"+(n?" "+n:""));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=vi({icon:e.icon,label:e.label,className:e.className,onClick:()=>{s=e.id,l(),o(e.id)}}):(t=q("button","persona-icon-btn"+(e.className?" "+e.className:"")),t.type="button",t.setAttribute("aria-label",e.label),t.title=e.label,t.textContent=e.label,t.addEventListener("click",()=>{s=e.id,l(),o(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=Bi,e.createWidgetHostLayout=Wc,e.createXmlParser=gr,e.defaultActionHandlers=Od,e.defaultJsonActionParser=Dd,e.defaultParseRules=Yc,e.detectColorScheme=za,e.directivePostprocessor=e=>{let t=[],r=Fe(e,t),o=$e(r);return t.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n=`<div class="persona-form-directive" data-tv-form="${We(t)}"></div>`;o=o.replace(r,n)}),o},e.ensureAskUserQuestionSheet=qt,e.escapeHtml=He,e.extractComponentDirectiveFromMessage=pc,e.fileToImagePart=async function(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>r(Error("Failed to read file")),o.readAsDataURL(e)})},e.formatEnrichedContext=function(e,t={}){if(0===e.length)return"No page elements found.";let r=t.mode??"structured",o=[];if("structured"===r){let t=e.map(e=>e.formattedSummary).filter(e=>!!e&&e.length>0);t.length>0&&o.push(`Structured summaries:\n${t.map(e=>`- ${e.split("\n").join("\n ")}`).join("\n")}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let t of e)"structured"===r&&t.formattedSummary||n[t.interactivity].push(t);if(n.clickable.length>0){let e=n.clickable.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}" (clickable)`);o.push(`Interactive elements:\n${e.join("\n")}`)}if(n.navigable.length>0){let e=n.navigable.map(e=>`- ${e.selector}${e.attributes.href?`[href="${e.attributes.href}"]`:""}: "${e.text.substring(0,100)}" (navigable)`);o.push(`Navigation links:\n${e.join("\n")}`)}if(n.input.length>0){let e=n.input.map(e=>`- ${e.selector}${e.attributes.type?`[type="${e.attributes.type}"]`:""}: "${e.text.substring(0,100)}" (input)`);o.push(`Form inputs:\n${e.join("\n")}`)}if(n.static.length>0){let e=n.static.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}"`);o.push(`Content:\n${e.join("\n")}`)}return o.join("\n\n")},e.generateAssistantMessageId=yt,e.generateMessageId=function(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`},e.generateStableSelector=np,e.generateUserMessageId=ft,e.getActiveTheme=ja,e.getAgentWidgetHandles=()=>[...Fc],e.getColorScheme=qa,e.getDisplayText=function(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("")},e.getHeaderLayout=Ai,e.getImageParts=function(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)},e.getPreset=function(e){return up[e]},e.hasComponentDirective=cc,e.hasImages=Cr,e.headerLayouts=ki,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),o=!0===e.useShadowDom,n=r.ownerDocument,a=e.config,s=Wc(r,a),i=[],l=(e,t)=>{let a=!(t?.launcher?.enabled??1)||Ys(t),s=n.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"),o){let t=e.attachShadow({mode:"open"});t.appendChild(s),Dc(t,n)}else e.appendChild(s),Dc(e,n);return r.id&&s.setAttribute("data-persona-instance",r.id),s},d=()=>{s.syncWidgetState(t.getState())},c=()=>{let r=l(s.host,a);t=Ic(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=Wc(r,e),a=e,c()},h=new Proxy({update(e){let r=Wd(a??{},e),o=Ys(a),n=Ys(r),i=Zs(a),l=Zs(r);o!==n||i!==l?u(r):(a=r,s.updateConfig(a),t.update(e),d())},destroy(){p(),s.destroy();let t=Fc.indexOf(h);-1!==t&&Fc.splice(t,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},{get(e,r,o){if("host"===r)return s.host;if(r in e)return Reflect.get(e,r,o);let n=t[r];return"function"==typeof n?n.bind(t):n}});return Fc.push(h),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=h),h},e.isAskUserQuestionMessage=Et,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=Ys,e.isHistoryProviderError=function(e){return e instanceof Fr},e.isSuggestRepliesMessage=Kt,e.isWebMcpToolName=c,e.isWelcomeVisible=tl,e.latestAgentSuggestions=Gt,e.listRegisteredStreamAnimations=()=>Array.from(xs.keys()),e.loadMarkdownParsers=Ee,e.markdownPostprocessor=$e,e.mergeWithDefaults=z,e.normalizeContent=function(e){return"string"==typeof e?[{type:"text",text:e}]:e},e.normalizeMediaType=ro,e.onMarkdownParsersReady=Le,e.parseAskUserQuestionPayload=Pt,e.parseSuggestRepliesPayload=Jt,e.parseWidgetPreferenceSlice=vd,e.pickBestVoice=co,e.pluginRegistry=Nd,e.registerIcons=e=>{for(let[t,r]of Object.entries(e))Y.set(t,r);ne()>0&&!ee&&re(!1)},e.registerStreamAnimationPlugin=Ss,e.removeAskUserQuestionSheet=jt,e.renderComponentDirective=lc,e.renderLoadingIndicatorWithFallback=Ni,e.renderLucideIcon=se,e.resolveArtifactDisplay=oo,e.resolveArtifactDisplayMode=no,e.resolveConfigPreferences=kd,e.resolveDockConfig=ei,e.resolveSanitizer=je,e.resolveTokens=Ma,e.resolveWelcomeConfig=el,e.stripWebMcpPrefix=d,e.themeToCssVariables=Ra,e.unregisterStreamAnimationPlugin=e=>{ws.some(t=>t.name===e)||xs.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=Ia,e}({});
|
|
8
8
|
//# sourceMappingURL=index.global.js.map
|