@runtypelabs/persona 4.33.0 → 4.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/dist/activity-ui.d.cts +3 -15
  2. package/dist/activity-ui.d.ts +3 -15
  3. package/dist/animations/glyph-cycle.d.cts +1 -3
  4. package/dist/animations/glyph-cycle.d.ts +1 -3
  5. package/dist/animations/wipe.d.cts +1 -3
  6. package/dist/animations/wipe.d.ts +1 -3
  7. package/dist/approval-ui.cjs +2 -2
  8. package/dist/approval-ui.d.cts +3 -15
  9. package/dist/approval-ui.d.ts +3 -15
  10. package/dist/approval-ui.js +1 -1
  11. package/dist/artifacts-ui.cjs +1 -1
  12. package/dist/artifacts-ui.d.cts +3 -21
  13. package/dist/artifacts-ui.d.ts +3 -21
  14. package/dist/background-runtime.d.cts +2 -3
  15. package/dist/background-runtime.d.ts +2 -3
  16. package/dist/{chunk-gu34lr-P.js → chunk-Brdx4NCz.js} +1 -1
  17. package/dist/{chunk-dLJWKfOb.js → chunk-C-rux8Q9.js} +1 -1
  18. package/dist/{chunk-Ds_twaZn.js → chunk-C4v-HNhS.js} +1 -1
  19. package/dist/{chunk-Bkma5hIU.js → chunk-CE4seJxF.js} +1 -1
  20. package/dist/{chunk-D6U0E82p.js → chunk-CV8EPIhT.js} +1 -1
  21. package/dist/{chunk-ql5N2I_t.js → chunk-CWzHNuVK.js} +1 -1
  22. package/dist/{chunk-DbGLjU2P.js → chunk-CYpt7PsO.js} +1 -1
  23. package/dist/{chunk-DOZmcve8.js → chunk-Csr59G5V.js} +1 -1
  24. package/dist/{chunk-DW7Vg_l2.js → chunk-CxNPSY-b.js} +1 -1
  25. package/dist/chunk-Dqa_GOcj.js +1 -0
  26. package/dist/chunk-DsWv3EGF.js +1 -0
  27. package/dist/{chunk-C7-m0EmI.js → chunk-NUNdcnAZ.js} +1 -1
  28. package/dist/{chunk-CXQJG7pb.js → chunk-YMkMvAsa.js} +2 -2
  29. package/dist/{chunk-C-EHtpbB.js → chunk-h5aOI_Pa.js} +1 -1
  30. package/dist/chunk-kizhspe5.js +1 -0
  31. package/dist/client-dispatch.js +1 -1
  32. package/dist/client-history.js +1 -1
  33. package/dist/client-stream.js +1 -1
  34. package/dist/{code-generators-DqauYyfX.d.cts → code-generators-DPAqTcAz.d.cts} +0 -2
  35. package/dist/{code-generators-DqauYyfX.d.ts → code-generators-DPAqTcAz.d.ts} +0 -2
  36. package/dist/codegen.cjs +1 -1
  37. package/dist/codegen.d.cts +1 -1
  38. package/dist/codegen.d.ts +1 -1
  39. package/dist/codegen.js +1 -1
  40. package/dist/composer-actions-runtime.cjs +1 -1
  41. package/dist/composer-actions-runtime.d.cts +4 -20
  42. package/dist/composer-actions-runtime.d.ts +4 -20
  43. package/dist/composer-actions-runtime.js +1 -1
  44. package/dist/{composer-input-DnqGCXZz.d.ts → composer-input-i_FiUp6J.d.cts} +1 -7
  45. package/dist/{composer-input-DnqGCXZz.d.cts → composer-input-i_FiUp6J.d.ts} +1 -7
  46. package/dist/{composer-store-6Iwy6WLI.d.ts → composer-store-DhGNgG7Z.d.cts} +1 -3
  47. package/dist/{composer-store-6Iwy6WLI.d.cts → composer-store-DhGNgG7Z.d.ts} +1 -3
  48. package/dist/config-diagnostics.d.cts +0 -2
  49. package/dist/config-diagnostics.d.ts +0 -2
  50. package/dist/{context-mention-manager-B-rHF98n.d.ts → context-mention-manager-DL-xwGfL.d.cts} +2 -6
  51. package/dist/{context-mention-manager-B-rHF98n.d.cts → context-mention-manager-DL-xwGfL.d.ts} +2 -6
  52. package/dist/context-mentions-inline.cjs +1 -1
  53. package/dist/context-mentions-inline.d.cts +2 -4
  54. package/dist/context-mentions-inline.d.ts +2 -4
  55. package/dist/context-mentions-inline.js +1 -1
  56. package/dist/context-mentions.cjs +1 -1
  57. package/dist/context-mentions.d.cts +3 -9
  58. package/dist/context-mentions.d.ts +3 -9
  59. package/dist/{defaults-BuOjqUAG.d.ts → defaults-Bga2Xrsp.d.cts} +1 -5
  60. package/dist/{defaults-BuOjqUAG.d.cts → defaults-Bga2Xrsp.d.ts} +1 -5
  61. package/dist/dictation-runtime.cjs +1 -1
  62. package/dist/dictation-runtime.d.cts +4 -13
  63. package/dist/dictation-runtime.d.ts +4 -13
  64. package/dist/dictation-runtime.js +1 -1
  65. package/dist/{dom-context-DHTabIn7.d.cts → dom-context-Bw-_9Evh.d.cts} +0 -2
  66. package/dist/{dom-context-DHTabIn7.d.ts → dom-context-Bw-_9Evh.d.ts} +0 -2
  67. package/dist/event-stream-view.cjs +1 -1
  68. package/dist/event-stream-view.d.cts +3 -16
  69. package/dist/event-stream-view.d.ts +3 -16
  70. package/dist/{fallback-speech-engine-SqEfkGda.d.ts → fallback-speech-engine-kLdyPcmk.d.cts} +1 -3
  71. package/dist/{fallback-speech-engine-SqEfkGda.d.cts → fallback-speech-engine-kLdyPcmk.d.ts} +1 -3
  72. package/dist/{feature-preferences-DqAmje-2.d.ts → feature-preferences-CmwZGKrf.d.cts} +1 -5
  73. package/dist/{feature-preferences-DqAmje-2.d.cts → feature-preferences-CmwZGKrf.d.ts} +1 -5
  74. package/dist/forms-ui.d.cts +2 -4
  75. package/dist/forms-ui.d.ts +2 -4
  76. package/dist/{history-confirm-dialog-B3L7QNcO.d.cts → history-confirm-dialog-i46-lPN_.d.cts} +2 -14
  77. package/dist/{history-confirm-dialog-B3L7QNcO.d.ts → history-confirm-dialog-i46-lPN_.d.ts} +2 -14
  78. package/dist/history-shell.cjs +1 -1
  79. package/dist/history-shell.d.cts +8 -27
  80. package/dist/history-shell.d.ts +8 -27
  81. package/dist/history-shell.js +1 -1
  82. package/dist/history-view.d.cts +1 -1
  83. package/dist/history-view.d.ts +1 -1
  84. package/dist/icons-extra.cjs +1 -1
  85. package/dist/icons-extra.d.cts +0 -2
  86. package/dist/icons-extra.d.ts +0 -2
  87. package/dist/index.cjs +45 -45
  88. package/dist/index.cjs.map +1 -1
  89. package/dist/index.d.cts +10 -10
  90. package/dist/index.d.ts +10 -10
  91. package/dist/index.global.js +1 -1
  92. package/dist/index.global.js.map +1 -1
  93. package/dist/index.js +49 -49
  94. package/dist/index.js.map +1 -1
  95. package/dist/install.global.js +1 -1
  96. package/dist/install.global.js.map +1 -1
  97. package/dist/launcher.global.js +2 -2
  98. package/dist/launcher.global.js.map +1 -1
  99. package/dist/{loading-label-runtime-loader-JecjOfJS.d.ts → loading-label-runtime-loader-Ccr3ETd3.d.cts} +1 -3
  100. package/dist/{loading-label-runtime-loader-JecjOfJS.d.cts → loading-label-runtime-loader-Ccr3ETd3.d.ts} +1 -3
  101. package/dist/loading-label-runtime.cjs +1 -1
  102. package/dist/loading-label-runtime.d.cts +1 -1
  103. package/dist/loading-label-runtime.d.ts +1 -1
  104. package/dist/loading-label-runtime.js +1 -1
  105. package/dist/markdown-parsers.js +1 -1
  106. package/dist/{message-bubble-CBYtpDsT.d.ts → message-bubble-C6AVaH7f.d.cts} +20 -3
  107. package/dist/{message-bubble-CBYtpDsT.d.cts → message-bubble-C6AVaH7f.d.ts} +20 -3
  108. package/dist/{plugin-kit-C1mRjLgW.d.cts → plugin-kit-BVggqE3C.d.cts} +0 -2
  109. package/dist/{plugin-kit-C1mRjLgW.d.ts → plugin-kit-BVggqE3C.d.ts} +0 -2
  110. package/dist/plugin-kit.d.cts +1 -1
  111. package/dist/plugin-kit.d.ts +1 -1
  112. package/dist/preferences-runtime.cjs +1 -1
  113. package/dist/preferences-runtime.d.cts +1 -1
  114. package/dist/preferences-runtime.d.ts +1 -1
  115. package/dist/preferences-runtime.js +1 -1
  116. package/dist/{preview-_UJwwt2L.d.cts → preview-BMdRffo4.d.cts} +2 -6
  117. package/dist/{preview-_UJwwt2L.d.ts → preview-BMdRffo4.d.ts} +2 -6
  118. package/dist/{registry-B5ZV3K-h.d.ts → registry-B16l8s1b.d.cts} +1 -8
  119. package/dist/{registry-B5ZV3K-h.d.cts → registry-B16l8s1b.d.ts} +1 -8
  120. package/dist/{session-Bys8_XuB.d.cts → session-CtZHe7fc.d.cts} +8 -92
  121. package/dist/{session-Bys8_XuB.d.ts → session-CtZHe7fc.d.ts} +8 -92
  122. package/dist/session-reconnect.d.cts +2 -4
  123. package/dist/session-reconnect.d.ts +2 -4
  124. package/dist/smart-dom-reader.d.cts +2 -8
  125. package/dist/smart-dom-reader.d.ts +2 -8
  126. package/dist/testing.d.cts +0 -2
  127. package/dist/testing.d.ts +0 -2
  128. package/dist/theme-editor-preview.cjs +42 -42
  129. package/dist/theme-editor-preview.d.cts +1 -1
  130. package/dist/theme-editor-preview.d.ts +1 -1
  131. package/dist/theme-editor-preview.js +25 -25
  132. package/dist/theme-editor.cjs +25 -5
  133. package/dist/theme-editor.d.cts +2 -22
  134. package/dist/theme-editor.d.ts +2 -22
  135. package/dist/theme-editor.js +1 -1
  136. package/dist/theme-reference.cjs +1 -1
  137. package/dist/theme-reference.d.cts +2 -4
  138. package/dist/theme-reference.d.ts +2 -4
  139. package/dist/theme-reference.js +1 -1
  140. package/dist/{tool-loading-animation-d5qAQcwv.d.ts → tool-loading-animation-D2cyFvmM.d.cts} +1 -7
  141. package/dist/{tool-loading-animation-d5qAQcwv.d.cts → tool-loading-animation-D2cyFvmM.d.ts} +1 -7
  142. package/dist/{tooltip-BkW-8MnD.d.cts → tooltip-DbXkAuJL.d.cts} +0 -2
  143. package/dist/{tooltip-BkW-8MnD.d.ts → tooltip-DbXkAuJL.d.ts} +0 -2
  144. package/dist/{turn-activity-ui-q6fHVnx-.d.cts → turn-activity-ui-Do1Nd-Ow.d.cts} +2 -12
  145. package/dist/{turn-activity-ui-q6fHVnx-.d.ts → turn-activity-ui-Do1Nd-Ow.d.ts} +2 -12
  146. package/dist/turn-activity-ui.d.cts +1 -1
  147. package/dist/turn-activity-ui.d.ts +1 -1
  148. package/dist/{types-B_mj21jg.d.cts → types-BC7MRxO5.d.cts} +76 -29
  149. package/dist/{types-B_mj21jg.d.ts → types-BC7MRxO5.d.ts} +76 -29
  150. package/dist/ui-extras.js +3 -3
  151. package/dist/voice-client-tools.d.cts +1 -3
  152. package/dist/voice-client-tools.d.ts +1 -3
  153. package/dist/voice-runtime.cjs +1 -1
  154. package/dist/voice-runtime.d.cts +2 -12
  155. package/dist/voice-runtime.d.ts +2 -12
  156. package/dist/voice-runtime.js +2 -2
  157. package/dist/voice-worklet-player.d.cts +2 -6
  158. package/dist/voice-worklet-player.d.ts +2 -6
  159. package/dist/{webmcp-runtime-entry-ClEO3qdI.d.ts → webmcp-runtime-entry-B8g46vS0.d.cts} +1 -5
  160. package/dist/{webmcp-runtime-entry-ClEO3qdI.d.cts → webmcp-runtime-entry-B8g46vS0.d.ts} +1 -5
  161. package/dist/webmcp-runtime.d.cts +1 -1
  162. package/dist/webmcp-runtime.d.ts +1 -1
  163. package/dist/widget.css +1 -1
  164. package/package.json +4 -4
  165. package/src/components/event-stream-view.test.ts +5 -0
  166. package/src/components/message-bubble.ts +26 -6
  167. package/src/components/scroll-to-bottom.test.ts +135 -0
  168. package/src/components/scroll-to-bottom.ts +50 -13
  169. package/src/components/user-message-collapse.ts +117 -0
  170. package/src/defaults.ts +6 -0
  171. package/src/styles/widget.css +56 -0
  172. package/src/theme-reference.ts +2 -2
  173. package/src/types/theme.ts +29 -0
  174. package/src/types.ts +49 -5
  175. package/src/ui.scroll-additive.test.ts +219 -117
  176. package/src/ui.scroll.test.ts +176 -13
  177. package/src/ui.ts +230 -107
  178. package/src/ui.turn-activity.test.ts +7 -7
  179. package/src/ui.user-message-collapse.test.ts +540 -0
  180. package/src/utils/auto-follow.test.ts +0 -38
  181. package/src/utils/auto-follow.ts +0 -35
  182. package/src/utils/theme.test.ts +23 -0
  183. package/src/utils/tokens.ts +16 -0
  184. package/dist/chunk-CVMIncEY.js +0 -1
  185. package/dist/chunk-DVgzoVCB.js +0 -1
  186. package/dist/chunk-d54BJdKd.js +0 -1
@@ -1 +1 @@
1
- import{a as e,r as t}from"./chunk-CEPM3FOp.js";import{r as n,t as r}from"./chunk-D5BxWOFB.js";import{t as i}from"./chunk-BAdIgC5d.js";import{t as a}from"./chunk-DDZBCAer.js";import{t as o}from"./chunk-Bb3MaswO.js";import{n as s}from"./chunk-Bj8Hnh10.js";import{Ban as c}from"lucide";const l=(e,t)=>`var(--persona-components-approval-${e.split(`.`).join(`-`)}, ${t})`,u=(e,t)=>`var(--persona-consumer-approval-${e.split(`.`).join(`-`)}, ${t})`;function d(n,r){let i=e=>{let r=t(n,`approval.${e}`);return typeof r==`string`?r:void 0},a=(e,t,n)=>i(e)||l(t,u(`requested.text`,n)),o=(t,r)=>i(t)??(e(n,`approval.${r}`)?`var(--persona-components-approval-${r.split(`.`).join(`-`)})`:void 0),s=r===`public`,c=`var(--persona-muted, #6b7280)`,d=s?`var(--persona-primary, #171717)`:`var(--persona-text, #0b0b0b)`,f=s?`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`:`var(--persona-text, #1f2937)`,p=i(`shadow`);return{backgroundColor:o(`backgroundColor`,`requested.background`),borderColor:o(`borderColor`,`requested.border`),shadow:p===void 0?o(`shadow`,`requested.shadow`):p.trim()===``?`none`:p,titleColor:a(`titleColor`,`requested.titleColor`,d),descriptionColor:a(`descriptionColor`,`requested.descriptionColor`,c),reasonColor:i(`reasonColor`)||i(`descriptionColor`)||l(`requested.reasonColor`,u(`requested.text`,c)),parameterBackgroundColor:i(`parameterBackgroundColor`)||l(`requested.parameters.background`,s?`var(--persona-container, #f8fafc)`:`var(--persona-container, rgba(11, 11, 11, 0.04))`),parameterTextColor:a(`parameterTextColor`,`requested.parameters.foreground`,s?`var(--persona-primary, #171717)`:`var(--persona-text, #1f2937)`),approveButtonColor:o(`approveButtonColor`,`approve.background`),approveButtonTextColor:i(`approveButtonTextColor`)||u(`approve.foreground`,`var(--persona-button-primary-fg)`),denyButtonColor:i(`denyButtonColor`)??(s?u(`deny.background`,`transparent`):void 0),denyButtonTextColor:i(`denyButtonTextColor`)||u(`deny.foreground`,f),denyBorderColor:i(`denyButtonTextColor`)||u(`deny.foreground`,`var(--persona-palette-colors-error-200)`),pendingIconColor:i(`titleColor`)||l(`requested.titleColor`,u(`requested.text`,`currentColor`))}}let f;const p=(...e)=>f?.render(...e)??null,m=(...e)=>f?.node(...e)??null;let h;const g=()=>{if(!h)throw Error(`Approval UI requires core popover dependencies.`);return h};let _=()=>void 0;const v=e=>{_=e.webMcpToolTitle,e.icons&&(f=e.icons),e.popover&&(h=e.popover)},y=e=>_(e),b=e=>{let t=(e.startsWith(`webmcp:`)?e.slice(i.length):e).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return e;let n=t.join(` `).toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)},x=e=>e?.approval===!1?void 0:e?.approval,S=(e,t,n)=>{let r=x(n)?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},C=(e,t,n)=>{let r=x(n);e.setAttribute(`aria-expanded`,t?`true`:`false`);let i=e.querySelector(`[data-approval-details-label]`);i&&(i.textContent=t?r?.hideDetailsLabel??`Hide details`:r?.showDetailsLabel??`Show details`);let a=e.querySelector(`[data-approval-details-chevron]`);if(a){a.innerHTML=``;let e=p(t?`chevron-up`:`chevron-down`,14,`currentColor`,2);e&&a.appendChild(e)}},w=(e,t,n,r=/* @__PURE__ */ new Map)=>{let i=t.querySelector(`button[data-bubble-type="approval"]`),a=t.querySelector(`[data-approval-details]`);if(!i||!a)return;let o=S(e,r,n);C(i,o,n),a.style.display=o?``:`none`},T=(e,t,n,r)=>{let i=d(n,`public`);if(D(t,n),!r)return;let a=t.querySelector(`[data-approval-status]`);if(a){a.textContent=r.status===`approved`?`Approved`:r.status===`denied`?`Denied`:r.status===`timeout`&&r.interrupted?`Interrupted`:r.status===`timeout`?`Timeout`:`Pending`;let e=r.status===`approved`?`success`:r.status===`denied`?`error`:r.status===`timeout`?`warning`:void 0;e&&(a.className=`persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium`,a.style.backgroundColor=`var(--persona-palette-colors-${e}-100)`,a.style.color=`var(--persona-palette-colors-${e}-700)`),a.setAttribute(`data-approval-status`,r.status)}let o=t.querySelector(`[data-approval-icon]`);if(o){o.innerHTML=``;let e=r.status===`denied`?`shield-x`:r.status===`timeout`?`shield-alert`:`shield-check`,t=r.status===`approved`?`var(--persona-feedback-success, var(--persona-palette-colors-success-600))`:r.status===`denied`?`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`:r.status===`timeout`?`var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))`:i.pendingIconColor,n=p(e,20,t,2);n&&o.appendChild(n)}let s=t.querySelector(`[data-approval-buttons]`);s&&(s.style.display=r.status===`pending`?``:`none`)},E=(e,t,i=/* @__PURE__ */ new Map)=>{let s=e.approval,c=x(t),l=s?.status===`pending`,u=r(`div`,`persona-approval-bubble persona-w-full persona-rounded-2xl persona-border persona-shadow-sm persona-overflow-hidden`);if(u.id=`bubble-${e.id}`,u.setAttribute(`data-message-id`,e.id),!s)return D(u,t),u;let d=r(`div`,`persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3`),f=n(`div`,{className:`persona-flex-shrink-0 persona-mt-0.5`,attrs:{"data-approval-icon":`true`}}),m=r(`div`,`persona-flex-1 persona-min-w-0`),h=r(`div`,`persona-flex persona-items-center persona-gap-2`),g=n(`span`,{className:`persona-text-sm persona-font-medium persona-text-persona-primary`,attrs:{"data-approval-title":`true`},text:c?.title??`Approval Required`});if(h.appendChild(g),!l){let e=r(`span`,`persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium`);e.setAttribute(`data-approval-status`,s.status),h.appendChild(e)}if(m.appendChild(h),s.status===`timeout`&&s.interrupted){let e=r(`p`,`persona-text-sm`);e.textContent=a,m.appendChild(e)}let _=s.toolType===`webmcp`||s.toolName.startsWith(`webmcp:`)?y(s.toolName):void 0,v=c?.formatDescription?.({toolName:s.toolName,toolType:s.toolType,description:s.description,parameters:s.parameters,..._?{displayTitle:_}:{},...s.reason?{reason:s.reason}:{}}),w=!s.toolName,E=v||(w?s.description:`The assistant wants to use “${_??b(s.toolName)}”.`),O=n(`p`,{className:`persona-text-sm persona-mt-0.5 persona-text-persona-muted`,attrs:{"data-approval-summary":`true`},text:E});if(m.appendChild(O),s.reason){let e=r(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);e.setAttribute(`data-approval-reason`,`true`);let t=r(`span`,`persona-font-medium`);t.textContent=`${c?.reasonLabel??`Agent's stated reason:`} `,e.appendChild(t),e.appendChild(document.createTextNode(s.reason)),m.appendChild(e)}let k=c?.detailsDisplay??`collapsed`,A=!!s.description&&!w,j=A||!!s.parameters;if(k!==`hidden`&&j){let n=S(e.id,i,t),a=r(`button`,`persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted`);a.type=`button`,a.setAttribute(`data-expand-header`,`true`),a.setAttribute(`data-bubble-type`,`approval`);let c=r(`span`);c.setAttribute(`data-approval-details-label`,`true`);let l=r(`span`,`persona-inline-flex persona-items-center`);l.setAttribute(`data-approval-details-chevron`,`true`),a.append(c,l),C(a,n,t),m.appendChild(a);let u=r(`div`);if(u.setAttribute(`data-approval-details`,`true`),u.style.display=n?``:`none`,A){let e=r(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);e.setAttribute(`data-approval-description`,`true`),e.textContent=s.description,u.appendChild(e)}if(s.parameters){let e=r(`pre`,`persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary`);e.setAttribute(`data-approval-parameters`,`true`),e.style.fontSize=`0.75rem`,e.style.lineHeight=`1rem`,e.textContent=o(s.parameters),u.appendChild(e)}m.appendChild(u)}if(l){let e=r(`div`,`persona-flex persona-gap-2 persona-mt-2`);e.setAttribute(`data-approval-buttons`,`true`);for(let t of[`approve`,`deny`]){let r=n(`button`,{className:`persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer`+(t===`approve`?` persona-border-none`:``),attrs:{type:`button`,"data-approval-action":t}}),i=p(t===`approve`?`shield-check`:`shield-x`,14,`currentColor`,2);i&&(i.style.marginRight=`4px`,r.appendChild(i)),r.appendChild(document.createTextNode(t===`approve`?c?.approveLabel??`Approve`:c?.denyLabel??`Deny`)),e.appendChild(r)}m.appendChild(e)}return d.append(f,m),u.appendChild(d),T(e.id,u,t,s),u},D=(e,t)=>{let n=d(t,`public`);e.style.backgroundColor=n.backgroundColor??`var(--persona-approval-bg)`,e.style.borderColor=n.borderColor??`var(--persona-approval-border)`,e.style.boxShadow=n.shadow===void 0?`var(--persona-approval-shadow)`:n.shadow.trim()||`none`;let r=(t,n)=>{e.querySelectorAll(t).forEach(e=>{e.style.color=n??``})};e.querySelector(`[data-approval-status]`)||e.querySelector(`[data-approval-icon] svg`)?.setAttribute(`stroke`,n.pendingIconColor),r(`[data-approval-title]`,n.titleColor),r(`[data-approval-summary], [data-approval-description], button[data-bubble-type='approval']`,n.descriptionColor),r(`[data-approval-reason]`,n.reasonColor),r(`[data-approval-parameters]`,n.parameterTextColor),e.querySelectorAll(`[data-approval-parameters]`).forEach(e=>{e.style.backgroundColor=n.parameterBackgroundColor??``});for(let t of[`approve`,`deny`]){let r=e.querySelector(`[data-approval-action="${t}"]`);if(!r)continue;let i=t===`approve`?n.approveButtonTextColor:n.denyButtonTextColor;r.style.backgroundColor=(t===`approve`?n.approveButtonColor??`var(--persona-approval-approve-bg)`:n.denyButtonColor)??``,r.style.color=i??``,r.querySelector(`svg`)?.setAttribute(`stroke`,i??`currentColor`),t===`deny`&&(r.style.border=`1px solid ${n.denyBorderColor}`)}};let O=0;const k=()=>({disclosurePrefix:`approval-${++O}`,keyHandlers:/* @__PURE__ */ new Map,popovers:/* @__PURE__ */ new Map,pendingOrder:[],latestPendingApprovalId:null}),A=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener(`keydown`,n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},j=(e,t)=>{A(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},M=(e,t,n)=>{let r=n?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},N=e=>{let t=r(`span`,`persona-approval-kbd`);return t.textContent=e,t},P=(e,t)=>{let n=r(`span`,`persona-approval-title`);t?.titleColor&&(n.style.color=t.titleColor);let i=e.toolType===`webmcp`||e.toolName.startsWith(`webmcp:`)?y(e.toolName):void 0,a=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??``,parameters:e.parameters,...i?{displayTitle:i}:{},...e.reason?{reason:e.reason}:{}});if(a)return n.textContent=a,n;let o=i??b(e.toolName),s=e.toolType&&e.toolType!==`webmcp`?e.toolType:null;n.append(`The assistant wants to use `);let c=document.createElement(`strong`);if(c.textContent=o,n.appendChild(c),s){n.append(` from `);let e=document.createElement(`strong`);e.textContent=s,n.appendChild(e)}return n},F=e=>{let t=r(`div`,`persona-approval-resolved`),i=m(c,15,`currentColor`,2);i&&t.appendChild(i);let o=r(`span`,`persona-approval-resolved-name`);o.textContent=e.toolName?b(e.toolName):`Tool`;let s=e.status===`timeout`&&e.interrupted?` approval expired. ${a}`:e.status===`timeout`?` timed out`:` denied`;return t.appendChild(n(`span`,{className:`persona-approval-resolved-text`},o,s)),t},I=(e,t,n,i,a,s,c,l,u=!1,d)=>{let f=d!==void 0,m=r(`div`,f?`persona-approval-row persona-activity-row`:`persona-approval-card persona-shadow-sm`);m.id=`bubble-${n.id}`,m.setAttribute(`data-message-id`,n.id),m.setAttribute(`data-bubble-type`,`approval`),a?.backgroundColor&&(m.style.background=a.backgroundColor),a?.borderColor&&(m.style.borderColor=a.borderColor),a?.shadow!==void 0&&(m.style.boxShadow=a.shadow.trim()===``?`none`:a.shadow);let h=a?.detailsDisplay??`collapsed`,_=!!i.description&&h!==`hidden`,v=i.parameters!=null&&h!==`hidden`&&!u,x=!!i.reason&&h!==`hidden`,S=_||v||f&&x,C=S&&M(n.id,t,a),w=a?.showDetailsLabel??`Show details`,T=a?.hideDetailsLabel??`Hide details`,E=r(f&&!S?`div`:`button`,`persona-approval-head`);E instanceof HTMLButtonElement&&(E.type=`button`),S?(E.setAttribute(`data-action`,`toggle-params`),E.setAttribute(`aria-expanded`,C?`true`:`false`),E.setAttribute(`aria-label`,C?T:w)):E.setAttribute(`data-static`,`true`);let D=r(`span`,`persona-approval-logo`),O=p(`shield-check`,16,`currentColor`,2);O&&D.appendChild(O),f||E.appendChild(D);let k=f?r(`span`,`persona-approval-title`):P(i,a),A=``;if(f){let e=(i.toolType===`webmcp`||i.toolName.startsWith(`webmcp:`)?y(i.toolName):void 0)??b(i.toolName),t=r(`span`,`persona-approval-status`);t.setAttribute(`role`,`status`),t.textContent=d,k.append(e,` · `,t),a?.titleColor&&(k.style.color=a.titleColor),A=`${e} · ${d}`}if(S){let e=r(`span`,`persona-approval-toggle`);e.setAttribute(`aria-hidden`,`true`);let t=p(`chevron-down`,14,`currentColor`,2);t&&e.appendChild(t),k.append(` `),k.appendChild(e)}E.appendChild(k),m.appendChild(E);let F=r(`div`,`persona-approval-body`),I;if(S){let e=r(`div`,`persona-approval-details`);e.setAttribute(`data-role`,`params`),e.hidden=!C;let t=t=>{let n=r(`div`,`persona-tool-detail`),i=r(`div`,`persona-tool-detail-label`);return i.textContent=t,n.appendChild(i),e.appendChild(n),n},n=f&&v?t(`Request`):e;if(f&&(_||x)&&(I=t(`Context`)),_){let t=r(`p`,`persona-approval-desc`);a?.descriptionColor&&(t.style.color=a.descriptionColor),t.textContent=i.description,(I??e).appendChild(t)}if(v){let e=r(`pre`,f?`persona-approval-params persona-tool-detail-value persona-tool-detail-code`:`persona-approval-params`);a?.parameterBackgroundColor&&(e.style.background=a.parameterBackgroundColor),a?.parameterTextColor&&(e.style.color=a.parameterTextColor),e.textContent=o(i.parameters),n.appendChild(e)}F.appendChild(e)}if(u){let e=r(`div`,`persona-approval-call`);e.setAttribute(`data-role`,`raw-call`);let t=r(`code`,`persona-approval-tool-name`);if(t.textContent=i.toolName,e.appendChild(t),i.parameters!=null){let t=r(`pre`,`persona-approval-params`);a?.parameterBackgroundColor&&(t.style.background=a.parameterBackgroundColor),a?.parameterTextColor&&(t.style.color=a.parameterTextColor),t.textContent=o(i.parameters),e.appendChild(t)}F.appendChild(e)}if(i.reason){let e=r(`p`,`persona-approval-reason`);a?.reasonColor?e.style.color=a.reasonColor:a?.descriptionColor&&(e.style.color=a.descriptionColor);let t=r(`span`,`persona-approval-reason-label`);t.textContent=`${a?.reasonLabel??`Agent's stated reason:`} `,e.append(t,document.createTextNode(i.reason)),f?I?.appendChild(e):F.appendChild(e)}let L=e=>{E.setAttribute(`aria-expanded`,String(e));let t=e?T:w;E.setAttribute(`aria-label`,f?`${A}. ${t}`:t)},R=()=>{let e=m.querySelector(`[data-role="params"]`);if(!e)return;let r=e.hidden!==!1;e.hidden=!r,f&&(F.hidden=!r),L(r),t.set(n.id,r)};if(f){if(S){let t=F.querySelector(`[data-role="params"]`);t.id=`${e.disclosurePrefix}-details-${n.id}`,E.setAttribute(`aria-controls`,t.id),L(C),F.hidden=!C,m.appendChild(F),E.addEventListener(`click`,R)}return m}let z=r(`div`,`persona-approval-actions`),B=a?.primaryAction===`allow-once`,V=a?.keyboardShortcuts!==!1&&a?.keyboardShortcuts!==`focused`,H=null,U=e=>{a?.approveButtonColor&&(e.style.background=a.approveButtonColor),a?.approveButtonTextColor&&(e.style.color=a.approveButtonTextColor)},W=r(`button`,`persona-approval-deny`);if(W.type=`button`,W.setAttribute(`data-action`,`deny`),a?.denyButtonColor&&(W.style.background=a.denyButtonColor),a?.denyButtonTextColor&&(W.style.color=a.denyButtonTextColor),W.append(a?.denyLabel??`Deny`),l){let t=r(`div`,`persona-approval-split`),i=r(`button`,`persona-approval-primary`);i.type=`button`,i.setAttribute(`data-action`,B?`allow`:`always`),U(i),i.append(a?.approveLabel??(B?`Allow once`:`Always allow`)),V&&i.append(N(`⏎`));let o=r(`button`,`persona-approval-caret`);o.type=`button`,o.setAttribute(`data-action`,`toggle-menu`),o.setAttribute(`aria-label`,`More options`),U(o);let c=p(`chevron-down`,15,`currentColor`,2);c&&o.appendChild(c),t.append(i,o),z.append(t,W),V&&W.append(N(`Esc`));let l=r(`div`,`persona-approval-menu`),u=r(`button`,`persona-approval-menu-item`);u.type=`button`,u.append(B?a?.alwaysAllowLabel??`Always allow`:`Allow once`),!B&&V&&u.append(N(`⌘⏎`)),l.appendChild(u),H=g().createPopover({anchor:t,content:l,placement:`bottom-start`,matchAnchorWidth:!0}),e.popovers.set(n.id,H),u.addEventListener(`click`,()=>{j(e,n.id),B?s({remember:!0}):s()})}else{let e=r(`button`,`persona-approval-primary persona-approval-primary--solo`);e.type=`button`,e.setAttribute(`data-action`,`allow`),U(e),e.append(a?.approveLabel??(B?`Allow once`:`Allow`)),z.append(e,W)}return F.appendChild(z),m.appendChild(F),m.addEventListener(`click`,t=>{let r=t.target instanceof Element?t.target.closest(`[data-action]`):null;if(!r)return;let i=r.getAttribute(`data-action`);i===`toggle-params`?R():i===`toggle-menu`?H?.toggle():i===`always`?(j(e,n.id),s({remember:!0})):i===`allow`?(j(e,n.id),s()):i===`deny`&&(j(e,n.id),c())}),m},L=(e=/* @__PURE__ */ new Map)=>{let t=k();return{plugin:{id:`persona-built-in-approval`,renderApproval:({message:n,approve:i,deny:a,config:o,execution:c,signal:l})=>{let u=n?.approval;if(!u)return null;let f={...s(o),...d(o,`plugin`)},p=!1,m=i,h=a;if(i=e=>{p||l?.aborted||u.status!==`pending`||(p=!0,e===void 0?m():m(e))},a=e=>{p||l?.aborted||u.status!==`pending`||(p=!0,e===void 0?h():h(e))},u.status!==`pending`){j(t,n.id);let o=u.status===`denied`?`Denied`:u.status===`timeout`?`Timed out`:c?.status===`running`?`Allowed · running`:c?.status===`completed`?`Completed`:c?.status===`failed`?`Failed`:`Allowed`;if(f?.resolvedDisplay===`row`)return I(t,e,n,u,f,i,a,!1,!1,o);if(f?.resolvedDisplay===`status-line`){let s=I(t,e,n,u,f,i,a,!1),c=r(`div`,`persona-approval-status`);return c.setAttribute(`role`,`status`),c.textContent=o,s.querySelector(`.persona-approval-actions`)?.replaceWith(c),s}if(u.status===`approved`){let e=document.createElement(`div`);return e.style.display=`none`,e}return F(u)}A(t,n.id);let _=!!o?.clientToken,v=f?.enableAlwaysAllow===!0,y=I(t,e,n,u,f,i,a,v,_),b=f?.keyboardShortcuts??`legacy`;if(b===`focused`||b===`legacy`&&v){t.pendingOrder.includes(n.id)||t.pendingOrder.push(n.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let e=e=>{if(!(e.defaultPrevented||e.isComposing||g().isEditableEventTarget(e))){if(b===`focused`){if(!e.composedPath().includes(y)||e.metaKey||e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.composedPath()[0];if(e.key===`Enter`&&t instanceof Element&&t.closest(`[data-action]`)?.getAttribute(`data-action`)!==`allow`)return}(b!==`legacy`||n.id===t.latestPendingApprovalId)&&(e.key===`Escape`||e.key===`Enter`)&&(e.preventDefault(),e.stopImmediatePropagation(),j(t,n.id),e.key===`Escape`?a():b===`focused`||f?.primaryAction===`allow-once`||e.metaKey||e.ctrlKey?i():i({remember:!0}))}};t.keyHandlers.set(n.id,e),document.addEventListener(`keydown`,e)}return l?.addEventListener(`abort`,()=>j(t,n.id),{once:!0}),y}},teardown:()=>{for(let e of[...t.keyHandlers.keys(),...t.popovers.keys()])j(t,e);t.latestPendingApprovalId=null}}};function R(e,t,r){let i=n(`div`,{className:`persona-error-detail persona-message-bubble`});i.innerHTML=t({text:e.content,message:e,streaming:!1});let a=n(`summary`,{className:`persona-error-summary`},i,n(`span`,{className:`persona-error-more`,text:`Show more`}),n(`span`,{className:`persona-error-less`,text:`Show less`}));return n(`div`,{className:`persona-error-block`,attrs:{role:`alert`,"data-message-id":e.id,"data-actions-for":e.id}},n(`strong`,{className:`persona-error-title`,text:`Something went wrong`}),n(`details`,{className:`persona-error-details`},a),r?n(`button`,{className:`persona-message-action-btn persona-error-retry`,text:`Retry`,attrs:{type:`button`,"data-action":`regenerate`,"aria-label":`Retry response`}}):null)}export{E as createApprovalBubble,L as createBuiltInApprovalPlugin,R as createErrorBlock,b as humanizeToolName,v as initApprovalUi,w as updateApprovalDetailsUI};
1
+ import{a as e,r as t}from"./chunk-CEPM3FOp.js";import{r as n,t as r}from"./chunk-D5BxWOFB.js";import{t as i}from"./chunk-BAdIgC5d.js";import{t as a}from"./chunk-DDZBCAer.js";import{t as o}from"./chunk-Bb3MaswO.js";import{n as s}from"./chunk-Bj8Hnh10.js";import{Ban as c}from"lucide";const l=(e,t)=>`var(--persona-components-approval-${e.split(`.`).join(`-`)}, ${t})`,u=(e,t)=>`var(--persona-consumer-approval-${e.split(`.`).join(`-`)}, ${t})`;function d(n,r){let i=e=>{let r=t(n,`approval.${e}`);return typeof r==`string`?r:void 0},a=(e,t,n)=>i(e)||l(t,u(`requested.text`,n)),o=(t,r)=>i(t)??(e(n,`approval.${r}`)?`var(--persona-components-approval-${r.split(`.`).join(`-`)})`:void 0),s=r===`public`,c=`var(--persona-muted, #6b7280)`,d=s?`var(--persona-primary, #171717)`:`var(--persona-text, #0b0b0b)`,f=s?`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`:`var(--persona-text, #1f2937)`,p=i(`shadow`);return{backgroundColor:o(`backgroundColor`,`requested.background`),borderColor:o(`borderColor`,`requested.border`),shadow:p===void 0?o(`shadow`,`requested.shadow`):p.trim()===``?`none`:p,titleColor:a(`titleColor`,`requested.titleColor`,d),descriptionColor:a(`descriptionColor`,`requested.descriptionColor`,c),reasonColor:i(`reasonColor`)||i(`descriptionColor`)||l(`requested.reasonColor`,u(`requested.text`,c)),parameterBackgroundColor:i(`parameterBackgroundColor`)||l(`requested.parameters.background`,s?`var(--persona-container, #f8fafc)`:`var(--persona-container, rgba(11, 11, 11, 0.04))`),parameterTextColor:a(`parameterTextColor`,`requested.parameters.foreground`,s?`var(--persona-primary, #171717)`:`var(--persona-text, #1f2937)`),approveButtonColor:o(`approveButtonColor`,`approve.background`),approveButtonTextColor:i(`approveButtonTextColor`)||u(`approve.foreground`,`var(--persona-button-primary-fg)`),denyButtonColor:i(`denyButtonColor`)??(s?u(`deny.background`,`transparent`):void 0),denyButtonTextColor:i(`denyButtonTextColor`)||u(`deny.foreground`,f),denyBorderColor:i(`denyButtonTextColor`)||u(`deny.foreground`,`var(--persona-palette-colors-error-200)`),pendingIconColor:i(`titleColor`)||l(`requested.titleColor`,u(`requested.text`,`currentColor`))}}let f;const p=(...e)=>f?.render(...e)??null,m=(...e)=>f?.node(...e)??null;let h;const g=()=>{if(!h)throw Error(`Approval UI requires core popover dependencies.`);return h};let _=()=>void 0;const v=e=>{_=e.webMcpToolTitle,e.icons&&(f=e.icons),e.popover&&(h=e.popover)},y=e=>_(e),b=e=>{let t=(e.startsWith(`webmcp:`)?e.slice(i.length):e).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return e;let n=t.join(` `).toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)},x=e=>e?.approval===!1?void 0:e?.approval,S=(e,t,n)=>{let r=x(n)?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},C=(e,t,n)=>{let r=x(n);e.setAttribute(`aria-expanded`,t?`true`:`false`);let i=e.querySelector(`[data-approval-details-label]`);i&&(i.textContent=t?r?.hideDetailsLabel??`Hide details`:r?.showDetailsLabel??`Show details`);let a=e.querySelector(`[data-approval-details-chevron]`);if(a){a.innerHTML=``;let e=p(t?`chevron-up`:`chevron-down`,14,`currentColor`,2);e&&a.appendChild(e)}},w=(e,t,n,r=/* @__PURE__ */ new Map)=>{let i=t.querySelector(`button[data-bubble-type="approval"]`),a=t.querySelector(`[data-approval-details]`);if(!i||!a)return;let o=S(e,r,n);C(i,o,n),a.style.display=o?``:`none`},T=(e,t,n,r)=>{let i=d(n,`public`);if(D(t,n),!r)return;let a=t.querySelector(`[data-approval-status]`);if(a){a.textContent=r.status===`approved`?`Approved`:r.status===`denied`?`Denied`:r.status===`timeout`&&r.interrupted?`Interrupted`:r.status===`timeout`?`Timeout`:`Pending`;let e=r.status===`approved`?`success`:r.status===`denied`?`error`:r.status===`timeout`?`warning`:void 0;e&&(a.className=`persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium`,a.style.backgroundColor=`var(--persona-palette-colors-${e}-100)`,a.style.color=`var(--persona-palette-colors-${e}-700)`),a.setAttribute(`data-approval-status`,r.status)}let o=t.querySelector(`[data-approval-icon]`);if(o){o.innerHTML=``;let e=r.status===`denied`?`shield-x`:r.status===`timeout`?`shield-alert`:`shield-check`,t=r.status===`approved`?`var(--persona-feedback-success, var(--persona-palette-colors-success-600))`:r.status===`denied`?`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`:r.status===`timeout`?`var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))`:i.pendingIconColor,n=p(e,20,t,2);n&&o.appendChild(n)}let s=t.querySelector(`[data-approval-buttons]`);s&&(s.style.display=r.status===`pending`?``:`none`)},E=(e,t,i=/* @__PURE__ */ new Map)=>{let s=e.approval,c=x(t),l=s?.status===`pending`,u=r(`div`,`persona-approval-bubble persona-w-full persona-rounded-2xl persona-border persona-shadow-sm persona-overflow-hidden`);if(u.id=`bubble-${e.id}`,u.setAttribute(`data-message-id`,e.id),!s)return D(u,t),u;let d=r(`div`,`persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3`),f=n(`div`,{className:`persona-flex-shrink-0 persona-mt-0.5`,attrs:{"data-approval-icon":`true`}}),m=r(`div`,`persona-flex-1 persona-min-w-0`),h=r(`div`,`persona-flex persona-items-center persona-gap-2`),g=n(`span`,{className:`persona-text-sm persona-font-medium persona-text-persona-primary`,attrs:{"data-approval-title":`true`},text:c?.title??`Approval Required`});if(h.appendChild(g),!l){let e=r(`span`,`persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium`);e.setAttribute(`data-approval-status`,s.status),h.appendChild(e)}if(m.appendChild(h),s.status===`timeout`&&s.interrupted){let e=r(`p`,`persona-text-sm`);e.textContent=a,m.appendChild(e)}let _=s.toolType===`webmcp`||s.toolName.startsWith(`webmcp:`)?y(s.toolName):void 0,v=c?.formatDescription?.({toolName:s.toolName,toolType:s.toolType,description:s.description,parameters:s.parameters,..._?{displayTitle:_}:{},...s.reason?{reason:s.reason}:{}}),w=!s.toolName,E=v||(w?s.description:`The assistant wants to use “${_??b(s.toolName)}”.`),O=n(`p`,{className:`persona-text-sm persona-mt-0.5 persona-text-persona-muted`,attrs:{"data-approval-summary":`true`},text:E});if(m.appendChild(O),s.reason){let e=r(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);e.setAttribute(`data-approval-reason`,`true`);let t=r(`span`,`persona-font-medium`);t.textContent=`${c?.reasonLabel??`Agent's stated reason:`} `,e.appendChild(t),e.appendChild(document.createTextNode(s.reason)),m.appendChild(e)}let k=c?.detailsDisplay??`collapsed`,A=!!s.description&&!w,j=A||!!s.parameters;if(k!==`hidden`&&j){let n=S(e.id,i,t),a=r(`button`,`persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted`);a.type=`button`,a.setAttribute(`data-expand-header`,`true`),a.setAttribute(`data-bubble-type`,`approval`);let c=r(`span`);c.setAttribute(`data-approval-details-label`,`true`);let l=r(`span`,`persona-inline-flex persona-items-center`);l.setAttribute(`data-approval-details-chevron`,`true`),a.append(c,l),C(a,n,t),m.appendChild(a);let u=r(`div`);if(u.setAttribute(`data-approval-details`,`true`),u.style.display=n?``:`none`,A){let e=r(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);e.setAttribute(`data-approval-description`,`true`),e.textContent=s.description,u.appendChild(e)}if(s.parameters){let e=r(`pre`,`persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary`);e.setAttribute(`data-approval-parameters`,`true`),e.style.fontSize=`0.75rem`,e.style.lineHeight=`1rem`,e.textContent=o(s.parameters),u.appendChild(e)}m.appendChild(u)}if(l){let e=r(`div`,`persona-flex persona-gap-2 persona-mt-2`);e.setAttribute(`data-approval-buttons`,`true`);for(let t of[`approve`,`deny`]){let r=n(`button`,{className:`persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer`+(t===`approve`?` persona-border-none`:``),attrs:{type:`button`,"data-approval-action":t}}),i=p(t===`approve`?`shield-check`:`shield-x`,14,`currentColor`,2);i&&(i.style.marginRight=`4px`,r.appendChild(i)),r.appendChild(document.createTextNode(t===`approve`?c?.approveLabel??`Approve`:c?.denyLabel??`Deny`)),e.appendChild(r)}m.appendChild(e)}return d.append(f,m),u.appendChild(d),T(e.id,u,t,s),u},D=(e,t)=>{let n=d(t,`public`);e.style.backgroundColor=n.backgroundColor??`var(--persona-approval-bg)`,e.style.borderColor=n.borderColor??`var(--persona-approval-border)`,e.style.boxShadow=n.shadow===void 0?`var(--persona-approval-shadow)`:n.shadow.trim()||`none`;let r=(t,n)=>{e.querySelectorAll(t).forEach(e=>{e.style.color=n??``})};e.querySelector(`[data-approval-status]`)||e.querySelector(`[data-approval-icon] svg`)?.setAttribute(`stroke`,n.pendingIconColor),r(`[data-approval-title]`,n.titleColor),r(`[data-approval-summary], [data-approval-description], button[data-bubble-type='approval']`,n.descriptionColor),r(`[data-approval-reason]`,n.reasonColor),r(`[data-approval-parameters]`,n.parameterTextColor),e.querySelectorAll(`[data-approval-parameters]`).forEach(e=>{e.style.backgroundColor=n.parameterBackgroundColor??``});for(let t of[`approve`,`deny`]){let r=e.querySelector(`[data-approval-action="${t}"]`);if(!r)continue;let i=t===`approve`?n.approveButtonTextColor:n.denyButtonTextColor;r.style.backgroundColor=(t===`approve`?n.approveButtonColor??`var(--persona-approval-approve-bg)`:n.denyButtonColor)??``,r.style.color=i??``,r.querySelector(`svg`)?.setAttribute(`stroke`,i??`currentColor`),t===`deny`&&(r.style.border=`1px solid ${n.denyBorderColor}`)}};let O=0;const k=()=>({disclosurePrefix:`approval-${++O}`,keyHandlers:/* @__PURE__ */ new Map,popovers:/* @__PURE__ */ new Map,pendingOrder:[],latestPendingApprovalId:null}),A=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener(`keydown`,n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},j=(e,t)=>{A(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},M=(e,t,n)=>{let r=n?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},N=e=>{let t=r(`span`,`persona-approval-kbd`);return t.textContent=e,t},P=(e,t)=>{let n=r(`span`,`persona-approval-title`);t?.titleColor&&(n.style.color=t.titleColor);let i=e.toolType===`webmcp`||e.toolName.startsWith(`webmcp:`)?y(e.toolName):void 0,a=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??``,parameters:e.parameters,...i?{displayTitle:i}:{},...e.reason?{reason:e.reason}:{}});if(a)return n.textContent=a,n;let o=i??b(e.toolName),s=e.toolType&&e.toolType!==`webmcp`?e.toolType:null;n.append(`The assistant wants to use `);let c=document.createElement(`strong`);if(c.textContent=o,n.appendChild(c),s){n.append(` from `);let e=document.createElement(`strong`);e.textContent=s,n.appendChild(e)}return n},F=e=>{let t=r(`div`,`persona-approval-resolved`),i=m(c,15,`currentColor`,2);i&&t.appendChild(i);let o=r(`span`,`persona-approval-resolved-name`);o.textContent=e.toolName?b(e.toolName):`Tool`;let s=e.status===`timeout`&&e.interrupted?` approval expired. ${a}`:e.status===`timeout`?` timed out`:` denied`;return t.appendChild(n(`span`,{className:`persona-approval-resolved-text`},o,s)),t},I=(e,t,n,i,a,s,c,l,u=!1,d)=>{let f=d!==void 0,m=r(`div`,f?`persona-approval-row persona-activity-row`:`persona-approval-card persona-shadow-sm`);m.id=`bubble-${n.id}`,m.setAttribute(`data-message-id`,n.id),m.setAttribute(`data-bubble-type`,`approval`),a?.backgroundColor&&(m.style.background=a.backgroundColor),a?.borderColor&&(m.style.borderColor=a.borderColor),a?.shadow!==void 0&&(m.style.boxShadow=a.shadow.trim()===``?`none`:a.shadow);let h=a?.detailsDisplay??`collapsed`,_=!!i.description&&h!==`hidden`,v=i.parameters!=null&&h!==`hidden`&&!u,x=!!i.reason&&h!==`hidden`,S=_||v||f&&x,C=S&&M(n.id,t,a),w=a?.showDetailsLabel??`Show details`,T=a?.hideDetailsLabel??`Hide details`,E=r(f&&!S?`div`:`button`,`persona-approval-head`);E instanceof HTMLButtonElement&&(E.type=`button`),S?(E.setAttribute(`data-action`,`toggle-params`),E.setAttribute(`aria-expanded`,C?`true`:`false`),E.setAttribute(`aria-label`,C?T:w)):E.setAttribute(`data-static`,`true`);let D=r(`span`,`persona-approval-logo`),O=p(`shield-check`,16,`currentColor`,2);O&&D.appendChild(O),f||E.appendChild(D);let k=f?r(`span`,`persona-approval-title`):P(i,a),A=``;if(f){let e=(i.toolType===`webmcp`||i.toolName.startsWith(`webmcp:`)?y(i.toolName):void 0)??b(i.toolName),t=r(`span`,`persona-approval-status`);t.setAttribute(`role`,`status`),t.textContent=d,k.append(e,` · `,t),a?.titleColor&&(k.style.color=a.titleColor),A=`${e} · ${d}`}if(S){let e=r(`span`,`persona-approval-toggle`);e.setAttribute(`aria-hidden`,`true`);let t=p(`chevron-down`,14,`currentColor`,2);t&&e.appendChild(t),k.append(` `),k.appendChild(e)}E.appendChild(k),m.appendChild(E);let F=r(`div`,`persona-approval-body`),I;if(S){let e=r(`div`,`persona-approval-details`);e.setAttribute(`data-role`,`params`),e.hidden=!C;let t=t=>{let n=r(`div`,`persona-tool-detail`),i=r(`div`,`persona-tool-detail-label`);return i.textContent=t,n.appendChild(i),e.appendChild(n),n},n=f&&v?t(`Request`):e;if(f&&(_||x)&&(I=t(`Context`)),_){let t=r(`p`,`persona-approval-desc`);a?.descriptionColor&&(t.style.color=a.descriptionColor),t.textContent=i.description,(I??e).appendChild(t)}if(v){let e=r(`pre`,f?`persona-approval-params persona-tool-detail-value persona-tool-detail-code`:`persona-approval-params`);a?.parameterBackgroundColor&&(e.style.background=a.parameterBackgroundColor),a?.parameterTextColor&&(e.style.color=a.parameterTextColor),e.textContent=o(i.parameters),n.appendChild(e)}F.appendChild(e)}if(u){let e=r(`div`,`persona-approval-call`);e.setAttribute(`data-role`,`raw-call`);let t=r(`code`,`persona-approval-tool-name`);if(t.textContent=i.toolName,e.appendChild(t),i.parameters!=null){let t=r(`pre`,`persona-approval-params`);a?.parameterBackgroundColor&&(t.style.background=a.parameterBackgroundColor),a?.parameterTextColor&&(t.style.color=a.parameterTextColor),t.textContent=o(i.parameters),e.appendChild(t)}F.appendChild(e)}if(i.reason){let e=r(`p`,`persona-approval-reason`);a?.reasonColor?e.style.color=a.reasonColor:a?.descriptionColor&&(e.style.color=a.descriptionColor);let t=r(`span`,`persona-approval-reason-label`);t.textContent=`${a?.reasonLabel??`Agent's stated reason:`} `,e.append(t,document.createTextNode(i.reason)),f?I?.appendChild(e):F.appendChild(e)}let L=e=>{E.setAttribute(`aria-expanded`,String(e));let t=e?T:w;E.setAttribute(`aria-label`,f?`${A}. ${t}`:t)},R=()=>{let e=m.querySelector(`[data-role="params"]`);if(!e)return;let r=e.hidden!==!1;e.hidden=!r,f&&(F.hidden=!r),L(r),t.set(n.id,r)};if(f){if(S){let t=F.querySelector(`[data-role="params"]`);t.id=`${e.disclosurePrefix}-details-${n.id}`,E.setAttribute(`aria-controls`,t.id),L(C),F.hidden=!C,m.appendChild(F),E.addEventListener(`click`,R)}return m}let z=r(`div`,`persona-approval-actions`),B=a?.primaryAction===`allow-once`,V=a?.keyboardShortcuts!==!1&&a?.keyboardShortcuts!==`focused`,H=null,U=e=>{a?.approveButtonColor&&(e.style.background=a.approveButtonColor),a?.approveButtonTextColor&&(e.style.color=a.approveButtonTextColor)},W=r(`button`,`persona-approval-deny`);if(W.type=`button`,W.setAttribute(`data-action`,`deny`),a?.denyButtonColor&&(W.style.background=a.denyButtonColor),a?.denyButtonTextColor&&(W.style.color=a.denyButtonTextColor),W.append(a?.denyLabel??`Deny`),l){let t=r(`div`,`persona-approval-split`),i=r(`button`,`persona-approval-primary`);i.type=`button`,i.setAttribute(`data-action`,B?`allow`:`always`),U(i),i.append(a?.approveLabel??(B?`Allow once`:`Always allow`)),V&&i.append(N(`⏎`));let o=r(`button`,`persona-approval-caret`);o.type=`button`,o.setAttribute(`data-action`,`toggle-menu`),o.setAttribute(`aria-label`,`More options`),U(o);let c=p(`chevron-down`,15,`currentColor`,2);c&&o.appendChild(c),t.append(i,o),z.append(t,W),V&&W.append(N(`Esc`));let l=r(`div`,`persona-approval-menu`),u=r(`button`,`persona-approval-menu-item`);u.type=`button`,u.append(B?a?.alwaysAllowLabel??`Always allow`:`Allow once`),!B&&V&&u.append(N(`⌘⏎`)),l.appendChild(u),H=g().createPopover({anchor:t,content:l,placement:`bottom-start`,matchAnchorWidth:!0}),e.popovers.set(n.id,H),u.addEventListener(`click`,()=>{j(e,n.id),B?s({remember:!0}):s()})}else{let e=r(`button`,`persona-approval-primary persona-approval-primary--solo`);e.type=`button`,e.setAttribute(`data-action`,`allow`),U(e),e.append(a?.approveLabel??(B?`Allow once`:`Allow`)),z.append(e,W)}return F.appendChild(z),m.appendChild(F),m.addEventListener(`click`,t=>{let r=t.target instanceof Element?t.target.closest(`[data-action]`):null;if(!r)return;let i=r.getAttribute(`data-action`);i===`toggle-params`?R():i===`toggle-menu`?H?.toggle():i===`always`?(j(e,n.id),s({remember:!0})):i===`allow`?(j(e,n.id),s()):i===`deny`&&(j(e,n.id),c())}),m},L=(e=/* @__PURE__ */ new Map)=>{let t=k();return{plugin:{id:`persona-built-in-approval`,renderApproval:({message:n,approve:i,deny:a,config:o,execution:c,signal:l})=>{let u=n?.approval;if(!u)return null;let f={...s(o),...d(o,`plugin`)},p=!1,m=i,h=a;if(i=e=>{p||l?.aborted||u.status!==`pending`||(p=!0,e===void 0?m():m(e))},a=e=>{p||l?.aborted||u.status!==`pending`||(p=!0,e===void 0?h():h(e))},u.status!==`pending`){j(t,n.id);let o=u.status===`denied`?`Denied`:u.status===`timeout`?`Timed out`:c?.status===`running`?`Allowed · running`:c?.status===`completed`?`Completed`:c?.status===`failed`?`Failed`:`Allowed`;if(f?.resolvedDisplay===`row`)return I(t,e,n,u,f,i,a,!1,!1,o);if(f?.resolvedDisplay===`status-line`){let s=I(t,e,n,u,f,i,a,!1),c=r(`div`,`persona-approval-status`);return c.setAttribute(`role`,`status`),c.textContent=o,s.querySelector(`.persona-approval-actions`)?.replaceWith(c),s}if(u.status===`approved`){let e=document.createElement(`div`);return e.style.display=`none`,e}return F(u)}A(t,n.id);let _=!!o?.clientToken,v=f?.enableAlwaysAllow===!0,y=I(t,e,n,u,f,i,a,v,_),b=f?.keyboardShortcuts??`legacy`;if(b===`focused`||b===`legacy`&&v){t.pendingOrder.includes(n.id)||t.pendingOrder.push(n.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let e=e=>{if(!(e.defaultPrevented||e.isComposing||g().isEditableEventTarget(e))){if(b===`focused`){if(!e.composedPath().includes(y)||e.metaKey||e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.composedPath()[0];if(e.key===`Enter`&&t instanceof Element&&t.closest(`[data-action]`)?.getAttribute(`data-action`)!==`allow`)return}b===`legacy`&&n.id!==t.latestPendingApprovalId||e.key!==`Escape`&&e.key!==`Enter`||(e.preventDefault(),e.stopImmediatePropagation(),j(t,n.id),e.key===`Escape`?a():b===`focused`||f?.primaryAction===`allow-once`||e.metaKey||e.ctrlKey?i():i({remember:!0}))}};t.keyHandlers.set(n.id,e),document.addEventListener(`keydown`,e)}return l?.addEventListener(`abort`,()=>j(t,n.id),{once:!0}),y}},teardown:()=>{for(let e of[...t.keyHandlers.keys(),...t.popovers.keys()])j(t,e);t.latestPendingApprovalId=null}}};function R(e,t,r){let i=n(`div`,{className:`persona-error-detail persona-message-bubble`});i.innerHTML=t({text:e.content,message:e,streaming:!1});let a=n(`summary`,{className:`persona-error-summary`},i,n(`span`,{className:`persona-error-more`,text:`Show more`}),n(`span`,{className:`persona-error-less`,text:`Show less`}));return n(`div`,{className:`persona-error-block`,attrs:{role:`alert`,"data-message-id":e.id,"data-actions-for":e.id}},n(`strong`,{className:`persona-error-title`,text:`Something went wrong`}),n(`details`,{className:`persona-error-details`},a),r?n(`button`,{className:`persona-message-action-btn persona-error-retry`,text:`Retry`,attrs:{type:`button`,"data-action":`regenerate`,"aria-label":`Retry response`}}):null)}export{E as createApprovalBubble,L as createBuiltInApprovalPlugin,R as createErrorBlock,b as humanizeToolName,v as initApprovalUi,w as updateApprovalDetailsUI};
@@ -1 +1 @@
1
- import{a as e,r as t}from"./chunk-CEPM3FOp.js";import{t as n}from"./chunk-D5BxWOFB.js";import{t as r}from"./chunk-DehTFE4q.js";const i=(e,t,r)=>{let i=r;for(let r of t){let t=n(`span`,`persona-tool-char`);t.style.setProperty(`--char-index`,String(i)),t.textContent=r===` `?`\xA0`:r,e.appendChild(t),i++}return i};function a(e,t){let{animation:n,duration:r,color:a,secondaryColor:o}=t;if(n===`none`||(e.setAttribute(`data-preserve-animation`,`true`),e.classList.add(`persona-tool-loading-${n}`),r&&e.style.setProperty(`--persona-tool-anim-duration`,r),a&&e.style.setProperty(`--persona-tool-anim-color`,a),o&&e.style.setProperty(`--persona-tool-anim-secondary-color`,o),n===`pulse`))return;let s=0,c=e=>{for(let t of Array.from(e.childNodes))if(t.nodeType===3){let e=document.createElement(`span`);s=i(e,t.textContent??``,s),t.replaceWith(...Array.from(e.childNodes))}else t instanceof HTMLElement&&!t.hasAttribute(`data-tool-elapsed`)&&c(t)};c(e)}const{resolveToolStyles:o,applyToolPadding:s,toolLoadingDuration:c}=r({getExplicitLegacyStyle:t,hasExplicitThemeStyle:e});function l(e,t,n){let r=t?.loadingLabel,i=n===`reasoning`,s=i?t?.reasoning:o(t),l=n===`waiting`?void 0:i?t?.features?.reasoningDisplay:t?.features?.toolCallDisplay,u=r?.animation??l?.loadingAnimation??(n===`waiting`||t?.future?.v5Defaults?`shimmer`:`none`);if(u===`none`)return;let d={animation:u,duration:r?.duration===void 0?i?`${s?.loadingAnimationDuration??2e3}ms`:c(t):`${r.duration}ms`,color:r?.color??s?.loadingAnimationColor,secondaryColor:r?.secondaryColor??s?.loadingAnimationSecondaryColor};e.dataset.personaLoadingLabel=n,e.dataset.personaLoadingText=e.textContent??``,e.dataset.personaLoadingAnimation=JSON.stringify([n,e.textContent,d,!!r?.animate,e.className,e.getAttribute(`style`)]),r?.animate?e.setAttribute(`data-preserve-animation`,`true`):a(e,d)}function u(e,t){let n=!1,r=/* @__PURE__ */ new Map,i=e.ownerDocument.defaultView?.matchMedia?.(`(prefers-reduced-motion: reduce)`),a=e=>{try{e()}catch(e){console.warn(`[persona] Loading label animation failed`,e)}},o=e=>{let t=r.get(e);r.delete(e),t?.handle&&a(()=>t.handle?.destroy())},s=e=>`${e.closest(`[data-wrapper-id]`)?.dataset.wrapperId??``}:${e.dataset.personaLoadingLabel}`,c=e=>{if(n)return;let a=i?.matches?void 0:t().loadingLabel?.animate;if(!a&&!r.size)return;let c=new Set(Array.from(e.querySelectorAll(`[data-persona-loading-label]`),s)),l=new Set(Array.from(e.querySelectorAll(`[data-persona-reuse]`),e=>e.dataset.wrapperId));for(let[e,t]of r){let n=l.has(e.closest(`[data-wrapper-id]`)?.dataset.wrapperId);(t.start!==a||!n&&!c.has(s(e)))&&o(e)}},l=()=>{if(n)return;let s=t(),c=i?.matches?void 0:s.loadingLabel?.animate;if(!c&&!r.size)return;let l=new Set(e.querySelectorAll(`[data-persona-loading-label]`));for(let[e,t]of r)(!c||t.start!==c||!l.has(e)||e.dataset.personaLoadingLabel!==t.kind)&&o(e);if(c)for(let e of l){if(n||t().loadingLabel?.animate!==c)break;let i={element:e,config:s,text:e.dataset.personaLoadingText??``,kind:e.dataset.personaLoadingLabel,reducedMotion:!1},o=r.get(e);if(o)a(()=>o.handle?.update?.(i));else{let t={start:c,kind:i.kind,handle:void 0};r.set(e,t),a(()=>{let n=c(i);r.get(e)===t?t.handle=n:n?.destroy()})}}};return i?.addEventListener?.(`change`,l),{prepare:c,sync:l,destroy(){n=!0,i?.removeEventListener?.(`change`,l);for(let e of r.keys())o(e)}}}export{a as applyLoadingAnimation,l as applyLoadingLabel,u as createLoadingLabelLifecycle};
1
+ import{a as e,r as t}from"./chunk-CEPM3FOp.js";import{t as n}from"./chunk-D5BxWOFB.js";import{t as r}from"./chunk-DehTFE4q.js";const i=(e,t,r)=>{let i=r;for(let r of t){let t=n(`span`,`persona-tool-char`);t.style.setProperty(`--char-index`,String(i)),t.textContent=r===` `?`\xA0`:r,e.appendChild(t),i++}return i};function a(e,t){let{animation:n,duration:r,color:a,secondaryColor:o}=t;if(n===`none`||(e.setAttribute(`data-preserve-animation`,`true`),e.classList.add(`persona-tool-loading-${n}`),r&&e.style.setProperty(`--persona-tool-anim-duration`,r),a&&e.style.setProperty(`--persona-tool-anim-color`,a),o&&e.style.setProperty(`--persona-tool-anim-secondary-color`,o),n===`pulse`))return;let s=0,c=e=>{for(let t of Array.from(e.childNodes))if(t.nodeType===3){let e=document.createElement(`span`);s=i(e,t.textContent??``,s),t.replaceWith(...Array.from(e.childNodes))}else t instanceof HTMLElement&&!t.hasAttribute(`data-tool-elapsed`)&&c(t)};c(e)}const{resolveToolStyles:o,applyToolPadding:s,toolLoadingDuration:c}=r({getExplicitLegacyStyle:t,hasExplicitThemeStyle:e});function l(e,t,n){let r=t?.loadingLabel,i=n===`reasoning`,s=i?t?.reasoning:o(t),l=n===`waiting`?void 0:i?t?.features?.reasoningDisplay:t?.features?.toolCallDisplay,u=r?.animation??l?.loadingAnimation??(n===`waiting`||t?.future?.v5Defaults?`shimmer`:`none`);if(u===`none`)return;let d={animation:u,duration:r?.duration===void 0?i?`${s?.loadingAnimationDuration??2e3}ms`:c(t):`${r.duration}ms`,color:r?.color??s?.loadingAnimationColor,secondaryColor:r?.secondaryColor??s?.loadingAnimationSecondaryColor};e.dataset.personaLoadingLabel=n,e.dataset.personaLoadingText=e.textContent??``,e.dataset.personaLoadingAnimation=JSON.stringify([n,e.textContent,d,!!r?.animate,e.className,e.getAttribute(`style`)]),r?.animate?e.setAttribute(`data-preserve-animation`,`true`):a(e,d)}function u(e,t){let n=!1,r=/* @__PURE__ */ new Map,i=e.ownerDocument.defaultView?.matchMedia?.(`(prefers-reduced-motion: reduce)`),a=e=>{try{e()}catch(e){console.warn(`[persona] Loading label animation failed`,e)}},o=e=>{let t=r.get(e);r.delete(e),t?.handle&&a(()=>t.handle?.destroy())},s=e=>`${e.closest(`[data-wrapper-id]`)?.dataset.wrapperId??``}:${e.dataset.personaLoadingLabel}`,c=e=>{if(n)return;let a=i?.matches?void 0:t().loadingLabel?.animate;if(!a&&!r.size)return;let c=new Set(Array.from(e.querySelectorAll(`[data-persona-loading-label]`),s)),l=new Set(Array.from(e.querySelectorAll(`[data-persona-reuse]`),e=>e.dataset.wrapperId));for(let[e,t]of r){let n=l.has(e.closest(`[data-wrapper-id]`)?.dataset.wrapperId);(t.start!==a||!n&&!c.has(s(e)))&&o(e)}},l=()=>{if(n)return;let s=t(),c=i?.matches?void 0:s.loadingLabel?.animate;if(!c&&!r.size)return;let l=new Set(e.querySelectorAll(`[data-persona-loading-label]`));for(let[e,t]of r)c&&t.start===c&&l.has(e)&&e.dataset.personaLoadingLabel===t.kind||o(e);if(c)for(let e of l){if(n||t().loadingLabel?.animate!==c)break;let i={element:e,config:s,text:e.dataset.personaLoadingText??``,kind:e.dataset.personaLoadingLabel,reducedMotion:!1},o=r.get(e);if(o)a(()=>o.handle?.update?.(i));else{let t={start:c,kind:i.kind,handle:void 0};r.set(e,t),a(()=>{let n=c(i);r.get(e)===t?t.handle=n:n?.destroy()})}}};return i?.addEventListener?.(`change`,l),{prepare:c,sync:l,destroy(){n=!0,i?.removeEventListener?.(`change`,l);for(let e of r.keys())o(e)}}}export{a as applyLoadingAnimation,l as applyLoadingLabel,u as createLoadingLabelLifecycle};
@@ -1 +1 @@
1
- import{i as e,r as t,t as n}from"./chunk-D5BxWOFB.js";import{r}from"./chunk-Bb41bKyp.js";import{n as i,r as a}from"./chunk-i4qGOJAL.js";import{a as o}from"./chunk-Cy1A8vbF.js";import{n as s}from"./chunk-CLMIHW4_.js";const c=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},l=e=>Object.freeze({...e}),u=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),d=e=>e?l(e):null;function ee(e){let{plugins:t,config:n}=e,r=!1,i=!1,a=!1,o=!1,s=null,ee=[],f=()=>{for(let e of ee.splice(0))try{e()}catch(e){c(`renderHistoryView cleanup`,e)}},p=(e,n)=>{for(let r of t){let t=r[e];if(t)try{let e=t(n);if(e)return e}catch(t){c(e,t)}}return null},m=()=>({presentation:e.getPresentation(),config:n}),h={header:t=>o?p(`renderHistoryHeader`,Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:l(t.identityStatus),pendingAction:d(t.pendingAction),copy:l(t.copy),actions:Object.freeze({close:_.close,startNewConversation:_.startNewConversation}),defaultRenderer:t.defaultRenderer})):null,conversation:e=>o?p(`renderHistoryConversation`,Object.freeze({...m(),conversation:u(e.conversation),active:e.active,pending:e.pending,open:e.open,requestDelete:e.requestDelete,defaultRenderer:e.defaultRenderer})):null,state:e=>o?p(`renderHistoryState`,Object.freeze({...m(),state:l(e.state),identityStatus:l(e.identityStatus),copy:l(e.copy),...e.retry?{retry:e.retry}:{},...e.startNewConversation?{startNewConversation:e.startNewConversation}:{},defaultRenderer:e.defaultRenderer})):null},te=t.flatMap(t=>(t.railSections??[]).map(t=>({...t,placement:t.placement??`above-conversations`,items:[],render:n=>t.render(Object.freeze({collapsed:n,presentation:e.getPresentation(),actions:_}))}))),g=e.createView({slots:h,renderDom:!1,onModelChange:()=>b(),railSections:te}),_=Object.freeze({...g.operations,close:e.close}),v=()=>(o=!0,g.setDomRenderEnabled(!0),g.element),ne=t=>Object.freeze({conversations:Object.freeze(t.conversations.map(u)),activeConversationId:t.activeConversationId,state:l(t.state),pendingAction:d(t.pendingAction),identityStatus:l(t.identityStatus),nextCursor:t.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:l(g.copy),actions:_,defaultRenderer:v,requestRender:()=>b(),onCleanup:e=>{ee.push(e)}}),y=()=>{o=!1;let e=null;for(let n of t)if(n.renderHistoryView){try{e=n.renderHistoryView(ne(g.getModel()))}catch(t){c(`renderHistoryView`,t),e=null}if(e)break}let n=!e||e.contains(g.element);return o=n,g.setDomRenderEnabled(n),e??g.element};function b(){if(!(!a||r||i)){i=!0;try{f();let t=y();if(t===s)return;let n=s;s=t,e.onElementChanged(t,n)}finally{i=!1}}}return a=!0,b(),{view:g,get element(){return s??g.element},requestRender:b,dispose:()=>{r=!0,f()}}}const f=/* @__PURE__ */ new Map([[`not_found`,`not_found`],[`conversation_deleted`,`not_found`],[`rate_limited`,`rate_limited`],[`authentication_required`,`authentication_required`],[`invalid_identity_proof`,`authentication_required`],[`visitor_identity_mismatch`,`authentication_required`],[`visitor_required`,`authentication_required`],[`identity_provider_failed`,`identity_provider_failed`],[`proof_not_admitted`,`proof_not_admitted`],[`identity_contract_violation`,`proof_not_admitted`],[`unauthorized`,`authentication_failed`],[`visitor_token_missing`,`authentication_failed`],[`conversation_credential_missing`,`authentication_failed`]]),p=/* @__PURE__ */ new Map([[`not_found`,`That conversation is no longer available.`],[`rate_limited`,`Too many history requests.`],[`authentication_failed`,`History access was not authorized.`],[`authentication_required`,`Sign in again to view account history.`],[`identity_provider_failed`,`The identity provider did not respond.`],[`proof_not_admitted`,`Account history is not available for this configuration.`],[`unsupported_scope`,`This history scope is not supported.`],[`unavailable`,`Conversation history is unavailable right now.`]]),m=e=>p.get(e)??`Conversation history is unavailable right now.`;function h(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let t=f.get(e.code)??`unavailable`;return new n(t,m(t),{...e.retryAfterSeconds===void 0?{}:{retryAfterSeconds:e.retryAfterSeconds}})}return new n(`unavailable`,m(`unavailable`))}function te(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,r=e.getIdentityProofConfigured()?[`browser`,`verified-user`]:[`browser`],o={scopes:r},s=e=>{if(!r.includes(e))throw new t(`unsupported_scope`,m(`unsupported_scope`))},c=async(t,n)=>{s(t);try{return await n()}catch(t){throw h(t,e.errors)}},l=t=>{let n=!1;return{conversationId:t.session.conversationId??``,conversationRevision:t.session.conversationRevision??``,async commit(){n||(n=!0,t.commit(),await e.onActivationCommitted(t.session))},discard(){n||(n=!0,t.discard())}}};return{capabilities:o,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(e){return n().subscribeHistoryIdentityStatus(e)},subscribeAvailability(e){return n().subscribeHistoryAvailability(e)},async list(e){return c(e.context.scope,async()=>{let t=await n().listConversations({...e.cursor?{cursor:e.cursor}:{},...e.limit===void 0?{}:{limit:e.limit},...e.targetId?{targetId:e.targetId}:{},scope:e.context.scope});return{items:t.data,nextCursor:t.nextCursor}})},async getPage(e,t){return c(t.context.scope,async()=>{let r=await n().getConversation(e,{...t.cursor?{messageCursor:t.cursor}:{},scope:t.context.scope}),o=i(r.messages,{...t.beforeCreatedAt?{beforeCreatedAt:t.beforeCreatedAt}:{}});return{summary:r.summary,messages:a([],o),conversationRevision:r.conversationRevision??``,nextCursor:r.nextMessageCursor}})},async prepareOpen(e,t){return c(t.context.scope,async()=>l(await n().prepareConversationSession(e)))},async prepareStartNew(e){return c(e.context.scope,async()=>l(await n().prepareNewConversationSession()))},async delete(e,t){await c(t.context.scope,()=>n().deleteConversation(e,{scope:t.context.scope}))},async deleteAll(e){return c(e.context.scope,()=>n().deleteAllConversations({...e.targetId===void 0?{}:{targetId:e.targetId},scope:e.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}const g=i=>{let a=s(i.config.features?.history?.copy),c=null,l=!1,u=null,d=null,f=`conversation`,p=null,m=null,h=null,g=null,_=0,v=null,ne=null,y=null,b=`persona-history-${Math.random().toString(36).slice(2,8)}`,x=()=>i.historyFeatureEnabled()&&!!c&&!l,re=()=>{let e=i.session.getStatus();return i.isStreaming||e===`paused`||e===`resuming`},ie=()=>{let e=i.config.features?.history?.scope;if(e)return e;let t=i.config.getIdentityProof?`verified-user`:`browser`,n=c?.capabilities.scopes;return!n||n.includes(t)?t:n[0]??t},S=()=>d?.scope??ie(),ae=()=>i.session.getClientSession()?.targetId??null,oe=e=>`${e.state}:${`reason`in e?e.reason:``}`,se=e=>{let t=oe(e);t!==g&&(g=t,i.eventBus.emit(`history:identityStatusChanged`,{status:e,timestamp:Date.now()}))},ce=null,le=null,ue=()=>{if(!i.historyFeatureEnabled())return null;let e=i.getHistoryProviderFactory();if(e)return e();let t=i.config.features?.history?.provider;return t?typeof t==`function`?(ce!==t&&(ce=t,le=t()),le):t:i.session.isClientTokenMode()?te({errors:i.historyErrors,client:i.session.getClient(),getIdentityProofConfigured:()=>typeof i.config.getIdentityProof==`function`,onActivationCommitted:e=>i.session.bindActivatedSession(e),getClient:()=>i.session.getClient()}):null},de=()=>{ne?.(),ne=null,y?.(),y=null,l=!1;let e=c;c=ue(),e&&e!==c&&i.discardConversationContinuity();let t={...i.historyInternals};c?t.historyProvider=c:delete t.historyProvider,i.historyInternals=t,i.session.setHistoryInternals(i.historyInternals),c&&(ne=c.subscribeAvailability?.(e=>{l=!e,e||q({restoreFocus:!1}),$()})??null,y=c.subscribeIdentityStatus(e=>se(e)),g=oe(c.getIdentityStatus()))},fe=()=>{let e=i.config.features?.history?.presentation??`panel`;if(e===`panel`||e===`auto`&&i.launcherEnabled&&!i.isDockedMountMode(i.config))return`panel`;let t=i.artifactSplitRoot??i.container;return(t.getBoundingClientRect().width||t.clientWidth)>=720?`rail`:`panel`},C=(e,t)=>{t?(e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`inert`,``)):(e.removeAttribute(`aria-hidden`),e.removeAttribute(`inert`))},pe=`data-persona-history-suppressed`,w=null,T=null,E=null,D=null,me=null,he=``,ge=()=>i.header===me?he:o(i.config)?``:`none`,_e=()=>i.historyPresentation===`panel`&&!!E&&D===E.element&&o(i.config)&&ge()!==`none`,ve=()=>{for(let e of Array.from(i.header.children))e!==w&&e.setAttribute(pe,``)},ye=()=>{for(let e of Array.from(i.container.querySelectorAll(`[${pe}]`)))e.removeAttribute(pe)},be=()=>{let e=E;if(!e)return;if(Array.from(i.header.children).some(e=>e!==w&&!e.hasAttribute(pe))){T&&T!==i.header&&(T.style.removeProperty(`min-height`),T=null);let e=i.header.offsetHeight;e>0&&(i.header.style.minHeight=`${e}px`,T=i.header)}w||=n(`div`,`persona-history-header-host`),e.setHeaderPlacement(`external`);let t=e.getHeaderElement();t.parentNode!==w&&w.replaceChildren(t),w.parentNode!==i.header&&i.header.appendChild(w),ve()},xe=()=>{T&&=(T.style.removeProperty(`min-height`),null),w&&(E?.setHeaderPlacement(`inline`),w.remove(),w=null,ye())},Se=null,Ce=()=>{Se&&(i.body.style.display=`none`,C(i.body,!0),i.footer.hidden=!0,C(i.footer,!0),i.panelSuggestions.style.display=`none`,C(i.panelSuggestions,!0),i.panelSuggestionsFade.style.display=`none`,_e()?(be(),i.header.style.display=ge(),C(i.header,!1)):(xe(),i.header.style.display=`none`,C(i.header,!0)))};i.reapplyHistoryHostChrome=Ce;let we=e=>{let t=i.body.style.display,n=i.footer.hidden,r=i.panelSuggestions.style.display,a=i.panelSuggestionsFade.style.display,s=i.footer,c=i.header,l=i.header.style.display;me=c,he=l,Se=()=>{Se=null,xe(),me=null,i.body.style.display=t,C(i.body,!1),i.panelSuggestions.style.display=r,C(i.panelSuggestions,!1),i.panelSuggestionsFade.style.display=a,s.hidden=n,C(s,!1),i.footer!==s&&(i.footer.hidden=!1,C(i.footer,!1)),c.style.display=l,C(c,!1),i.header!==c&&(i.header.style.display=o(i.config)?``:`none`,C(i.header,!1))},i.container.insertBefore(e,i.footer.parentNode===i.container?i.footer:i.panelSuggestions),Ce()},O=null,k=null,Te=null,A=null,Ee=()=>[i.header,i.panelElements.closeButtonWrapper,i.panelElements.clearChatButtonWrapper,i.body,i.footer,i.scrollToBottomButton],De=()=>i.config.features?.history?.rail?.collapsible!==!1,j=()=>i.config.features?.history?.rail?.side===`right`?`right`:`left`,Oe=e=>Math.min(400,Math.max(200,Math.round(e))),ke=()=>i.config.features?.history?.rail?.resizable===!0,M,Ae=()=>{if(M===void 0&&(M=null,i.config.persistState!==!1))try{let e=Number(window.localStorage.getItem(`${i.currentKeyPrefix()}rail-width`));e&&(M=e)}catch{}return M},N=()=>Oe(Ae()??i.config.features?.history?.rail?.width??260),je=e=>{if(M=e,i.config.persistState!==!1)try{window.localStorage.setItem(`${i.currentKeyPrefix()}rail-width`,String(e))}catch{}},Me=()=>De()&&i.config.features?.history?.rail?.collapsedBehavior===`overlay`,P=!1,Ne=e=>{let t=n(`img`);return t.src=e,t.alt=``,t.setAttribute(`aria-hidden`,`true`),t},Pe=()=>{let e=i.config.features?.history?.rail?.brand;if(!e)return;let t=!1,n;return r=>{if(e.render)try{return e.render({collapsed:r})??null}catch(e){return t||(t=!0,console.warn(`[persona] history rail brand threw`,e)),null}return n===void 0&&(n=e.iconUrl?Ne(e.iconUrl):e.icon?i.renderLucideIcon(e.icon,20):null),n?n.cloneNode(!0):null}},Fe=()=>i.config.features?.history?.rail?.sections?.map(e=>{let t=!1,n=n=>{t||(t=!0,console.warn(`[persona] history rail section threw`,e.id,n))};return{id:e.id,title:e.title,placement:e.placement??`above-conversations`,items:e.items.map(e=>{let t;return{id:e.id,label:e.label,badge:e.badge,iconNode:()=>{if(t!==void 0)return t;try{t=e.renderIcon?e.renderIcon()??null:e.iconUrl?Ne(e.iconUrl):e.icon?i.renderLucideIcon(e.icon,20):null}catch(e){n(e),t=null}return t},onSelect:()=>{try{e.onSelect()}catch(e){n(e)}}}})}})??[],Ie=e=>{let t=Fe();for(let n of e)t.some(e=>e.id===n.id)?console.warn(`[persona] duplicate history rail section id`,n.id):t.push(n);return t.length?t:void 0},F=null,Le=()=>`${i.currentKeyPrefix()}rail-collapsed`,Re=()=>{if(F===null&&(F=i.config.features?.history?.rail?.defaultCollapsed===!0,i.config.persistState!==!1))try{let e=window.localStorage.getItem(Le());e&&(F=e===`1`)}catch{}return F},ze=e=>{if(F=e,i.config.persistState!==!1)try{window.localStorage.setItem(Le(),e?`1`:`0`)}catch{}},I=()=>i.historyPresentation===`rail`&&De()&&!Me()&&Re(),Be=()=>{},Ve=()=>{Me()?Be():(ze(!Re()),u?.view.setCollapsed(I()),i.applyRailChrome(),i.repinAnchoredMessage())},He=()=>{let e=i.config.features?.history?.rail?.collapseShortcut;return!e||!i.parseCombo(e)?null:{combo:e,hint:i.formatCombo(e),aria:i.ariaCombo(e)}},Ue=`var(--persona-history-overlay-margin,8px)`,L=null,R=null,We=0,z=null,B=null,V=!1,Ge=0,Ke=()=>window.matchMedia?.(`(pointer: coarse)`).matches===!0,H=()=>x()&&Me()&&(i.historyPresentation??fe())===`rail`,qe=()=>i.historyVisible&&!P,U=()=>{B!==null&&clearTimeout(B),B=null},Je=()=>{i.loadHistoryView().catch(()=>{})},Ye=()=>{U(),P&&(B=setTimeout(()=>{B=null,!V&&P&&(z?.contains(document.activeElement)||q({restoreFocus:!1}))},300))},Xe=(e,t)=>{let n=z?.getBoundingClientRect();if(!n)return!1;let r=L?.getBoundingClientRect(),i=r?Math.min(r.top,n.top):n.top;return e>=n.left&&e<=n.right&&t>=i&&t<=n.bottom||!!r&&e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom},Ze=e=>{P&&(V=Xe(e.clientX,e.clientY),V?U():B===null&&Ye())},Qe=e=>{!i.historyVisible&&H()&&(P=!0,K({invoker:L,keyboard:e?.keyboard===!0}).then(()=>{i.historyVisible?!V&&document.activeElement!==L&&q():P=!1}))},$e=()=>{let e=D?.querySelector(`[data-persona-history-focus="collapse"]`);e&&(e.setAttribute(`aria-label`,P?a.expandLabel:a.collapseLabel),e.setAttribute(`aria-expanded`,P?`false`:`true`))},et=()=>{ze(!1);let e=u;if(!P||!e){K({invoker:L});return}let t=document.activeElement===L;P=!1,ft(),e.element.remove(),mt(e.element),$e(),t&&_t(),i.repinAnchoredMessage(),$()},tt=()=>{ze(!0),q()};Be=()=>{!i.historyVisible||P?et():tt()};let nt=()=>{let e=He(),t=i.createHeaderIconButton({ariaLabel:a.expandLabel,iconName:`panel-left`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-rail-trigger`,tooltip:!1,attrs:{"data-persona-rail-trigger":``,"aria-controls":b,...e?{"aria-keyshortcuts":e.aria}:{}}}),n=t.button;n.addEventListener(`mouseenter`,()=>{V=!0,U(),!(Ke()||Date.now()<Ge)&&Qe()}),n.addEventListener(`mouseleave`,()=>{V=!1,Ge=0,Ye()}),n.addEventListener(`focus`,()=>{i.historyVisible||Je()}),n.addEventListener(`click`,e=>{x()&&(e.detail!==0&&Ke()&&!i.historyVisible?Qe():et())}),L=n,R=t.wrapper},W=()=>{if(R&&!R.isConnected&&(R=null,L=null),!H()){R?.remove(),R=null,L=null;return}L||nt();let e=R,t=L;if(!e||!t)return;let n=j()===`right`?null:i.header.firstChild;(n??i.header.lastChild)!==e&&i.header.insertBefore(e,n),e.style.display=qe()||We>0?`none`:``,t.setAttribute(`aria-label`,a.expandLabel),t.setAttribute(`aria-expanded`,i.historyVisible?`true`:`false`),z&&i.applyRailChrome()},rt=e=>{if(!P)return;let t=e.target;t instanceof Node&&(z?.contains(t)||R?.contains(t)||t instanceof Element&&t.closest(`.persona-dropdown-menu,[role="alertdialog"]`)||q({restoreFocus:!1}))};document.addEventListener(`pointerdown`,rt,!0),i.destroyCallbacks.push(()=>{document.removeEventListener(`pointerdown`,rt,!0),document.removeEventListener(`pointermove`,Ze),G?.(),U()});let it=null,G=null,at=e=>{je(Oe(e)),i.applyRailChrome(),i.repinAnchoredMessage()},ot=()=>{let e=n(`div`,`persona-rail-resizer`);return e.tabIndex=0,e.setAttribute(`role`,`separator`),e.setAttribute(`aria-orientation`,`vertical`),e.setAttribute(`aria-valuemin`,`200`),e.setAttribute(`aria-valuemax`,`400`),e.addEventListener(`pointerdown`,t=>{let n=k;if(!n||t.button!==0)return;t.preventDefault(),G?.();let r=t.clientX,a=n.getBoundingClientRect().width||N(),o=j()===`right`?-1:1,s=a,c=i.mount.ownerDocument;n.style.transition=`none`;let l=t=>{s=Oe(a+o*(t.clientX-r)),n.style.flex=`0 0 ${s}px`,e.setAttribute(`aria-valuenow`,String(s))},u=()=>{G=null,c.removeEventListener(`pointermove`,l),c.removeEventListener(`pointerup`,u),c.removeEventListener(`pointercancel`,u),n.style.removeProperty(`transition`);try{e.releasePointerCapture(t.pointerId)}catch{}at(s)};G=u,c.addEventListener(`pointermove`,l),c.addEventListener(`pointerup`,u),c.addEventListener(`pointercancel`,u);try{e.setPointerCapture(t.pointerId)}catch{}}),e.addEventListener(`keydown`,e=>{let t=j()===`right`?-16:16,n=N(),r=e.key===`ArrowRight`?n+t:e.key===`ArrowLeft`?n-t:e.key===`Home`?200:e.key===`End`?400:null;r!==null&&(e.preventDefault(),at(r))}),e},st=(e,t)=>{if(!ke()||I()){G?.(),it?.remove();return}let n=it??ot();it=n,n.setAttribute(`aria-label`,a.resizeLabel),n.setAttribute(`aria-valuenow`,String(N())),n.nextElementSibling!==t&&e.insertBefore(n,t)};i.applyRailChrome=()=>{u?.view.setRailSide(j());let e=j()===`right`,t=z;if(t){let n=L?L.getBoundingClientRect().bottom-i.container.getBoundingClientRect().top:0;t.style.top=`calc(${Math.max(0,Math.round(n))}px + ${Ue})`,t.style.width=`${N()}px`,t.style.left=e?``:Ue,t.style.right=e?Ue:``}let n=k,r=O,a=Te;if(!n||!r||!a)return;n.style.flex=`0 0 ${I()?52:N()}px`;let o=`1px solid var(--persona-divider,#e5e7eb)`;n.style.borderRight=e?``:o,n.style.borderLeft=e?o:``;let s=e?a:n;r.firstElementChild!==s&&r.append(s,e?n:a),st(r,e?n:a)};let ct=e=>{if(A&&k){A.replaceWith(e),A=null,i.applyRailChrome();return}let t=n(`div`,`persona-history-rail-shell`);t.style.cssText=`display:flex;flex-direction:row;flex:1 1 auto;min-height:0`;let r=n(`div`,`persona-history-rail-conversation`);r.style.cssText=`display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative`;let a=n(`div`,`persona-history-rail-host`);a.style.cssText=`display:flex;min-height:0;overflow:hidden`,i.container.insertBefore(t,i.header.parentNode===i.container?i.header:i.body);for(let e of Ee())e?.parentNode===i.container&&r.appendChild(e);t.append(a,r),a.appendChild(e),O=t,k=a,Te=r,i.applyRailChrome()},lt=()=>{if(O)return;let e=n(`div`,`persona-history-rail-placeholder`);e.style.cssText=`flex:1 1 auto;min-height:0`,A=e,ct(e),i.repinAnchoredMessage()},ut=()=>{A&&(ft(),i.repinAnchoredMessage())},dt=e=>{let t=n(`div`,`persona-history-rail-overlay`);t.style.cssText=`position:absolute;bottom:${Ue};display:flex;overflow:hidden;z-index:${r-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,i.container.style.position=`relative`,i.container.appendChild(t),t.appendChild(e),document.addEventListener(`pointermove`,Ze),z=t,i.applyRailChrome(),$e()},ft=()=>{Se?.(),z&&=(V&&(Ge=Date.now()+150),document.removeEventListener(`pointermove`,Ze),z.remove(),null);let e=O;if(e){G?.();for(let t of Ee())if(t&&e.contains(t)){let n=t===i.scrollToBottomButton?i.panelSuggestions:e;i.container.insertBefore(t,n)}e.remove(),O=null,k=null,Te=null,A=null}},pt=e=>{D=e,e.id=b,e.style.flex=`1 1 auto`,e.style.minHeight=`0`},mt=e=>{pt(e),(i.historyPresentation!==`rail`||P)&&ut(),i.historyPresentation===`rail`?P?dt(e):ct(e):we(e)},ht=()=>{if(W(),Ht(),!i.historyVisible||!u)return;let e=fe();if(e===i.historyPresentation)return;let t=document.activeElement,n=t instanceof HTMLElement&&(u.element.contains(t)||w?.contains(t)===!0)?t:null;ft(),u.element.remove(),u.view.setHeaderPlacement(`inline`),i.historyPresentation=e,u.view.setPresentation(e),u.view.setCollapsed(I()),u.requestRender(),u.element.isConnected||mt(u.element),n?.isConnected?n.focus():_t(),i.syncScrollToBottomButton(),i.repinAnchoredMessage(),$()},gt=(e,t)=>w?.querySelector(t)??e.querySelector(t),_t=()=>{let e=u?.element??D;if(!e)return;let t=gt(e,`[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]`);if(t){t.focus();return}let n=gt(e,`.persona-history-title`)??e;n.tabIndex=-1,n.focus()},K=async e=>{if(!x()||i.historyVisible)return;let t=c;if(!t)return;if(!P&&H()&&Re()){W();return}vt();let n=++_;f=e?.returnSurface??`conversation`,p=e?.invoker??m;let r=H()&&!P;r&&(We+=1,W(),lt());let s;try{s=await i.loadHistoryView()}catch{i.announceHistory(a.openHistoryLabel),r&&(--We,n===_&&(ut(),W()));return}if(r&&--We,n!==_||i.historyVisible)return;d={scope:ie()},i.historyPresentation=fe(),i.historyVisible=!0;let l=i.historyPresentation===`panel`&&o(i.config)&&i.header.style.display!==`none`?`external`:`inline`,h=i.config.features?.history?.rowAvatar,te=He(),g=te?{hint:te.hint,aria:te.aria}:null,v={provider:t,context:d,targetId:ae(),presentation:i.historyPresentation,collapsible:De(),collapsed:I(),railSide:j(),renderRailHeader:i.config.features?.history?.rail?.renderHeader,railBrand:Pe(),onToggleCollapse:Ve,...g?{collapseShortcut:g}:{},headerPlacement:l,showScopeStatus:i.config.features?.history?.showScopeStatus!==!1,showDelete:i.config.features?.history?.showDelete!==!1,showDeleteAll:i.config.features?.history?.showDeleteAll!==!1,...i.config.features?.history?.listActions?.length?{listActions:i.config.features.history.listActions}:{},rowAvatar:h===!1?!1:typeof h==`string`?h:i.config.launcher?.iconUrl,activeConversationId:i.session.getActiveConversationId(),...i.config.features?.history?.grouping?{grouping:i.config.features.history.grouping}:{},...i.config.features?.history?.copy?{copy:i.config.features.history.copy}:{},...i.config.features?.history?.pageSize===void 0?{}:{pageSize:i.config.features.history.pageSize},onSelect:e=>At(e,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:e=>i.setActiveConversationSummary(e),attachTooltip:i.attachTooltip,onStartNew:()=>jt({focusComposer:!0}),onClose:()=>q(),onRequestDeleteConversation:e=>Rt(e),onRequestClearHistory:()=>zt(),...t.resetDevice?{onRequestResetIdentity:()=>Bt()}:{}};u=ee({plugins:i.plugins,config:i.config,getPresentation:()=>i.historyPresentation??`panel`,getReturnSurface:()=>f,close:()=>q(),createView:({slots:e,renderDom:t,onModelChange:n,railSections:r})=>(E=s.createHistoryView({...v,railSections:Ie(r),slots:e,renderDom:t,onModelChange:n,onAnnounce:i.announceHistory}),E),onElementChanged:(e,t)=>{if(!t?.isConnected)return mt(e);pt(e),t.replaceWith(e),Ce()}}),u.view.setNewConversationRequired(i.historySessionState.recovery===`new_conversation_required`),e?.focus!==!1&&(i.historyPresentation!==`rail`||e?.keyboard===!0)&&_t(),i.syncScrollToBottomButton(),i.repinAnchoredMessage(),$(),i.eventBus.emit(`history:opened`,{presentation:i.historyPresentation,returnSurface:f,timestamp:Date.now()})},vt=()=>{},q=e=>{if(!i.historyVisible)return;_+=1;let t=f,n=p,r=u,a=e?.restoreFocus!==!1;i.historyVisible=!1;let o=!1,s=null,c=()=>{if(!o){if(o=!0,vt=()=>{},s!==null&&clearTimeout(s),P=!1,U(),ft(),r?.dispose(),r?.view.destroy(),r?.element.remove(),u===r&&(u=null,E=null,D=null,i.historyPresentation=null,d=null,p=null),i.syncScrollToBottomButton(),i.repinAnchoredMessage(),$(),a){let e=n??m;e?.isConnected?e.focus():i.maybeFocusInput()}i.eventBus.emit(`history:closed`,{returnSurface:t,timestamp:Date.now()})}},l=r&&r.element===r.view.element?r.view.playExit():null;l?(vt=c,s=setTimeout(c,250),l.then(c)):c()},yt=e=>{if(e.key===`Escape`&&i.historyVisible&&u){if(i.historyPresentation===`rail`){let t=e.target;if(!(t instanceof Node)||!(u.element.contains(t)||P&&R?.contains(t)===!0))return}e.preventDefault(),e.stopPropagation(),q()}};i.container.addEventListener(`keydown`,yt),i.destroyCallbacks.push(()=>i.container.removeEventListener(`keydown`,yt));let J=0,Y=null,bt=null,xt=()=>{bt&&clearTimeout(bt),bt=null};i.destroyCallbacks.push(xt);let St=()=>{xt();let e=i.conversationOpenPendingEl;e&&(i.conversationOpenTakeover=!0,e.hidden=!1,i.messagesWrapper.style.display=`none`,i.updateWelcome())},X=()=>{J+=1,xt(),Y?.remove(),Y=null,i.conversationOpenPendingEl&&(i.conversationOpenPendingEl.remove(),i.conversationOpenPendingEl=null,i.conversationOpenTakeover=!1,i.messagesWrapper.style.removeProperty(`display`),C(i.footer,!1),i.updateWelcome())},Ct=()=>{try{if(window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches)return;i.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:`ease-out`})}catch{}},wt=n=>{let r=i.config.layout?.messages?.layout??`bubble`,a=t(`div`,{className:`persona-flex`,attrs:{"aria-hidden":`true`}});i.applyMessageRowLayout(a,n);let o=t(`div`,{className:e(i.getBubbleClasses(n,r).join(` `),`persona-conversation-loading-bubble`),attrs:{"data-persona-theme-zone":`${n}-message`},style:{width:n===`user`?`64%`:`100%`,backgroundColor:r===`flat`?`transparent`:`var(--persona-message-${n}-bg, var(--persona-${n===`user`?`accent`:`container`}))`,color:`var(--persona-message-${n}-text, ${n===`user`&&r!==`flat`?`white`:`var(--persona-text)`})`}},...[`94%`,...n===`assistant`?[`86%`]:[],`62%`].map(e=>t(`div`,{className:`persona-conversation-loading-line`,style:{width:e}})));return i.applyBubbleGeometry(o,n,r,{...i.resolveThemeDefaults(i.config.future).components.message[n],...i.config.theme?.components?.message?.[n],...i.config.darkTheme?.components?.message?.[n]}),a.appendChild(o),a},Tt=()=>t(`div`,{className:`persona-conversation-loading-body`,style:{gap:i.messagesWrapper.style.gap}},wt(`user`),wt(`assistant`),wt(`user`),wt(`assistant`)),Et=()=>i.config.loadingIndicator?.conversationOpenVariant===`skeleton`?Tt():t(`div`,{className:`persona-conversation-loading-spinner`,attrs:{"aria-hidden":`true`}},t(`span`,{className:`persona-conversation-loading-ring`})),Dt=e=>{i.conversationOpenPendingEl?.remove(),i.conversationOpenPendingEl=e,e.hidden=!i.conversationOpenTakeover,i.body.insertBefore(e,i.messagesWrapper),xt(),i.conversationOpenTakeover||(bt=setTimeout(St,250)),C(i.footer,!0)},Ot=()=>{let n={config:i.config,streaming:!1,location:`conversation-open`,defaultRenderer:Et},r=null,o=i.plugins.find(e=>e.renderLoadingIndicator);o?.renderLoadingIndicator&&(r=o.renderLoadingIndicator(n)),r===null&&i.config.loadingIndicator?.render&&(r=i.config.loadingIndicator.render(n));let s=r??Et();Dt(t(`div`,{className:e(`persona-conversation-loading`,s.classList.contains(`persona-conversation-loading-spinner`)&&`persona-conversation-loading--centered`),attrs:{role:`status`,"aria-label":a.openConversationLoadingLabel},style:{maxWidth:i.messagesWrapper.style.maxWidth||`none`}},s))},kt=e=>{let n=()=>{At(e,{focusComposer:!0}).catch(()=>{})},r=x()?()=>{X(),K()}:void 0,o=(e,n)=>{let r=t(`button`,{className:`persona-conversation-loading-error-action`,attrs:{type:`button`},text:e});return r.addEventListener(`click`,n),r},s=()=>t(`div`,{className:`persona-conversation-loading-error-body`},t(`p`,{className:`persona-conversation-loading-error-title`,text:a.openConversationErrorTitle}),t(`div`,{className:`persona-conversation-loading-error-actions`},o(a.openConversationRetryLabel,n),r?o(a.openConversationBackLabel,r):null)),c=Object.freeze({conversationId:e,config:i.config,copy:Object.freeze({title:a.openConversationErrorTitle,retryLabel:a.openConversationRetryLabel,backLabel:a.openConversationBackLabel}),retry:n,...r?{back:r}:{},defaultRenderer:s}),l=null;for(let e of i.plugins)if(e.renderHistoryOpenError){try{l=e.renderHistoryOpenError(c)}catch(e){console.warn(`[persona] renderHistoryOpenError threw`,e),l=null}if(l)break}if(Y?.remove(),Y=t(`div`,{className:`persona-conversation-loading-error`,attrs:{role:`alert`}},l??s()),!i.session.getActiveConversationId()&&i.session.getMessages().length===0&&!i.composerStore.getState().text&&!i.attachmentManager?.hasAttachments()){let e=Y;Y=null,Dt(e),St()}else i.body.insertBefore(Y,i.messagesWrapper);i.announceHistory(a.openConversationErrorTitle)};i.eventBus.on(`history:closed`,()=>{i.conversationOpenPendingEl&&C(i.footer,!0)});let At=async(e,{focusComposer:t=!1,busy:n=`reject`}={})=>{let r=S();if(n===`background`&&(i.session.assertBackgroundSwitchable(),i.composerStore.getState().phase===`preparing`))throw new i.SessionHistoryError(`conversation_busy`,`Finish preparing this turn before switching conversations`);if(n===`reject`&&(i.session.isStreaming()||[`paused`,`resuming`].includes(i.session.getStatus())||i.composerStore.getState().phase===`preparing`))throw new i.SessionHistoryError(`conversation_busy`,`Finish or stop the current turn before switching conversations`);n===`stop`&&(++i.composerConversationGeneration,i.submissionAbort?.abort(),i.submissionAbort=null,i.composerStore.setPreparing(!1),i.session.cancel());let a=i.conversationStateKey();(!i.conversationOpenPendingEl||i.pendingConversationReading?.key!==a)&&(i.pendingConversationReading={key:a,reading:i.captureConversationReading()});let o=null,s=!!u;u?.view.setActiveConversationId(e),X();let c=J;Ot(),i.historyVisible&&(i.historyPresentation===`panel`||P)&&q({restoreFocus:!1}),i.suppressScrollSend=!0;try{await i.session.openConversation(e,{scope:r,busy:n,onBeforeCommit:()=>{i.saveConversationContinuity(),o=i.composerConversationGeneration,i.conversationPersistenceOwner=o},onCommitted:()=>{i.restoreConversationContinuity(),i.conversationPersistenceOwner===o&&(i.conversationPersistenceOwner=null),i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),i.persistState()}})}catch(t){if(i.conversationPersistenceOwner===o&&(i.conversationPersistenceOwner=null),o===i.composerConversationGeneration&&i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),c===J){let t=i.pendingConversationReading?.reading;X(),t&&i.restoreConversationReading(t),i.pendingConversationReading=null,u?.view.setActiveConversationId(i.session.getActiveConversationId()),kt(e),i.suppressScrollSend=!1}throw t}finally{(c===J||!i.conversationOpenPendingEl)&&(i.suppressScrollSend=!1)}c===J&&(X(),i.pendingConversationReading=null,i.messageCache.clear(),Ct(),Q(),s||i.setActiveConversationSummary(null),i.eventBus.emit(`history:conversationOpened`,{conversationId:e,title:i.activeConversationTitle,scope:r,timestamp:Date.now()}),t&&i.maybeFocusInput())},jt=async({focusComposer:e=!1}={})=>{X();let t=null;try{await i.session.startNewConversation({scope:S(),onBeforeCommit:()=>{i.saveConversationContinuity(),t=i.composerConversationGeneration,i.conversationPersistenceOwner=t},onCommitted:()=>{i.restoreConversationContinuity(!0),i.conversationPersistenceOwner===t&&(i.conversationPersistenceOwner=null),i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),i.persistState(),i.pendingConversationReading=null}})}catch(e){throw i.conversationPersistenceOwner===t&&(i.conversationPersistenceOwner=null),t===i.composerConversationGeneration&&i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),e}i.setActiveConversationSummary(null),i.messageCache.clear(),i.resetAnchorState(),i.resumeAutoScroll(),i.jumpToBottomInstant(),Q();let n=i.session.getActiveConversationId();u?.view.setActiveConversationId(n),i.eventBus.emit(`history:conversationStarted`,{conversationId:n,timestamp:Date.now()}),i.historyVisible&&(i.historyPresentation===`panel`||P)&&q({restoreFocus:!1}),e&&i.maybeFocusInput()},Mt=async(e,t)=>{let n=await i.session.updateConversation(e,{...t,...t.title===void 0?{}:{title:t.title.trim()}});return u?.view.applyConversationSummary(n),!u&&e===i.session.getActiveConversationId()&&i.setActiveConversationSummary(n),n},Nt=async e=>{let t=S(),n=i.session.getActiveConversationId()===e;await i.session.deleteConversation(e,{scope:t}),i.discardConversationContinuity(e),n&&(i.attachmentManager?.destroy({release:!0}),i.attachmentManager=null,i.restoreConversationContinuity(!0)),u?.view.removeConversationSummary(e),n&&(i.setActiveConversationSummary(null),i.messageCache.clear(),i.resetAnchorState(),i.resumeAutoScroll(),Q()),i.eventBus.emit(`history:conversationDeleted`,{conversationId:e,scope:t,wasActive:n,timestamp:Date.now()})},Pt=async e=>{let t=e?.scope??S(),n=e?.allTargets?null:e?.targetId??ae(),r=await i.session.clearConversationHistory({...n?{targetId:n}:{},scope:t});return i.discardConversationContinuity(),i.setActiveConversationSummary(null),i.messageCache.clear(),i.resetAnchorState(),i.resumeAutoScroll(),Q(),i.eventBus.emit(`history:cleared`,{deleted:r.deleted,scope:t,targetId:n,timestamp:Date.now()}),r},Ft=async()=>{if(!c?.resetDevice)throw Error(`[Persona] resetHistoryIdentity() requires a history provider that can reset this device`);let e=!1;try{e=(await i.session.resetHistoryDevice()).remoteRevocationConfirmed}finally{i.discardConversationContinuity(),X(),i.setActiveConversationSummary(null),i.session.clearArtifacts(),i.messageCache.clear(),i.lastAppliedMessages=null,i.config.clearStoredSessionId?.(),i.config.clearStoredConversationId?.(),i.persistentMetadata={},i.actionManager.syncFromMetadata(),i.clearPersistedDraft();let e=i.storageAdapter;e?.clear&&i.runStorageMutation(()=>e.clear(),`[AgentWidget] Failed to clear storage adapter:`),i.resetAnchorState(),i.resumeAutoScroll(),Q(),q({restoreFocus:!1}),i.maybeFocusInput(),i.open||i.launcherSurfaceInstance?.launcher.element.focus()}return i.announceHistory(e?a.identityResetNotice:a.identityResetUnconfirmedNotice),i.eventBus.emit(`history:identityReset`,{remoteRevocationConfirmed:e,timestamp:Date.now()}),{remoteRevocationConfirmed:e}},It=()=>i.artifactSplitRoot?i.panel:i.container,Lt=async e=>{let t=await i.loadHistoryView().catch(()=>null);return typeof t?.showHistoryConfirm==`function`?t.showHistoryConfirm(e):window.confirm(`${e.title}\n\n${e.description}`)},Rt=async e=>await Lt({host:It(),title:a.deleteConversationConfirmTitle,description:a.deleteConversationConfirm,confirmLabel:a.deleteConversationConfirmLabel,cancelLabel:a.confirmCancelLabel})?(await Nt(e),`deleted`):`cancelled`,zt=async()=>{let e=S()===`verified-user`;return await Lt({host:It(),title:a.clearHistoryConfirmTitle,description:e?a.clearHistoryVerifiedConfirm:a.clearHistoryConfirm,confirmLabel:a.clearHistoryConfirmLabel,cancelLabel:a.confirmCancelLabel})?(await Pt(),`cleared`):`cancelled`},Bt=async()=>{if(!await Lt({host:It(),title:a.resetIdentityConfirmTitle,description:a.resetIdentityConfirm,confirmLabel:a.resetIdentityConfirmLabel,cancelLabel:a.confirmCancelLabel}))return{outcome:`cancelled`};let{remoteRevocationConfirmed:e}=await Ft();return{outcome:`reset`,remoteRevocationConfirmed:e}},Z=n(`button`,`persona-history-earlier`);Z.type=`button`,Z.textContent=a.showEarlierMessagesLabel,Z.setAttribute(`data-persona-history-earlier`,``),Object.assign(Z.style,{alignSelf:`center`,minHeight:`44px`,padding:`0 16px`,borderRadius:`999px`,border:`1px solid var(--persona-border, rgba(0,0,0,0.12))`,background:`transparent`,color:`inherit`,font:`inherit`,cursor:`pointer`,flexShrink:`0`});let Q=()=>{x()&&i.historySessionState.nextMessageCursor&&i.session.getActiveConversationId()?(Z.textContent=a.showEarlierMessagesLabel,Z.parentNode!==i.body&&i.body.insertBefore(Z,i.body.firstChild)):Z.remove()};Z.addEventListener(`click`,()=>{let e=i.session.getActiveConversationId(),t=i.historySessionState.nextMessageCursor;if(!e||!t||Z.disabled)return;Z.disabled=!0;let n=i.body.scrollHeight,r=i.body.scrollTop;i.session.loadOlderMessages(e,t,{scope:S()}).then(()=>{i.body.scrollTop=r+(i.body.scrollHeight-n),i.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Z.disabled=!1,Q()})});let Vt=()=>{let e=i.createHeaderIconButton({ariaLabel:a.openHistoryLabel,iconName:`history`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-history-toggle`,attrs:{"data-persona-history-toggle":``}});return e.button.addEventListener(`click`,t=>{x()&&!re()&&(i.historyVisible?q():K({invoker:e.button,keyboard:t.detail===0}))}),e},Ht=()=>{if(!x()){h?.remove(),m=null,h=null;return}if(h&&!h.isConnected&&(m=null,h=null),!m&&i.header){let e=Vt();m=e.button,h=e.wrapper;let t=i.panelElements.clearChatButtonWrapper||i.panelElements.closeButtonWrapper;t?.parentNode&&i.header.contains(t)?t.parentNode.insertBefore(h,t):i.header.appendChild(h)}if(!m||!h)return;let e=H()||i.historyVisible&&i.historyPresentation===`rail`;if(h.style.display=e?`none`:``,e){document.activeElement===m&&_t();return}let t=re();m.disabled=t,m.setAttribute(`aria-disabled`,t?`true`:`false`);let n=t?a.openHistoryBusyLabel:a.openHistoryLabel;m.setAttribute(`aria-label`,n),(i.config.features?.history?.presentation??`panel`)===`panel`?(m.removeAttribute(`aria-expanded`),m.removeAttribute(`aria-controls`)):(m.setAttribute(`aria-expanded`,i.historyVisible?`true`:`false`),m.setAttribute(`aria-controls`,b))},Ut=!1,Wt=()=>{let e=i.panelElements.clearChatButton;e&&(x()?(Ut||=(v=e.getAttribute(`aria-label`)??``,!0),e.setAttribute(`aria-label`,a.newConversationLabel),e.removeAttribute(`title`)):Ut&&(Ut=!1,v&&e.setAttribute(`aria-label`,v)))},$=()=>{a=s(i.config.features?.history?.copy),Ht(),W(),Wt(),Q()};return i.historyChromeSync=$,de(),$(),i.destroyCallbacks.push(()=>{ne?.(),y?.(),_+=1,vt(),u?.dispose(),u?.view.destroy(),u=null}),{clearConversationOpenPending:X,cancelConversationOpenTakeover:xt,historyOperationScope:S,discardConversationContinuity:i.discardConversationContinuity,historyAvailable:x,historyScope:ie,installHistoryProvider:de,syncHistoryChromeImpl:$,syncHistoryPresentation:ht,syncEarlierMessagesPill:Q,openHistory:K,closeHistory:q,openHistoryConversation:At,startNewConversation:jt,updateHistoryConversation:Mt,deleteHistoryConversation:Nt,requestDeleteConversation:Rt,clearConversationHistory:Pt,resetHistoryIdentity:Ft,railCollapseShortcut:He,railCollapsible:De,railTriggerApplies:H,railOverlayMode:Me,toggleRailCollapsed:Ve,toggleRailPinned:()=>Be(),get historyProvider(){return c},get historySurface(){return u},get railShell(){return O},get railHost(){return k},get railColumn(){return Te}}};export{g as createHistoryShell};
1
+ import{i as e,r as t,t as n}from"./chunk-D5BxWOFB.js";import{r}from"./chunk-Bb41bKyp.js";import{n as i,r as a}from"./chunk-i4qGOJAL.js";import{a as o}from"./chunk-Cy1A8vbF.js";import{n as s}from"./chunk-CLMIHW4_.js";const c=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},l=e=>Object.freeze({...e}),u=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),d=e=>e?l(e):null;function ee(e){let{plugins:t,config:n}=e,r=!1,i=!1,a=!1,o=!1,s=null,ee=[],f=()=>{for(let e of ee.splice(0))try{e()}catch(e){c(`renderHistoryView cleanup`,e)}},p=(e,n)=>{for(let r of t){let t=r[e];if(t)try{let e=t(n);if(e)return e}catch(t){c(e,t)}}return null},m=()=>({presentation:e.getPresentation(),config:n}),h={header:t=>o?p(`renderHistoryHeader`,Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:l(t.identityStatus),pendingAction:d(t.pendingAction),copy:l(t.copy),actions:Object.freeze({close:_.close,startNewConversation:_.startNewConversation}),defaultRenderer:t.defaultRenderer})):null,conversation:e=>o?p(`renderHistoryConversation`,Object.freeze({...m(),conversation:u(e.conversation),active:e.active,pending:e.pending,open:e.open,requestDelete:e.requestDelete,defaultRenderer:e.defaultRenderer})):null,state:e=>o?p(`renderHistoryState`,Object.freeze({...m(),state:l(e.state),identityStatus:l(e.identityStatus),copy:l(e.copy),...e.retry?{retry:e.retry}:{},...e.startNewConversation?{startNewConversation:e.startNewConversation}:{},defaultRenderer:e.defaultRenderer})):null},te=t.flatMap(t=>(t.railSections??[]).map(t=>({...t,placement:t.placement??`above-conversations`,items:[],render:n=>t.render(Object.freeze({collapsed:n,presentation:e.getPresentation(),actions:_}))}))),g=e.createView({slots:h,renderDom:!1,onModelChange:()=>b(),railSections:te}),_=Object.freeze({...g.operations,close:e.close}),v=()=>(o=!0,g.setDomRenderEnabled(!0),g.element),ne=t=>Object.freeze({conversations:Object.freeze(t.conversations.map(u)),activeConversationId:t.activeConversationId,state:l(t.state),pendingAction:d(t.pendingAction),identityStatus:l(t.identityStatus),nextCursor:t.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:l(g.copy),actions:_,defaultRenderer:v,requestRender:()=>b(),onCleanup:e=>{ee.push(e)}}),y=()=>{o=!1;let e=null;for(let n of t)if(n.renderHistoryView){try{e=n.renderHistoryView(ne(g.getModel()))}catch(t){c(`renderHistoryView`,t),e=null}if(e)break}let n=!e||e.contains(g.element);return o=n,g.setDomRenderEnabled(n),e??g.element};function b(){if(!(!a||r||i)){i=!0;try{f();let t=y();if(t===s)return;let n=s;s=t,e.onElementChanged(t,n)}finally{i=!1}}}return a=!0,b(),{view:g,get element(){return s??g.element},requestRender:b,dispose:()=>{r=!0,f()}}}const f=/* @__PURE__ */ new Map([[`not_found`,`not_found`],[`conversation_deleted`,`not_found`],[`rate_limited`,`rate_limited`],[`authentication_required`,`authentication_required`],[`invalid_identity_proof`,`authentication_required`],[`visitor_identity_mismatch`,`authentication_required`],[`visitor_required`,`authentication_required`],[`identity_provider_failed`,`identity_provider_failed`],[`proof_not_admitted`,`proof_not_admitted`],[`identity_contract_violation`,`proof_not_admitted`],[`unauthorized`,`authentication_failed`],[`visitor_token_missing`,`authentication_failed`],[`conversation_credential_missing`,`authentication_failed`]]),p=/* @__PURE__ */ new Map([[`not_found`,`That conversation is no longer available.`],[`rate_limited`,`Too many history requests.`],[`authentication_failed`,`History access was not authorized.`],[`authentication_required`,`Sign in again to view account history.`],[`identity_provider_failed`,`The identity provider did not respond.`],[`proof_not_admitted`,`Account history is not available for this configuration.`],[`unsupported_scope`,`This history scope is not supported.`],[`unavailable`,`Conversation history is unavailable right now.`]]),m=e=>p.get(e)??`Conversation history is unavailable right now.`;function h(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let t=f.get(e.code)??`unavailable`;return new n(t,m(t),{...e.retryAfterSeconds===void 0?{}:{retryAfterSeconds:e.retryAfterSeconds}})}return new n(`unavailable`,m(`unavailable`))}function te(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,r=e.getIdentityProofConfigured()?[`browser`,`verified-user`]:[`browser`],o={scopes:r},s=e=>{if(!r.includes(e))throw new t(`unsupported_scope`,m(`unsupported_scope`))},c=async(t,n)=>{s(t);try{return await n()}catch(t){throw h(t,e.errors)}},l=t=>{let n=!1;return{conversationId:t.session.conversationId??``,conversationRevision:t.session.conversationRevision??``,async commit(){n||(n=!0,t.commit(),await e.onActivationCommitted(t.session))},discard(){n||(n=!0,t.discard())}}};return{capabilities:o,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(e){return n().subscribeHistoryIdentityStatus(e)},subscribeAvailability(e){return n().subscribeHistoryAvailability(e)},async list(e){return c(e.context.scope,async()=>{let t=await n().listConversations({...e.cursor?{cursor:e.cursor}:{},...e.limit===void 0?{}:{limit:e.limit},...e.targetId?{targetId:e.targetId}:{},scope:e.context.scope});return{items:t.data,nextCursor:t.nextCursor}})},async getPage(e,t){return c(t.context.scope,async()=>{let r=await n().getConversation(e,{...t.cursor?{messageCursor:t.cursor}:{},scope:t.context.scope}),o=i(r.messages,{...t.beforeCreatedAt?{beforeCreatedAt:t.beforeCreatedAt}:{}});return{summary:r.summary,messages:a([],o),conversationRevision:r.conversationRevision??``,nextCursor:r.nextMessageCursor}})},async prepareOpen(e,t){return c(t.context.scope,async()=>l(await n().prepareConversationSession(e)))},async prepareStartNew(e){return c(e.context.scope,async()=>l(await n().prepareNewConversationSession()))},async delete(e,t){await c(t.context.scope,()=>n().deleteConversation(e,{scope:t.context.scope}))},async deleteAll(e){return c(e.context.scope,()=>n().deleteAllConversations({...e.targetId===void 0?{}:{targetId:e.targetId},scope:e.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}const g=i=>{let a=s(i.config.features?.history?.copy),c=null,l=!1,u=null,d=null,f=`conversation`,p=null,m=null,h=null,g=null,_=0,v=null,ne=null,y=null,b=`persona-history-${Math.random().toString(36).slice(2,8)}`,x=()=>i.historyFeatureEnabled()&&!!c&&!l,re=()=>{let e=i.session.getStatus();return i.isStreaming||e===`paused`||e===`resuming`},ie=()=>{let e=i.config.features?.history?.scope;if(e)return e;let t=i.config.getIdentityProof?`verified-user`:`browser`,n=c?.capabilities.scopes;return!n||n.includes(t)?t:n[0]??t},S=()=>d?.scope??ie(),ae=()=>i.session.getClientSession()?.targetId??null,oe=e=>`${e.state}:${`reason`in e?e.reason:``}`,se=e=>{let t=oe(e);t!==g&&(g=t,i.eventBus.emit(`history:identityStatusChanged`,{status:e,timestamp:Date.now()}))},ce=null,le=null,ue=()=>{if(!i.historyFeatureEnabled())return null;let e=i.getHistoryProviderFactory();if(e)return e();let t=i.config.features?.history?.provider;return t?typeof t==`function`?(ce!==t&&(ce=t,le=t()),le):t:i.session.isClientTokenMode()?te({errors:i.historyErrors,client:i.session.getClient(),getIdentityProofConfigured:()=>typeof i.config.getIdentityProof==`function`,onActivationCommitted:e=>i.session.bindActivatedSession(e),getClient:()=>i.session.getClient()}):null},de=()=>{ne?.(),ne=null,y?.(),y=null,l=!1;let e=c;c=ue(),e&&e!==c&&i.discardConversationContinuity();let t={...i.historyInternals};c?t.historyProvider=c:delete t.historyProvider,i.historyInternals=t,i.session.setHistoryInternals(i.historyInternals),c&&(ne=c.subscribeAvailability?.(e=>{l=!e,e||q({restoreFocus:!1}),$()})??null,y=c.subscribeIdentityStatus(e=>se(e)),g=oe(c.getIdentityStatus()))},fe=()=>{let e=i.config.features?.history?.presentation??`panel`;if(e===`panel`||e===`auto`&&i.launcherEnabled&&!i.isDockedMountMode(i.config))return`panel`;let t=i.artifactSplitRoot??i.container;return(t.getBoundingClientRect().width||t.clientWidth)>=720?`rail`:`panel`},C=(e,t)=>{t?(e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`inert`,``)):(e.removeAttribute(`aria-hidden`),e.removeAttribute(`inert`))},pe=`data-persona-history-suppressed`,w=null,T=null,E=null,D=null,me=null,he=``,ge=()=>i.header===me?he:o(i.config)?``:`none`,_e=()=>i.historyPresentation===`panel`&&!!E&&D===E.element&&o(i.config)&&ge()!==`none`,ve=()=>{for(let e of Array.from(i.header.children))e!==w&&e.setAttribute(pe,``)},ye=()=>{for(let e of Array.from(i.container.querySelectorAll(`[${pe}]`)))e.removeAttribute(pe)},be=()=>{let e=E;if(!e)return;if(Array.from(i.header.children).some(e=>e!==w&&!e.hasAttribute(pe))){T&&T!==i.header&&(T.style.removeProperty(`min-height`),T=null);let e=i.header.offsetHeight;e>0&&(i.header.style.minHeight=`${e}px`,T=i.header)}w||=n(`div`,`persona-history-header-host`),e.setHeaderPlacement(`external`);let t=e.getHeaderElement();t.parentNode!==w&&w.replaceChildren(t),w.parentNode!==i.header&&i.header.appendChild(w),ve()},xe=()=>{T&&=(T.style.removeProperty(`min-height`),null),w&&(E?.setHeaderPlacement(`inline`),w.remove(),w=null,ye())},Se=null,Ce=()=>{Se&&(i.body.style.display=`none`,C(i.body,!0),i.footer.hidden=!0,C(i.footer,!0),i.panelSuggestions.style.display=`none`,C(i.panelSuggestions,!0),i.panelSuggestionsFade.style.display=`none`,_e()?(be(),i.header.style.display=ge(),C(i.header,!1)):(xe(),i.header.style.display=`none`,C(i.header,!0)))};i.reapplyHistoryHostChrome=Ce;let we=e=>{let t=i.body.style.display,n=i.footer.hidden,r=i.panelSuggestions.style.display,a=i.panelSuggestionsFade.style.display,s=i.footer,c=i.header,l=i.header.style.display;me=c,he=l,Se=()=>{Se=null,xe(),me=null,i.body.style.display=t,C(i.body,!1),i.panelSuggestions.style.display=r,C(i.panelSuggestions,!1),i.panelSuggestionsFade.style.display=a,s.hidden=n,C(s,!1),i.footer!==s&&(i.footer.hidden=!1,C(i.footer,!1)),c.style.display=l,C(c,!1),i.header!==c&&(i.header.style.display=o(i.config)?``:`none`,C(i.header,!1))},i.container.insertBefore(e,i.footer.parentNode===i.container?i.footer:i.panelSuggestions),Ce()},O=null,k=null,Te=null,A=null,Ee=()=>[i.header,i.panelElements.closeButtonWrapper,i.panelElements.clearChatButtonWrapper,i.body,i.footer,i.scrollToBottomButton],De=()=>i.config.features?.history?.rail?.collapsible!==!1,j=()=>i.config.features?.history?.rail?.side===`right`?`right`:`left`,Oe=e=>Math.min(400,Math.max(200,Math.round(e))),ke=()=>i.config.features?.history?.rail?.resizable===!0,M,Ae=()=>{if(M===void 0&&(M=null,i.config.persistState!==!1))try{let e=Number(window.localStorage.getItem(`${i.currentKeyPrefix()}rail-width`));e&&(M=e)}catch{}return M},N=()=>Oe(Ae()??i.config.features?.history?.rail?.width??260),je=e=>{if(M=e,i.config.persistState!==!1)try{window.localStorage.setItem(`${i.currentKeyPrefix()}rail-width`,String(e))}catch{}},Me=()=>De()&&i.config.features?.history?.rail?.collapsedBehavior===`overlay`,P=!1,Ne=e=>{let t=n(`img`);return t.src=e,t.alt=``,t.setAttribute(`aria-hidden`,`true`),t},Pe=()=>{let e=i.config.features?.history?.rail?.brand;if(!e)return;let t=!1,n;return r=>{if(e.render)try{return e.render({collapsed:r})??null}catch(e){return t||(t=!0,console.warn(`[persona] history rail brand threw`,e)),null}return n===void 0&&(n=e.iconUrl?Ne(e.iconUrl):e.icon?i.renderLucideIcon(e.icon,20):null),n?n.cloneNode(!0):null}},Fe=()=>i.config.features?.history?.rail?.sections?.map(e=>{let t=!1,n=n=>{t||(t=!0,console.warn(`[persona] history rail section threw`,e.id,n))};return{id:e.id,title:e.title,placement:e.placement??`above-conversations`,items:e.items.map(e=>{let t;return{id:e.id,label:e.label,badge:e.badge,iconNode:()=>{if(t!==void 0)return t;try{t=e.renderIcon?e.renderIcon()??null:e.iconUrl?Ne(e.iconUrl):e.icon?i.renderLucideIcon(e.icon,20):null}catch(e){n(e),t=null}return t},onSelect:()=>{try{e.onSelect()}catch(e){n(e)}}}})}})??[],Ie=e=>{let t=Fe();for(let n of e)t.some(e=>e.id===n.id)?console.warn(`[persona] duplicate history rail section id`,n.id):t.push(n);return t.length?t:void 0},F=null,Le=()=>`${i.currentKeyPrefix()}rail-collapsed`,Re=()=>{if(F===null&&(F=i.config.features?.history?.rail?.defaultCollapsed===!0,i.config.persistState!==!1))try{let e=window.localStorage.getItem(Le());e&&(F=e===`1`)}catch{}return F},ze=e=>{if(F=e,i.config.persistState!==!1)try{window.localStorage.setItem(Le(),e?`1`:`0`)}catch{}},I=()=>i.historyPresentation===`rail`&&De()&&!Me()&&Re(),Be=()=>{},Ve=()=>{Me()?Be():(ze(!Re()),u?.view.setCollapsed(I()),i.applyRailChrome(),i.repinAnchoredMessage())},He=()=>{let e=i.config.features?.history?.rail?.collapseShortcut;return!e||!i.parseCombo(e)?null:{combo:e,hint:i.formatCombo(e),aria:i.ariaCombo(e)}},Ue=`var(--persona-history-overlay-margin,8px)`,L=null,R=null,We=0,z=null,B=null,V=!1,Ge=0,Ke=()=>window.matchMedia?.(`(pointer: coarse)`).matches===!0,H=()=>x()&&Me()&&(i.historyPresentation??fe())===`rail`,qe=()=>i.historyVisible&&!P,U=()=>{B!==null&&clearTimeout(B),B=null},Je=()=>{i.loadHistoryView().catch(()=>{})},Ye=()=>{U(),P&&(B=setTimeout(()=>{B=null,!V&&P&&(z?.contains(document.activeElement)||q({restoreFocus:!1}))},300))},Xe=(e,t)=>{let n=z?.getBoundingClientRect();if(!n)return!1;let r=L?.getBoundingClientRect(),i=r?Math.min(r.top,n.top):n.top;return e>=n.left&&e<=n.right&&t>=i&&t<=n.bottom||!!r&&e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom},Ze=e=>{P&&(V=Xe(e.clientX,e.clientY),V?U():B===null&&Ye())},Qe=e=>{!i.historyVisible&&H()&&(P=!0,K({invoker:L,keyboard:e?.keyboard===!0}).then(()=>{i.historyVisible?!V&&document.activeElement!==L&&q():P=!1}))},$e=()=>{let e=D?.querySelector(`[data-persona-history-focus="collapse"]`);e&&(e.setAttribute(`aria-label`,P?a.expandLabel:a.collapseLabel),e.setAttribute(`aria-expanded`,P?`false`:`true`))},et=()=>{ze(!1);let e=u;if(!P||!e){K({invoker:L});return}let t=document.activeElement===L;P=!1,ft(),e.element.remove(),mt(e.element),$e(),t&&_t(),i.repinAnchoredMessage(),$()},tt=()=>{ze(!0),q()};Be=()=>{!i.historyVisible||P?et():tt()};let nt=()=>{let e=He(),t=i.createHeaderIconButton({ariaLabel:a.expandLabel,iconName:`panel-left`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-rail-trigger`,tooltip:!1,attrs:{"data-persona-rail-trigger":``,"aria-controls":b,...e?{"aria-keyshortcuts":e.aria}:{}}}),n=t.button;n.addEventListener(`mouseenter`,()=>{V=!0,U(),!(Ke()||Date.now()<Ge)&&Qe()}),n.addEventListener(`mouseleave`,()=>{V=!1,Ge=0,Ye()}),n.addEventListener(`focus`,()=>{i.historyVisible||Je()}),n.addEventListener(`click`,e=>{x()&&(e.detail!==0&&Ke()&&!i.historyVisible?Qe():et())}),L=n,R=t.wrapper},W=()=>{if(R&&!R.isConnected&&(R=null,L=null),!H()){R?.remove(),R=null,L=null;return}L||nt();let e=R,t=L;if(!e||!t)return;let n=j()===`right`?null:i.header.firstChild;(n??i.header.lastChild)!==e&&i.header.insertBefore(e,n),e.style.display=qe()||We>0?`none`:``,t.setAttribute(`aria-label`,a.expandLabel),t.setAttribute(`aria-expanded`,i.historyVisible?`true`:`false`),z&&i.applyRailChrome()},rt=e=>{if(!P)return;let t=e.target;t instanceof Node&&(z?.contains(t)||R?.contains(t)||t instanceof Element&&t.closest(`.persona-dropdown-menu,[role="alertdialog"]`)||q({restoreFocus:!1}))};document.addEventListener(`pointerdown`,rt,!0),i.destroyCallbacks.push(()=>{document.removeEventListener(`pointerdown`,rt,!0),document.removeEventListener(`pointermove`,Ze),G?.(),U()});let it=null,G=null,at=e=>{je(Oe(e)),i.applyRailChrome(),i.repinAnchoredMessage()},ot=()=>{let e=n(`div`,`persona-rail-resizer`);return e.tabIndex=0,e.setAttribute(`role`,`separator`),e.setAttribute(`aria-orientation`,`vertical`),e.setAttribute(`aria-valuemin`,`200`),e.setAttribute(`aria-valuemax`,`400`),e.addEventListener(`pointerdown`,t=>{let n=k;if(!n||t.button!==0)return;t.preventDefault(),G?.();let r=t.clientX,a=n.getBoundingClientRect().width||N(),o=j()===`right`?-1:1,s=a,c=i.mount.ownerDocument;n.style.transition=`none`;let l=t=>{s=Oe(a+o*(t.clientX-r)),n.style.flex=`0 0 ${s}px`,e.setAttribute(`aria-valuenow`,String(s))},u=()=>{G=null,c.removeEventListener(`pointermove`,l),c.removeEventListener(`pointerup`,u),c.removeEventListener(`pointercancel`,u),n.style.removeProperty(`transition`);try{e.releasePointerCapture(t.pointerId)}catch{}at(s)};G=u,c.addEventListener(`pointermove`,l),c.addEventListener(`pointerup`,u),c.addEventListener(`pointercancel`,u);try{e.setPointerCapture(t.pointerId)}catch{}}),e.addEventListener(`keydown`,e=>{let t=j()===`right`?-16:16,n=N(),r=e.key===`ArrowRight`?n+t:e.key===`ArrowLeft`?n-t:e.key===`Home`?200:e.key===`End`?400:null;r!==null&&(e.preventDefault(),at(r))}),e},st=(e,t)=>{if(!ke()||I()){G?.(),it?.remove();return}let n=it??ot();it=n,n.setAttribute(`aria-label`,a.resizeLabel),n.setAttribute(`aria-valuenow`,String(N())),n.nextElementSibling!==t&&e.insertBefore(n,t)};i.applyRailChrome=()=>{u?.view.setRailSide(j());let e=j()===`right`,t=z;if(t){let n=L?L.getBoundingClientRect().bottom-i.container.getBoundingClientRect().top:0;t.style.top=`calc(${Math.max(0,Math.round(n))}px + ${Ue})`,t.style.width=`${N()}px`,t.style.left=e?``:Ue,t.style.right=e?Ue:``}let n=k,r=O,a=Te;if(!n||!r||!a)return;n.style.flex=`0 0 ${I()?52:N()}px`;let o=`1px solid var(--persona-divider,#e5e7eb)`;n.style.borderRight=e?``:o,n.style.borderLeft=e?o:``;let s=e?a:n;r.firstElementChild!==s&&r.append(s,e?n:a),st(r,e?n:a)};let ct=e=>{if(A&&k){A.replaceWith(e),A=null,i.applyRailChrome();return}let t=n(`div`,`persona-history-rail-shell`);t.style.cssText=`display:flex;flex-direction:row;flex:1 1 auto;min-height:0`;let r=n(`div`,`persona-history-rail-conversation`);r.style.cssText=`display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative`;let a=n(`div`,`persona-history-rail-host`);a.style.cssText=`display:flex;min-height:0;overflow:hidden`,i.container.insertBefore(t,i.header.parentNode===i.container?i.header:i.body);for(let e of Ee())e?.parentNode===i.container&&r.appendChild(e);t.append(a,r),a.appendChild(e),O=t,k=a,Te=r,i.applyRailChrome()},lt=()=>{if(O)return;let e=n(`div`,`persona-history-rail-placeholder`);e.style.cssText=`flex:1 1 auto;min-height:0`,A=e,ct(e),i.repinAnchoredMessage()},ut=()=>{A&&(ft(),i.repinAnchoredMessage())},dt=e=>{let t=n(`div`,`persona-history-rail-overlay`);t.style.cssText=`position:absolute;bottom:${Ue};display:flex;overflow:hidden;z-index:${r-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,i.container.style.position=`relative`,i.container.appendChild(t),t.appendChild(e),document.addEventListener(`pointermove`,Ze),z=t,i.applyRailChrome(),$e()},ft=()=>{Se?.(),z&&=(V&&(Ge=Date.now()+150),document.removeEventListener(`pointermove`,Ze),z.remove(),null);let e=O;if(e){G?.();for(let t of Ee())if(t&&e.contains(t)){let n=t===i.scrollToBottomButton?i.panelSuggestions:e;i.container.insertBefore(t,n)}e.remove(),O=null,k=null,Te=null,A=null}},pt=e=>{D=e,e.id=b,e.style.flex=`1 1 auto`,e.style.minHeight=`0`},mt=e=>{pt(e),(i.historyPresentation!==`rail`||P)&&ut(),i.historyPresentation===`rail`?P?dt(e):ct(e):we(e)},ht=()=>{if(W(),Ht(),!i.historyVisible||!u)return;let e=fe();if(e===i.historyPresentation)return;let t=document.activeElement,n=t instanceof HTMLElement&&(u.element.contains(t)||w?.contains(t)===!0)?t:null;ft(),u.element.remove(),u.view.setHeaderPlacement(`inline`),i.historyPresentation=e,u.view.setPresentation(e),u.view.setCollapsed(I()),u.requestRender(),u.element.isConnected||mt(u.element),n?.isConnected?n.focus():_t(),i.syncScrollToBottomButton(),i.repinAnchoredMessage(),$()},gt=(e,t)=>w?.querySelector(t)??e.querySelector(t),_t=()=>{let e=u?.element??D;if(!e)return;let t=gt(e,`[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]`);if(t){t.focus();return}let n=gt(e,`.persona-history-title`)??e;n.tabIndex=-1,n.focus()},K=async e=>{if(!x()||i.historyVisible)return;let t=c;if(!t)return;if(!P&&H()&&Re()){W();return}vt();let n=++_;f=e?.returnSurface??`conversation`,p=e?.invoker??m;let r=H()&&!P;r&&(We+=1,W(),lt());let s;try{s=await i.loadHistoryView()}catch{i.announceHistory(a.openHistoryLabel),r&&(--We,n===_&&(ut(),W()));return}if(r&&--We,n!==_||i.historyVisible)return;d={scope:ie()},i.historyPresentation=fe(),i.historyVisible=!0;let l=i.historyPresentation===`panel`&&o(i.config)&&i.header.style.display!==`none`?`external`:`inline`,h=i.config.features?.history?.rowAvatar,te=He(),g=te?{hint:te.hint,aria:te.aria}:null,v={provider:t,context:d,targetId:ae(),presentation:i.historyPresentation,collapsible:De(),collapsed:I(),railSide:j(),renderRailHeader:i.config.features?.history?.rail?.renderHeader,railBrand:Pe(),onToggleCollapse:Ve,...g?{collapseShortcut:g}:{},headerPlacement:l,showScopeStatus:i.config.features?.history?.showScopeStatus!==!1,showDelete:i.config.features?.history?.showDelete!==!1,showDeleteAll:i.config.features?.history?.showDeleteAll!==!1,...i.config.features?.history?.listActions?.length?{listActions:i.config.features.history.listActions}:{},rowAvatar:h===!1?!1:typeof h==`string`?h:i.config.launcher?.iconUrl,activeConversationId:i.session.getActiveConversationId(),...i.config.features?.history?.grouping?{grouping:i.config.features.history.grouping}:{},...i.config.features?.history?.copy?{copy:i.config.features.history.copy}:{},...i.config.features?.history?.pageSize===void 0?{}:{pageSize:i.config.features.history.pageSize},onSelect:e=>At(e,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:e=>i.setActiveConversationSummary(e),attachTooltip:i.attachTooltip,onStartNew:()=>jt({focusComposer:!0}),onClose:()=>q(),onRequestDeleteConversation:e=>Rt(e),onRequestClearHistory:()=>zt(),...t.resetDevice?{onRequestResetIdentity:()=>Bt()}:{}};u=ee({plugins:i.plugins,config:i.config,getPresentation:()=>i.historyPresentation??`panel`,getReturnSurface:()=>f,close:()=>q(),createView:({slots:e,renderDom:t,onModelChange:n,railSections:r})=>(E=s.createHistoryView({...v,railSections:Ie(r),slots:e,renderDom:t,onModelChange:n,onAnnounce:i.announceHistory}),E),onElementChanged:(e,t)=>{if(!t?.isConnected)return mt(e);pt(e),t.replaceWith(e),Ce()}}),u.view.setNewConversationRequired(i.historySessionState.recovery===`new_conversation_required`),e?.focus!==!1&&(i.historyPresentation!==`rail`||e?.keyboard===!0)&&_t(),i.syncScrollToBottomButton(),i.repinAnchoredMessage(),$(),i.eventBus.emit(`history:opened`,{presentation:i.historyPresentation,returnSurface:f,timestamp:Date.now()})},vt=()=>{},q=e=>{if(!i.historyVisible)return;_+=1;let t=f,n=p,r=u,a=e?.restoreFocus!==!1;i.historyVisible=!1;let o=!1,s=null,c=()=>{if(!o){if(o=!0,vt=()=>{},s!==null&&clearTimeout(s),P=!1,U(),ft(),r?.dispose(),r?.view.destroy(),r?.element.remove(),u===r&&(u=null,E=null,D=null,i.historyPresentation=null,d=null,p=null),i.syncScrollToBottomButton(),i.repinAnchoredMessage(),$(),a){let e=n??m;e?.isConnected?e.focus():i.maybeFocusInput()}i.eventBus.emit(`history:closed`,{returnSurface:t,timestamp:Date.now()})}},l=r&&r.element===r.view.element?r.view.playExit():null;l?(vt=c,s=setTimeout(c,250),l.then(c)):c()},yt=e=>{if(e.key===`Escape`&&i.historyVisible&&u){if(i.historyPresentation===`rail`){let t=e.target;if(!(t instanceof Node)||!(u.element.contains(t)||P&&R?.contains(t)===!0))return}e.preventDefault(),e.stopPropagation(),q()}};i.container.addEventListener(`keydown`,yt),i.destroyCallbacks.push(()=>i.container.removeEventListener(`keydown`,yt));let J=0,Y=null,bt=null,xt=()=>{bt&&clearTimeout(bt),bt=null};i.destroyCallbacks.push(xt);let St=()=>{xt();let e=i.conversationOpenPendingEl;e&&(i.conversationOpenTakeover=!0,e.hidden=!1,i.messagesWrapper.style.display=`none`,i.updateWelcome())},X=()=>{J+=1,xt(),Y?.remove(),Y=null,i.conversationOpenPendingEl&&(i.conversationOpenPendingEl.remove(),i.conversationOpenPendingEl=null,i.conversationOpenTakeover=!1,i.messagesWrapper.style.removeProperty(`display`),C(i.footer,!1),i.updateWelcome())},Ct=()=>{try{if(window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches)return;i.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:`ease-out`})}catch{}},wt=n=>{let r=i.config.layout?.messages?.layout??`bubble`,a=t(`div`,{className:`persona-flex`,attrs:{"aria-hidden":`true`}});i.applyMessageRowLayout(a,n);let o=t(`div`,{className:e(i.getBubbleClasses(n,r).join(` `),`persona-conversation-loading-bubble`),attrs:{"data-persona-theme-zone":`${n}-message`},style:{width:n===`user`?`64%`:`100%`,backgroundColor:r===`flat`?`transparent`:`var(--persona-message-${n}-bg, var(--persona-${n===`user`?`accent`:`container`}))`,color:`var(--persona-message-${n}-text, ${n===`user`&&r!==`flat`?`white`:`var(--persona-text)`})`}},...[`94%`,...n===`assistant`?[`86%`]:[],`62%`].map(e=>t(`div`,{className:`persona-conversation-loading-line`,style:{width:e}})));return i.applyBubbleGeometry(o,n,r,{...i.resolveThemeDefaults(i.config.future).components.message[n],...i.config.theme?.components?.message?.[n],...i.config.darkTheme?.components?.message?.[n]}),a.appendChild(o),a},Tt=()=>t(`div`,{className:`persona-conversation-loading-body`,style:{gap:i.messagesWrapper.style.gap}},wt(`user`),wt(`assistant`),wt(`user`),wt(`assistant`)),Et=()=>i.config.loadingIndicator?.conversationOpenVariant===`skeleton`?Tt():t(`div`,{className:`persona-conversation-loading-spinner`,attrs:{"aria-hidden":`true`}},t(`span`,{className:`persona-conversation-loading-ring`})),Dt=e=>{i.conversationOpenPendingEl?.remove(),i.conversationOpenPendingEl=e,e.hidden=!i.conversationOpenTakeover,i.body.insertBefore(e,i.messagesWrapper),xt(),i.conversationOpenTakeover||(bt=setTimeout(St,250)),C(i.footer,!0)},Ot=()=>{let n={config:i.config,streaming:!1,location:`conversation-open`,defaultRenderer:Et},r=null,o=i.plugins.find(e=>e.renderLoadingIndicator);o?.renderLoadingIndicator&&(r=o.renderLoadingIndicator(n)),r===null&&i.config.loadingIndicator?.render&&(r=i.config.loadingIndicator.render(n));let s=r??Et();Dt(t(`div`,{className:e(`persona-conversation-loading`,s.classList.contains(`persona-conversation-loading-spinner`)&&`persona-conversation-loading--centered`),attrs:{role:`status`,"aria-label":a.openConversationLoadingLabel},style:{maxWidth:i.messagesWrapper.style.maxWidth||`none`}},s))},kt=e=>{let n=()=>{At(e,{focusComposer:!0}).catch(()=>{})},r=x()?()=>{X(),K()}:void 0,o=(e,n)=>{let r=t(`button`,{className:`persona-conversation-loading-error-action`,attrs:{type:`button`},text:e});return r.addEventListener(`click`,n),r},s=()=>t(`div`,{className:`persona-conversation-loading-error-body`},t(`p`,{className:`persona-conversation-loading-error-title`,text:a.openConversationErrorTitle}),t(`div`,{className:`persona-conversation-loading-error-actions`},o(a.openConversationRetryLabel,n),r?o(a.openConversationBackLabel,r):null)),c=Object.freeze({conversationId:e,config:i.config,copy:Object.freeze({title:a.openConversationErrorTitle,retryLabel:a.openConversationRetryLabel,backLabel:a.openConversationBackLabel}),retry:n,...r?{back:r}:{},defaultRenderer:s}),l=null;for(let e of i.plugins)if(e.renderHistoryOpenError){try{l=e.renderHistoryOpenError(c)}catch(e){console.warn(`[persona] renderHistoryOpenError threw`,e),l=null}if(l)break}if(Y?.remove(),Y=t(`div`,{className:`persona-conversation-loading-error`,attrs:{role:`alert`}},l??s()),!i.session.getActiveConversationId()&&i.session.getMessages().length===0&&!i.composerStore.getState().text&&!i.attachmentManager?.hasAttachments()){let e=Y;Y=null,Dt(e),St()}else i.body.insertBefore(Y,i.messagesWrapper);i.announceHistory(a.openConversationErrorTitle)};i.eventBus.on(`history:closed`,()=>{i.conversationOpenPendingEl&&C(i.footer,!0)});let At=async(e,{focusComposer:t=!1,busy:n=`reject`}={})=>{let r=S();if(n===`background`&&(i.session.assertBackgroundSwitchable(),i.composerStore.getState().phase===`preparing`))throw new i.SessionHistoryError(`conversation_busy`,`Finish preparing this turn before switching conversations`);if(n===`reject`&&(i.session.isStreaming()||[`paused`,`resuming`].includes(i.session.getStatus())||i.composerStore.getState().phase===`preparing`))throw new i.SessionHistoryError(`conversation_busy`,`Finish or stop the current turn before switching conversations`);n===`stop`&&(++i.composerConversationGeneration,i.submissionAbort?.abort(),i.submissionAbort=null,i.composerStore.setPreparing(!1),i.session.cancel());let a=i.conversationStateKey();i.conversationOpenPendingEl&&i.pendingConversationReading?.key===a||(i.pendingConversationReading={key:a,reading:i.captureConversationReading()});let o=null,s=!!u;u?.view.setActiveConversationId(e),X();let c=J;Ot(),i.historyVisible&&(i.historyPresentation===`panel`||P)&&q({restoreFocus:!1}),i.suppressScrollSend=!0;try{await i.session.openConversation(e,{scope:r,busy:n,onBeforeCommit:()=>{i.saveConversationContinuity(),o=i.composerConversationGeneration,i.conversationPersistenceOwner=o},onCommitted:()=>{i.restoreConversationContinuity(),i.conversationPersistenceOwner===o&&(i.conversationPersistenceOwner=null),i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),i.persistState()}})}catch(t){if(i.conversationPersistenceOwner===o&&(i.conversationPersistenceOwner=null),o===i.composerConversationGeneration&&i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),c===J){let t=i.pendingConversationReading?.reading;X(),t&&i.restoreConversationReading(t),i.pendingConversationReading=null,u?.view.setActiveConversationId(i.session.getActiveConversationId()),kt(e),i.suppressScrollSend=!1}throw t}finally{c!==J&&i.conversationOpenPendingEl||(i.suppressScrollSend=!1)}c===J&&(X(),i.pendingConversationReading=null,i.messageCache.clear(),Ct(),Q(),s||i.setActiveConversationSummary(null),i.eventBus.emit(`history:conversationOpened`,{conversationId:e,title:i.activeConversationTitle,scope:r,timestamp:Date.now()}),t&&i.maybeFocusInput())},jt=async({focusComposer:e=!1}={})=>{X();let t=null;try{await i.session.startNewConversation({scope:S(),onBeforeCommit:()=>{i.saveConversationContinuity(),t=i.composerConversationGeneration,i.conversationPersistenceOwner=t},onCommitted:()=>{i.restoreConversationContinuity(!0),i.conversationPersistenceOwner===t&&(i.conversationPersistenceOwner=null),i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),i.persistState(),i.pendingConversationReading=null}})}catch(e){throw i.conversationPersistenceOwner===t&&(i.conversationPersistenceOwner=null),t===i.composerConversationGeneration&&i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),e}i.setActiveConversationSummary(null),i.messageCache.clear(),i.resetAnchorState(),i.resumeAutoScroll(),i.jumpToBottomInstant(),Q();let n=i.session.getActiveConversationId();u?.view.setActiveConversationId(n),i.eventBus.emit(`history:conversationStarted`,{conversationId:n,timestamp:Date.now()}),i.historyVisible&&(i.historyPresentation===`panel`||P)&&q({restoreFocus:!1}),e&&i.maybeFocusInput()},Mt=async(e,t)=>{let n=await i.session.updateConversation(e,{...t,...t.title===void 0?{}:{title:t.title.trim()}});return u?.view.applyConversationSummary(n),!u&&e===i.session.getActiveConversationId()&&i.setActiveConversationSummary(n),n},Nt=async e=>{let t=S(),n=i.session.getActiveConversationId()===e;await i.session.deleteConversation(e,{scope:t}),i.discardConversationContinuity(e),n&&(i.attachmentManager?.destroy({release:!0}),i.attachmentManager=null,i.restoreConversationContinuity(!0)),u?.view.removeConversationSummary(e),n&&(i.setActiveConversationSummary(null),i.messageCache.clear(),i.resetAnchorState(),i.resumeAutoScroll(),Q()),i.eventBus.emit(`history:conversationDeleted`,{conversationId:e,scope:t,wasActive:n,timestamp:Date.now()})},Pt=async e=>{let t=e?.scope??S(),n=e?.allTargets?null:e?.targetId??ae(),r=await i.session.clearConversationHistory({...n?{targetId:n}:{},scope:t});return i.discardConversationContinuity(),i.setActiveConversationSummary(null),i.messageCache.clear(),i.resetAnchorState(),i.resumeAutoScroll(),Q(),i.eventBus.emit(`history:cleared`,{deleted:r.deleted,scope:t,targetId:n,timestamp:Date.now()}),r},Ft=async()=>{if(!c?.resetDevice)throw Error(`[Persona] resetHistoryIdentity() requires a history provider that can reset this device`);let e=!1;try{e=(await i.session.resetHistoryDevice()).remoteRevocationConfirmed}finally{i.discardConversationContinuity(),X(),i.setActiveConversationSummary(null),i.session.clearArtifacts(),i.messageCache.clear(),i.lastAppliedMessages=null,i.config.clearStoredSessionId?.(),i.config.clearStoredConversationId?.(),i.persistentMetadata={},i.actionManager.syncFromMetadata(),i.clearPersistedDraft();let e=i.storageAdapter;e?.clear&&i.runStorageMutation(()=>e.clear(),`[AgentWidget] Failed to clear storage adapter:`),i.resetAnchorState(),i.resumeAutoScroll(),Q(),q({restoreFocus:!1}),i.maybeFocusInput(),i.open||i.launcherSurfaceInstance?.launcher.element.focus()}return i.announceHistory(e?a.identityResetNotice:a.identityResetUnconfirmedNotice),i.eventBus.emit(`history:identityReset`,{remoteRevocationConfirmed:e,timestamp:Date.now()}),{remoteRevocationConfirmed:e}},It=()=>i.artifactSplitRoot?i.panel:i.container,Lt=async e=>{let t=await i.loadHistoryView().catch(()=>null);return typeof t?.showHistoryConfirm==`function`?t.showHistoryConfirm(e):window.confirm(`${e.title}\n\n${e.description}`)},Rt=async e=>await Lt({host:It(),title:a.deleteConversationConfirmTitle,description:a.deleteConversationConfirm,confirmLabel:a.deleteConversationConfirmLabel,cancelLabel:a.confirmCancelLabel})?(await Nt(e),`deleted`):`cancelled`,zt=async()=>{let e=S()===`verified-user`;return await Lt({host:It(),title:a.clearHistoryConfirmTitle,description:e?a.clearHistoryVerifiedConfirm:a.clearHistoryConfirm,confirmLabel:a.clearHistoryConfirmLabel,cancelLabel:a.confirmCancelLabel})?(await Pt(),`cleared`):`cancelled`},Bt=async()=>{if(!await Lt({host:It(),title:a.resetIdentityConfirmTitle,description:a.resetIdentityConfirm,confirmLabel:a.resetIdentityConfirmLabel,cancelLabel:a.confirmCancelLabel}))return{outcome:`cancelled`};let{remoteRevocationConfirmed:e}=await Ft();return{outcome:`reset`,remoteRevocationConfirmed:e}},Z=n(`button`,`persona-history-earlier`);Z.type=`button`,Z.textContent=a.showEarlierMessagesLabel,Z.setAttribute(`data-persona-history-earlier`,``),Object.assign(Z.style,{alignSelf:`center`,minHeight:`44px`,padding:`0 16px`,borderRadius:`999px`,border:`1px solid var(--persona-border, rgba(0,0,0,0.12))`,background:`transparent`,color:`inherit`,font:`inherit`,cursor:`pointer`,flexShrink:`0`});let Q=()=>{x()&&i.historySessionState.nextMessageCursor&&i.session.getActiveConversationId()?(Z.textContent=a.showEarlierMessagesLabel,Z.parentNode!==i.body&&i.body.insertBefore(Z,i.body.firstChild)):Z.remove()};Z.addEventListener(`click`,()=>{let e=i.session.getActiveConversationId(),t=i.historySessionState.nextMessageCursor;if(!e||!t||Z.disabled)return;Z.disabled=!0;let n=i.body.scrollHeight,r=i.body.scrollTop;i.session.loadOlderMessages(e,t,{scope:S()}).then(()=>{i.body.scrollTop=r+(i.body.scrollHeight-n),i.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Z.disabled=!1,Q()})});let Vt=()=>{let e=i.createHeaderIconButton({ariaLabel:a.openHistoryLabel,iconName:`history`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-history-toggle`,attrs:{"data-persona-history-toggle":``}});return e.button.addEventListener(`click`,t=>{x()&&!re()&&(i.historyVisible?q():K({invoker:e.button,keyboard:t.detail===0}))}),e},Ht=()=>{if(!x()){h?.remove(),m=null,h=null;return}if(h&&!h.isConnected&&(m=null,h=null),!m&&i.header){let e=Vt();m=e.button,h=e.wrapper;let t=i.panelElements.clearChatButtonWrapper||i.panelElements.closeButtonWrapper;t?.parentNode&&i.header.contains(t)?t.parentNode.insertBefore(h,t):i.header.appendChild(h)}if(!m||!h)return;let e=H()||i.historyVisible&&i.historyPresentation===`rail`;if(h.style.display=e?`none`:``,e){document.activeElement===m&&_t();return}let t=re();m.disabled=t,m.setAttribute(`aria-disabled`,t?`true`:`false`);let n=t?a.openHistoryBusyLabel:a.openHistoryLabel;m.setAttribute(`aria-label`,n),(i.config.features?.history?.presentation??`panel`)===`panel`?(m.removeAttribute(`aria-expanded`),m.removeAttribute(`aria-controls`)):(m.setAttribute(`aria-expanded`,i.historyVisible?`true`:`false`),m.setAttribute(`aria-controls`,b))},Ut=!1,Wt=()=>{let e=i.panelElements.clearChatButton;e&&(x()?(Ut||=(v=e.getAttribute(`aria-label`)??``,!0),e.setAttribute(`aria-label`,a.newConversationLabel),e.removeAttribute(`title`)):Ut&&(Ut=!1,v&&e.setAttribute(`aria-label`,v)))},$=()=>{a=s(i.config.features?.history?.copy),Ht(),W(),Wt(),Q()};return i.historyChromeSync=$,de(),$(),i.destroyCallbacks.push(()=>{ne?.(),y?.(),_+=1,vt(),u?.dispose(),u?.view.destroy(),u=null}),{clearConversationOpenPending:X,cancelConversationOpenTakeover:xt,historyOperationScope:S,discardConversationContinuity:i.discardConversationContinuity,historyAvailable:x,historyScope:ie,installHistoryProvider:de,syncHistoryChromeImpl:$,syncHistoryPresentation:ht,syncEarlierMessagesPill:Q,openHistory:K,closeHistory:q,openHistoryConversation:At,startNewConversation:jt,updateHistoryConversation:Mt,deleteHistoryConversation:Nt,requestDeleteConversation:Rt,clearConversationHistory:Pt,resetHistoryIdentity:Ft,railCollapseShortcut:He,railCollapsible:De,railTriggerApplies:H,railOverlayMode:Me,toggleRailCollapsed:Ve,toggleRailPinned:()=>Be(),get historyProvider(){return c},get historySurface(){return u},get railShell(){return O},get railHost(){return k},get railColumn(){return Te}}};export{g as createHistoryShell};
@@ -1 +1 @@
1
- import{t as e}from"./chunk-DVgzoVCB.js";const t=32768,n=49152,r=e=>{let t=e??{},n=typeof t.targetId==`string`?t.targetId:null;return{id:typeof t.id==`string`?t.id:``,title:typeof t.title==`string`?t.title:``,targetId:n,preview:typeof t.preview==`string`?t.preview:null,messageCount:typeof t.messageCount==`number`?t.messageCount:0,createdAt:typeof t.createdAt==`string`?t.createdAt:``,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:``}},i=`The identity proof was not admitted; account history is unavailable`,a=`The identity proof was rejected`,o=`The request carried no visitor credential`,s=`The stored visitor belongs to a different signed-in user`;function c(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function l(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function u(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function d(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let a=await e.reinitWithProof(n);if(a.visitor?.identityStatus!==`admitted`||a.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);return a}async function f(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function p(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,o);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,s);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function m(e,t,n){let r=await f(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,o):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,s):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function h(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function g(t,n,r){_(t);let i=r.trackIdentity!==!1,a=await t.initSession(),o=null;l(t,r.scope)===`verified-user`&&(o=await u(t,a,i),o&&(a=await d(t,a,o,i)));let s=t.historyInternals.visitorStore,g=!1;for(;;){let l=s?.revision()??0,u=await t.readVisitorToken();if(!u&&!r.visitorTokenOptional)throw new t.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let d=await fetch(c(t,n,{...r.query,sessionId:a.sessionId}),{method:r.method,headers:{"X-Persona-Version":e,...u?{"X-Visitor-Token":u}:{},...o?{"X-Identity-Proof":o}:{},...r.body===void 0?{}:{"Content-Type":`application/json`}},...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.keepalive?{keepalive:!0}:{}});if(d.status===401&&!g){g=!0,a=await p(t,await f(t,d),o,i);continue}if(!d.ok)throw await m(t,d,i);let _=d.headers.get(`X-History-Identity-Status`),v=await d.json().catch(()=>void 0);if(s&&s.revision()!==l)throw new t.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return h(t,_,o!==null,i),v}}function _(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function v(e,t){let n=await g(e,`conversations`,{method:`GET`,query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit===void 0?{}:{limit:t.limit},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(r),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function y(e,t,n){let i=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:r(i),messages:Array.isArray(i?.messages)?i.messages:[],nextMessageCursor:typeof i?.nextMessageCursor==`string`?i.nextMessageCursor:null,conversationRevision:typeof i?.conversationRevision==`string`?i.conversationRevision:null}}async function b(e,r,i){_(e);let a=0;for(let n of i){let r=n.displayContent.length;if(r>t)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${t} character limit`);a+=r}if(a>n)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${n} character limit`);await e.initSession();let o=e.historyInternals.visitorStore,s=o?.revision()??0,c=await g(e,`conversations/${encodeURIComponent(r)}/display-projections`,{method:`PATCH`,body:{messages:i},scope:`browser`,keepalive:a<=n,trackIdentity:!1}),l=typeof c?.conversationRevision==`string`?c.conversationRevision:null;return l&&e.clientSession?.conversationId===r&&(o?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function x(e,t,n){let r=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function S(e,t){let n=await g(e,`conversations`,{method:`DELETE`,query:{...t?.targetId===void 0?{}:{targetId:t.targetId}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted==`number`?n.deleted:0}}async function C(e){_(e),e.setHistoryIdentityStatus({state:`resetting`});try{await g(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}export{S as deleteAllConversations,x as deleteConversation,b as finalizeDisplayProjections,y as getConversation,m as historyErrorFor,v as listConversations,f as readErrorCode,p as recoverFromUnauthorized,C as resetVisitor};
1
+ import{t as e}from"./chunk-Dqa_GOcj.js";const t=32768,n=49152,r=e=>{let t=e??{},n=typeof t.targetId==`string`?t.targetId:null;return{id:typeof t.id==`string`?t.id:``,title:typeof t.title==`string`?t.title:``,targetId:n,preview:typeof t.preview==`string`?t.preview:null,messageCount:typeof t.messageCount==`number`?t.messageCount:0,createdAt:typeof t.createdAt==`string`?t.createdAt:``,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:``}},i=`The identity proof was not admitted; account history is unavailable`,a=`The identity proof was rejected`,o=`The request carried no visitor credential`,s=`The stored visitor belongs to a different signed-in user`;function c(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function l(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function u(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function d(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let a=await e.reinitWithProof(n);if(a.visitor?.identityStatus!==`admitted`||a.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);return a}async function f(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function p(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,o);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,s);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function m(e,t,n){let r=await f(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,o):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,s):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function h(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function g(t,n,r){_(t);let i=r.trackIdentity!==!1,a=await t.initSession(),o=null;l(t,r.scope)===`verified-user`&&(o=await u(t,a,i),o&&(a=await d(t,a,o,i)));let s=t.historyInternals.visitorStore,g=!1;for(;;){let l=s?.revision()??0,u=await t.readVisitorToken();if(!u&&!r.visitorTokenOptional)throw new t.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let d=await fetch(c(t,n,{...r.query,sessionId:a.sessionId}),{method:r.method,headers:{"X-Persona-Version":e,...u?{"X-Visitor-Token":u}:{},...o?{"X-Identity-Proof":o}:{},...r.body===void 0?{}:{"Content-Type":`application/json`}},...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.keepalive?{keepalive:!0}:{}});if(d.status===401&&!g){g=!0,a=await p(t,await f(t,d),o,i);continue}if(!d.ok)throw await m(t,d,i);let _=d.headers.get(`X-History-Identity-Status`),v=await d.json().catch(()=>void 0);if(s&&s.revision()!==l)throw new t.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return h(t,_,o!==null,i),v}}function _(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function v(e,t){let n=await g(e,`conversations`,{method:`GET`,query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit===void 0?{}:{limit:t.limit},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(r),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function y(e,t,n){let i=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:r(i),messages:Array.isArray(i?.messages)?i.messages:[],nextMessageCursor:typeof i?.nextMessageCursor==`string`?i.nextMessageCursor:null,conversationRevision:typeof i?.conversationRevision==`string`?i.conversationRevision:null}}async function b(e,r,i){_(e);let a=0;for(let n of i){let r=n.displayContent.length;if(r>t)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${t} character limit`);a+=r}if(a>n)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${n} character limit`);await e.initSession();let o=e.historyInternals.visitorStore,s=o?.revision()??0,c=await g(e,`conversations/${encodeURIComponent(r)}/display-projections`,{method:`PATCH`,body:{messages:i},scope:`browser`,keepalive:a<=n,trackIdentity:!1}),l=typeof c?.conversationRevision==`string`?c.conversationRevision:null;return l&&e.clientSession?.conversationId===r&&(o?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function x(e,t,n){let r=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function S(e,t){let n=await g(e,`conversations`,{method:`DELETE`,query:{...t?.targetId===void 0?{}:{targetId:t.targetId}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted==`number`?n.deleted:0}}async function C(e){_(e),e.setHistoryIdentityStatus({state:`resetting`});try{await g(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}export{S as deleteAllConversations,x as deleteConversation,b as finalizeDisplayProjections,y as getConversation,m as historyErrorFor,v as listConversations,f as readErrorCode,p as recoverFromUnauthorized,C as resetVisitor};
@@ -0,0 +1 @@
1
+ const e=`4.34.0`;export{e as t};
@@ -0,0 +1 @@
1
+ import{f as e,m as t,p as n,r,s as i}from"./chunk-CEPM3FOp.js";import{r as a,t as o}from"./chunk-BnfM7-qg.js";import{t as s}from"./chunk-CnxIZOzx.js";import{i as c,r as l,t as u}from"./chunk-D5BxWOFB.js";import{r as d}from"./chunk-Bb41bKyp.js";import{t as f}from"./chunk-BlTD-Wgn.js";import{n as p,t as m}from"./chunk-BAkaTZpd.js";import{i as h,n as g,r as _,t as v}from"./chunk-BGPPJ_ui.js";import{t as y}from"./chunk-Bj8Hnh10.js";import{r as b}from"./chunk-Cy1A8vbF.js";import{Activity as x,ArrowDown as S,ArrowLeft as C,ArrowRight as w,ArrowUp as T,ArrowUpRight as E,AtSign as ee,Bot as D,Check as O,ChevronDown as k,ChevronLeft as A,ChevronRight as j,ChevronUp as M,Clipboard as N,ClipboardCopy as P,CodeXml as te,Copy as ne,Download as re,Ellipsis as ie,ExternalLink as ae,Eye as oe,File as se,FileCode as ce,FileSpreadsheet as le,FileText as ue,History as de,ImagePlus as fe,Loader as pe,LoaderCircle as me,Maximize as he,Menu as ge,MessageSquare as _e,Mic as ve,Minimize as ye,Minus as be,PanelLeft as xe,Paperclip as Se,Pencil as Ce,Plus as we,Quote as Te,RefreshCw as Ee,Search as De,Send as Oe,ShieldAlert as ke,ShieldCheck as Ae,ShieldX as je,Square as Me,Star as Ne,ThumbsDown as Pe,ThumbsUp as Fe,Trash as Ie,Trash2 as Le,Upload as Re,Volume2 as ze,X as Be}from"lucide";const Ve={activity:x,"arrow-down":S,"arrow-up":T,"arrow-up-right":E,bot:D,"chevron-down":k,"chevron-up":M,"chevron-right":j,"chevron-left":A,check:O,clipboard:N,"clipboard-copy":P,"code-xml":te,copy:ne,file:se,"file-code":ce,"file-spreadsheet":le,"file-text":ue,"image-plus":fe,loader:pe,"loader-circle":me,mic:ve,paperclip:Se,quote:Te,"refresh-cw":Ee,search:De,send:Oe,"shield-alert":ke,"shield-check":Ae,"shield-x":je,square:Me,"square-text":[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`}],[`path`,{d:`M7 8h10M7 12h10M7 16h6`}]],"thumbs-down":Pe,"thumbs-up":Fe,upload:Re,"volume-2":ze,"voice-bars":[[`path`,{d:`M4 10v4`}],[`path`,{d:`M8 6v12`}],[`path`,{d:`M12 3v18`}],[`path`,{d:`M16 7v10`}],[`path`,{d:`M20 10v4`}]],x:Be,"at-sign":ee,"arrow-left":C,"arrow-right":w,"external-link":ae,ellipsis:ie,menu:ge,"panel-left":xe,plus:we,minus:be,pencil:Ce,trash:Ie,"trash-2":Le,download:re,maximize:he,minimize:ye,"message-square":_e,star:Ne,eye:oe,history:de},He=/* @__PURE__ */ `brain.toolbox.wrench.circle.database.terminal.user.mail.phone.calendar.clock.building.map-pin.lock.key.credit-card.hash.globe.link.circle-check.circle-x.triangle-alert.info.ban.shield.ellipsis-vertical.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(`.`),F=new Map(Object.entries(Ve)),I=/* @__PURE__ */ new Map;let L=!1;const Ue=/* @__PURE__ */ new Set,We=e=>{let t=[...Ue];e&&Ue.clear();for(let e of t)try{e()}catch{}},Ge=()=>{let e=0;for(let[t,n]of I){let r=F.get(n);if(!r)continue;I.delete(t),e++;let i=s(r);if(i)for(t.removeAttribute(`data-persona-icon-pending`);i.firstChild;)t.appendChild(i.firstChild)}return e},Ke=e=>{if(!L){for(let[t,n]of Object.entries(e))F.has(t)||F.set(t,n);L=!0,Ge(),We(!0)}},qe=()=>L?null:o().then(e=>Ke(e.EXTRA_LUCIDE_ICONS)),Je=()=>{qe()?.catch(e=>{console.warn(`[Persona] Failed to load the icons-extra chunk`,e)})},Ye=(e,t,n)=>{let r=s([],e,t,n);return r.setAttribute(`data-persona-icon-pending`,`true`),r},R=(e,t=24,n=`currentColor`,r=2)=>{let i=F.get(e);if(i)return s(i,t,n,r);if(He.includes(e)){let i=Ye(t,n,r);return I.size>=500&&I.delete(I.keys().next().value),I.set(i,e),Je(),i}return console.warn(`Unknown Persona icon "${e}". Use registerIcons().`),null},Xe=(e,t)=>e.visible!==!1&&(e.mode!==`transient`||t===`connecting`||t===`paused`||t===`resuming`||t===`error`),Ze=(e,t,n)=>{let r=t.mode===`transient`,i=e.hasAttribute(`data-persona-composer-reason`)||e.hasAttribute(`data-persona-composer-notice`);e.style.display=Xe(t,n)||r&&i&&t.visible!==!1?``:`none`,e.classList.toggle(`persona-mt-2`,!r),e.classList.toggle(`persona-mb-2`,r)},Qe=(e,t,n)=>{t.parentElement&&e.parentElement===t.parentElement&&(n.mode===`transient`?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))};function $e(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith(`px`))return 20;let r=parseFloat(n);return Number.isFinite(r)&&r>0?r:20}function et(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:e>0?e:t}function tt(e,t){e.style.maxHeight=`${t*$e(e)}px`,e.style.overflowY=`auto`}function nt(e){let t=e?.ownerDocument?.defaultView??(typeof window<`u`?window:null);if(!t||typeof t.matchMedia!=`function`)return!1;try{return t.matchMedia(`(pointer: coarse)`).matches===!0}catch{return!1}}function rt(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function it(e,t){if(e.key!==`Enter`||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,r=t.submitKey??`enter`;return r===`none`?!1:r===`mod-enter`?n:n||!rt(t)}function at(e){return(e.submitKey??`enter`)===`enter`?rt(e)?`enter`:`send`:`enter`}function ot(e,t){e.setAttribute(`enterkeyhint`,at(t))}function z(e,t){let n=t?.autocomplete;e.setAttribute(`autocomplete`,typeof n==`string`&&n?n:`off`);let r=(t,n)=>{n===void 0?e.removeAttribute(t):e.setAttribute(t,n)};r(`autocapitalize`,typeof t?.autocapitalize==`string`?t.autocapitalize:void 0),r(`spellcheck`,typeof t?.spellcheck==`boolean`?String(t.spellcheck):void 0),r(`inputmode`,typeof t?.inputmode==`string`&&t.inputmode?t.inputmode:void 0),r(`aria-label`,typeof t?.ariaLabel==`string`&&t.ariaLabel?t.ariaLabel:void 0)}function st(e){return e===!0?{disabled:!0}:!e||typeof e!=`object`?{disabled:!1}:{disabled:!0,reason:typeof e.reason==`string`&&e.reason?e.reason:void 0}}const{setLoader:ct,load:lt}=a({fallbackImport:()=>import(`./chunk-Co3VVwGe.js`)}),ut=lt,{setLoader:dt,load:ft}=a({fallbackImport:()=>import(`./chunk-CE4seJxF.js`),resetOnSetLoader:!0}),pt=ft;let B=400,V=300,H=0;const U=e=>Math.max(0,e);function mt(e){e.delayMs!==void 0&&(B=U(e.delayMs)),e.skipDelayMs!==void 0&&(V=U(e.skipDelayMs))}const ht=()=>Date.now()<H,gt=e=>{H=e>0?Date.now()+e:0},W=/* @__PURE__ */ new WeakMap,_t=e=>typeof e.closest==`function`&&e.closest(`[data-persona-tooltip-suppressed]`)!==null;function vt(e){W.get(e)?.hide()}const yt=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e,bt=e=>{let t=e.getRootNode?.();return yt(t)?t:e.closest(`dialog[open]`)??e.ownerDocument.body},G=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),xt=[...[`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 K(e){W.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:r,hint:i,enabled:a=!0,gap:o=8,viewportPadding:s=8}=e,c=()=>t.ownerDocument,l=()=>c().defaultView??window,u=null,f=null,p=null,m=null,h,g=!1,_=!1,v=!1,y=()=>(typeof r==`function`?r():r).trim(),b=()=>(typeof i==`function`?i():i??``).trim(),x=()=>U(e.delayMs??B),S=()=>U(e.skipDelayMs??V),C=()=>{h!==void 0&&(l().clearTimeout(h),h=void 0)},w=()=>{C();let e=u!==null;m?.(),m=null,u?.remove(),u=null,f=null,p=null,e&&gt(S())},T=()=>{if(!u)return;let e=c(),n=l(),r=t.getBoundingClientRect(),i=u.getBoundingClientRect(),a=e.documentElement.clientWidth||n.innerWidth,d=e.documentElement.clientHeight||n.innerHeight,f=a-s-i.width,p=r.left+r.width/2-i.width/2,m=G(p,s,f),h=r.top-s,g=d-s-r.bottom,_=h>=i.height+o||h>=g?`top`:`bottom`,v=_===`top`?r.top-o-i.height:r.bottom+o,y=d-s-i.height,b=G(v,s,y),x=r.left+r.width/2,S=Math.max(10,i.width-10),C=G(x-m,10,S);u.dataset.placement=_,u.style.left=`${m}px`,u.style.top=`${b}px`,u.style.setProperty(`--persona-tooltip-arrow-x`,`${C}px`)},E=()=>{if(v||!a||u||!t.isConnected||_t(t))return;let e=y(),n=bt(t);if(!e||!n)return;let r=c(),i=l();u=r.createElement(`div`),u.className=`persona-control-tooltip`,u.setAttribute(`role`,`tooltip`),u.dataset.state=`measuring`,u.style.zIndex=String(d);let o=i.getComputedStyle?.(t);if(o){for(let e of xt){let t=o.getPropertyValue(e).trim();t&&u.style.setProperty(e,t)}o.fontFamily&&(u.style.fontFamily=o.fontFamily)}f=r.createElement(`span`),f.className=`persona-control-tooltip__label`,f.textContent=e,u.appendChild(f);let s=b();s&&(p=r.createElement(`span`),p.className=`persona-control-tooltip__hint`,p.textContent=s,u.appendChild(p));let h=r.createElement(`span`);h.className=`persona-control-tooltip__arrow`,u.appendChild(h),n.appendChild(u),T(),u.dataset.state=`open`;let g=()=>{if(!t.isConnected){w();return}f&&(f.textContent=y()),p&&(p.textContent=b());let e=bt(t);u&&e&&u.parentNode!==e&&e.appendChild(u),T()};i.addEventListener(`scroll`,g,!0),i.addEventListener(`resize`,g);let _=t.closest(`[data-persona-root]`);_?.addEventListener(`persona:internal:host-moved`,g);let x=t.getRootNode(),S=yt(x)?x:r.documentElement,C=typeof MutationObserver>`u`?null:new MutationObserver(()=>{t.isConnected||w()});C?.observe(S,{childList:!0,subtree:!0}),m=()=>{i.removeEventListener(`scroll`,g,!0),i.removeEventListener(`resize`,g),_?.removeEventListener(`persona:internal:host-moved`,g),C?.disconnect()}},ee=e=>{v||u||(C(),e||x()<=0||ht()?E():h=l().setTimeout(()=>{h=void 0,E()},x()))},D=()=>{g||_?ee(_):w()},O=()=>{let e=l();e.matchMedia&&e.matchMedia(`(hover: none)`).matches||(g=!0,D())},k=()=>{g=!1,D()},A=()=>{try{_=t.matches(`:focus-visible`)}catch{_=!0}D()},j=()=>{_=!1,D()},M=()=>{g=!1,_=!1,w()},N=e=>{e.key===`Escape`&&M()};n.addEventListener(`mouseenter`,O),n.addEventListener(`mouseleave`,k),t.addEventListener(`focus`,A),t.addEventListener(`blur`,j),t.addEventListener(`keydown`,N),t.addEventListener(`click`,M);let P={get isOpen(){return u!==null},show:E,hide:w,reposition:T,destroy:()=>{v||(v=!0,w(),n.removeEventListener(`mouseenter`,O),n.removeEventListener(`mouseleave`,k),t.removeEventListener(`focus`,A),t.removeEventListener(`blur`,j),t.removeEventListener(`keydown`,N),t.removeEventListener(`click`,M),W.delete(t))}};return W.set(t,P),P}const q=(e,t,n,r)=>{let[i,a]=t.split(`.`);return[e?.theme,e?.darkTheme].some(e=>e?.components?.[i]?.[a]?.[n]!==void 0)?`var(--persona-components-${t.replace(`.`,`-`)}-${n}, ${r})`:r},J=(e,t)=>{let n=e&&r(e,t);return typeof n==`string`&&n?n:void 0},Y=(e,t,n,r)=>{let i=t.startsWith(`var(`);e.classList.toggle(`persona-theme-padding`,i),e.style.padding=i?``:t,i?e.style.setProperty(`--persona-theme-padding`,t):e.style.removeProperty(`--persona-theme-padding`),n&&(e.style.paddingLeft=e.style.paddingRight=n),r&&(e.style.paddingTop=e.style.paddingBottom=r)},X=(e,t,n)=>{let r=t.startsWith(`var(`)&&t.includes(`--persona-components-`);e.classList.toggle(`persona-control-size`,r),r?e.style.setProperty(`--persona-control-size`,t):e.style.removeProperty(`--persona-control-size`),e.style.width=e.style.height=t,e.style.minWidth=e.style.minHeight=n??``},St=`min(440px, calc(100vw - 24px))`,Ct=`40px`,wt={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:400,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:St,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:`40px`,headerIconSize:Ct,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:``,streamingIndicator:`arrow`,scrollBehavior:`instant`,scrollDurationMs:220,transition:`none`},scrollBehavior:{mode:`anchor-top`,anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:_,reasoningDisplay:v,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},Tt={},Z={colorScheme:`light`,errorDisplay:`block`,messageActions:{visibility:void 0},suggestionChipsConfig:{fontWeight:void 0},approval:y,loadingIndicator:{variant:`label`},launcher:{variant:`circle`,width:`min(400px, calc(100vw - 24px))`,headerIconSize:`20px`},features:{artifacts:{enabled:!0},scrollToBottom:{streamingIndicator:`dots`,transition:`fade`,scrollBehavior:`smooth`},userMessageCollapse:{enabled:!0},toolCallDisplay:h,reasoningDisplay:g},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 Et(e){return e?.future?.v5Defaults===!0?`v5`:`v4`}function Q(t){let n=Et(t)===`v5`?Z:Tt;return e(wt,n)}Q();function Dt(t,n){if(t||n)return t?n?e(t,n):t:n}function Ot(e){let r=Q(e);return e?i(t(b({...r,...e,colorScheme:n(e,[`colorScheme`]).includes(`colorScheme`)?e.colorScheme:e.brand?void 0:r.colorScheme,...r.approval||e.approval!==void 0?{approval:e.approval!==!1&&{...r.approval||{},...e.approval}}:{},theme:Dt(r.theme,e.theme),darkTheme:Dt(r.darkTheme,e.darkTheme),launcher:{...r.launcher,...e.launcher,dock:{...r.launcher?.dock,...e.launcher?.dock},clearChat:{...r.launcher?.clearChat,...e.launcher?.clearChat}},...r.composer||e.composer?{composer:{...r.composer,...e.composer}}:{},tooltip:{...r.tooltip,...e.tooltip},copy:{...r.copy,...e.copy},sendButton:{...r.sendButton,...e.sendButton},statusIndicator:{...r.statusIndicator,...e.statusIndicator},voiceRecognition:{...r.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=r.features?.artifacts,n=e.features?.artifacts,i=r.features?.scrollToBottom,a=e.features?.scrollToBottom,o=r.features?.scrollBehavior,s=e.features?.scrollBehavior,c=r.features?.streamAnimation,l=e.features?.streamAnimation,u=r.features?.askUserQuestion,d=e.features?.askUserQuestion,f=r.features?.userMessageCollapse,p=e.features?.userMessageCollapse,m=r.features?.history,h=e.features?.history,g=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},_=i===void 0&&a===void 0?void 0:{...i,...a},v=o===void 0&&s===void 0?void 0:{...o,...s},y=c===void 0&&l===void 0?void 0:{...c,...l},b=u===void 0&&d===void 0?void 0:{...u,...d,styles:{...u?.styles,...d?.styles}},x=m===void 0&&h===void 0?void 0:{...m,...h,copy:{...m?.copy,...h?.copy}};return{...r.features,...e.features,toolCallDisplay:{...r.features?.toolCallDisplay,...e.features?.toolCallDisplay,...e.features?.toolCallDisplay?.layout===void 0&&e.features?.toolCallDisplay?.variant!==void 0?{layout:e.features.toolCallDisplay.variant}:{}},reasoningDisplay:{...r.features?.reasoningDisplay,...e.features?.reasoningDisplay,...e.features?.reasoningDisplay?.layout===void 0&&e.features?.reasoningDisplay?.variant!==void 0?{layout:e.features.reasoningDisplay.variant}:{}},..._===void 0?{}:{scrollToBottom:_},...v===void 0?{}:{scrollBehavior:v},...g===void 0?{}:{artifacts:g},...y===void 0?{}:{streamAnimation:y},...b===void 0?{}:{askUserQuestion:b},...x===void 0?{}:{history:x},...f!==void 0||p!==void 0?{userMessageCollapse:{...f,...p}}:{}}})(),suggestionChips:e.suggestionChips??r.suggestionChips,suggestionChipsConfig:{...r.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...r.layout,...e.layout,header:{...r.layout?.header,...e.layout?.header},messages:{...r.layout?.messages,...e.layout?.messages,...r.layout?.messages?.user||e.layout?.messages?.user?{user:{...r.layout?.messages?.user,...e.layout?.messages?.user}}:{},...r.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...r.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...r.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...r.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...r.layout?.slots,...e.layout?.slots}},markdown:{...r.markdown,...e.markdown,options:{...r.markdown?.options,...e.markdown?.options}},messageActions:{...r.messageActions,...e.messageActions}},e),e,Z),e):i(t(b(r),void 0,Z))}const kt=(e,t)=>{let n=u(`textarea`);n.setAttribute(`data-persona-composer-input`,``),n.placeholder=e?.copy?.inputPlaceholder??`How can I help...`,n.dir=`auto`,ot(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:nt(n)}),z(n,e?.composer?.inputAttributes),n.className=`persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea`,n.rows=1,n.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,n.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`;let r=et(e?.composer?.maxLines,t?.defaultMaxLines??3),i=`${r*20}px`;n.style.maxHeight=i,n.style.overflowY=`auto`;let a=()=>{let e=n.style.maxHeight;if(e!==i){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=r*$e(n);return i=`${t}px`,n.style.maxHeight=i,t},o=()=>{n.addEventListener(`input`,()=>{n.style.height=`auto`;let e=Math.min(n.scrollHeight,a());n.style.height=`${e}px`})};return n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.addEventListener(`focus`,()=>{n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.style.boxShadow=`none`}),n.addEventListener(`blur`,()=>{n.style.border=`none`,n.style.outline=`none`}),{textarea:n,attachAutoResize:o}},At=`[data-persona-glyph-stack]`,jt=(e,t,n=`send`)=>{let r=l(`span`,{className:`persona-composer-glyph-stack`,attrs:{"data-mode":n,"data-persona-glyph-stack":``}});return e.setAttribute(`data-glyph`,`send`),t.setAttribute(`data-glyph`,`stop`),r.append(e,t),r},Mt=/* @__PURE__ */ new WeakMap,$=(e,t,n=!0)=>{Mt.set(e,t);let r=t?.sendButton??{},i=r.useIcon??!1,a=e.getAttribute(`data-persona-send-mode`)===`stop`?`stop`:`send`,o=e=>J(t,`sendButton.${e}`),s=(e,n)=>q(t,`composer.send`,e,n),l=o(`size`)||r.size;e.style.fontSize=i?`18px`:``,e.style.lineHeight=i?`1`:``,e.className=c(`persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer`,i?`persona-flex persona-items-center persona-justify-center ${m}`:`persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold`,i&&!o(`backgroundColor`)&&`persona-bg-persona-primary`,!i&&!o(`textColor`)&&`persona-text-white`),X(e,i?l||(s(`size`,``)?s(`size`,`var(--persona-composer-control-size, 40px)`):``):``,i?l:void 0);let u=s(`foreground`,i?`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`:`#ffffff`),d=s(`background`,i?`var(--persona-button-primary-bg, var(--persona-primary, #111827))`:`var(--persona-accent, #0f0f0f)`);e.style.color=o(`textColor`)||(a===`stop`&&s(`foreground`,``)?`var(--persona-button-stop-fg, ${u})`:s(`foreground`,``)||(i?u:``)),e.style.backgroundColor=(i?o(`backgroundColor`):void 0)||(s(`background`,``)?a===`stop`?`var(--persona-button-stop-bg, ${d})`:d:``);let f=o(`borderWidth`)||(s(`borderWidth`,``)?s(`borderWidth`,r.borderWidth||`0px`):r.borderWidth||``);e.style.borderWidth=f,e.style.borderStyle=f?`solid`:``,e.style.borderColor=o(`borderColor`)||(s(`borderColor`,``)?s(`borderColor`,r.borderColor||`transparent`):r.borderColor||``),e.style.borderRadius=s(`borderRadius`,``)?s(`borderRadius`,`var(--persona-components-composer-sendButtonRadius, var(--persona-button-radius))`):``,Y(e,s(`padding`,i?`0`:`8px 16px`),i?void 0:o(`paddingX`)||(s(`padding`,``)?void 0:r.paddingX),i?void 0:o(`paddingY`)||(s(`padding`,``)?void 0:r.paddingY));let p=parseFloat(r.iconSize??``)||Math.round((parseFloat(r.size??``)||40)*.5);if(n){if(e.replaceChildren(),i){let t=r.iconStrokeWidth??2,n=r.iconName?R(r.iconName,p,`currentColor`,t):null,i=R(r.stopIconName??`square`,p,`currentColor`,t);n&&i?e.appendChild(jt(n,i,a)):n?e.appendChild(n):e.textContent=r.iconText??`↑`}else e.textContent=a===`stop`?t?.copy?.stopButtonLabel??`Stop`:t?.copy?.sendButtonLabel??`Send`}for(let n of Array.from(e.querySelectorAll(`svg`))){n.style.width=n.style.height=o(`iconSize`)?``:s(`iconSize`,`var(--persona-components-composer-sendIconSize, ${p}px)`);let e=t?.sendButton?.iconStrokeWidth;n.style.strokeWidth=e===void 0?s(`iconStrokeWidth`,``):String(e)}},Nt=e=>{let t=e?.sendButton,n=u(`div`,`persona-send-button-wrapper`),r=l(`button`,{attrs:{type:`submit`,"data-persona-composer-submit":``,"data-persona-send-mode":`send`}});return $(r,e),r.setAttribute(`aria-label`,t?.tooltipText??`Send message`),n.appendChild(r),K({anchor:r,trigger:n,text:()=>r.getAttribute(`aria-label`)??``,enabled:t?.showTooltip??!1}),{button:r,wrapper:n,setMode:e=>{if(r.getAttribute(`data-persona-send-mode`)===e)return;r.setAttribute(`data-persona-send-mode`,e),r.setAttribute(`aria-label`,e===`stop`?t?.stopTooltipText??`Stop generating`:t?.tooltipText??`Send message`);let n=Mt.get(r);$(r,n,!1),r.querySelector(At)?.setAttribute(`data-mode`,e),(n?.sendButton?.useIcon??!1)||(r.textContent=e===`stop`?n?.copy?.stopButtonLabel??`Stop`:n?.copy?.sendButtonLabel??`Send`)},glyphStack:r.querySelector(At)}},Pt=(e,t,n=`idle`,r=`none`)=>{let i=t?.voiceRecognition??{},a=e=>J(t,`voiceRecognition.${e}`),o=(e,n)=>q(t,`voice.control`,e,n),s=a(`iconSize`)||i.iconSize;X(e,s||(o(`size`,``)?o(`size`,`var(--persona-composer-control-size, 40px)`):``),s),e.classList.add(m),e.classList.toggle(p,!s&&!o(`size`,``)),e.style.fontSize=`18px`,e.style.lineHeight=`1`;let c=a(`iconColor`)||J(t,`sendButton.textColor`)||o(`foreground`,`var(--persona-text, #111827)`),l=a(`backgroundColor`)||J(t,`sendButton.backgroundColor`)||o(`background`,i.backgroundColor||`transparent`),u=a(`borderColor`)||o(`borderColor`,i.borderColor||`transparent`),d=a(`borderWidth`)||o(`borderWidth`,i.borderWidth||``);e.style.borderWidth=d,e.style.borderStyle=d?`solid`:``,e.style.borderRadius=o(`borderRadius`,``)?o(`borderRadius`,`var(--persona-button-radius)`):``,Y(e,o(`padding`,``)?o(`padding`,`0px`):``,a(`paddingX`)||(o(`padding`,``)?void 0:i.paddingX),a(`paddingY`)||(o(`padding`,``)?void 0:i.paddingY));let f=a(`recordingBackgroundColor`)||`var(--persona-voice-recording-bg, #ef4444)`,h=a(`recordingIconColor`)||`var(--persona-voice-recording-indicator, #ffffff)`,g=a(`recordingBorderColor`)||`var(--persona-consumer-voice-recording-border, ${i.recordingBorderColor||u})`,_=c,v=l,y=u,b=i.iconName??`mic`;if(n===`recording`)_=h,v=f,y=g;else if(n===`processing`)_=a(`processingIconColor`)||`var(--persona-consumer-voice-processing-icon, ${c})`,v=a(`processingBackgroundColor`)||`var(--persona-consumer-voice-processing-background, ${l})`,y=a(`processingBorderColor`)||`var(--persona-components-voice-processing-border, ${u})`,b=i.processingIconName??`loader`;else if(n===`speaking`){let e=r===`barge-in`;_=a(`speakingIconColor`)||`var(--persona-consumer-voice-speaking-icon, ${e&&a(`recordingIconColor`)||c})`,v=a(`speakingBackgroundColor`)||`var(--persona-components-voice-speaking-background, ${e?f:l})`,y=a(`speakingBorderColor`)||`var(--persona-components-voice-speaking-border, ${e?g:u})`,b=i.speakingIconName??(r===`cancel`?`square`:e?`mic`:`volume-2`)}e.style.color=_,e.style.backgroundColor=v,e.style.borderColor=y,e.setAttribute(`data-state`,n);let x=parseFloat(i.iconSize??``)||24,S=R(b,x,`currentColor`,1.5);if(e.replaceChildren(),S){let t=s||(o(`iconSize`,``)?o(`iconSize`,`var(--persona-composer-control-icon-size, 24px)`):``);S.style.width=S.style.height=t,!s&&o(`iconSize`,``)&&(S.style.flexBasis=t),S.style.strokeWidth=o(`iconStrokeWidth`,`1.5`),e.appendChild(S)}else e.textContent=`🎤`},Ft=e=>{let t=e?.voiceRecognition??{};if(t.enabled!==!0||t.showButton===!1)return null;let n=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),r=t.provider?.type===`runtype`,i=t.provider?.type===`custom`||t.dictation?.provider?.type===`custom`;if(!(n||r||i))return null;let a=u(`div`,`persona-send-button-wrapper`),o=l(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-control`,attrs:{type:`button`,"data-persona-composer-mic":``,"data-state":`idle`,"aria-label":t.tooltipText??`Start voice recognition`}});Pt(o,e),a.appendChild(o);let s=t.tooltipText??`Start voice recognition`;return K({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??s,enabled:t.showTooltip??!1}),{button:o,wrapper:a}},It=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=u(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`);n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let r=u(`input`);r.type=`file`,r.setAttribute(`data-persona-composer-attachment-input`,``),r.accept=(t.allowedTypes??f).join(`,`),r.multiple=(t.maxFiles??4)>1,r.style.display=`none`,r.setAttribute(`aria-label`,`Attach files`);let i=t.buttonIconName??`paperclip`,a=u(`div`,`persona-send-button-wrapper`),o=l(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${m} ${p}`,attrs:{type:`button`,"data-persona-composer-attachment-button":``,"aria-label":t.buttonTooltipText??`Attach file`},style:{fontSize:`18px`,lineHeight:`1`}}),s=R(i,24,`currentColor`,1.5);s?o.appendChild(s):o.textContent=`📎`,o.addEventListener(`click`,e=>{e.preventDefault(),r.click()}),a.appendChild(o);let c=t.buttonTooltipText??`Attach file`;return K({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??c}),{button:o,wrapper:a,input:r,previewsContainer:n}},Lt=e=>{let t=e?.statusIndicator??{},n=t.align===`left`?`persona-text-left`:t.align===`center`?`persona-text-center`:`persona-text-right`,r=u(`div`,`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute(`data-persona-composer-status`,``),Ze(r,t,`idle`);let i=t.idleText??`Online`;if(t.idleLink){let e=u(`a`);e.href=t.idleLink,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=i,e.style.color=`inherit`,e.style.textDecoration=`none`,r.appendChild(e)}else r.textContent=i;return r},Rt=()=>l(`div`,{className:`persona-mb-3 persona-flex persona-flex-wrap persona-gap-2`,attrs:{"data-persona-composer-suggestions":``}});function zt(e){let{config:t,onOpen:n}=e,r=t.buttonIconName??`plus`,i=t.buttonTooltipText??`Add context`,a=u(`div`,`persona-send-button-wrapper`),o=l(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${m} ${p}`,attrs:{type:`button`,"data-persona-composer-mention-button":``,"aria-label":i,"aria-haspopup":`listbox`,"aria-expanded":`false`},style:{fontSize:`18px`,lineHeight:`1`}}),s=R(r,24,`currentColor`,1.5);return s?o.appendChild(s):o.textContent=`+`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n()}),a.appendChild(o),K({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??i}),{button:o,wrapper:a}}function Bt(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=l(`span`,{className:c(`persona-mention-token`,t.readonly&&`persona-mention-token-readonly`),attrs:{"data-mention-source":e.sourceId,title:e.label,role:`img`,"aria-label":`${e.label} mention`}});e.color&&n.style.setProperty(`--persona-mention-token-accent`,e.color);let r=R(e.iconName??`at-sign`,13,`currentColor`,2);if(r){let e=u(`span`,`persona-mention-token-icon`);e.appendChild(r),n.appendChild(e)}return n.appendChild(l(`span`,{className:`persona-mention-token-label`,text:`@${e.label}`})),n}export{it as A,vt as C,z as D,ot as E,qe as F,R as I,et as M,Ze as N,tt as O,Qe as P,mt as S,ut as T,Y as _,It as a,J as b,Nt as c,Z as d,St as f,Et as g,Q as h,$ as i,st as j,nt as k,Lt as l,Ot as m,zt as n,kt as o,Ct as p,Pt as r,Ft as s,Bt as t,Rt as u,X as v,pt as w,K as x,q as y};
@@ -1 +1 @@
1
- import{r as e,t}from"./chunk-D5BxWOFB.js";import{a as n,h as r,i,o as a,p as o,r as s}from"./chunk-BEDTp-dm.js";import{r as c,t as l}from"./chunk-CNhThrLX.js";import{r as u}from"./chunk-BAkaTZpd.js";import{r as d}from"./chunk-Crczk7D3.js";const f=[`--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`],p=()=>({wrapper:e(`span`,{className:`persona-composer-model-picker-wrapper`,attrs:{"data-persona-composer-model-picker-wrapper":``}}),chevron:e(`span`,{className:`persona-composer-model-picker-chevron`,attrs:{"aria-hidden":`true`}})});function m(n){let r=n.label??`Model`,i=n.presentation??`native`,a=null,o=e=>{let t=n.getSelectedModelId();return e.find(e=>e.id===t)??e[0]},s=()=>{let t=e(`select`,{className:`persona-composer-model-picker`,attrs:{"aria-label":r,"data-persona-composer-model-picker":``}}),i=``,s=()=>{let r=n.getModels(),a=r.map(e=>`${e.id}:${e.label}`).join(`|`);a!==i&&(i=a,t.replaceChildren(...r.map(t=>{let n=e(`option`,{attrs:{value:t.id}});return n.textContent=t.label,n}))),t.value=o(r)?.id??``};s(),a=s;let c=()=>{t.value&&n.onSelect(t.value)};t.addEventListener(`change`,c);let l=e=>e.stopPropagation();t.addEventListener(`click`,l);let{wrapper:u,chevron:d}=p();return u.append(t,d),{element:u,destroy:()=>{a===s&&(a=null),t.removeEventListener(`change`,c),t.removeEventListener(`click`,l)}}},c=()=>{let i=e(`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`}}),s=t(`span`,`persona-composer-model-picker-label`),c=t(`span`,`persona-composer-model-picker-suffix`);i.append(s,c);let d=e(`div`,{className:`persona-composer-model-menu`,attrs:{role:`listbox`,tabindex:`-1`,"aria-label":r,"data-persona-composer-model-menu":``}}),m=/* @__PURE__ */ new Map,h=``,g=null,_=()=>g?.isOpen===!0,v=(e=!1)=>{_()&&(g?.close(),i.setAttribute(`aria-expanded`,`false`),e&&i.focus())},y=e=>{let t=[...m.values()];t.length!==0&&t[(e%t.length+t.length)%t.length].focus()},b=e=>{if(_())return;g||=l({anchor:i,content:d,placement:`top-start`,offset:6,onDismiss:()=>i.setAttribute(`aria-expanded`,`false`)}),u(i,d,f),g.open(),i.setAttribute(`aria-expanded`,`true`);let t=[...m.keys()].indexOf(o(n.getModels())?.id??``);y(e??(t>=0?t:0))},x=e=>{v(!0),n.onSelect(e)},S=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute(`data-persona-model-option`);t&&x(t)},C=r=>{let i=e(`button`,{className:`persona-composer-model-option`,attrs:{type:`button`,role:`option`,tabindex:`-1`,"aria-selected":`false`,"data-persona-model-option":r.id}});if(r.icon){let e=n.renderIcon(r.icon,16,`currentColor`,1.5);if(e){let n=t(`span`,`persona-composer-model-option-icon`);n.appendChild(e),i.appendChild(n)}}let a=t(`span`,`persona-composer-model-option-body`),o=t(`span`,`persona-composer-model-option-label`);if(o.textContent=r.label,a.appendChild(o),r.description){let e=t(`span`,`persona-composer-model-option-description`);e.textContent=r.description,a.appendChild(e)}i.appendChild(a);let s=t(`span`,`persona-composer-model-option-check`);s.setAttribute(`aria-hidden`,`true`);let c=n.renderIcon(`check`,16,`currentColor`,2);return c&&s.appendChild(c),i.appendChild(s),i.addEventListener(`click`,S),i},w=()=>{let e=n.getModels(),t=e.map(e=>`${e.id}:${e.label}:${e.icon??``}:${e.description??``}`).join(`|`);if(t!==h){h=t;for(let e of m.values())e.removeEventListener(`click`,S);m.clear(),d.replaceChildren(...e.map(e=>{let t=C(e);return m.set(e.id,t),t}))}let a=o(e);for(let[e,t]of m)t.setAttribute(`aria-selected`,String(e===a?.id));s.textContent=a?.label??``;let l=n.getSuffix?.()??``;c.textContent=l,i.setAttribute(`aria-label`,[r,[a?.label,l].filter(Boolean).join(` `)].filter(Boolean).join(`: `))};w(),a=w;let T=e=>{e.preventDefault(),e.stopPropagation(),_()?v(!0):b()},E=e=>{e.key===`ArrowDown`?(e.preventDefault(),_()?y(0):b(0)):e.key===`ArrowUp`&&(e.preventDefault(),_()?y(-1):b(-1))},D=e=>{let t=[...m.values()],n=t.indexOf(e.target?.closest?.(`.persona-composer-model-option`));switch(e.key){case`ArrowDown`:e.preventDefault(),y(n+1);return;case`ArrowUp`:e.preventDefault(),y(n-1);return;case`Home`:e.preventDefault(),y(0);return;case`End`:e.preventDefault(),y(t.length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),v(!0);return;case`Tab`:v(!0);return}};i.addEventListener(`click`,T),i.addEventListener(`keydown`,E),d.addEventListener(`keydown`,D);let{wrapper:O,chevron:k}=p();return O.append(i,k),{element:O,destroy:()=>{a===w&&(a=null),i.removeEventListener(`click`,T),i.removeEventListener(`keydown`,E),d.removeEventListener(`keydown`,D);for(let e of m.values())e.removeEventListener(`click`,S);m.clear(),g?.destroy(),g=null,d.remove()}}};return{action:{id:`core:model`,kind:`custom`,placement:`end`,order:700,presentation:i===`popover`?`bar`:`auto`,label:r,render:()=>i===`popover`?c():s()},repaint:()=>a?.()}}function h(n){let r=null;return{action:{id:i(n.groupId),kind:`custom`,placement:`start`,presentation:`bar`,label:n.getGroup()?.label??n.groupId,render:()=>{let i=e(`div`,{className:`persona-composer-segmented`,attrs:{"data-persona-composer-mode-group":n.groupId}}),a=/* @__PURE__ */ new Map,o=``,s=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute(`data-persona-composer-mode`);t&&(n.getActiveIds().includes(t)&&n.getGroup()?.selection===`single`||n.onSelect(t))},c=r=>{let i=e(`button`,{className:`persona-composer-segmented-item`,attrs:{type:`button`,"data-persona-composer-mode":r.id,"aria-label":r.label}});if(r.iconName){let e=n.renderIcon(r.iconName,16,`currentColor`,1.5);e&&i.appendChild(e)}let a=t(`span`,`persona-composer-segmented-label`);return a.textContent=r.shortLabel??r.label,i.appendChild(a),i.addEventListener(`click`,s),i},l=()=>{let e=n.getGroup();e?.label?(i.setAttribute(`role`,`group`),i.setAttribute(`aria-label`,e.label)):(i.removeAttribute(`role`),i.removeAttribute(`aria-label`));let t=n.getModes(),r=t.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??``}`).join(`|`);if(r!==o){o=r;for(let e of a.values())e.removeEventListener(`click`,s);a.clear();let e=t.map(e=>{let t=c(e);return a.set(e.id,t),t});i.replaceChildren(...e)}let l=n.getActiveIds();for(let[e,t]of a)t.setAttribute(`aria-pressed`,String(l.includes(e)))};return l(),r=l,{element:i,destroy:()=>{r===l&&(r=null);for(let e of a.values())e.removeEventListener(`click`,s);a.clear()}}}},repaint:()=>r?.()}}function g(n){let r=n.row,i=``,a=!1,o=new Set(n.initialIds??[]),s=r=>{let i=e(`span`,{className:`persona-mention-chip persona-composer-mode-chip`,attrs:{"data-persona-composer-mode":r.id}});if(r.iconName){let e=t(`span`,`persona-mention-chip-icon`),a=n.renderIcon(r.iconName,12,`currentColor`,1.5);a&&e.appendChild(a),i.appendChild(e)}let a=t(`span`,`persona-mention-chip-label`);a.textContent=r.shortLabel??r.label,i.appendChild(a);let o=e(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${r.label}`}}),s=n.renderIcon(`x`,12,`currentColor`,2);return s?o.appendChild(s):o.textContent=`×`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n.onRemove(r.id)}),i.appendChild(o),i},c=()=>Array.from(r.querySelectorAll(`:scope > [data-persona-composer-mode]`)),l=e=>{e.setAttribute(`data-persona-chip-exit`,``),e.setAttribute(`aria-hidden`,`true`),e.style.pointerEvents=`none`;let t=()=>{e.remove(),d(r)},n=r.ownerDocument.defaultView,i=typeof n?.getComputedStyle==`function`?n.getComputedStyle(e).animationName:``;!i||i===`none`?t():(e.addEventListener(`animationend`,t,{once:!0}),e.addEventListener(`animationcancel`,t,{once:!0}))},u=()=>{for(let e of c())e.remove()};return{element:r,render:(e,t)=>{if(a)return;let n=t.filter(t=>e.includes(t.id)),u=n.map(e=>`${e.id}:${e.shortLabel??e.label}`).join(`|`);if(u===i)return;i=u;let f=/* @__PURE__ */ new Map;for(let e of c()){let t=e.getAttribute(`data-persona-composer-mode`);t&&n.some(e=>e.id===t)&&!e.hasAttribute(`data-persona-chip-exit`)?f.set(t,e):e.hasAttribute(`data-persona-chip-exit`)||l(e)}let p=r.firstChild;for(let e of n){let t=f.get(e.id);t||(t=s(e),o.has(e.id)||(t.setAttribute(`data-persona-chip-enter`,``),t.addEventListener(`animationend`,()=>t?.removeAttribute(`data-persona-chip-enter`),{once:!0}))),o.delete(e.id),t!==p&&r.insertBefore(t,p),p=t.nextSibling}d(r)},destroy:()=>{a=!0,u(),d(r)}}}function _(e){let t=null,r=null,i=/* @__PURE__ */ new Map,o=t=>{let n=i.get(t);if(n)return n;let r=h({renderIcon:e.renderIcon,groupId:t,getGroup:()=>e.getConfig().composer?.modeGroups?.find(e=>e.id===t),getModes:()=>e.getModes().filter(e=>e.groupId===t),getActiveIds:()=>e.getState().activeModeIds,onSelect:t=>e.onModeChange(t)});return i.set(t,r),r};return{collect:()=>{let i=[],c=e.getState().activeModeIds,l=new Set(e.getChipModes().map(e=>e.id)),u=/* @__PURE__ */ new Set;if(e.getModes().forEach((t,r)=>{if(a(t.groupId,e.getConfig().composer?.modeGroups)){let a=t.groupId;if(u.has(a))return;u.add(a);let s=o(a);s.action.order=n(r),s.action.label=e.getConfig().composer?.modeGroups?.find(e=>e.id===a)?.label??a,i.push(s.action);return}let d=c.includes(t.id)&&!l.has(t.id);i.push({id:s(t.id),kind:`button`,placement:`start`,order:n(r),presentation:d?`bar`:t.presentation??`auto`,label:t.label,shortLabel:d?t.shortLabel??t.label:t.shortLabel,iconName:t.iconName,trailingIconName:t.trailingIconName,pressed:c.includes(t.id),onSelect:()=>e.onModeChange(t.id)})}),e.getConfig().composer?.models?.length&&!e.hasComposerPlugin()){let n=e.getConfig().composer?.modelPicker?.presentation??`native`;(!t||r!==n)&&(r=n,t=m({renderIcon:e.renderIcon,getModels:()=>e.getConfig().composer?.models??[],getSelectedModelId:()=>e.getState().selectedModelId,onSelect:t=>e.onModelChange(t),presentation:n,getSuffix:()=>e.getConfig().composer?.modelPicker?.suffix})),i.push(t.action)}return i},repaint:()=>{for(let[t,n]of i)a(t,e.getConfig().composer?.modeGroups)?n.repaint():i.delete(t);t?.repaint()}}}export{o as createComposerActionRenderer,_ as createComposerCoreControls,g as createComposerModeChipRow,m as createComposerModelPickerAction,h as createComposerSegmentedModeAction,l as createPopover,r as ensureComposerActionStyles,c as isEditableEventTarget};
1
+ import{r as e,t}from"./chunk-D5BxWOFB.js";import{a as n,h as r,i,o as a,p as o,r as s}from"./chunk-BEDTp-dm.js";import{r as c,t as l}from"./chunk-CNhThrLX.js";import{r as u}from"./chunk-BAkaTZpd.js";import{r as d}from"./chunk-Crczk7D3.js";const f=[`--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`],p=()=>({wrapper:e(`span`,{className:`persona-composer-model-picker-wrapper`,attrs:{"data-persona-composer-model-picker-wrapper":``}}),chevron:e(`span`,{className:`persona-composer-model-picker-chevron`,attrs:{"aria-hidden":`true`}})});function m(n){let r=n.label??`Model`,i=n.presentation??`native`,a=null,o=e=>{let t=n.getSelectedModelId();return e.find(e=>e.id===t)??e[0]},s=()=>{let t=e(`select`,{className:`persona-composer-model-picker`,attrs:{"aria-label":r,"data-persona-composer-model-picker":``}}),i=``,s=()=>{let r=n.getModels(),a=r.map(e=>`${e.id}:${e.label}`).join(`|`);a!==i&&(i=a,t.replaceChildren(...r.map(t=>{let n=e(`option`,{attrs:{value:t.id}});return n.textContent=t.label,n}))),t.value=o(r)?.id??``};s(),a=s;let c=()=>{t.value&&n.onSelect(t.value)};t.addEventListener(`change`,c);let l=e=>e.stopPropagation();t.addEventListener(`click`,l);let{wrapper:u,chevron:d}=p();return u.append(t,d),{element:u,destroy:()=>{a===s&&(a=null),t.removeEventListener(`change`,c),t.removeEventListener(`click`,l)}}},c=()=>{let i=e(`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`}}),s=t(`span`,`persona-composer-model-picker-label`),c=t(`span`,`persona-composer-model-picker-suffix`);i.append(s,c);let d=e(`div`,{className:`persona-composer-model-menu`,attrs:{role:`listbox`,tabindex:`-1`,"aria-label":r,"data-persona-composer-model-menu":``}}),m=/* @__PURE__ */ new Map,h=``,g=null,_=()=>g?.isOpen===!0,v=(e=!1)=>{_()&&(g?.close(),i.setAttribute(`aria-expanded`,`false`),e&&i.focus())},y=e=>{let t=[...m.values()];t.length!==0&&t[(e%t.length+t.length)%t.length].focus()},b=e=>{if(_())return;g||=l({anchor:i,content:d,placement:`top-start`,offset:6,onDismiss:()=>i.setAttribute(`aria-expanded`,`false`)}),u(i,d,f),g.open(),i.setAttribute(`aria-expanded`,`true`);let t=[...m.keys()].indexOf(o(n.getModels())?.id??``);y(e??(t>=0?t:0))},x=e=>{v(!0),n.onSelect(e)},S=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute(`data-persona-model-option`);t&&x(t)},C=r=>{let i=e(`button`,{className:`persona-composer-model-option`,attrs:{type:`button`,role:`option`,tabindex:`-1`,"aria-selected":`false`,"data-persona-model-option":r.id}});if(r.icon){let e=n.renderIcon(r.icon,16,`currentColor`,1.5);if(e){let n=t(`span`,`persona-composer-model-option-icon`);n.appendChild(e),i.appendChild(n)}}let a=t(`span`,`persona-composer-model-option-body`),o=t(`span`,`persona-composer-model-option-label`);if(o.textContent=r.label,a.appendChild(o),r.description){let e=t(`span`,`persona-composer-model-option-description`);e.textContent=r.description,a.appendChild(e)}i.appendChild(a);let s=t(`span`,`persona-composer-model-option-check`);s.setAttribute(`aria-hidden`,`true`);let c=n.renderIcon(`check`,16,`currentColor`,2);return c&&s.appendChild(c),i.appendChild(s),i.addEventListener(`click`,S),i},w=()=>{let e=n.getModels(),t=e.map(e=>`${e.id}:${e.label}:${e.icon??``}:${e.description??``}`).join(`|`);if(t!==h){h=t;for(let e of m.values())e.removeEventListener(`click`,S);m.clear(),d.replaceChildren(...e.map(e=>{let t=C(e);return m.set(e.id,t),t}))}let a=o(e);for(let[e,t]of m)t.setAttribute(`aria-selected`,String(e===a?.id));s.textContent=a?.label??``;let l=n.getSuffix?.()??``;c.textContent=l,i.setAttribute(`aria-label`,[r,[a?.label,l].filter(Boolean).join(` `)].filter(Boolean).join(`: `))};w(),a=w;let T=e=>{e.preventDefault(),e.stopPropagation(),_()?v(!0):b()},E=e=>{e.key===`ArrowDown`?(e.preventDefault(),_()?y(0):b(0)):e.key===`ArrowUp`&&(e.preventDefault(),_()?y(-1):b(-1))},D=e=>{let t=[...m.values()],n=t.indexOf(e.target?.closest?.(`.persona-composer-model-option`));switch(e.key){case`ArrowDown`:e.preventDefault(),y(n+1);return;case`ArrowUp`:e.preventDefault(),y(n-1);return;case`Home`:e.preventDefault(),y(0);return;case`End`:e.preventDefault(),y(t.length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),v(!0);return;case`Tab`:v(!0);return}};i.addEventListener(`click`,T),i.addEventListener(`keydown`,E),d.addEventListener(`keydown`,D);let{wrapper:O,chevron:k}=p();return O.append(i,k),{element:O,destroy:()=>{a===w&&(a=null),i.removeEventListener(`click`,T),i.removeEventListener(`keydown`,E),d.removeEventListener(`keydown`,D);for(let e of m.values())e.removeEventListener(`click`,S);m.clear(),g?.destroy(),g=null,d.remove()}}};return{action:{id:`core:model`,kind:`custom`,placement:`end`,order:700,presentation:i===`popover`?`bar`:`auto`,label:r,render:()=>i===`popover`?c():s()},repaint:()=>a?.()}}function h(n){let r=null;return{action:{id:i(n.groupId),kind:`custom`,placement:`start`,presentation:`bar`,label:n.getGroup()?.label??n.groupId,render:()=>{let i=e(`div`,{className:`persona-composer-segmented`,attrs:{"data-persona-composer-mode-group":n.groupId}}),a=/* @__PURE__ */ new Map,o=``,s=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute(`data-persona-composer-mode`);t&&(n.getActiveIds().includes(t)&&n.getGroup()?.selection===`single`||n.onSelect(t))},c=r=>{let i=e(`button`,{className:`persona-composer-segmented-item`,attrs:{type:`button`,"data-persona-composer-mode":r.id,"aria-label":r.label}});if(r.iconName){let e=n.renderIcon(r.iconName,16,`currentColor`,1.5);e&&i.appendChild(e)}let a=t(`span`,`persona-composer-segmented-label`);return a.textContent=r.shortLabel??r.label,i.appendChild(a),i.addEventListener(`click`,s),i},l=()=>{let e=n.getGroup();e?.label?(i.setAttribute(`role`,`group`),i.setAttribute(`aria-label`,e.label)):(i.removeAttribute(`role`),i.removeAttribute(`aria-label`));let t=n.getModes(),r=t.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??``}`).join(`|`);if(r!==o){o=r;for(let e of a.values())e.removeEventListener(`click`,s);a.clear();let e=t.map(e=>{let t=c(e);return a.set(e.id,t),t});i.replaceChildren(...e)}let l=n.getActiveIds();for(let[e,t]of a)t.setAttribute(`aria-pressed`,String(l.includes(e)))};return l(),r=l,{element:i,destroy:()=>{r===l&&(r=null);for(let e of a.values())e.removeEventListener(`click`,s);a.clear()}}}},repaint:()=>r?.()}}function g(n){let r=n.row,i=``,a=!1,o=new Set(n.initialIds??[]),s=r=>{let i=e(`span`,{className:`persona-mention-chip persona-composer-mode-chip`,attrs:{"data-persona-composer-mode":r.id}});if(r.iconName){let e=t(`span`,`persona-mention-chip-icon`),a=n.renderIcon(r.iconName,12,`currentColor`,1.5);a&&e.appendChild(a),i.appendChild(e)}let a=t(`span`,`persona-mention-chip-label`);a.textContent=r.shortLabel??r.label,i.appendChild(a);let o=e(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${r.label}`}}),s=n.renderIcon(`x`,12,`currentColor`,2);return s?o.appendChild(s):o.textContent=`×`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n.onRemove(r.id)}),i.appendChild(o),i},c=()=>Array.from(r.querySelectorAll(`:scope > [data-persona-composer-mode]`)),l=e=>{e.setAttribute(`data-persona-chip-exit`,``),e.setAttribute(`aria-hidden`,`true`),e.style.pointerEvents=`none`;let t=()=>{e.remove(),d(r)},n=r.ownerDocument.defaultView,i=typeof n?.getComputedStyle==`function`?n.getComputedStyle(e).animationName:``;!i||i===`none`?t():(e.addEventListener(`animationend`,t,{once:!0}),e.addEventListener(`animationcancel`,t,{once:!0}))},u=()=>{for(let e of c())e.remove()};return{element:r,render:(e,t)=>{if(a)return;let n=t.filter(t=>e.includes(t.id)),u=n.map(e=>`${e.id}:${e.shortLabel??e.label}`).join(`|`);if(u===i)return;i=u;let f=/* @__PURE__ */ new Map;for(let e of c()){let t=e.getAttribute(`data-persona-composer-mode`);t&&n.some(e=>e.id===t)&&!e.hasAttribute(`data-persona-chip-exit`)?f.set(t,e):e.hasAttribute(`data-persona-chip-exit`)||l(e)}let p=r.firstChild;for(let e of n){let t=f.get(e.id);t||(t=s(e),o.has(e.id)||(t.setAttribute(`data-persona-chip-enter`,``),t.addEventListener(`animationend`,()=>t?.removeAttribute(`data-persona-chip-enter`),{once:!0}))),o.delete(e.id),t!==p&&r.insertBefore(t,p),p=t.nextSibling}d(r)},destroy:()=>{a=!0,u(),d(r)}}}function _(e){let t=null,r=null,i=/* @__PURE__ */ new Map,o=t=>{let n=i.get(t);if(n)return n;let r=h({renderIcon:e.renderIcon,groupId:t,getGroup:()=>e.getConfig().composer?.modeGroups?.find(e=>e.id===t),getModes:()=>e.getModes().filter(e=>e.groupId===t),getActiveIds:()=>e.getState().activeModeIds,onSelect:t=>e.onModeChange(t)});return i.set(t,r),r};return{collect:()=>{let i=[],c=e.getState().activeModeIds,l=new Set(e.getChipModes().map(e=>e.id)),u=/* @__PURE__ */ new Set;if(e.getModes().forEach((t,r)=>{if(a(t.groupId,e.getConfig().composer?.modeGroups)){let a=t.groupId;if(u.has(a))return;u.add(a);let s=o(a);s.action.order=n(r),s.action.label=e.getConfig().composer?.modeGroups?.find(e=>e.id===a)?.label??a,i.push(s.action);return}let d=c.includes(t.id)&&!l.has(t.id);i.push({id:s(t.id),kind:`button`,placement:`start`,order:n(r),presentation:d?`bar`:t.presentation??`auto`,label:t.label,shortLabel:d?t.shortLabel??t.label:t.shortLabel,iconName:t.iconName,trailingIconName:t.trailingIconName,pressed:c.includes(t.id),onSelect:()=>e.onModeChange(t.id)})}),e.getConfig().composer?.models?.length&&!e.hasComposerPlugin()){let n=e.getConfig().composer?.modelPicker?.presentation??`native`;t&&r===n||(r=n,t=m({renderIcon:e.renderIcon,getModels:()=>e.getConfig().composer?.models??[],getSelectedModelId:()=>e.getState().selectedModelId,onSelect:t=>e.onModelChange(t),presentation:n,getSuffix:()=>e.getConfig().composer?.modelPicker?.suffix})),i.push(t.action)}return i},repaint:()=>{for(let[t,n]of i)a(t,e.getConfig().composer?.modeGroups)?n.repaint():i.delete(t);t?.repaint()}}}export{o as createComposerActionRenderer,_ as createComposerCoreControls,g as createComposerModeChipRow,m as createComposerModelPickerAction,h as createComposerSegmentedModeAction,l as createPopover,r as ensureComposerActionStyles,c as isEditableEventTarget};