@runtypelabs/persona 4.24.0 → 4.26.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 (237) hide show
  1. package/dist/animations/glyph-cycle.d.cts +1 -1
  2. package/dist/animations/glyph-cycle.d.ts +1 -1
  3. package/dist/animations/{types-Db61aI9J.d.cts → types-BwKTZhg9.d.cts} +14 -0
  4. package/dist/animations/{types-Db61aI9J.d.ts → types-BwKTZhg9.d.ts} +14 -0
  5. package/dist/animations/wipe.d.cts +1 -1
  6. package/dist/animations/wipe.d.ts +1 -1
  7. package/dist/animations-extra.d.cts +14 -0
  8. package/dist/animations-extra.d.ts +14 -0
  9. package/dist/approval-ui-QAKWNFNM.js +1 -0
  10. package/dist/approval-ui.cjs +2 -2
  11. package/dist/approval-ui.d.cts +243 -8
  12. package/dist/approval-ui.d.ts +243 -8
  13. package/dist/approval-ui.js +2 -2
  14. package/dist/{artifacts-ui-IGB5YKLO.js → artifacts-ui-NJGMM27I.js} +1 -1
  15. package/dist/artifacts-ui.cjs +4 -4
  16. package/dist/artifacts-ui.d.cts +243 -8
  17. package/dist/artifacts-ui.d.ts +243 -8
  18. package/dist/artifacts-ui.js +5 -5
  19. package/dist/chunk-2ANTRKTV.js +1 -0
  20. package/dist/chunk-4HPTPUC6.js +1 -0
  21. package/dist/chunk-6V3MNEKB.js +1 -0
  22. package/dist/chunk-HGUCGM3K.js +9 -0
  23. package/dist/chunk-IO5VVUKP.js +3 -0
  24. package/dist/chunk-J4J3Y2P2.js +1 -0
  25. package/dist/chunk-K6HKIP5K.js +1 -0
  26. package/dist/chunk-K7NA7G7J.js +1 -0
  27. package/dist/chunk-MXUTS3LB.js +1 -0
  28. package/dist/chunk-PDPVORUF.js +1 -0
  29. package/dist/chunk-QPPJUSZH.js +1 -0
  30. package/dist/chunk-QRKGQPU7.js +1 -0
  31. package/dist/chunk-S6PBWE75.js +1 -0
  32. package/dist/chunk-T7QM7YMF.js +1 -0
  33. package/dist/chunk-TR2H475E.js +1 -0
  34. package/dist/chunk-UPO4GUFC.js +1 -0
  35. package/dist/chunk-ZC66NAIR.js +1 -0
  36. package/dist/client-history-YPEG45Q4.js +1 -0
  37. package/dist/client-history.js +1 -0
  38. package/dist/client-stream-42FOI3EC.js +4 -0
  39. package/dist/client-stream.js +5 -0
  40. package/dist/codegen.cjs +1 -1
  41. package/dist/codegen.js +1 -1
  42. package/dist/context-mentions-E7HJYWO6.js +161 -0
  43. package/dist/{context-mentions-inline-I2RDEBAK.js → context-mentions-inline-QVESLW55.js} +1 -1
  44. package/dist/context-mentions.cjs +7 -7
  45. package/dist/context-mentions.d.cts +243 -8
  46. package/dist/context-mentions.d.ts +243 -8
  47. package/dist/context-mentions.js +8 -8
  48. package/dist/event-stream-view-FOIJHFQO.js +1 -0
  49. package/dist/event-stream-view.cjs +1 -1
  50. package/dist/event-stream-view.d.cts +246 -31
  51. package/dist/event-stream-view.d.ts +246 -31
  52. package/dist/event-stream-view.js +1 -1
  53. package/dist/forms-ui.d.cts +295 -667
  54. package/dist/forms-ui.d.ts +295 -667
  55. package/dist/history-shell-QDQ44PSE.js +3 -0
  56. package/dist/history-shell.js +3 -0
  57. package/dist/{history-view-BD6OXLNA.js → history-view-NCFBI5GR.js} +2 -2
  58. package/dist/history-view.cjs +2 -2
  59. package/dist/history-view.d.cts +35 -1
  60. package/dist/history-view.d.ts +35 -1
  61. package/dist/history-view.js +2 -2
  62. package/dist/index.cjs +80 -74
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.cts +301 -738
  65. package/dist/index.d.ts +301 -738
  66. package/dist/index.global.js +3 -215
  67. package/dist/index.global.js.map +1 -1
  68. package/dist/index.js +81 -75
  69. package/dist/index.js.map +1 -1
  70. package/dist/install.global.js +1 -1
  71. package/dist/install.global.js.map +1 -1
  72. package/dist/launcher.global.js +3 -67
  73. package/dist/launcher.global.js.map +1 -1
  74. package/dist/markdown-parsers.js +22 -22
  75. package/dist/runtype-tts-entry-NFBVWR7N.js +1 -0
  76. package/dist/runtype-tts.js +1 -1
  77. package/dist/session-actions-ISSKSI66.js +1 -0
  78. package/dist/session-actions.js +1 -0
  79. package/dist/session-reconnect.d.cts +243 -8
  80. package/dist/session-reconnect.d.ts +243 -8
  81. package/dist/smart-dom-reader.cjs +13 -13
  82. package/dist/smart-dom-reader.d.cts +243 -8
  83. package/dist/smart-dom-reader.d.ts +243 -8
  84. package/dist/smart-dom-reader.js +11 -11
  85. package/dist/theme-editor-preview.cjs +116 -98
  86. package/dist/theme-editor-preview.d.cts +245 -8
  87. package/dist/theme-editor-preview.d.ts +245 -8
  88. package/dist/theme-editor-preview.js +49 -54
  89. package/dist/theme-editor.cjs +2 -2
  90. package/dist/theme-editor.d.cts +244 -23
  91. package/dist/theme-editor.d.ts +244 -23
  92. package/dist/theme-editor.js +2 -2
  93. package/dist/theme-reference.d.cts +14 -0
  94. package/dist/theme-reference.d.ts +14 -0
  95. package/dist/ui-extras-entry-WAYFKVNW.js +3 -0
  96. package/dist/ui-extras.js +72 -0
  97. package/dist/voice-runtime-UOQOFAFY.js +17 -0
  98. package/dist/voice-runtime.cjs +17 -1
  99. package/dist/voice-runtime.d.cts +11643 -192
  100. package/dist/voice-runtime.d.ts +11643 -192
  101. package/dist/voice-runtime.js +17 -1
  102. package/dist/voice-worklet-player.cjs +19 -4
  103. package/dist/voice-worklet-player.d.cts +9 -10
  104. package/dist/voice-worklet-player.d.ts +9 -10
  105. package/dist/voice-worklet-player.js +19 -4
  106. package/dist/webmcp-polyfill.js +1 -1
  107. package/dist/webmcp-runtime-V6ZWW3PI.js +6 -0
  108. package/dist/webmcp-runtime.cjs +2 -2
  109. package/dist/webmcp-runtime.d.cts +1 -33
  110. package/dist/webmcp-runtime.d.ts +1 -33
  111. package/dist/webmcp-runtime.js +2 -2
  112. package/dist/widget.css +1 -1
  113. package/package.json +11 -5
  114. package/src/approval-paused-tool-settle.test.ts +221 -0
  115. package/src/client-approve.test.ts +311 -0
  116. package/src/client-history-eager.ts +9 -0
  117. package/src/client-history-loader.ts +23 -0
  118. package/src/client-history.ts +579 -0
  119. package/src/client-resume.ts +177 -0
  120. package/src/client-stream-eager.ts +12 -0
  121. package/src/client-stream-loader.ts +25 -0
  122. package/src/client-stream.ts +1880 -0
  123. package/src/client.test.ts +31 -1
  124. package/src/client.ts +293 -2607
  125. package/src/components/approval-actions.test.ts +27 -0
  126. package/src/components/approval-actions.ts +27 -3
  127. package/src/components/message-bubble.test.ts +19 -0
  128. package/src/components/message-bubble.ts +2 -0
  129. package/src/components/registry.ts +6 -6
  130. package/src/components/tool-bubble.test.ts +9 -0
  131. package/src/components/tool-bubble.ts +1 -0
  132. package/src/history-shell-bundle.test.ts +54 -0
  133. package/src/history-shell-eager.ts +12 -0
  134. package/src/history-shell-loader.ts +27 -0
  135. package/src/history-shell.ts +2362 -0
  136. package/src/history-view-loader.ts +2 -0
  137. package/src/history-view.ts +3 -0
  138. package/src/index-core.ts +8 -0
  139. package/src/index-global.ts +90 -248
  140. package/src/index.ts +13 -0
  141. package/src/install.ts +6 -4
  142. package/src/internal/runtype-history-provider.test.ts +1 -0
  143. package/src/internal/runtype-history-provider.ts +28 -13
  144. package/src/plugins/registry.ts +8 -8
  145. package/src/session-actions-chunk.test.ts +55 -0
  146. package/src/session-actions-eager.ts +11 -0
  147. package/src/session-actions-loader.ts +37 -0
  148. package/src/session-actions.ts +909 -0
  149. package/src/session-history.test.ts +3 -1
  150. package/src/session.ts +875 -1530
  151. package/src/session.voice.test.ts +1241 -5
  152. package/src/styles/widget.css +58 -0
  153. package/src/theme-editor/state.ts +91 -91
  154. package/src/types.ts +269 -5
  155. package/src/ui-ask-user-sheet.ts +382 -0
  156. package/src/ui-extras-eager.ts +10 -0
  157. package/src/ui-extras-entry.ts +9 -0
  158. package/src/ui-extras-loader.ts +26 -0
  159. package/src/ui.artifact-rail-resize.test.ts +2 -1
  160. package/src/ui.ask-user-chunk.test.ts +93 -0
  161. package/src/ui.history-chunk.test.ts +2 -1
  162. package/src/ui.history-config-provider.test.ts +2 -1
  163. package/src/ui.history-confirm-fallback.test.ts +142 -0
  164. package/src/ui.history-controller.test.ts +2 -1
  165. package/src/ui.history-lifecycle.test.ts +2 -1
  166. package/src/ui.history-render-hooks.test.ts +2 -1
  167. package/src/ui.history-shell.test.ts +2 -1
  168. package/src/ui.rail-overlay.test.ts +2 -1
  169. package/src/ui.rail-resize.test.ts +2 -1
  170. package/src/ui.rail-trigger-pending.test.ts +2 -1
  171. package/src/ui.ts +399 -2770
  172. package/src/ui.voice-prewarm.test.ts +222 -0
  173. package/src/utils/attachment-manager.ts +67 -67
  174. package/src/utils/constants.ts +3 -0
  175. package/src/utils/context-mention-controller.ts +323 -323
  176. package/src/utils/context-mention-manager.ts +40 -40
  177. package/src/utils/context-mention-orchestrator.ts +28 -0
  178. package/src/utils/event-stream-buffer.ts +50 -50
  179. package/src/utils/event-stream-store.ts +43 -43
  180. package/src/utils/throughput-tracker.ts +34 -34
  181. package/src/utils/virtual-scroller.ts +67 -67
  182. package/src/utils/visitor-store.test.ts +50 -0
  183. package/src/utils/visitor-store.ts +23 -5
  184. package/src/voice/__fixtures__/voice-wire/README.md +1 -0
  185. package/src/voice/__fixtures__/voice-wire/client/cancel.json +3 -0
  186. package/src/voice/__fixtures__/voice-wire/client/context.json +4 -0
  187. package/src/voice/__fixtures__/voice-wire/client/delegation_result.json +6 -0
  188. package/src/voice/__fixtures__/voice-wire/client/delegation_update.json +6 -0
  189. package/src/voice/__fixtures__/voice-wire/client/ping.json +3 -0
  190. package/src/voice/__fixtures__/voice-wire/client/playback_progress.json +5 -0
  191. package/src/voice/__fixtures__/voice-wire/client/start.json +3 -0
  192. package/src/voice/__fixtures__/voice-wire/server/artifact.json +11 -0
  193. package/src/voice/__fixtures__/voice-wire/server/attached.json +4 -0
  194. package/src/voice/__fixtures__/voice-wire/server/audio_clear.json +4 -0
  195. package/src/voice/__fixtures__/voice-wire/server/audio_end.json +3 -0
  196. package/src/voice/__fixtures__/voice-wire/server/delegation_cancelled.json +5 -0
  197. package/src/voice/__fixtures__/voice-wire/server/delegation_completed.json +8 -0
  198. package/src/voice/__fixtures__/voice-wire/server/delegation_started.json +15 -0
  199. package/src/voice/__fixtures__/voice-wire/server/error.json +6 -0
  200. package/src/voice/__fixtures__/voice-wire/server/metrics.json +10 -0
  201. package/src/voice/__fixtures__/voice-wire/server/pong.json +3 -0
  202. package/src/voice/__fixtures__/voice-wire/server/session_config.json +16 -0
  203. package/src/voice/__fixtures__/voice-wire/server/transcript_final.json +7 -0
  204. package/src/voice/__fixtures__/voice-wire/server/transcript_interim.json +4 -0
  205. package/src/voice/__fixtures__/voice-wire/server/transcript_partial.json +6 -0
  206. package/src/voice/__fixtures__/voice-wire/server/transcript_update.json +10 -0
  207. package/src/voice/__fixtures__/voice-wire/server/warning.json +5 -0
  208. package/src/voice/audio-playback-manager.test.ts +57 -0
  209. package/src/voice/audio-playback-manager.ts +120 -98
  210. package/src/voice/browser-voice-provider.ts +37 -37
  211. package/src/voice/fallback-speech-engine.ts +22 -16
  212. package/src/voice/keyed-voice-transcript.ts +314 -0
  213. package/src/voice/mic-state-styles.ts +182 -0
  214. package/src/voice/read-aloud-controller.ts +46 -44
  215. package/src/voice/runtype-speech-engine.ts +35 -33
  216. package/src/voice/runtype-voice-provider.ts +856 -164
  217. package/src/voice/session-voice-wiring.ts +266 -0
  218. package/src/voice/voice-delegation.test.ts +71 -0
  219. package/src/voice/voice-delegation.ts +364 -0
  220. package/src/voice/voice-turn-tracker.ts +6 -6
  221. package/src/voice/voice.test.ts +1250 -7
  222. package/src/voice/worklet-playback-engine.test.ts +81 -0
  223. package/src/voice/worklet-playback-engine.ts +21 -3
  224. package/src/voice-runtime-loader.ts +4 -1
  225. package/src/voice-runtime.ts +7 -0
  226. package/src/webmcp-runtime-entry.ts +41 -39
  227. package/dist/approval-ui-3NMYNXBD.js +0 -1
  228. package/dist/chunk-5EIIHQLQ.js +0 -1
  229. package/dist/chunk-7CO4T5KB.js +0 -1
  230. package/dist/chunk-EFJBUH5F.js +0 -1
  231. package/dist/chunk-R2TMIMDI.js +0 -3
  232. package/dist/chunk-UTVLOTWB.js +0 -9
  233. package/dist/context-mentions-45MODWOY.js +0 -161
  234. package/dist/event-stream-view-GL3ADRY2.js +0 -1
  235. package/dist/runtype-tts-entry-UJAEF7NZ.js +0 -1
  236. package/dist/voice-runtime-EFR3R5ES.js +0 -1
  237. package/dist/webmcp-runtime-JI7T4QYF.js +0 -6
@@ -0,0 +1 @@
1
+ import{a as G,e as M}from"./chunk-ZC66NAIR.js";import{f as Ce}from"./chunk-S6PBWE75.js";import{c as xe}from"./chunk-2ANTRKTV.js";import{a as T,c as w,d as B}from"./chunk-76IELU7F.js";var je=8,Ge=8,ee=10,Te=200,Le=300,Ae=0,$=t=>Math.max(0,t);function At(t){t.delayMs!==void 0&&(Te=$(t.delayMs)),t.skipDelayMs!==void 0&&(Le=$(t.skipDelayMs))}var Ye=()=>Date.now()<Ae,$e=t=>{Ae=t>0?Date.now()+t:0},Y=new WeakMap,Xe="data-persona-tooltip-suppressed",Qe=t=>typeof t.closest=="function"&&t.closest(`[${Xe}]`)!==null;function Et(t){Y.get(t)?.hide()}var Ee=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,qe=t=>{let e=t.getRootNode?.();return Ee(e)?e:t.ownerDocument.body},te=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),Ze=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(t=>`--persona-tooltip-${t}`),"--persona-font-family","--persona-radius-sm"];function O(t){Y.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:r,enabled:i=!0,gap:s=je,viewportPadding:l=Ge}=t,d=()=>e.ownerDocument,u=()=>d().defaultView??window,a=null,p=null,m=null,f=null,h,y=!1,c=!1,g=!1,A=()=>(typeof o=="function"?o():o).trim(),v=()=>(typeof r=="function"?r():r??"").trim(),N=()=>$(t.delayMs??Te),ue=()=>$(t.skipDelayMs??Le),b=()=>{h!==void 0&&(u().clearTimeout(h),h=void 0)},E=()=>{b();let x=a!==null;f?.(),f=null,a?.remove(),a=null,p=null,m=null,x&&$e(ue())},S=()=>{if(!a)return;let x=d(),I=u(),C=e.getBoundingClientRect(),L=a.getBoundingClientRect(),_=x.documentElement.clientWidth||I.innerWidth,H=x.documentElement.clientHeight||I.innerHeight,K=_-l-L.width,D=C.left+C.width/2-L.width/2,W=te(D,l,K),V=C.top-l,z=H-l-C.bottom,j=L.height+s,R=V>=j||V>=z?"top":"bottom",Be=R==="top"?C.top-s-L.height:C.bottom+s,Fe=H-l-L.height,Ue=te(Be,l,Fe),Ke=C.left+C.width/2,Ve=Math.max(ee,L.width-ee),ze=te(Ke-W,ee,Ve);a.dataset.placement=R,a.style.left=`${W}px`,a.style.top=`${Ue}px`,a.style.setProperty("--persona-tooltip-arrow-x",`${ze}px`)},P=()=>{if(g||!i||a||!e.isConnected||Qe(e))return;let x=A(),I=qe(e);if(!x||!I)return;let C=d(),L=u();a=C.createElement("div"),a.className="persona-control-tooltip",a.setAttribute("role","tooltip"),a.dataset.state="measuring",a.style.zIndex=String(xe);let _=L.getComputedStyle?.(e);if(_){for(let j of Ze){let R=_.getPropertyValue(j).trim();R&&a.style.setProperty(j,R)}_.fontFamily&&(a.style.fontFamily=_.fontFamily)}p=C.createElement("span"),p.className="persona-control-tooltip__label",p.textContent=x,a.appendChild(p);let H=v();H&&(m=C.createElement("span"),m.className="persona-control-tooltip__hint",m.textContent=H,a.appendChild(m));let K=C.createElement("span");K.className="persona-control-tooltip__arrow",a.appendChild(K),I.appendChild(a),S(),a.dataset.state="open";let D=()=>{if(!e.isConnected){E();return}p&&(p.textContent=A()),m&&(m.textContent=v()),S()};L.addEventListener("scroll",D,!0),L.addEventListener("resize",D);let W=e.getRootNode(),V=Ee(W)?W:C.documentElement,z=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||E()});z?.observe(V,{childList:!0,subtree:!0}),f=()=>{L.removeEventListener("scroll",D,!0),L.removeEventListener("resize",D),z?.disconnect()}},Re=x=>{if(!(g||a)){if(b(),x||N()<=0||Ye()){P();return}h=u().setTimeout(()=>{h=void 0,P()},N())}},U=()=>{y||c?Re(c):E()},me=()=>{let x=u();(!x.matchMedia||!x.matchMedia("(hover: none)").matches)&&(y=!0,U())},fe=()=>{y=!1,U()},ge=()=>{try{c=e.matches(":focus-visible")}catch{c=!0}U()},he=()=>{c=!1,U()},J=()=>{y=!1,c=!1,E()},ye=x=>{x.key==="Escape"&&J()};n.addEventListener("mouseenter",me),n.addEventListener("mouseleave",fe),e.addEventListener("focus",ge),e.addEventListener("blur",he),e.addEventListener("keydown",ye),e.addEventListener("click",J);let be={get isOpen(){return a!==null},show:P,hide:E,reposition:S,destroy:()=>{g||(g=!0,E(),n.removeEventListener("mouseenter",me),n.removeEventListener("mouseleave",fe),e.removeEventListener("focus",ge),e.removeEventListener("blur",he),e.removeEventListener("keydown",ye),e.removeEventListener("click",J),Y.delete(e))}};return Y.set(e,be),be}var Je=(t,e)=>t.visible!==!1&&(t.mode!=="transient"||e==="connecting"||e==="paused"||e==="resuming"||e==="error"),we=(t,e,n)=>{let o=e.mode==="transient",r=t.hasAttribute("data-persona-composer-reason")||t.hasAttribute("data-persona-composer-notice");t.style.display=Je(e,n)||o&&r&&e.visible!==!1?"":"none",t.classList.toggle("persona-mt-2",!o),t.classList.toggle("persona-mb-2",o)},vt=(t,e,n)=>{!e.parentElement||t.parentElement!==e.parentElement||(n.mode==="transient"?t.nextElementSibling!==e&&e.before(t):e.nextElementSibling!==t&&e.after(t))};var ve=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function X(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let i=n[o];ve(i)&&ve(r)?n[o]=X(i,r):n[o]=r}return n}var re=Symbol("persona.defaultsProvenance"),ie=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Me(t,e=""){return Object.entries(t).flatMap(([n,o])=>{let r=e?`${e}.${n}`:n;return ie(o)?Me(o,r):[r]})}function Se(t,e){for(let n of e.split(".")){if(!ie(t)||!Object.prototype.hasOwnProperty.call(t,n))return"absent";if(t=t[n],t===void 0)return"clear"}return"explicit"}function Pe(t,e){return t?.[re]??e.filter(n=>Se(t,n)==="explicit")}function et(t,e){return Object.defineProperty(t,re,{value:e,enumerable:!0,configurable:!0}),t}function se(t,e,n){return et(t,Pe(e,Me(n)))}function Pt(t,e,n){let o=e[re];if(o)return o;let r=new Set(Pe(t,n));for(let i of n){let s=Se(e,i);s==="clear"&&r.delete(i),s==="explicit"&&r.add(i)}return[...r]}function kt(t,e,n){let o={...t};for(let r of e){if(n.includes(r))continue;let i=r.split("."),s=o;for(let l of i.slice(0,-1)){let d=s[l];if(!ie(d)){s=void 0;break}s[l]={...d},s=s[l]}s&&delete s[i[i.length-1]]}return o}var _t="var(--persona-components-panel-width)",ae=Symbol("persona.panelAliasProvenance"),k=(t,e)=>t!=null&&Object.prototype.hasOwnProperty.call(t,e),Q=(t,e)=>k(t,e)&&t[e]!==void 0,tt=t=>({launcherWidth:Q(t?.launcher,"width"),legacyLauncherWidth:Q(t,"launcherWidth"),sidebarWidth:Q(t?.launcher,"sidebarWidth"),dockWidth:Q(t?.launcher?.dock,"width")}),ke=t=>{let e=t?.[ae];return e?{...e}:tt(t)},nt=(t,e)=>(Object.defineProperty(t,ae,{value:e,enumerable:!0,configurable:!0}),t),le=(t,e)=>nt(t,ke(e)),Dt=(t,e)=>{let n=e[ae];if(n)return{...n};let o=ke(t);return k(e,"launcherWidth")&&(o.legacyLauncherWidth=e.launcherWidth!==void 0),k(e,"launcher")&&e.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(k(e.launcher,"width")&&(o.launcherWidth=e.launcher?.width!==void 0),k(e.launcher,"sidebarWidth")&&(o.sidebarWidth=e.launcher?.sidebarWidth!==void 0),k(e.launcher,"dock")&&e.launcher?.dock===void 0?o.dockWidth=!1:k(e.launcher?.dock,"width")&&(o.dockWidth=e.launcher?.dock?.width!==void 0),o)};var ot="min(440px, calc(100vw - 24px))";var rt="40px",ce="How can I help...",it={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},st={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},at={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:ot,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:rt,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)"},lt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:at,copy:{inputPlaceholder:ce,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",borderWidth:"0px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:it,reasoningDisplay:st,streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1},dt={},ct={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},de={launcher:ct,features:{toolCallDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,grouped:!0,groupedMode:"collapsible",loadingAnimation:"shimmer"},reasoningDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,loadingAnimation:"shimmer"}},composer:{layout:"single-row",placement:"overlay"},sendButton:{iconName:"arrow-up"},statusIndicator:{mode:"transient"},layout:{contentMaxWidth:"768px",topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:"full"}}}};function pt(t){return t?.future?.v5Defaults===!0?"v5":"v4"}function _e(t){let e=pt(t)==="v5"?de:dt;return X(lt,e)}var Bt=_e();function Ie(t,e){if(!(!t&&!e))return t?e?X(t,e):t:e}function Ft(t){let e=_e(t);return t?se(le({...e,...t,theme:Ie(e.theme,t.theme),darkTheme:Ie(e.darkTheme,t.darkTheme),launcher:{...e.launcher,...t.launcher,dock:{...e.launcher?.dock,...t.launcher?.dock},clearChat:{...e.launcher?.clearChat,...t.launcher?.clearChat}},...e.composer||t.composer?{composer:{...e.composer,...t.composer}}:{},tooltip:{...e.tooltip,...t.tooltip},copy:{...e.copy,...t.copy},sendButton:{...e.sendButton,...t.sendButton},statusIndicator:{...e.statusIndicator,...t.statusIndicator},voiceRecognition:{...e.voiceRecognition,...t.voiceRecognition},features:(()=>{let n=e.features?.artifacts,o=t.features?.artifacts,r=e.features?.scrollToBottom,i=t.features?.scrollToBottom,s=e.features?.scrollBehavior,l=t.features?.scrollBehavior,d=e.features?.streamAnimation,u=t.features?.streamAnimation,a=e.features?.askUserQuestion,p=t.features?.askUserQuestion,m=e.features?.history,f=t.features?.history,h=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},y=r===void 0&&i===void 0?void 0:{...r,...i},c=s===void 0&&l===void 0?void 0:{...s,...l},g=d===void 0&&u===void 0?void 0:{...d,...u},A=a===void 0&&p===void 0?void 0:{...a,...p,styles:{...a?.styles,...p?.styles}},v=m===void 0&&f===void 0?void 0:{...m,...f,copy:{...m?.copy,...f?.copy}};return{...e.features,...t.features,toolCallDisplay:{...e.features?.toolCallDisplay,...t.features?.toolCallDisplay},reasoningDisplay:{...e.features?.reasoningDisplay,...t.features?.reasoningDisplay},...y!==void 0?{scrollToBottom:y}:{},...c!==void 0?{scrollBehavior:c}:{},...h!==void 0?{artifacts:h}:{},...g!==void 0?{streamAnimation:g}:{},...A!==void 0?{askUserQuestion:A}:{},...v!==void 0?{history:v}:{}}})(),suggestionChips:t.suggestionChips??e.suggestionChips,suggestionChipsConfig:{...e.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...e.layout,...t.layout,header:{...e.layout?.header,...t.layout?.header},messages:{...e.layout?.messages,...t.layout?.messages,...e.layout?.messages?.user||t.layout?.messages?.user?{user:{...e.layout?.messages?.user,...t.layout?.messages?.user}}:{},...e.layout?.messages?.assistant||t.layout?.messages?.assistant?{assistant:{...e.layout?.messages?.assistant,...t.layout?.messages?.assistant}}:{},avatar:{...e.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...e.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...e.layout?.slots,...t.layout?.slots}},markdown:{...e.markdown,...t.markdown,options:{...e.markdown?.options,...t.markdown?.options}},messageActions:{...e.messageActions,...t.messageActions}},t),t,de):se(le(e),void 0,de)}function pe(t){let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return 20;let n=e.getComputedStyle(t).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function De(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function Kt(t,e){t.style.maxHeight=`${e*pe(t)}px`,t.style.overflowY="auto"}function Oe(t){let e=t?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!e||typeof e.matchMedia!="function")return!1;try{return e.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function Ne(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function Vt(t,e){if(t.key!=="Enter"||t.shiftKey||t.isComposing)return!1;let n=t.metaKey===!0||t.ctrlKey===!0,o=e.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!Ne(e)}function ut(t){return(t.submitKey??"enter")!=="enter"||Ne(t)?"enter":"send"}function He(t,e){t.setAttribute("enterkeyhint",ut(e))}function We(t,e){let n=e?.autocomplete;t.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,i)=>{i===void 0?t.removeAttribute(r):t.setAttribute(r,i)};o("autocapitalize",typeof e?.autocapitalize=="string"?e.autocapitalize:void 0),o("spellcheck",typeof e?.spellcheck=="boolean"?String(e.spellcheck):void 0),o("inputmode",typeof e?.inputmode=="string"&&e.inputmode?e.inputmode:void 0),o("aria-label",typeof e?.ariaLabel=="string"&&e.ariaLabel?e.ariaLabel:void 0)}function zt(t){return t===!0?{disabled:!0}:!t||typeof t!="object"?{disabled:!1}:{disabled:!0,reason:typeof t.reason=="string"&&t.reason?t.reason:void 0}}var F="persona-composer-control",q="persona-composer-control--glyph",gt=40,Z=24,Jt=(t,e,n)=>{let o=t.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(t);for(let i of n){let s=r.getPropertyValue(i).trim();s?e.style.setProperty(i,s):e.style.removeProperty(i)}},en=(t,e)=>{let n=T("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??ce,n.dir="auto",He(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:Oe(n)}),We(n,t?.composer?.inputAttributes),n.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=De(t?.composer?.maxLines,e?.defaultMaxLines??3),r=`${o*20}px`;n.style.maxHeight=r,n.style.overflowY="auto";let i=()=>{let l=n.style.maxHeight;if(l!==r){let u=parseFloat(l);if(Number.isFinite(u)&&u>0)return u}let d=o*pe(n);return r=`${d}px`,n.style.maxHeight=r,d},s=()=>{n.addEventListener("input",()=>{n.style.height="auto";let l=Math.min(n.scrollHeight,i());n.style.height=`${l}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:s}},ht="[data-persona-glyph-stack]",yt=(t,e,n="send")=>{let o=w("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return t.setAttribute("data-glyph","send"),e.setAttribute("data-glyph","stop"),o.append(t,e),o},tn=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,i=e.stopIconName??"square",s=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",d=t?.copy?.sendButtonLabel??"Send",u=t?.copy?.stopButtonLabel??"Stop",a=e.showTooltip??!1,p=e.size,m=parseFloat(p??"")||gt,f=e.backgroundColor,h=e.textColor,y=T("div","persona-send-button-wrapper"),c=w("button",{className:B("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${F}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!f&&"persona-bg-persona-primary",!n&&!h&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?p:void 0,height:n?p:void 0,minWidth:n?p:void 0,minHeight:n?p:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?h||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":h||void 0,backgroundColor:n&&f||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),g=null,A=null,v=null;if(n){let b=parseFloat(e.iconSize??"")||Math.round(m*.5),E=e.iconStrokeWidth??2,S=h?.trim()||"currentColor";if(r&&(g=M(r,b,S,E)),A=M(i,b,S,E),!e.iconSize)for(let P of[g,A])P&&(P.style.width=`var(--persona-components-composer-sendIconSize, ${b}px)`,P.style.height=`var(--persona-components-composer-sendIconSize, ${b}px)`);g&&A?(v=yt(g,A),c.appendChild(v)):g?c.appendChild(g):(c.textContent=o,A=null)}else c.textContent=d;c.setAttribute("aria-label",s),y.appendChild(c),O({anchor:c,trigger:y,text:()=>c.getAttribute("aria-label")??"",enabled:a});let N="send";return{button:c,wrapper:y,setMode:b=>{if(b===N)return;N=b;let E=b==="stop"?l:s;c.setAttribute("aria-label",E),c.setAttribute("data-persona-send-mode",b),n?(c.querySelector(ht)??v)?.setAttribute("data-mode",b):c.textContent=b==="stop"?u:d},glyphStack:v}},nn=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=e.provider?.type==="runtype",i=e.provider?.type==="custom";if(!(o||r||i))return null;let l=e.iconName??"mic",d=e.iconSize,u=parseFloat(d??"")||Z,a=e.backgroundColor??t?.sendButton?.backgroundColor,p=e.iconColor??t?.sendButton?.textColor,m=T("div","persona-send-button-wrapper"),f=w("button",{className:B("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",F,!d&&q),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":e.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:p||"var(--persona-text, #111827)",backgroundColor:a||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),y=M(l,u,p||"currentColor",1.5);y?f.appendChild(y):f.textContent="\u{1F3A4}",m.appendChild(f);let c=e.tooltipText??"Start voice recognition",g=e.showTooltip??!1;return O({anchor:f,trigger:m,text:()=>f.getAttribute("aria-label")??c,enabled:g}),{button:f,wrapper:m}},on=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=T("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=T("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(e.allowedTypes??Ce).join(","),o.multiple=(e.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=e.buttonIconName??"paperclip",i=T("div","persona-send-button-wrapper"),s=w("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${F} ${q}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=M(r,Z,"currentColor",1.5);l?s.appendChild(l):s.textContent="\u{1F4CE}",s.addEventListener("click",u=>{u.preventDefault(),o.click()}),i.appendChild(s);let d=e.buttonTooltipText??"Attach file";return O({anchor:s,trigger:i,text:()=>s.getAttribute("aria-label")??d}),{button:s,wrapper:i,input:o,previewsContainer:n}},rn=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=T("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),we(o,e,"idle");let r=e.idleText??"Online";if(e.idleLink){let i=T("a");i.href=e.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=r,i.style.color="inherit",i.style.textDecoration="none",o.appendChild(i)}else o.textContent=r;return o},sn=()=>w("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function un(t){let{config:e,onOpen:n}=t,o=e.buttonIconName??"plus",r=e.buttonTooltipText??"Add context",i=T("div","persona-send-button-wrapper"),s=w("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${F} ${q}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=M(o,Z,"currentColor",1.5);return l?s.appendChild(l):s.textContent="+",s.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),i.appendChild(s),O({anchor:s,trigger:i,text:()=>s.getAttribute("aria-label")??r}),{button:s,wrapper:i}}var{setLoader:gn,load:bt}=G({fallbackImport:()=>import("./context-mentions-E7HJYWO6.js")});var hn=bt;var{setLoader:xn,load:xt}=G({fallbackImport:()=>import("./context-mentions-inline-QVESLW55.js"),resetOnSetLoader:!0});var Cn=xt;function En(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=w("span",{className:B("persona-mention-token",e.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":t.sourceId,title:t.label,role:"img","aria-label":`${t.label} mention`}});t.color&&n.style.setProperty("--persona-mention-token-accent",t.color);let o=M(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=T("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(w("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}export{X as a,Me as b,et as c,Pt as d,kt as e,_t as f,ke as g,nt as h,Dt as i,ot as j,rt as k,it as l,st as m,de as n,pt as o,_e as p,Ft as q,we as r,vt as s,At as t,Xe as u,Et as v,O as w,De as x,Kt as y,Oe as z,Vt as A,He as B,We as C,zt as D,F as E,q as F,gt as G,Z as H,Jt as I,en as J,yt as K,tn as L,nn as M,on as N,rn as O,sn as P,un as Q,hn as R,Cn as S,En as T};
@@ -0,0 +1 @@
1
+ var p="suggest_replies";var u={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},h={name:p,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:u,origin:"sdk",annotations:{readOnlyHint:!0}},S=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),c=e=>e.variant==="tool"&&e.toolCall?.name===p,d=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let s=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let o=r;if(typeof o.label!="string"||!o.label.trim())return[];let i={label:o.label.trim()};return typeof o.prompt=="string"&&o.prompt.trim()&&(i.prompt=o.prompt.trim()),typeof o.description=="string"&&o.description.trim()&&(i.description=o.description.trim()),[i]});return s.length>4?(console.warn(`[persona] suggest_replies: ${s.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),s.slice(0,4)):s},m=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!c(n))continue;let s=d(n.toolCall?.args);return s.length>0?s:null}return null},g=new Set,f=(e,t,n)=>{let s=`${e}:${t}:${n}`;g.has(s)||(g.add(s),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},x=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,s=i=>{let l=t?.[i],a=n?.[i];l===void 0||a===void 0||l!==a&&f(i,a,l)};e&&(s("enabled"),s("expose"));let r=t?.enabled??n?.enabled??!0,o=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:o}};export{p as a,h as b,S as c,c as d,m as e,x as f};
@@ -0,0 +1 @@
1
+ function i(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function r(e){let o=()=>{e.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:e,getValue:()=>e.value,getLogicalText:()=>e.value,getSelection:()=>({start:e.selectionStart??0,end:e.selectionEnd??0}),setSelection:(t,n=t)=>{e.setSelectionRange(t,n)},setValueWithCaret:(t,n)=>{e.value=t,e.setSelectionRange(n,n)},setValue:t=>{e.value=t,e.setSelectionRange(t.length,t.length),o(),e.focus()},submit:()=>i(e.form),dispatchInput:o,focus:()=>e.focus()}}export{i as a,r as b};
@@ -0,0 +1 @@
1
+ import{a as p}from"./chunk-7NQ4ZTHF.js";var f=t=>{let{fallbackImport:r,resetOnSetLoader:o=!1}=t,e=null,n=null,i=null;return{setLoader:a=>{e=a,o&&(n=null,i=null)},load:()=>n?Promise.resolve(n):i||(i=(e??r)().then(l=>(n=l,l)).catch(l=>{throw i=null,l}),i),provide:a=>{n=a},getSync:()=>n}};var{setLoader:b,load:I}=f({fallbackImport:()=>import("./icons-extra-UKCDOG7Q.js")}),Ne=b,g=I;import{Activity as v,ArrowDown as C,ArrowLeft as x,ArrowRight as k,ArrowUp as w,ArrowUpRight as y,AtSign as S,Bot as E,Check as L,ChevronDown as T,ChevronLeft as A,ChevronRight as P,ChevronUp as R,Clipboard as N,ClipboardCopy as O,CodeXml as _,Copy as M,Download as D,Ellipsis as U,EllipsisVertical as F,ExternalLink as X,Eye as j,File as q,FileCode as z,FileSpreadsheet as V,FileText as G,History as B,ImagePlus as H,Loader as K,LoaderCircle as Q,Maximize as $,Menu as J,MessageSquare as W,Mic as Y,Minimize as Z,Minus as ee,PanelLeft as te,Paperclip as re,Pencil as oe,Plus as ne,Quote as ie,RefreshCw as se,Search as ae,Send as le,ShieldAlert as ce,ShieldCheck as de,ShieldX as ue,Square as pe,Star as he,ThumbsDown as me,ThumbsUp as fe,Trash as ge,Trash2 as be,Upload as Ie,Volume2 as ve,X as Ce}from"lucide";var xe={activity:v,"arrow-down":C,"arrow-up":w,"arrow-up-right":y,bot:E,"chevron-down":T,"chevron-up":R,"chevron-right":P,"chevron-left":A,check:L,clipboard:N,"clipboard-copy":O,"code-xml":_,copy:M,file:q,"file-code":z,"file-spreadsheet":V,"file-text":G,"image-plus":H,loader:K,"loader-circle":Q,mic:Y,paperclip:re,quote:ie,"refresh-cw":se,search:ae,send:le,"shield-alert":ce,"shield-check":de,"shield-x":ue,square:pe,"thumbs-down":me,"thumbs-up":fe,upload:Ie,"volume-2":ve,x:Ce,"at-sign":S,"arrow-left":x,"arrow-right":k,"external-link":X,ellipsis:U,"ellipsis-vertical":F,menu:J,"panel-left":te,plus:ne,minus:ee,pencil:oe,trash:ge,"trash-2":be,download:D,maximize:$,minimize:Z,"message-square":W,star:he,eye:j,history:B},ke=["user","mail","phone","calendar","clock","building","map-pin","lock","key","credit-card","hash","globe","link","circle-check","circle-x","triangle-alert","info","ban","shield","house","pen-line","save","share","funnel","settings","rotate-cw","shopping-cart","shopping-bag","package","truck","tag","gift","receipt","wallet","store","dollar-sign","percent","play","pause","volume-x","camera","image","film","headphones","message-circle","bell","heart","eye-off","bookmark","calendar-days","timer","folder","folder-open","files","chart-column","sparkles","zap","sun","moon","flag","lightbulb","monitor","smartphone"],c=new Map(Object.entries(xe)),s=new Set,h=!1,d=new Set,we=t=>{let r=[...d];t&&d.clear();for(let o of r)try{o()}catch{}},Ue=t=>h?()=>{}:(d.add(t),()=>{d.delete(t)}),ye=()=>{let t=0;for(let r of[...s]){let o=c.get(r.name);if(!o)continue;s.delete(r),t++;let e=p(o,r.size,r.color,r.strokeWidth);if(e)for(r.el.removeAttribute("data-persona-icon-pending");e.firstChild;)r.el.appendChild(e.firstChild)}return t};var m=!1,Se=()=>{g().then(t=>{if(!h){for(let[r,o]of Object.entries(t.EXTRA_LUCIDE_ICONS))c.has(r)||c.set(r,o);h=!0,ye(),we(!0)}}).catch(t=>{m=!0,console.warn("[Persona] Failed to load the icons-extra chunk",t)})},Ee=(t,r,o)=>{let e=document.createElementNS("http://www.w3.org/2000/svg","svg");return e.setAttribute("width",String(t)),e.setAttribute("height",String(t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke",r),e.setAttribute("stroke-width",String(o)),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.setAttribute("aria-hidden","true"),e.setAttribute("data-persona-icon-pending","true"),e},Fe=(t,r=24,o="currentColor",e=2)=>{let n=c.get(t);if(n)return p(n,r,o,e);if(ke.includes(t)){m&&(m=!1);let i=Ee(r,o,e);if(s.size>=500){let u=s.values().next().value;u&&s.delete(u)}return s.add({el:i,name:t,size:r,color:o,strokeWidth:e}),Se(),i}return console.warn(`Lucide icon "${t}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null};export{f as a,Ne as b,g as c,Ue as d,Fe as e};
@@ -0,0 +1 @@
1
+ import{a as g}from"./chunk-QPPJUSZH.js";var H=32768,c=49152,p=t=>{let e=t??{},i=typeof e.targetId=="string"?e.targetId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:i,preview:typeof e.preview=="string"?e.preview:null,messageCount:typeof e.messageCount=="number"?e.messageCount:0,createdAt:typeof e.createdAt=="string"?e.createdAt:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}},v="The identity proof was not admitted; account history is unavailable",m="The identity proof was rejected",C="The request carried no visitor credential",w="The stored visitor belongs to a different signed-in user";function E(t,e,i){let r=new URLSearchParams;for(let[n,s]of Object.entries(i))s===void 0||s===""||r.set(n,String(s));let o=r.toString();return`${t.clientApiBase()}/v1/client/${e}${o?`?${o}`:""}`}function b(t,e){if(e)return e;let i=t.config.features?.history?.scope;return i||(t.config.getIdentityProof?"verified-user":"browser")}async function T(t,e,i){let r=t.config.getIdentityProof;if(!r)return i&&t.setHistoryIdentityStatus(t.browserOnlyStatus()),null;i&&t.setHistoryIdentityStatus({state:"verifying"});let o;try{o=await r()??null}catch{throw i&&t.setHistoryIdentityStatus({state:"identity_provider_failed"}),new t.HistoryClientError("identity_provider_failed","The identity proof provider failed")}if(o)return o;if(e.visitor?.endUserId!=null)throw i&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new t.HistoryClientError("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return i&&t.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async function P(t,e,i,r){if(e.visitor?.endUserId!=null)return e;let o=await t.reinitWithProof(i);if(!(o.visitor?.identityStatus==="admitted"&&o.visitor?.endUserId!=null))throw r&&t.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new t.HistoryClientError("proof_not_admitted",v);return o}async function _(t,e){let i=await e.json().catch(()=>({}));return typeof i.error=="string"?i.error:typeof i.message=="string"?i.message:""}async function A(t,e,i,r){let o=e.toLowerCase();if(o.includes("invalid_identity_proof"))throw r&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new t.HistoryClientError("invalid_identity_proof",m);if(o.includes("visitor token required"))throw new t.HistoryClientError("visitor_token_missing",C);if(o.includes("visitor_identity_mismatch")){if(!i)throw r&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new t.HistoryClientError("visitor_identity_mismatch",w);return t.reinitWithProof(i)}if(o.includes("expired")||o.includes("not found"))return t.clearClientSession(),t.initSession();throw new t.HistoryClientError("unauthorized",e||"History request was not authorized")}async function h(t,e,i){let r=await _(t,e);if(e.status===404)return new t.HistoryClientError("not_found","Conversation not found");if(e.status===429){let o=Number.parseInt(e.headers.get("Retry-After")??"",10);return new t.HistoryClientError("rate_limited","Too many history requests",{...Number.isFinite(o)?{retryAfterSeconds:o}:{}})}if(e.status===503&&r.includes("identity_proof_not_admitted"))return i&&t.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new t.HistoryClientError("proof_not_admitted",v);if(e.status===401){let o=r.toLowerCase();return o.includes("invalid_identity_proof")?(i&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new t.HistoryClientError("invalid_identity_proof",m)):o.includes("visitor token required")?new t.HistoryClientError("visitor_token_missing",C):o.includes("visitor_identity_mismatch")?new t.HistoryClientError("visitor_identity_mismatch",w):new t.HistoryClientError("unauthorized",r||"History request was not authorized")}return new t.HistoryClientError("request_failed",r||`History request failed (${e.status})`)}function R(t,e,i,r){let o=e?.toLowerCase()??null;if(i){if(o==="admitted"){r&&t.setHistoryIdentityStatus({state:"verified"});return}throw r&&t.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),o==="ignored"?new t.HistoryClientError("identity_contract_violation","Server reported an ignored identity proof on a success response"):new t.HistoryClientError("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(o==="admitted")throw new t.HistoryClientError("identity_contract_violation","Server admitted an identity proof that was never sent");r&&t.setHistoryIdentityStatus(t.browserOnlyStatus())}async function y(t,e,i){f(t);let r=i.trackIdentity!==!1,o=await t.initSession(),n=null;b(t,i.scope)==="verified-user"&&(n=await T(t,o,r),n&&(o=await P(t,o,n,r)));let s=t.historyInternals.visitorStore,a=!1;for(;;){let u=s?.revision()??0,d=await t.readVisitorToken();if(!d&&!i.visitorTokenOptional)throw new t.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let l=await fetch(E(t,e,{...i.query,sessionId:o.sessionId}),{method:i.method,headers:{"X-Persona-Version":g,...d?{"X-Visitor-Token":d}:{},...n?{"X-Identity-Proof":n}:{},...i.body!==void 0?{"Content-Type":"application/json"}:{}},...i.body!==void 0?{body:JSON.stringify(i.body)}:{},...i.keepalive?{keepalive:!0}:{}});if(l.status===401&&!a){a=!0,o=await A(t,await _(t,l),n,r);continue}if(!l.ok)throw await h(t,l,r);let S=l.headers.get("X-History-Identity-Status"),I=await l.json().catch(()=>{});if(s&&s.revision()!==u)throw new t.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return R(t,S,n!==null,r),I}}function f(t){if(!t.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!t.isHistoryCapable())throw new t.HistoryClientError("history_disabled","Visitor history is disabled for this surface")}async function O(t,e){let i=await y(t,"conversations",{method:"GET",query:{...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{data:(Array.isArray(i?.data)?i.data:[]).map(p),nextCursor:typeof i?.nextCursor=="string"?i.nextCursor:null}}async function x(t,e,i){let r=await y(t,`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...i?.messageCursor?{messageCursor:i.messageCursor}:{}},...i?.scope?{scope:i.scope}:{}});return{summary:p(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor=="string"?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision=="string"?r.conversationRevision:null}}async function q(t,e,i){f(t);let r=0;for(let u of i){let d=u.displayContent.length;if(d>H)throw new t.HistoryClientError("payload_too_large",`displayContent exceeds the ${H} character limit`);r+=d}if(r>c)throw new t.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${c} character limit`);await t.initSession();let o=t.historyInternals.visitorStore,n=o?.revision()??0,s=await y(t,`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:i},scope:"browser",keepalive:r<=c,trackIdentity:!1}),a=typeof s?.conversationRevision=="string"?s.conversationRevision:null;return a&&t.clientSession?.conversationId===e&&(o?.revision()??0)===n&&t.historyInternals.setStoredConversationRevision?.(a),{conversationRevision:a}}async function D(t,e,i){let r=await y(t,`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...i?.scope?{scope:i.scope}:{}});return{deleted:typeof r?.deleted=="number"?r.deleted:0}}async function M(t,e){let i=await y(t,"conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof i?.deleted=="number"?i.deleted:0}}async function N(t){f(t),t.setHistoryIdentityStatus({state:"resetting"});try{await y(t,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await t.historyInternals.visitorStore?.clear(),t.setHistoryIdentityStatus(t.derivedBrowserOnly())}return{reset:!0}}export{M as deleteAllConversations,D as deleteConversation,q as finalizeDisplayProjections,x as getConversation,h as historyErrorFor,O as listConversations,_ as readErrorCode,A as recoverFromUnauthorized,N as resetVisitor};
@@ -0,0 +1 @@
1
+ var y="4.26.0";var f=y;var g=32768,p=49152,b=t=>{let e=t??{},i=typeof e.targetId=="string"?e.targetId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:i,preview:typeof e.preview=="string"?e.preview:null,messageCount:typeof e.messageCount=="number"?e.messageCount:0,createdAt:typeof e.createdAt=="string"?e.createdAt:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}},v="The identity proof was not admitted; account history is unavailable",w="The identity proof was rejected",H="The request carried no visitor credential",C="The stored visitor belongs to a different signed-in user";function j(t,e,i){let s=new URLSearchParams;for(let[r,o]of Object.entries(i))o===void 0||o===""||s.set(r,String(o));let n=s.toString();return`${t.clientApiBase()}/v1/client/${e}${n?`?${n}`:""}`}function I(t,e){if(e)return e;let i=t.config.features?.history?.scope;return i||(t.config.getIdentityProof?"verified-user":"browser")}async function E(t,e,i){let s=t.config.getIdentityProof;if(!s)return i&&t.setHistoryIdentityStatus(t.browserOnlyStatus()),null;i&&t.setHistoryIdentityStatus({state:"verifying"});let n;try{n=await s()??null}catch{throw i&&t.setHistoryIdentityStatus({state:"identity_provider_failed"}),new t.HistoryClientError("identity_provider_failed","The identity proof provider failed")}if(n)return n;if(e.visitor?.endUserId!=null)throw i&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new t.HistoryClientError("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return i&&t.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async function k(t,e,i,s){if(e.visitor?.endUserId!=null)return e;let n=await t.reinitWithProof(i);if(!(n.visitor?.identityStatus==="admitted"&&n.visitor?.endUserId!=null))throw s&&t.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new t.HistoryClientError("proof_not_admitted",v);return n}async function h(t,e){let i=await e.json().catch(()=>({}));return typeof i.error=="string"?i.error:typeof i.message=="string"?i.message:""}async function T(t,e,i,s){let n=e.toLowerCase();if(n.includes("invalid_identity_proof"))throw s&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new t.HistoryClientError("invalid_identity_proof",w);if(n.includes("visitor token required"))throw new t.HistoryClientError("visitor_token_missing",H);if(n.includes("visitor_identity_mismatch")){if(!i)throw s&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new t.HistoryClientError("visitor_identity_mismatch",C);return t.reinitWithProof(i)}if(n.includes("expired")||n.includes("not found"))return t.clearClientSession(),t.initSession();throw new t.HistoryClientError("unauthorized",e||"History request was not authorized")}async function q(t,e,i){let s=await h(t,e);if(e.status===404)return new t.HistoryClientError("not_found","Conversation not found");if(e.status===429){let n=Number.parseInt(e.headers.get("Retry-After")??"",10);return new t.HistoryClientError("rate_limited","Too many history requests",{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(e.status===503&&s.includes("identity_proof_not_admitted"))return i&&t.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new t.HistoryClientError("proof_not_admitted",v);if(e.status===401){let n=s.toLowerCase();return n.includes("invalid_identity_proof")?(i&&t.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new t.HistoryClientError("invalid_identity_proof",w)):n.includes("visitor token required")?new t.HistoryClientError("visitor_token_missing",H):n.includes("visitor_identity_mismatch")?new t.HistoryClientError("visitor_identity_mismatch",C):new t.HistoryClientError("unauthorized",s||"History request was not authorized")}return new t.HistoryClientError("request_failed",s||`History request failed (${e.status})`)}function P(t,e,i,s){let n=e?.toLowerCase()??null;if(i){if(n==="admitted"){s&&t.setHistoryIdentityStatus({state:"verified"});return}throw s&&t.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),n==="ignored"?new t.HistoryClientError("identity_contract_violation","Server reported an ignored identity proof on a success response"):new t.HistoryClientError("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(n==="admitted")throw new t.HistoryClientError("identity_contract_violation","Server admitted an identity proof that was never sent");s&&t.setHistoryIdentityStatus(t.browserOnlyStatus())}async function l(t,e,i){m(t);let s=i.trackIdentity!==!1,n=await t.initSession(),r=null;I(t,i.scope)==="verified-user"&&(r=await E(t,n,s),r&&(n=await k(t,n,r,s)));let o=t.historyInternals.visitorStore,a=!1;for(;;){let c=o?.revision()??0,d=await t.readVisitorToken();if(!d&&!i.visitorTokenOptional)throw new t.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(j(t,e,{...i.query,sessionId:n.sessionId}),{method:i.method,headers:{"X-Persona-Version":f,...d?{"X-Visitor-Token":d}:{},...r?{"X-Identity-Proof":r}:{},...i.body!==void 0?{"Content-Type":"application/json"}:{}},...i.body!==void 0?{body:JSON.stringify(i.body)}:{},...i.keepalive?{keepalive:!0}:{}});if(u.status===401&&!a){a=!0,n=await T(t,await h(t,u),r,s);continue}if(!u.ok)throw await q(t,u,s);let x=u.headers.get("X-History-Identity-Status"),_=await u.json().catch(()=>{});if(o&&o.revision()!==c)throw new t.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return P(t,x,r!==null,s),_}}function m(t){if(!t.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!t.isHistoryCapable())throw new t.HistoryClientError("history_disabled","Visitor history is disabled for this surface")}async function z(t,e){let i=await l(t,"conversations",{method:"GET",query:{...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{data:(Array.isArray(i?.data)?i.data:[]).map(b),nextCursor:typeof i?.nextCursor=="string"?i.nextCursor:null}}async function M(t,e,i){let s=await l(t,`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...i?.messageCursor?{messageCursor:i.messageCursor}:{}},...i?.scope?{scope:i.scope}:{}});return{summary:b(s),messages:Array.isArray(s?.messages)?s.messages:[],nextMessageCursor:typeof s?.nextMessageCursor=="string"?s.nextMessageCursor:null,conversationRevision:typeof s?.conversationRevision=="string"?s.conversationRevision:null}}async function N(t,e,i){m(t);let s=0;for(let c of i){let d=c.displayContent.length;if(d>g)throw new t.HistoryClientError("payload_too_large",`displayContent exceeds the ${g} character limit`);s+=d}if(s>p)throw new t.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${p} character limit`);await t.initSession();let n=t.historyInternals.visitorStore,r=n?.revision()??0,o=await l(t,`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:i},scope:"browser",keepalive:s<=p,trackIdentity:!1}),a=typeof o?.conversationRevision=="string"?o.conversationRevision:null;return a&&t.clientSession?.conversationId===e&&(n?.revision()??0)===r&&t.historyInternals.setStoredConversationRevision?.(a),{conversationRevision:a}}async function L(t,e,i){let s=await l(t,`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...i?.scope?{scope:i.scope}:{}});return{deleted:typeof s?.deleted=="number"?s.deleted:0}}async function U(t,e){let i=await l(t,"conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof i?.deleted=="number"?i.deleted:0}}async function $(t){m(t),t.setHistoryIdentityStatus({state:"resetting"});try{await l(t,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await t.historyInternals.visitorStore?.clear(),t.setHistoryIdentityStatus(t.derivedBrowserOnly())}return{reset:!0}}export{U as deleteAllConversations,L as deleteConversation,N as finalizeDisplayProjections,M as getConversation,q as historyErrorFor,z as listConversations,h as readErrorCode,T as recoverFromUnauthorized,$ as resetVisitor};
@@ -0,0 +1,4 @@
1
+ import{c as me,d as ye,e as Ie}from"./chunk-K6HKIP5K.js";import"./chunk-K7NA7G7J.js";import{d as we}from"./chunk-2ANTRKTV.js";import"./chunk-TR2H475E.js";import{e as de,p as z}from"./chunk-NQLDCJAP.js";import"./chunk-76IELU7F.js";async function Te(c,h,m){let u={"Content-Type":"application/json",...c.headers};c.getHeaders&&Object.assign(u,await c.getHeaders());let M={executionId:h.executionId,approvalId:h.approvalId,decision:m,streamResponse:!0},x=(k,p)=>fetch(`${c.clientApiBase()}${k}`,{method:"POST",headers:u,body:JSON.stringify({...p,...M})}),A=`/v1/agents/${h.agentId}/approve`;if(!c.isClientTokenMode())return x(A);let{sessionId:y}=await c.initSession(),S=await x("/v1/client/approve",{sessionId:y});if(S.status===404){let k=await S.clone().json().catch(()=>null);if(!k||k.error==="Not Found")return x(A)}return S}async function Se(c,h,m,u){let M=c.isClientTokenMode(),x=M?c.getClientApiUrl("resume"):`${c.config.apiUrl?.replace(/\/+$/,"")||we}/resume`,A,y=null;if(M){let p=await c.initSession();A=p.sessionId,p.durableRecovery?.enabled===!0&&(y=await c.readVisitorToken())}let S={"Content-Type":"application/json",...y?{"X-Visitor-Token":y}:{},...c.headers};c.getHeaders&&Object.assign(S,await c.getHeaders());let k={executionId:h,toolOutputs:m,streamResponse:u?.streamResponse??!0,...u?.after?{after:u.after}:{}};if(A&&(k.sessionId=A),M&&A){let p=[...Ie(c.config),...await(await c.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:D,commit:ee}=await c.sendWithClientToolsDiff(A,p,d=>{let f={...k,...d};return c.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(x,{method:"POST",headers:S,body:JSON.stringify(f),signal:u?.signal})},{emptyMeansReplace:!0});return D.ok&&ee(),D}return fetch(x,{method:"POST",headers:S,body:JSON.stringify(k),signal:u?.signal})}function ke(c){let h=c.toLowerCase(),u={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[h];if(u)return`attachment.${u}`;let M=h.indexOf("/");if(M>0){let x=h.slice(M+1).split(";")[0]?.trim()??"";if(x&&x!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(x))return`attachment.${x}`}return"attachment"}var he=c=>c.startsWith("{")||c.startsWith("[")||c.startsWith("<");function We(c,h){if(!c)return h;let m=c.trim(),u=h.trim();if(m.length===0)return h;if(u.length===0)return c;let M=he(m);if(!he(u))return c;if(!M||u===m||u.startsWith(m))return h;let A=z(c);return z(h)!==null&&A===null?h:c}async function be(c,h,m,u,M,x,A){if(!c.parseSSEEvent)return!1;try{let y=await c.parseSSEEvent(h);if(y===null)return!1;let S=p=>{let D={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:x(),...p!==void 0&&{partId:p}};return u.current=D,M(D),D},k=p=>u.current?u.current:S(p);if(y.text!==void 0){y.partId!==void 0&&A.current!==null&&y.partId!==A.current&&(u.current&&(u.current.streaming=!1,M(u.current)),S(y.partId)),y.partId!==void 0&&(A.current=y.partId);let p=k(y.partId);y.partId!==void 0&&!p.partId&&(p.partId=y.partId),p.content+=y.text,M(p)}return y.done&&(u.current&&(u.current.streaming=!1,M(u.current)),A.current=null,m({type:"status",status:"idle"})),y.error&&(A.current=null,m({type:"error",error:new Error(y.error)})),!0}catch(y){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",y),!1}}async function Ee(c,h,m,u,M){let x=h.getReader(),A=new TextDecoder,y="",S=Date.now(),k=0,p=()=>S+k++,D=n=>{let e=n.reasoning?{...n.reasoning,chunks:[...n.reasoning.chunks]}:void 0,t=n.toolCall?{...n.toolCall,chunks:n.toolCall.chunks?[...n.toolCall.chunks]:void 0}:void 0,o=n.tools?n.tools.map(s=>({...s,chunks:s.chunks?[...s.chunks]:void 0})):void 0;return{...n,reasoning:e,toolCall:t,tools:o}},ee=n=>{if(n.role!=="assistant"||n.variant)return!0;let e=Array.isArray(n.contentParts)&&n.contentParts.length>0,t=typeof n.rawContent=="string"&&n.rawContent.trim()!=="";return typeof n.content=="string"&&n.content.trim()!==""||e||t||!!n.stopReason},d=n=>{ee(n)&&m({type:"message",message:D(n)})},f=null,U=null,O={current:null},Ce={current:null},F=null,E="",$=new Map,v=new Map,te=new Map,Q=new Map,ne=new Map,X=u,ce=!1,oe=()=>{if(f)return f;let n,e="",t=F;return!ce&&X?(n=X,ce=!0,e=M??""):X&&t?n=`${X}_${t}`:n=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:n,role:"assistant",content:e,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},d(f),f},se=n=>{let e=Q.get(n);if(e)return e;let t={id:`reason-${n}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:n,status:"streaming",chunks:[]}};return Q.set(n,t),d(t),t},H=new Set,re=new Map,ge=new Set,J=new Map,Ae=n=>{if(!n)return!1;let e=n.replace(/_+/g,"_").replace(/^_|_$/g,"");return e==="emit_artifact_markdown"||e==="emit_artifact_component"},L=n=>{let e=ne.get(n);if(e)return e;let t={id:`tool-${n}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:n,status:"pending"}};return ne.set(n,t),d(t),t},ue=n=>{if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let e=Number(n);if(!Number.isNaN(e)&&Number.isFinite(e))return e;let t=Date.parse(n);if(!Number.isNaN(t))return t}return Date.now()},ie=n=>{if(typeof n=="string")return n;if(n==null)return"";try{return JSON.stringify(n)}catch{return String(n)}},T=new Map,W=new Map,Me=(n,e)=>{let t=ie(e),o=W.get(n.id),s=We(o,t);n.rawContent=s;let r=T.get(n.id),i=I=>{let g=n.content??"";I.trim()!==""&&(g.trim().length===0||I.startsWith(g)||I.trimStart().startsWith(g.trim()))&&(n.content=I)},l=()=>{if(r){let I=r.close?.();I instanceof Promise&&I.catch(()=>{})}T.delete(n.id),W.delete(n.id),n.streaming=!1,d(n)};if(!r){i(t),l();return}let a=z(s);if(a!==null&&a.trim()!==""){i(a),l();return}let w=I=>{let g=typeof I=="string"?I:I?.text??null;if(g!==null&&g.trim()!=="")return g;let N=r.getExtractedText();return N!==null&&N.trim()!==""?N:t},C;try{C=r.processChunk(s)}catch{i(t),l();return}if(C instanceof Promise){C.then(I=>{i(w(I)),l()}).catch(()=>{i(t),l()});return}i(w(C)),l()},K=null,ae=(n,e,t,o)=>{n.rawContent=e,T.has(n.id)||T.set(n.id,c.createStreamParser());let s=T.get(n.id),r=e.trim().startsWith("{")||e.trim().startsWith("[");if(r&&W.set(n.id,e),s.__isPlainTextParser===!0){n.content=o!==void 0?e:n.content+t,W.delete(n.id),T.delete(n.id),n.rawContent=void 0,d(n);return}let l=s.processChunk(e);if(l instanceof Promise)l.then(a=>{let w=typeof a=="string"?a:a?.text??null;w!==null&&w.trim()!==""?(n.content=w,d(n)):!r&&!e.trim().startsWith("<")&&(n.content=o!==void 0?e:n.content+t,W.delete(n.id),T.delete(n.id),n.rawContent=void 0,d(n))}).catch(()=>{n.content=o!==void 0?e:n.content+t,W.delete(n.id),T.delete(n.id),n.rawContent=void 0,d(n)});else{let a=typeof l=="string"?l:l?.text??null;a!==null&&a.trim()!==""?(n.content=a,d(n)):!r&&!e.trim().startsWith("<")&&(n.content=o!==void 0?e:n.content+t,W.delete(n.id),T.delete(n.id),n.rawContent=void 0,d(n))}},V=(n,e)=>{let t=e??n.content;if(t==null||t===""){n.streaming=!1,d(n);return}let s=W.get(n.id)??ie(t);n.rawContent=s;let r=T.get(n.id),i=null,l=!1;if(r&&(i=r.getExtractedText(),i===null&&(i=z(s)),i===null)){let a=r.processChunk(s);a instanceof Promise?(l=!0,a.then(w=>{let C=typeof w=="string"?w:w?.text??null;C!==null&&(n.content=C,n.streaming=!1,T.delete(n.id),W.delete(n.id),d(n))}).catch(()=>{})):i=typeof a=="string"?a:a?.text??null}if(!l){i!==null&&i.trim()!==""?n.content=i:W.has(n.id)||(n.content=ie(t));let a=T.get(n.id);if(a){let w=a.close?.();w instanceof Promise&&w.catch(()=>{}),T.delete(n.id)}W.delete(n.id),n.streaming=!1,d(n)}},pe=(n,e,t)=>{let o=v.get(n);if(o)return o;let s={id:`nested-${e}-${n}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...t?{variant:t}:{},...t==="reasoning"?{reasoning:{id:n,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:e}};return v.set(n,s),d(s),s},G=[],le,Y=new Map,_=0,B="agent",fe=!1,Z=null,j=null,xe=c.config().iterationDisplay??"separate";for(le=()=>{for(let n=0;n<G.length;n++){let e=G[n];if(!fe&&B!=="flow"&&typeof e.stepType=="string"&&(B="flow"),e.type==="reasoning_start"){let t=typeof e.id=="string"?e.id:null,o=typeof e.parentToolCallId=="string"&&e.parentToolCallId?e.parentToolCallId:null;if(t&&o){$.set(t,o),pe(t,o,"reasoning");continue}let s=e.id,r=se(s);r.reasoning=r.reasoning??{id:s,status:"streaming",chunks:[]},r.reasoning.startedAt=r.reasoning.startedAt??Date.now(),r.reasoning.completedAt=void 0,r.reasoning.durationMs=void 0,(e.scope==="loop"||e.scope==="turn")&&(r.reasoning.scope=e.scope),r.streaming=!0,r.reasoning.status="streaming",d(r)}else if(e.type==="reasoning_delta"){let t=typeof e.id=="string"?e.id:null;if(t&&$.has(t)&&v.has(t)){let r=v.get(t),i=e.delta;i&&r.reasoning&&(r.reasoning.chunks.push(String(i)),d(r));continue}let o=e.id,s=se(o);s.reasoning=s.reasoning??{id:o,status:"streaming",chunks:[]},s.reasoning.startedAt=s.reasoning.startedAt??Date.now(),e.delta&&s.reasoning.chunks.push(e.delta),s.reasoning.status="streaming",s.streaming=!0,d(s)}else if(e.type==="reasoning_complete"){let t=typeof e.id=="string"?e.id:null;if(t&&$.has(t)&&v.has(t)){let i=v.get(t);if(i.reasoning){let l=typeof e.text=="string"?e.text:"";l&&i.reasoning.chunks.length===0&&i.reasoning.chunks.push(l),i.reasoning.status="complete",i.streaming=!1,d(i)}$.delete(t),v.delete(t);continue}let o=e.id,s=typeof e.text=="string"?e.text:"";!Q.get(o)&&(s||e.scope==="loop")&&se(o);let r=Q.get(o);if(r?.reasoning){(e.scope==="loop"||e.scope==="turn")&&(r.reasoning.scope=e.scope),s&&r.reasoning.chunks.length===0&&r.reasoning.chunks.push(s),r.reasoning.status="complete",r.reasoning.completedAt=Date.now();let i=r.reasoning.startedAt??Date.now();r.reasoning.durationMs=Math.max(0,(r.reasoning.completedAt??Date.now())-i),r.streaming=!1,d(r)}}else if(e.type==="tool_start"){f&&(f.streaming=!1,d(f),f=null),typeof e.iteration=="number"&&(_=e.iteration);let t=e.toolCallId,o=e.toolName;if(Ae(o)){H.add(t);continue}let s=L(t),r=s.toolCall??{id:t,status:"pending"};r.name=o??r.name,r.status="running",r.success=void 0,r.error=void 0,r.duration=void 0,e.parameters!==void 0&&(r.args=e.parameters),r.startedAt=r.startedAt??ue(e.startedAt),r.completedAt=void 0,r.durationMs=void 0,s.toolCall=r,s.streaming=!0,e.executionId&&(s.agentMetadata={executionId:e.executionId,iteration:e.iteration}),d(s)}else if(e.type==="tool_output_delta"){let t=e.toolCallId;if(H.has(t))continue;let o=L(t),s=o.toolCall??{id:t,status:"running"};s.startedAt=s.startedAt??Date.now();let r=e.delta;r&&(s.chunks=s.chunks??[],s.chunks.push(String(r))),s.status="running",o.toolCall=s,o.streaming=!0,e.executionId&&(o.agentMetadata=o.agentMetadata??{executionId:e.executionId,iteration:_}),d(o)}else if(e.type==="tool_complete"){let t=e.toolCallId;if(H.has(t)){H.delete(t);continue}let o=L(t),s=o.toolCall??{id:t,status:"running"};s.status="complete",e.result!==void 0&&(s.result=e.result),s.name=e.toolName??s.name,s.success=e.success,s.error=e.error,s.completedAt=Date.now();let r=e.executionTime;if(typeof r=="number")s.durationMs=r,s.duration=r;else{let i=s.startedAt??Date.now();s.durationMs=Math.max(0,(s.completedAt??Date.now())-i)}o.toolCall=s,o.streaming=!1,e.executionId&&(o.agentMetadata=o.agentMetadata??{executionId:e.executionId,iteration:e.iteration??_}),d(o)}else if(e.type==="await"&&e.toolName){let t=typeof e.toolCallId=="string"&&e.toolCallId.length>0?e.toolCallId:void 0,o=t??e.toolId??`local-${p()}`,s=L(o),r=e.toolName,i=e.origin==="webmcp"&&!de(r)?`webmcp:${r}`:r,l=de(i),a=s.toolCall??{id:o,status:"pending"};a.name=i,a.args=e.parameters,a.status=l?"running":"complete",a.chunks=a.chunks??[],a.startedAt=a.startedAt??ue(e.awaitedAt),l?(a.completedAt=void 0,a.duration=void 0,a.durationMs=void 0):a.completedAt=a.completedAt??a.startedAt,s.toolCall=a,s.streaming=!1,s.agentMetadata={...s.agentMetadata,executionId:e.executionId??s.agentMetadata?.executionId,awaitingLocalTool:!0,...t?{webMcpToolCallId:t}:{}},d(s)}else if(e.type==="text_start"){let t=typeof e.id=="string"?e.id:null,o=typeof e.parentToolCallId=="string"&&e.parentToolCallId?e.parentToolCallId:null;if(t&&o){$.set(t,o);continue}let s=f;s&&(B==="flow"?(V(s),K=s):(s.streaming=!1,d(s)),f=null),F=typeof e.id=="string"?e.id:F,E=""}else if(e.type==="text_delta"){let t=typeof e.id=="string"?e.id:null,o=t?$.get(t):void 0;if(t&&o){let i=typeof e.delta=="string"?e.delta:"",l=(te.get(t)??"")+i;if(te.set(t,l),l.trim()==="")continue;let a=pe(t,o);a.agentMetadata={...a.agentMetadata,executionId:e.executionId,parentToolId:o},ae(a,l,i,void 0);continue}if(F=typeof e.id=="string"?e.id:F,B==="flow"){let i=typeof e.delta=="string"?e.delta:"";if(E+=i,E.trim()==="")continue;let l=oe();l.agentMetadata={executionId:e.executionId,iteration:_},ae(l,E,i,void 0),U=l;continue}let s=typeof e.delta=="string"?e.delta:"";E+=s;let r=oe();r.agentMetadata={executionId:e.executionId,iteration:_,turnId:Z??void 0,agentName:j?.agentName},ae(r,E,s,void 0),U=r}else if(e.type==="text_complete"){let t=typeof e.id=="string"?e.id:null;if(t&&$.has(t)){let s=v.get(t);s&&V(s),$.delete(t),te.delete(t),v.delete(t);continue}let o=f;o&&(B==="flow"?(V(o),K=o):((o.content??"")===""&&typeof e.text=="string"&&(o.content=e.text),o.streaming=!1,d(o)),f=null),F=null,E=""}else if(e.type==="step_complete"){if(e.stepType==="tool")continue;if(e.success===!1){let t=e.error||"Step failed";m({type:"error",error:new Error(t)});let o=f;o&&o.streaming&&(o.streaming=!1,d(o)),m({type:"status",status:"idle"});continue}{let t=K;K=null;let o=e.stopReason,r=(e.result&&typeof e.result=="object"?e.result:null)?.response;if(t)o&&(t.stopReason=o),r!=null?Me(t,r):t.streaming!==!1&&(T.delete(t.id),W.delete(t.id),t.streaming=!1,d(t));else{let i=r!=null&&r!=="";if(i||o){let l=oe();o&&(l.stopReason=o),i?V(l,r):(l.streaming=!1,d(l))}}continue}}else if(e.type==="execution_start")B=e.kind==="flow"?"flow":"agent",fe=!0,B==="agent"&&(j={executionId:e.executionId,agentId:e.agentId??"virtual",agentName:e.agentName??""});else if(e.type==="turn_start"){let t=typeof e.iteration=="number"?e.iteration:_;if(t!==_){if(xe==="separate"&&t>1){let o=f;o&&(o.streaming=!1,d(o),f=null)}_=t}Z=typeof e.id=="string"?e.id:null,U=null}else if(e.type==="tool_input_delta"){let t=e.toolCallId;if(t){let o=ne.get(t);o?.toolCall&&(o.toolCall.chunks=o.toolCall.chunks??[],o.toolCall.chunks.push(e.delta??""),d(o))}}else if(e.type==="tool_input_complete"){if(H.has(e.toolCallId))continue;let t=L(e.toolCallId),o=t.toolCall;o.args=e.parameters,o.name=e.toolName??o.name,d(t)}else if(e.type==="turn_complete"){let t=e.stopReason,o=f??U;if(t&&o!==null){let s=e.id;(!s||o.agentMetadata?.turnId===s)&&(o.stopReason=t,d(o))}Z===e.id&&(Z=null)}else if(e.type==="media_start"){let t=String(e.id);Y.set(t,{mediaType:typeof e.mediaType=="string"?e.mediaType:void 0,toolCallId:e.toolCallId,parts:[]})}else if(e.type==="media_delta"){let t=Y.get(String(e.id));t&&typeof e.delta=="string"&&t.parts.push(e.delta)}else if(e.type==="media_complete"){let t=String(e.id),o=Y.get(t);Y.delete(t);let s=(typeof e.mediaType=="string"?e.mediaType:void 0)??o?.mediaType??"application/octet-stream",r=typeof e.data=="string"?e.data:void 0,i=typeof e.url=="string"?e.url:o&&o.parts.length>0?o.parts.join(""):void 0,l=null;if(r)l={type:"media",data:r,mediaType:s};else if(i){let I=s.toLowerCase();l={type:I==="image"||I.startsWith("image/")?"image-url":"file-url",url:i,mediaType:s}}let a=e.toolCallId??o?.toolCallId,w=l?[l]:[],C=[];for(let I of w){if(!I||typeof I!="object")continue;let g=I,N=typeof g.type=="string"?g.type:void 0,q=typeof g.mediaType=="string"?g.mediaType.toLowerCase():"",b=null,P="";if(N==="media"){let R=typeof g.data=="string"?g.data:void 0;if(!R)continue;P=q.length>0?q:"application/octet-stream",b=`data:${P};base64,${R}`}else if(N==="image-url"){let R=typeof g.url=="string"?g.url:void 0;if(!R)continue;P=q,b=R}else if(N==="file-url"){let R=typeof g.url=="string"?g.url:void 0;if(!R)continue;P=q,b=R}else continue;if(b)if(N==="image-url"||P.startsWith("image/"))C.push({type:"image",image:b,...P.includes("/")?{mimeType:P}:{}});else if(P.startsWith("audio/"))C.push({type:"audio",audio:b,mimeType:P});else if(P.startsWith("video/"))C.push({type:"video",video:b,mimeType:P});else{let R=P||"application/octet-stream";C.push({type:"file",data:b,mimeType:R,filename:ke(R)})}}if(C.length>0){let I=p(),g=a,q={id:`agent-media-${typeof g=="string"&&g.length>0?`${g}-${I}`:String(I)}`,role:"assistant",content:"",contentParts:C,createdAt:new Date().toISOString(),streaming:!1,sequence:I,agentMetadata:{executionId:e.executionId,iteration:_}};d(q);let b=f;b&&(b.streaming=!1,d(b)),f=null,O.current=null}}else if(e.type==="execution_complete"){let t=f;t&&(e.kind==="flow"&&t.streaming!==!1?V(t):(t.streaming=!1,d(t)),f=null),F=null,E="",K=null,m({type:"status",status:"idle",terminal:!0})}else if(e.type==="execution_error"){let t=typeof e.error=="string"?e.error:e.error?.message??"Execution error";m({type:"error",error:new Error(t)})}else if(e.type!=="ping"){if(e.type==="approval_start"){let t=e.approvalId??`approval-${p()}`,o={id:`approval-${t}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:t,status:"pending",agentId:j?.agentId??"virtual",executionId:e.executionId??j?.executionId??"",toolName:e.toolName??"",toolType:e.toolType,description:e.description??`Execute ${e.toolName??"tool"}`,...typeof e.reason=="string"&&e.reason?{reason:e.reason}:{},parameters:e.parameters,...typeof e.toolCallId=="string"&&e.toolCallId?{toolCallId:e.toolCallId}:{}}};d(o)}else if(e.type==="approval_complete"){let t=e.approvalId;if(t){let s={id:`approval-${t}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:t,status:e.decision??"approved",agentId:j?.agentId??"virtual",executionId:e.executionId??j?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};d(s)}}else if(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete"){if(e.type==="artifact_start"){let t=e.artifactType,o=String(e.id),s=typeof e.title=="string"?e.title:void 0,r=e.file,i;if(r&&typeof r=="object"&&!Array.isArray(r)&&typeof r.path=="string"&&typeof r.mimeType=="string"&&(i={path:r.path,mimeType:r.mimeType,...typeof r.language=="string"?{language:r.language}:{}}),m({type:"artifact_start",id:o,artifactType:t,title:s,component:typeof e.component=="string"?e.component:void 0,...i?{file:i}:{}}),J.set(o,{markdown:"",title:s,file:i}),!ge.has(o)){ge.add(o);let l=me(c.config().features?.artifacts,{artifactType:t,...i?{file:i}:{}}),a=typeof e.component=="string"?e.component:void 0,w={id:`artifact-ref-${o}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:ye(l,{artifactId:o,title:s,artifactType:t,status:"streaming",...i?{file:i}:{},...a?{component:a}:{}})};re.set(o,w),d(w)}}else if(e.type==="artifact_delta"){let t=String(e.id),o=typeof e.delta=="string"?e.delta:String(e.delta??"");m({type:"artifact_delta",id:t,artDelta:o});let s=J.get(t);s&&(s.markdown+=o)}else if(e.type==="artifact_update"){let t=e.props&&typeof e.props=="object"&&!Array.isArray(e.props)?e.props:{};m({type:"artifact_update",id:String(e.id),props:t,component:typeof e.component=="string"?e.component:void 0});let o=J.get(String(e.id));o&&(o.props={...o.props??{},...t})}else if(e.type==="artifact_complete"){let t=String(e.id);m({type:"artifact_complete",id:t});let o=re.get(t);if(o){o.streaming=!1;try{let s=JSON.parse(o.rawContent??"{}");if(s.props){s.props.status="complete";let r=J.get(t);r?.markdown&&(s.props.markdown=r.markdown),r?.file&&(s.props.file=r.file),s.component==="PersonaArtifactInline"&&r?.props&&Object.keys(r.props).length>0&&(s.props.componentProps=r.props)}o.rawContent=JSON.stringify(s)}catch{}J.delete(t),d(o),re.delete(t)}}}else if(e.type==="error"&&e.recoverable===!1&&e.error!=null&&e.error!==""){let t=typeof e.error=="string"?e.error:e.error?.message!=null?String(e.error.message):"Execution error";m({type:"error",error:new Error(t)});let o=f;o&&o.streaming&&(o.streaming=!1,d(o)),m({type:"status",status:"idle"})}}}G.length=0};;){let{done:n,value:e}=await x.read();if(n)break;y+=A.decode(e,{stream:!0});let t=y.split(`
2
+
3
+ `);y=t.pop()??"";for(let o of t){let s=o.split(`
4
+ `),r="message",i="",l=null;for(let g of s)g.startsWith("event:")?r=g.replace("event:","").trim():g.startsWith("data:")?i+=g.replace("data:","").trim():g.startsWith("id:")&&(l=g.slice(3).trim());let a=()=>{l!==null&&l!==""&&m({type:"cursor",id:l})};if(!i){a();continue}let w;try{w=JSON.parse(i)}catch(g){m({type:"error",error:g instanceof Error?g:new Error("Failed to parse chat stream payload")});continue}let C=w!==null&&typeof w=="object"&&!Array.isArray(w)?w:null,I=r!=="message"?r:typeof C?.type=="string"?C.type:"message";if(c.onSSEEvent?.(I,w),c.parseSSEEvent){O.current=f;let g=await be(c,w,m,O,d,p,Ce);if(O.current&&O.current!==f&&(f=O.current),g){a();continue}}C&&(G.push({...C,type:I}),le()),a()}}le()}export{We as preferFinalStructuredContent,Te as resolveApproval,Se as resumeFlow,Ee as streamResponse};
@@ -0,0 +1,5 @@
1
+ var Je=Object.create;var Ie=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var Ce=(n,a)=>()=>(a||n((a={exports:{}}).exports,a),a.exports);var Ve=(n,a,c,r)=>{if(a&&typeof a=="object"||typeof a=="function")for(let g of Ke(a))!Xe.call(n,g)&&g!==c&&Ie(n,g,{get:()=>a[g],enumerable:!(r=Qe(a,g))||r.enumerable});return n};var Ee=(n,a,c)=>(c=n!=null?Je(Ge(n)):{},Ve(a||!n||!n.__esModule?Ie(c,"default",{value:n,enumerable:!0}):c,n));var xe=Ce(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.Allow=u.ALL=u.COLLECTION=u.ATOM=u.SPECIAL=u.INF=u._INFINITY=u.INFINITY=u.NAN=u.BOOL=u.NULL=u.OBJ=u.ARR=u.NUM=u.STR=void 0;u.STR=1;u.NUM=2;u.ARR=4;u.OBJ=8;u.NULL=16;u.BOOL=32;u.NAN=64;u.INFINITY=128;u._INFINITY=256;u.INF=u.INFINITY|u._INFINITY;u.SPECIAL=u.NULL|u.BOOL|u.INF|u.NAN;u.ATOM=u.STR|u.NUM|u.SPECIAL;u.COLLECTION=u.ARR|u.OBJ;u.ALL=u.ATOM|u.COLLECTION;u.Allow={STR:u.STR,NUM:u.NUM,ARR:u.ARR,OBJ:u.OBJ,NULL:u.NULL,BOOL:u.BOOL,NAN:u.NAN,INFINITY:u.INFINITY,_INFINITY:u._INFINITY,INF:u.INF,SPECIAL:u.SPECIAL,ATOM:u.ATOM,COLLECTION:u.COLLECTION,ALL:u.ALL};u.default=u.Allow});var he=Ce(C=>{"use strict";var Ze=C&&C.__createBinding||(Object.create?(function(n,a,c,r){r===void 0&&(r=c);var g=Object.getOwnPropertyDescriptor(a,c);(!g||("get"in g?!a.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return a[c]}}),Object.defineProperty(n,r,g)}):(function(n,a,c,r){r===void 0&&(r=c),n[r]=a[c]})),et=C&&C.__exportStar||function(n,a){for(var c in n)c!=="default"&&!Object.prototype.hasOwnProperty.call(a,c)&&Ze(a,n,c)};Object.defineProperty(C,"__esModule",{value:!0});C.Allow=C.MalformedJSON=C.PartialJSON=C.parseJSON=C.parse=void 0;var P=xe();Object.defineProperty(C,"Allow",{enumerable:!0,get:function(){return P.Allow}});et(xe(),C);var ie=class extends Error{};C.PartialJSON=ie;var ae=class extends Error{};C.MalformedJSON=ae;function Ne(n,a=P.Allow.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return tt(n.trim(),a)}C.parseJSON=Ne;var tt=(n,a)=>{let c=n.length,r=0,g=w=>{throw new ie(`${w} at position ${r}`)},h=w=>{throw new ae(`${w} at position ${r}`)},T=()=>(E(),r>=c&&g("Unexpected end of input"),n[r]==='"'?y():n[r]==="{"?S():n[r]==="["?L():n.substring(r,r+4)==="null"||P.Allow.NULL&a&&c-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||P.Allow.BOOL&a&&c-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||P.Allow.BOOL&a&&c-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||P.Allow.INFINITY&a&&c-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||P.Allow._INFINITY&a&&1<c-r&&c-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||P.Allow.NAN&a&&c-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):b()),y=()=>{let w=r,p=!1;for(r++;r<c&&(n[r]!=='"'||p&&n[r-1]==="\\");)p=n[r]==="\\"?!p:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(w,++r-Number(p)))}catch(A){h(String(A))}else if(P.Allow.STR&a)try{return JSON.parse(n.substring(w,r-Number(p))+'"')}catch{return JSON.parse(n.substring(w,n.lastIndexOf("\\"))+'"')}g("Unterminated string literal")},S=()=>{r++,E();let w={};try{for(;n[r]!=="}";){if(E(),r>=c&&P.Allow.OBJ&a)return w;let p=y();E(),r++;try{let A=T();w[p]=A}catch(A){if(P.Allow.OBJ&a)return w;throw A}E(),n[r]===","&&r++}}catch{if(P.Allow.OBJ&a)return w;g("Expected '}' at end of object")}return r++,w},L=()=>{r++;let w=[];try{for(;n[r]!=="]";)w.push(T()),E(),n[r]===","&&r++}catch{if(P.Allow.ARR&a)return w;g("Expected ']' at end of array")}return r++,w},b=()=>{if(r===0){n==="-"&&h("Not sure what '-' is");try{return JSON.parse(n)}catch(p){if(P.Allow.NUM&a)try{return JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}h(String(p))}}let w=r;for(n[r]==="-"&&r++;n[r]&&",]}".indexOf(n[r])===-1;)r++;r==c&&!(P.Allow.NUM&a)&&g("Unterminated number literal");try{return JSON.parse(n.substring(w,r))}catch{n.substring(w,r)==="-"&&g("Not sure what '-' is");try{return JSON.parse(n.substring(w,n.lastIndexOf("e")))}catch(A){h(String(A))}}},E=()=>{for(;r<c&&`
2
+ \r `.includes(n[r]);)r++};return T()},nt=Ne;C.parse=nt});var Ye="webmcp:";var Ae=n=>n.startsWith(Ye);function H(n){return n==="card"?"collapsed":n}function oe(n){return n.split(";",1)[0].trim().toLowerCase()}function ze(n,a){if(!n)return;let c=Object.entries(n);for(let[g,h]of c)if(oe(g)===a)return{mode:H(h),selector:oe(g)};let r=`${a.split("/",1)[0]}/*`;for(let[g,h]of c)if(oe(g)===r)return{mode:H(h),selector:r}}function je(n,a){let c=n?.display,r=typeof c=="string"?{default:c}:c??{};if(a.file&&r.files){if(typeof r.files=="string")return{mode:H(r.files),matchedBy:{type:"files"}};let y=a.file.mimeType?oe(a.file.mimeType):void 0,S=y?ze(r.files.byMediaType,y):void 0;if(y&&S)return{mode:S.mode,matchedBy:{type:"mediaType",mediaType:y,selector:S.selector}};if(r.files.default)return{mode:H(r.files.default),matchedBy:{type:"files"}}}let g=r.byKind?.[a.artifactType];if(g)return{mode:H(g),matchedBy:{type:"kind",kind:a.artifactType,configuredBy:"byKind"}};let h=r.byType?.[a.artifactType];if(h)return{mode:H(h),matchedBy:{type:"kind",kind:a.artifactType,configuredBy:"byType"}};let T=a.presentation?.preferredMode;return T?{mode:H(T),matchedBy:{type:"preferredMode"}}:r.default?{mode:H(r.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Pe(n,a){return je(n,a).mode}function Le(n,a){return JSON.stringify({component:n==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:a.artifactId,title:a.title,artifactType:a.artifactType,status:a.status,...a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{},...n==="inline"&&a.component?{component:a.component}:{},...n==="inline"&&a.componentProps?{componentProps:a.componentProps}:{},...a.markdown!==void 0?{markdown:a.markdown}:{}}})}var be=Ee(he(),1);var j=n=>{try{let a=JSON.parse(n);if(a&&typeof a=="object"&&typeof a.text=="string")return a.text}catch{return null}return null};var le=Ee(he(),1);var _e="ask_user_question",We=8;var rt="suggest_replies";var st={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},Oe={name:rt,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:st,origin:"sdk",annotations:{readOnlyHint:!0}};var Re=new Set,ot=(n,a,c)=>{let r=`${n}:${a}:${c}`;Re.has(r)||(Re.add(r),console.warn(`[persona] suggestions.followUps.${n} and features.suggestReplies.${n} disagree; suggestions.followUps.${n} wins.`))},ve=n=>{let a=n?.suggestions?.followUps,c=n?.features?.suggestReplies,r=T=>{let y=a?.[T],S=c?.[T];y===void 0||S===void 0||y!==S&&ot(T,S,y)};n&&(r("enabled"),r("expose"));let g=a?.enabled??c?.enabled??!0,h=g?a?.expose??c?.expose??!1:!1;return{enabled:g,expose:h}};var it={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:We,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},at={name:_e,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:it,origin:"sdk",annotations:{readOnlyHint:!0}},Ue=n=>{let a=[],c=n?.features?.askUserQuestion;return c?.expose===!0&&c.enabled!==!1&&a.push(at),ve(n).expose&&a.push(Oe),a};var lt=1e5,Et=lt+1,Fe="https://api.runtype.com";async function ct(n,a,c){let r={"Content-Type":"application/json",...n.headers};n.getHeaders&&Object.assign(r,await n.getHeaders());let g={executionId:a.executionId,approvalId:a.approvalId,decision:c,streamResponse:!0},h=(L,b)=>fetch(`${n.clientApiBase()}${L}`,{method:"POST",headers:r,body:JSON.stringify({...b,...g})}),T=`/v1/agents/${a.agentId}/approve`;if(!n.isClientTokenMode())return h(T);let{sessionId:y}=await n.initSession(),S=await h("/v1/client/approve",{sessionId:y});if(S.status===404){let L=await S.clone().json().catch(()=>null);if(!L||L.error==="Not Found")return h(T)}return S}async function ut(n,a,c,r){let g=n.isClientTokenMode(),h=g?n.getClientApiUrl("resume"):`${n.config.apiUrl?.replace(/\/+$/,"")||Fe}/resume`,T,y=null;if(g){let b=await n.initSession();T=b.sessionId,b.durableRecovery?.enabled===!0&&(y=await n.readVisitorToken())}let S={"Content-Type":"application/json",...y?{"X-Visitor-Token":y}:{},...n.headers};n.getHeaders&&Object.assign(S,await n.getHeaders());let L={executionId:a,toolOutputs:c,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(T&&(L.sessionId=T),g&&T){let b=[...Ue(n.config),...await(await n.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:E,commit:w}=await n.sendWithClientToolsDiff(T,b,p=>{let A={...L,...p};return n.debug&&console.debug("[AgentWidgetClient] client token resume",A),fetch(h,{method:"POST",headers:S,body:JSON.stringify(A),signal:r?.signal})},{emptyMeansReplace:!0});return E.ok&&w(),E}return fetch(h,{method:"POST",headers:S,body:JSON.stringify(L),signal:r?.signal})}function dt(n){let a=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[a];if(r)return`attachment.${r}`;let g=a.indexOf("/");if(g>0){let h=a.slice(g+1).split(";")[0]?.trim()??"";if(h&&h!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(h))return`attachment.${h}`}return"attachment"}var De=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function pt(n,a){if(!n)return a;let c=n.trim(),r=a.trim();if(c.length===0)return a;if(r.length===0)return n;let g=De(c);if(!De(r))return n;if(!g||r===c||r.startsWith(c))return a;let T=j(n);return j(a)!==null&&T===null?a:n}async function gt(n,a,c,r,g,h,T){if(!n.parseSSEEvent)return!1;try{let y=await n.parseSSEEvent(a);if(y===null)return!1;let S=b=>{let E={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:h(),...b!==void 0&&{partId:b}};return r.current=E,g(E),E},L=b=>r.current?r.current:S(b);if(y.text!==void 0){y.partId!==void 0&&T.current!==null&&y.partId!==T.current&&(r.current&&(r.current.streaming=!1,g(r.current)),S(y.partId)),y.partId!==void 0&&(T.current=y.partId);let b=L(y.partId);y.partId!==void 0&&!b.partId&&(b.partId=y.partId),b.content+=y.text,g(b)}return y.done&&(r.current&&(r.current.streaming=!1,g(r.current)),T.current=null,c({type:"status",status:"idle"})),y.error&&(T.current=null,c({type:"error",error:new Error(y.error)})),!0}catch(y){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",y),!1}}async function vt(n,a,c,r,g){let h=a.getReader(),T=new TextDecoder,y="",S=Date.now(),L=0,b=()=>S+L++,E=s=>{let e=s.reasoning?{...s.reasoning,chunks:[...s.reasoning.chunks]}:void 0,t=s.toolCall?{...s.toolCall,chunks:s.toolCall.chunks?[...s.toolCall.chunks]:void 0}:void 0,o=s.tools?s.tools.map(i=>({...i,chunks:i.chunks?[...i.chunks]:void 0})):void 0;return{...s,reasoning:e,toolCall:t,tools:o}},w=s=>{if(s.role!=="assistant"||s.variant)return!0;let e=Array.isArray(s.contentParts)&&s.contentParts.length>0,t=typeof s.rawContent=="string"&&s.rawContent.trim()!=="";return typeof s.content=="string"&&s.content.trim()!==""||e||t||!!s.stopReason},p=s=>{w(s)&&c({type:"message",message:E(s)})},A=null,Z=null,J={current:null},Be={current:null},q=null,D="",B=new Map,v=new Map,ce=new Map,ee=new Map,ue=new Map,te=r,Te=!1,de=()=>{if(A)return A;let s,e="",t=q;return!Te&&te?(s=te,Te=!0,e=g??""):te&&t?s=`${te}_${t}`:s=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,A={id:s,role:"assistant",content:e,createdAt:new Date().toISOString(),streaming:!0,sequence:b()},p(A),A},pe=s=>{let e=ee.get(s);if(e)return e;let t={id:`reason-${s}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:b(),reasoning:{id:s,status:"streaming",chunks:[]}};return ee.set(s,t),p(t),t},G=new Set,ge=new Map,Me=new Set,X=new Map,He=s=>{if(!s)return!1;let e=s.replace(/_+/g,"_").replace(/^_|_$/g,"");return e==="emit_artifact_markdown"||e==="emit_artifact_component"},V=s=>{let e=ue.get(s);if(e)return e;let t={id:`tool-${s}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:b(),toolCall:{id:s,status:"pending"}};return ue.set(s,t),p(t),t},ke=s=>{if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"){let e=Number(s);if(!Number.isNaN(e)&&Number.isFinite(e))return e;let t=Date.parse(s);if(!Number.isNaN(t))return t}return Date.now()},fe=s=>{if(typeof s=="string")return s;if(s==null)return"";try{return JSON.stringify(s)}catch{return String(s)}},N=new Map,_=new Map,qe=(s,e)=>{let t=fe(e),o=_.get(s.id),i=pt(o,t);s.rawContent=i;let l=N.get(s.id),d=M=>{let x=s.content??"";M.trim()!==""&&(x.trim().length===0||M.startsWith(x)||M.trimStart().startsWith(x.trim()))&&(s.content=M)},m=()=>{if(l){let M=l.close?.();M instanceof Promise&&M.catch(()=>{})}N.delete(s.id),_.delete(s.id),s.streaming=!1,p(s)};if(!l){d(t),m();return}let f=j(i);if(f!==null&&f.trim()!==""){d(f),m();return}let k=M=>{let x=typeof M=="string"?M:M?.text??null;if(x!==null&&x.trim()!=="")return x;let F=l.getExtractedText();return F!==null&&F.trim()!==""?F:t},I;try{I=l.processChunk(i)}catch{d(t),m();return}if(I instanceof Promise){I.then(M=>{d(k(M)),m()}).catch(()=>{d(t),m()});return}d(k(I)),m()},Y=null,me=(s,e,t,o)=>{s.rawContent=e,N.has(s.id)||N.set(s.id,n.createStreamParser());let i=N.get(s.id),l=e.trim().startsWith("{")||e.trim().startsWith("[");if(l&&_.set(s.id,e),i.__isPlainTextParser===!0){s.content=o!==void 0?e:s.content+t,_.delete(s.id),N.delete(s.id),s.rawContent=void 0,p(s);return}let m=i.processChunk(e);if(m instanceof Promise)m.then(f=>{let k=typeof f=="string"?f:f?.text??null;k!==null&&k.trim()!==""?(s.content=k,p(s)):!l&&!e.trim().startsWith("<")&&(s.content=o!==void 0?e:s.content+t,_.delete(s.id),N.delete(s.id),s.rawContent=void 0,p(s))}).catch(()=>{s.content=o!==void 0?e:s.content+t,_.delete(s.id),N.delete(s.id),s.rawContent=void 0,p(s)});else{let f=typeof m=="string"?m:m?.text??null;f!==null&&f.trim()!==""?(s.content=f,p(s)):!l&&!e.trim().startsWith("<")&&(s.content=o!==void 0?e:s.content+t,_.delete(s.id),N.delete(s.id),s.rawContent=void 0,p(s))}},z=(s,e)=>{let t=e??s.content;if(t==null||t===""){s.streaming=!1,p(s);return}let i=_.get(s.id)??fe(t);s.rawContent=i;let l=N.get(s.id),d=null,m=!1;if(l&&(d=l.getExtractedText(),d===null&&(d=j(i)),d===null)){let f=l.processChunk(i);f instanceof Promise?(m=!0,f.then(k=>{let I=typeof k=="string"?k:k?.text??null;I!==null&&(s.content=I,s.streaming=!1,N.delete(s.id),_.delete(s.id),p(s))}).catch(()=>{})):d=typeof f=="string"?f:f?.text??null}if(!m){d!==null&&d.trim()!==""?s.content=d:_.has(s.id)||(s.content=fe(t));let f=N.get(s.id);if(f){let k=f.close?.();k instanceof Promise&&k.catch(()=>{}),N.delete(s.id)}_.delete(s.id),s.streaming=!1,p(s)}},we=(s,e,t)=>{let o=v.get(s);if(o)return o;let i={id:`nested-${e}-${s}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:b(),...t?{variant:t}:{},...t==="reasoning"?{reasoning:{id:s,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:e}};return v.set(s,i),p(i),i},ne=[],ye,re=new Map,U=0,$="agent",Se=!1,se=null,Q=null,$e=n.config().iterationDisplay??"separate";for(ye=()=>{for(let s=0;s<ne.length;s++){let e=ne[s];if(!Se&&$!=="flow"&&typeof e.stepType=="string"&&($="flow"),e.type==="reasoning_start"){let t=typeof e.id=="string"?e.id:null,o=typeof e.parentToolCallId=="string"&&e.parentToolCallId?e.parentToolCallId:null;if(t&&o){B.set(t,o),we(t,o,"reasoning");continue}let i=e.id,l=pe(i);l.reasoning=l.reasoning??{id:i,status:"streaming",chunks:[]},l.reasoning.startedAt=l.reasoning.startedAt??Date.now(),l.reasoning.completedAt=void 0,l.reasoning.durationMs=void 0,(e.scope==="loop"||e.scope==="turn")&&(l.reasoning.scope=e.scope),l.streaming=!0,l.reasoning.status="streaming",p(l)}else if(e.type==="reasoning_delta"){let t=typeof e.id=="string"?e.id:null;if(t&&B.has(t)&&v.has(t)){let l=v.get(t),d=e.delta;d&&l.reasoning&&(l.reasoning.chunks.push(String(d)),p(l));continue}let o=e.id,i=pe(o);i.reasoning=i.reasoning??{id:o,status:"streaming",chunks:[]},i.reasoning.startedAt=i.reasoning.startedAt??Date.now(),e.delta&&i.reasoning.chunks.push(e.delta),i.reasoning.status="streaming",i.streaming=!0,p(i)}else if(e.type==="reasoning_complete"){let t=typeof e.id=="string"?e.id:null;if(t&&B.has(t)&&v.has(t)){let d=v.get(t);if(d.reasoning){let m=typeof e.text=="string"?e.text:"";m&&d.reasoning.chunks.length===0&&d.reasoning.chunks.push(m),d.reasoning.status="complete",d.streaming=!1,p(d)}B.delete(t),v.delete(t);continue}let o=e.id,i=typeof e.text=="string"?e.text:"";!ee.get(o)&&(i||e.scope==="loop")&&pe(o);let l=ee.get(o);if(l?.reasoning){(e.scope==="loop"||e.scope==="turn")&&(l.reasoning.scope=e.scope),i&&l.reasoning.chunks.length===0&&l.reasoning.chunks.push(i),l.reasoning.status="complete",l.reasoning.completedAt=Date.now();let d=l.reasoning.startedAt??Date.now();l.reasoning.durationMs=Math.max(0,(l.reasoning.completedAt??Date.now())-d),l.streaming=!1,p(l)}}else if(e.type==="tool_start"){A&&(A.streaming=!1,p(A),A=null),typeof e.iteration=="number"&&(U=e.iteration);let t=e.toolCallId,o=e.toolName;if(He(o)){G.add(t);continue}let i=V(t),l=i.toolCall??{id:t,status:"pending"};l.name=o??l.name,l.status="running",l.success=void 0,l.error=void 0,l.duration=void 0,e.parameters!==void 0&&(l.args=e.parameters),l.startedAt=l.startedAt??ke(e.startedAt),l.completedAt=void 0,l.durationMs=void 0,i.toolCall=l,i.streaming=!0,e.executionId&&(i.agentMetadata={executionId:e.executionId,iteration:e.iteration}),p(i)}else if(e.type==="tool_output_delta"){let t=e.toolCallId;if(G.has(t))continue;let o=V(t),i=o.toolCall??{id:t,status:"running"};i.startedAt=i.startedAt??Date.now();let l=e.delta;l&&(i.chunks=i.chunks??[],i.chunks.push(String(l))),i.status="running",o.toolCall=i,o.streaming=!0,e.executionId&&(o.agentMetadata=o.agentMetadata??{executionId:e.executionId,iteration:U}),p(o)}else if(e.type==="tool_complete"){let t=e.toolCallId;if(G.has(t)){G.delete(t);continue}let o=V(t),i=o.toolCall??{id:t,status:"running"};i.status="complete",e.result!==void 0&&(i.result=e.result),i.name=e.toolName??i.name,i.success=e.success,i.error=e.error,i.completedAt=Date.now();let l=e.executionTime;if(typeof l=="number")i.durationMs=l,i.duration=l;else{let d=i.startedAt??Date.now();i.durationMs=Math.max(0,(i.completedAt??Date.now())-d)}o.toolCall=i,o.streaming=!1,e.executionId&&(o.agentMetadata=o.agentMetadata??{executionId:e.executionId,iteration:e.iteration??U}),p(o)}else if(e.type==="await"&&e.toolName){let t=typeof e.toolCallId=="string"&&e.toolCallId.length>0?e.toolCallId:void 0,o=t??e.toolId??`local-${b()}`,i=V(o),l=e.toolName,d=e.origin==="webmcp"&&!Ae(l)?`webmcp:${l}`:l,m=Ae(d),f=i.toolCall??{id:o,status:"pending"};f.name=d,f.args=e.parameters,f.status=m?"running":"complete",f.chunks=f.chunks??[],f.startedAt=f.startedAt??ke(e.awaitedAt),m?(f.completedAt=void 0,f.duration=void 0,f.durationMs=void 0):f.completedAt=f.completedAt??f.startedAt,i.toolCall=f,i.streaming=!1,i.agentMetadata={...i.agentMetadata,executionId:e.executionId??i.agentMetadata?.executionId,awaitingLocalTool:!0,...t?{webMcpToolCallId:t}:{}},p(i)}else if(e.type==="text_start"){let t=typeof e.id=="string"?e.id:null,o=typeof e.parentToolCallId=="string"&&e.parentToolCallId?e.parentToolCallId:null;if(t&&o){B.set(t,o);continue}let i=A;i&&($==="flow"?(z(i),Y=i):(i.streaming=!1,p(i)),A=null),q=typeof e.id=="string"?e.id:q,D=""}else if(e.type==="text_delta"){let t=typeof e.id=="string"?e.id:null,o=t?B.get(t):void 0;if(t&&o){let d=typeof e.delta=="string"?e.delta:"",m=(ce.get(t)??"")+d;if(ce.set(t,m),m.trim()==="")continue;let f=we(t,o);f.agentMetadata={...f.agentMetadata,executionId:e.executionId,parentToolId:o},me(f,m,d,void 0);continue}if(q=typeof e.id=="string"?e.id:q,$==="flow"){let d=typeof e.delta=="string"?e.delta:"";if(D+=d,D.trim()==="")continue;let m=de();m.agentMetadata={executionId:e.executionId,iteration:U},me(m,D,d,void 0),Z=m;continue}let i=typeof e.delta=="string"?e.delta:"";D+=i;let l=de();l.agentMetadata={executionId:e.executionId,iteration:U,turnId:se??void 0,agentName:Q?.agentName},me(l,D,i,void 0),Z=l}else if(e.type==="text_complete"){let t=typeof e.id=="string"?e.id:null;if(t&&B.has(t)){let i=v.get(t);i&&z(i),B.delete(t),ce.delete(t),v.delete(t);continue}let o=A;o&&($==="flow"?(z(o),Y=o):((o.content??"")===""&&typeof e.text=="string"&&(o.content=e.text),o.streaming=!1,p(o)),A=null),q=null,D=""}else if(e.type==="step_complete"){if(e.stepType==="tool")continue;if(e.success===!1){let t=e.error||"Step failed";c({type:"error",error:new Error(t)});let o=A;o&&o.streaming&&(o.streaming=!1,p(o)),c({type:"status",status:"idle"});continue}{let t=Y;Y=null;let o=e.stopReason,l=(e.result&&typeof e.result=="object"?e.result:null)?.response;if(t)o&&(t.stopReason=o),l!=null?qe(t,l):t.streaming!==!1&&(N.delete(t.id),_.delete(t.id),t.streaming=!1,p(t));else{let d=l!=null&&l!=="";if(d||o){let m=de();o&&(m.stopReason=o),d?z(m,l):(m.streaming=!1,p(m))}}continue}}else if(e.type==="execution_start")$=e.kind==="flow"?"flow":"agent",Se=!0,$==="agent"&&(Q={executionId:e.executionId,agentId:e.agentId??"virtual",agentName:e.agentName??""});else if(e.type==="turn_start"){let t=typeof e.iteration=="number"?e.iteration:U;if(t!==U){if($e==="separate"&&t>1){let o=A;o&&(o.streaming=!1,p(o),A=null)}U=t}se=typeof e.id=="string"?e.id:null,Z=null}else if(e.type==="tool_input_delta"){let t=e.toolCallId;if(t){let o=ue.get(t);o?.toolCall&&(o.toolCall.chunks=o.toolCall.chunks??[],o.toolCall.chunks.push(e.delta??""),p(o))}}else if(e.type==="tool_input_complete"){if(G.has(e.toolCallId))continue;let t=V(e.toolCallId),o=t.toolCall;o.args=e.parameters,o.name=e.toolName??o.name,p(t)}else if(e.type==="turn_complete"){let t=e.stopReason,o=A??Z;if(t&&o!==null){let i=e.id;(!i||o.agentMetadata?.turnId===i)&&(o.stopReason=t,p(o))}se===e.id&&(se=null)}else if(e.type==="media_start"){let t=String(e.id);re.set(t,{mediaType:typeof e.mediaType=="string"?e.mediaType:void 0,toolCallId:e.toolCallId,parts:[]})}else if(e.type==="media_delta"){let t=re.get(String(e.id));t&&typeof e.delta=="string"&&t.parts.push(e.delta)}else if(e.type==="media_complete"){let t=String(e.id),o=re.get(t);re.delete(t);let i=(typeof e.mediaType=="string"?e.mediaType:void 0)??o?.mediaType??"application/octet-stream",l=typeof e.data=="string"?e.data:void 0,d=typeof e.url=="string"?e.url:o&&o.parts.length>0?o.parts.join(""):void 0,m=null;if(l)m={type:"media",data:l,mediaType:i};else if(d){let M=i.toLowerCase();m={type:M==="image"||M.startsWith("image/")?"image-url":"file-url",url:d,mediaType:i}}let f=e.toolCallId??o?.toolCallId,k=m?[m]:[],I=[];for(let M of k){if(!M||typeof M!="object")continue;let x=M,F=typeof x.type=="string"?x.type:void 0,K=typeof x.mediaType=="string"?x.mediaType.toLowerCase():"",W=null,R="";if(F==="media"){let O=typeof x.data=="string"?x.data:void 0;if(!O)continue;R=K.length>0?K:"application/octet-stream",W=`data:${R};base64,${O}`}else if(F==="image-url"){let O=typeof x.url=="string"?x.url:void 0;if(!O)continue;R=K,W=O}else if(F==="file-url"){let O=typeof x.url=="string"?x.url:void 0;if(!O)continue;R=K,W=O}else continue;if(W)if(F==="image-url"||R.startsWith("image/"))I.push({type:"image",image:W,...R.includes("/")?{mimeType:R}:{}});else if(R.startsWith("audio/"))I.push({type:"audio",audio:W,mimeType:R});else if(R.startsWith("video/"))I.push({type:"video",video:W,mimeType:R});else{let O=R||"application/octet-stream";I.push({type:"file",data:W,mimeType:O,filename:dt(O)})}}if(I.length>0){let M=b(),x=f,K={id:`agent-media-${typeof x=="string"&&x.length>0?`${x}-${M}`:String(M)}`,role:"assistant",content:"",contentParts:I,createdAt:new Date().toISOString(),streaming:!1,sequence:M,agentMetadata:{executionId:e.executionId,iteration:U}};p(K);let W=A;W&&(W.streaming=!1,p(W)),A=null,J.current=null}}else if(e.type==="execution_complete"){let t=A;t&&(e.kind==="flow"&&t.streaming!==!1?z(t):(t.streaming=!1,p(t)),A=null),q=null,D="",Y=null,c({type:"status",status:"idle",terminal:!0})}else if(e.type==="execution_error"){let t=typeof e.error=="string"?e.error:e.error?.message??"Execution error";c({type:"error",error:new Error(t)})}else if(e.type!=="ping"){if(e.type==="approval_start"){let t=e.approvalId??`approval-${b()}`,o={id:`approval-${t}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:b(),approval:{id:t,status:"pending",agentId:Q?.agentId??"virtual",executionId:e.executionId??Q?.executionId??"",toolName:e.toolName??"",toolType:e.toolType,description:e.description??`Execute ${e.toolName??"tool"}`,...typeof e.reason=="string"&&e.reason?{reason:e.reason}:{},parameters:e.parameters,...typeof e.toolCallId=="string"&&e.toolCallId?{toolCallId:e.toolCallId}:{}}};p(o)}else if(e.type==="approval_complete"){let t=e.approvalId;if(t){let i={id:`approval-${t}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:b(),approval:{id:t,status:e.decision??"approved",agentId:Q?.agentId??"virtual",executionId:e.executionId??Q?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};p(i)}}else if(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete"){if(e.type==="artifact_start"){let t=e.artifactType,o=String(e.id),i=typeof e.title=="string"?e.title:void 0,l=e.file,d;if(l&&typeof l=="object"&&!Array.isArray(l)&&typeof l.path=="string"&&typeof l.mimeType=="string"&&(d={path:l.path,mimeType:l.mimeType,...typeof l.language=="string"?{language:l.language}:{}}),c({type:"artifact_start",id:o,artifactType:t,title:i,component:typeof e.component=="string"?e.component:void 0,...d?{file:d}:{}}),X.set(o,{markdown:"",title:i,file:d}),!Me.has(o)){Me.add(o);let m=Pe(n.config().features?.artifacts,{artifactType:t,...d?{file:d}:{}}),f=typeof e.component=="string"?e.component:void 0,k={id:`artifact-ref-${o}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:b(),rawContent:Le(m,{artifactId:o,title:i,artifactType:t,status:"streaming",...d?{file:d}:{},...f?{component:f}:{}})};ge.set(o,k),p(k)}}else if(e.type==="artifact_delta"){let t=String(e.id),o=typeof e.delta=="string"?e.delta:String(e.delta??"");c({type:"artifact_delta",id:t,artDelta:o});let i=X.get(t);i&&(i.markdown+=o)}else if(e.type==="artifact_update"){let t=e.props&&typeof e.props=="object"&&!Array.isArray(e.props)?e.props:{};c({type:"artifact_update",id:String(e.id),props:t,component:typeof e.component=="string"?e.component:void 0});let o=X.get(String(e.id));o&&(o.props={...o.props??{},...t})}else if(e.type==="artifact_complete"){let t=String(e.id);c({type:"artifact_complete",id:t});let o=ge.get(t);if(o){o.streaming=!1;try{let i=JSON.parse(o.rawContent??"{}");if(i.props){i.props.status="complete";let l=X.get(t);l?.markdown&&(i.props.markdown=l.markdown),l?.file&&(i.props.file=l.file),i.component==="PersonaArtifactInline"&&l?.props&&Object.keys(l.props).length>0&&(i.props.componentProps=l.props)}o.rawContent=JSON.stringify(i)}catch{}X.delete(t),p(o),ge.delete(t)}}}else if(e.type==="error"&&e.recoverable===!1&&e.error!=null&&e.error!==""){let t=typeof e.error=="string"?e.error:e.error?.message!=null?String(e.error.message):"Execution error";c({type:"error",error:new Error(t)});let o=A;o&&o.streaming&&(o.streaming=!1,p(o)),c({type:"status",status:"idle"})}}}ne.length=0};;){let{done:s,value:e}=await h.read();if(s)break;y+=T.decode(e,{stream:!0});let t=y.split(`
3
+
4
+ `);y=t.pop()??"";for(let o of t){let i=o.split(`
5
+ `),l="message",d="",m=null;for(let x of i)x.startsWith("event:")?l=x.replace("event:","").trim():x.startsWith("data:")?d+=x.replace("data:","").trim():x.startsWith("id:")&&(m=x.slice(3).trim());let f=()=>{m!==null&&m!==""&&c({type:"cursor",id:m})};if(!d){f();continue}let k;try{k=JSON.parse(d)}catch(x){c({type:"error",error:x instanceof Error?x:new Error("Failed to parse chat stream payload")});continue}let I=k!==null&&typeof k=="object"&&!Array.isArray(k)?k:null,M=l!=="message"?l:typeof I?.type=="string"?I.type:"message";if(n.onSSEEvent?.(M,k),n.parseSSEEvent){J.current=A;let x=await gt(n,k,c,J,p,b,Be);if(J.current&&J.current!==A&&(A=J.current),x){f();continue}}I&&(ne.push({...I,type:M}),ye()),f()}}ye()}export{pt as preferFinalStructuredContent,ct as resolveApproval,ut as resumeFlow,vt as streamResponse};
package/dist/codegen.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var $=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var W=(e,i)=>{for(var r in i)$(e,r,{get:i[r],enumerable:!0})},H=(e,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of M(i))!R.call(e,a)&&a!==r&&$(e,a,{get:()=>i[a],enumerable:!(s=T(i,a))||s.enumerable});return e};var N=e=>H($({},"__esModule",{value:!0}),e);var X={};W(X,{generateCodeSnippet:()=>I});module.exports=N(X);var j="4.24.0";var A=j;function x(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${A}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function q(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var O=`({ text, message }: any) => {
1
+ "use strict";var $=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var W=(e,i)=>{for(var r in i)$(e,r,{get:i[r],enumerable:!0})},H=(e,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of M(i))!R.call(e,a)&&a!==r&&$(e,a,{get:()=>i[a],enumerable:!(s=T(i,a))||s.enumerable});return e};var N=e=>H($({},"__esModule",{value:!0}),e);var X={};W(X,{generateCodeSnippet:()=>I});module.exports=N(X);var j="4.26.0";var A=j;function x(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${A}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function q(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var O=`({ text, message }: any) => {
2
2
  const jsonSource = (message as any).rawContent || text || message.content;
3
3
  if (!jsonSource || typeof jsonSource !== 'string') return null;
4
4
  let cleanJson = jsonSource
package/dist/codegen.js CHANGED
@@ -1,4 +1,4 @@
1
- var S="4.24.0";var j=S;function $(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${j}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function _(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var A=`({ text, message }: any) => {
1
+ var S="4.26.0";var j=S;function $(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${j}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function _(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var A=`({ text, message }: any) => {
2
2
  const jsonSource = (message as any).rawContent || text || message.content;
3
3
  if (!jsonSource || typeof jsonSource !== 'string') return null;
4
4
  let cleanJson = jsonSource
@@ -0,0 +1,161 @@
1
+ import{a as X}from"./chunk-PDPVORUF.js";import{b as J,e as Z}from"./chunk-HGUCGM3K.js";import{a as ee,b as te}from"./chunk-Q735PSZL.js";import{a as $}from"./chunk-7NQ4ZTHF.js";import{a as S,c as M}from"./chunk-76IELU7F.js";import{a as j,c as Y}from"./chunk-IO5VVUKP.js";import{b as ne}from"./chunk-UPO4GUFC.js";import{X as pe}from"lucide";var ie=null,oe=s=>{ie=s},D=(s,e,t,n)=>ie?.(s,e,t,n)??null;function re(s){let{ref:e,config:t,onRemove:n}=s;if(t.renderMentionChip){let C="resolving",A,L=t.renderMentionChip({ref:e,status:C,payload:A,remove:n});return{get el(){return L},setStatus:(O,k)=>{if(O===C&&k===A)return;C=O,A=k;let z=t.renderMentionChip({ref:e,status:C,payload:A,remove:n});L.replaceWith(z),L=z}}}let i=e.iconName??t.chipIconName??"at-sign",o=M("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),r=S("span","persona-mention-chip-icon"),d=C=>{r.replaceChildren();let A=D(C,13,"currentColor",2);A&&r.appendChild(A)};d(i);let a=S("span","persona-mention-chip-spinner"),l=M("span",{className:"persona-mention-chip-label",text:e.label}),u=M("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),f=$(pe,11,"currentColor",2.5);return f?u.appendChild(f):u.textContent="\xD7",u.addEventListener("click",C=>{C.preventDefault(),C.stopPropagation(),n()}),o.appendChild(a),o.appendChild(l),o.appendChild(u),{el:o,setStatus:C=>{o.setAttribute("data-status",C),C==="resolving"?(a.parentNode!==o&&o.insertBefore(a,l),r.parentNode===o&&r.remove(),o.setAttribute("title",e.label)):(a.parentNode===o&&a.remove(),r.parentNode!==o&&o.insertBefore(r,l),C==="error"?(d("triangle-alert"),o.setAttribute("title",`Couldn't add ${e.label} to context`)):(d(i),o.setAttribute("title",e.label)))}}}function F(s,e){return{sourceId:s.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var se=(s,e)=>`${s}\0${e}`,V=class{constructor(e){this.mentions=[];this.#e=e,this.#r()}#e;get#c(){return this.#e.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(e,t,n=""){let i=se(e.id,t.id);if(this.mentions.some(d=>d.key===i))return this.#i(e,t,"duplicate");if(this.atLimit())return this.#i(e,t,"limit");let o=F(e,t),r={key:i,source:e,item:t,ref:o,status:"resolving",args:n};return r.chip=re({ref:o,config:this.#e.mentionConfig,onRemove:()=>this.remove(i)}),r.chip.el.setAttribute("data-persona-chip-enter",""),r.chip.el.addEventListener("animationend",()=>r.chip?.el.removeAttribute("data-persona-chip-enter"),{once:!0}),this.#e.contextRow.appendChild(r.chip.el),this.#h(r),this.#r(),!0}atLimit(){return this.mentions.length>=this.#c}admit(e,t){return this.atLimit()?this.#i(e,t,"limit"):!0}track(e,t,n,i="",o){let r={key:e,source:t,item:n,ref:F(t,n),status:"resolving",args:i,reportStatus:o};this.#h(r)}#i(e,t,n){return this.#e.mentionConfig.onMentionRejected?.(t,n),this.#e.emit?.("rejected",{sourceId:e.id,itemId:t.id,reason:n}),!1}#h(e){this.mentions.push(e),e.source.resolveOn==="submit"?(e.status="ready",e.chip?.setStatus("ready"),e.reportStatus?.("resolved")):e.resolvePromise=this.#s(e),this.#e.announce(`Added ${e.ref.label} to context`)}#C(e,t,n=this.#e.getComposerText()){return{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:n,args:t,signal:e}}async#s(e){let t=new AbortController;e.abort=t;try{let n=await e.source.resolve(e.item,this.#C(t.signal,e.args));if(t.signal.aborted)return;e.payload=n,e.status="ready",e.chip?.setStatus("ready",n),e.reportStatus?.("resolved")}catch(n){if(t.signal.aborted)return;e.status="error",e.chip?.setStatus("error"),e.reportStatus?.("error"),(this.#e.announceError??this.#e.announce)(`Couldn't attach ${e.ref.label} to context`),this.#e.mentionConfig.onMentionResolveError?.(e.item,n),this.#e.emit?.("resolve-error",{sourceId:e.source.id,itemId:e.item.id})}}remove(e){let t=this.mentions.findIndex(i=>i.key===e);if(t===-1)return;let[n]=this.mentions.splice(t,1);n.abort?.abort(),n.chip?.el.remove(),this.#r(),this.#e.announce(`Removed ${n.ref.label} from context`)}getRefs(){return this.mentions.map(e=>e.ref)}removeLast(){let e=this.mentions[this.mentions.length-1];return e?(this.remove(e.key),!0):!1}clear(){for(let e of this.mentions)e.abort?.abort(),e.chip?.el.remove();this.mentions.length=0,this.#r()}collectForSubmit(){let e=[...this.mentions],t=e.map(o=>o.ref),n=this.#e.getComposerText();for(let o of e)o.chip?.el.remove();return this.mentions.length=0,this.#r(),{refs:t,finalize:async()=>{let o=await Promise.all(e.map(async u=>{try{return u.source.resolveOn==="submit"?await u.source.resolve(u.item,this.#C(new AbortController().signal,u.args,n)):(u.resolvePromise&&await u.resolvePromise,u.payload??null)}catch(f){try{this.#e.mentionConfig.onMentionResolveError?.(u.item,f)}catch(x){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",x)}return this.#e.emit?.("resolve-error",{sourceId:u.source.id,itemId:u.item.id}),null}})),r=[],d=[],a={},l=new Set;for(let u=0;u<e.length;u++){let f=e[u],x=o[u];if(!x)continue;let C=se(f.source.id,f.item.id);if(!l.has(C)){if(l.add(C),x.llmAppend&&x.llmAppend.trim())try{r.push(Z({label:f.ref.label,text:x.llmAppend,ref:f.ref,item:f.item},r.length,this.#e.mentionConfig.llmFormat))}catch(A){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",A)}x.contentParts?.length&&d.push(...x.contentParts),x.context&&((a[f.source.id]??={})[f.item.id]=x.context)}}return{blocks:r,contentParts:d,context:a}}}}#r(){J(this.#e.contextRow)}};var ae=`
2
+ .persona-mention-menu {
3
+ box-sizing: border-box;
4
+ display: flex;
5
+ flex-direction: column;
6
+ max-height: var(--persona-mention-menu-max-height, 280px);
7
+ overflow: hidden;
8
+ background: var(--persona-mention-menu-bg, var(--persona-surface, #ffffff));
9
+ border: 1px solid var(--persona-mention-menu-border, var(--persona-border, #e5e7eb));
10
+ border-radius: var(--persona-mention-menu-radius, 10px);
11
+ box-shadow: var(--persona-mention-menu-shadow, 0 8px 28px rgba(0, 0, 0, 0.12));
12
+ font-family: var(--persona-font-family, inherit);
13
+ }
14
+ .persona-mention-list {
15
+ min-height: 0;
16
+ overflow-y: auto;
17
+ padding: 4px;
18
+ }
19
+ .persona-mention-search {
20
+ display: flex;
21
+ align-items: center;
22
+ gap: 6px;
23
+ padding: 8px 10px;
24
+ border-bottom: 1px solid var(--persona-mention-menu-border, var(--persona-border, #e5e7eb));
25
+ }
26
+ .persona-mention-search-icon {
27
+ display: inline-flex;
28
+ align-items: center;
29
+ flex: 0 0 auto;
30
+ color: var(--persona-mention-group-fg, var(--persona-muted, #6b7280));
31
+ }
32
+ .persona-mention-search-input {
33
+ flex: 1 1 auto;
34
+ min-width: 0;
35
+ padding: 0;
36
+ border: none;
37
+ outline: none;
38
+ background: transparent;
39
+ font-family: inherit;
40
+ /* 16px, not 14px: iOS Safari zooms the page when focusing an input under 16px. */
41
+ font-size: 16px;
42
+ line-height: 1.4;
43
+ color: var(--persona-text, #111827);
44
+ }
45
+ .persona-mention-search-input::placeholder {
46
+ color: var(--persona-mention-group-fg, var(--persona-muted, #6b7280));
47
+ }
48
+ .persona-mention-group + .persona-mention-group {
49
+ margin-top: 2px;
50
+ border-top: 1px solid var(--persona-mention-menu-border, var(--persona-border, #f1f1f1));
51
+ padding-top: 2px;
52
+ }
53
+ .persona-mention-group-header {
54
+ padding: 6px 8px 4px;
55
+ font-size: 11px;
56
+ font-weight: 600;
57
+ text-transform: uppercase;
58
+ letter-spacing: 0.04em;
59
+ color: var(--persona-mention-group-fg, var(--persona-muted, #6b7280));
60
+ }
61
+ .persona-mention-option {
62
+ display: flex;
63
+ align-items: center;
64
+ gap: 8px;
65
+ padding: 7px 8px;
66
+ border-radius: 6px;
67
+ cursor: pointer;
68
+ color: var(--persona-text, #111827);
69
+ }
70
+ .persona-mention-option[data-active="true"] {
71
+ background: var(--persona-mention-option-active-bg, var(--persona-container, #f1f5f9));
72
+ }
73
+ .persona-mention-option-icon {
74
+ display: inline-flex;
75
+ align-items: center;
76
+ flex: 0 0 auto;
77
+ opacity: 0.7;
78
+ }
79
+ .persona-mention-option-text {
80
+ display: flex;
81
+ flex-direction: column;
82
+ min-width: 0;
83
+ }
84
+ .persona-mention-option-labelline {
85
+ display: flex;
86
+ align-items: baseline;
87
+ gap: 6px;
88
+ min-width: 0;
89
+ }
90
+ .persona-mention-option-label {
91
+ font-size: 13px;
92
+ line-height: 1.3;
93
+ overflow: hidden;
94
+ text-overflow: ellipsis;
95
+ white-space: nowrap;
96
+ }
97
+ .persona-mention-option-arghint {
98
+ flex: 0 0 auto;
99
+ font-size: 12px;
100
+ line-height: 1.3;
101
+ color: var(--persona-muted, #6b7280);
102
+ opacity: 0.85;
103
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
104
+ }
105
+ .persona-mention-option-desc {
106
+ font-size: 11px;
107
+ line-height: 1.3;
108
+ color: var(--persona-muted, #6b7280);
109
+ overflow: hidden;
110
+ text-overflow: ellipsis;
111
+ white-space: nowrap;
112
+ }
113
+ .persona-mention-status,
114
+ .persona-mention-empty,
115
+ .persona-mention-hint {
116
+ padding: 7px 8px;
117
+ font-size: 12px;
118
+ color: var(--persona-muted, #6b7280);
119
+ }
120
+ .persona-mention-error {
121
+ display: flex;
122
+ align-items: center;
123
+ justify-content: space-between;
124
+ gap: 8px;
125
+ color: var(--persona-mention-error, #dc2626);
126
+ }
127
+ .persona-mention-error-text {
128
+ min-width: 0;
129
+ overflow: hidden;
130
+ text-overflow: ellipsis;
131
+ white-space: nowrap;
132
+ }
133
+ .persona-mention-retry {
134
+ flex: 0 0 auto;
135
+ padding: 4px 8px;
136
+ border: 1px solid var(--persona-mention-error, #dc2626);
137
+ border-radius: 6px;
138
+ background: transparent;
139
+ color: var(--persona-mention-error, #dc2626);
140
+ font: inherit;
141
+ font-size: 12px;
142
+ cursor: pointer;
143
+ }
144
+ .persona-mention-retry:hover {
145
+ background: var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.06));
146
+ }
147
+ .persona-mention-hint {
148
+ font-style: italic;
149
+ opacity: 0.8;
150
+ }
151
+ @media (pointer: coarse) {
152
+ .persona-mention-option {
153
+ min-height: 44px;
154
+ }
155
+ .persona-mention-retry {
156
+ min-height: 36px;
157
+ }
158
+ }
159
+ `;function _(s){let e=s.replace(/^\s+/,""),t=e.search(/\s/);return t===-1?{name:e,args:""}:{name:e.slice(0,t),args:e.slice(t+1).trim()}}import{Search as he}from"lucide";var le=new Map,me=(s,e,t)=>{let n=`${s}|${e}|${t}`,i=le.get(n);return i===void 0&&(i=D(s,e,"currentColor",t),le.set(n,i)),i?i.cloneNode(!0):null};function ce(s){let{config:e,listboxId:t}=s,n=M("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),i=M("div",{className:"persona-mention-search",style:{display:"none"}}),o=S("span","persona-mention-search-icon"),r=$(he,15,"currentColor",2);r&&o.appendChild(r);let d=M("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":t,"aria-label":e.searchPlaceholder??"Search context",placeholder:e.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});i.append(o,d),d.addEventListener("input",()=>s.onSearchInput?.(d.value)),d.addEventListener("keydown",c=>s.onSearchKeydown?.(c));let a=M("div",{className:"persona-mention-list",attrs:{role:"listbox",id:t,"aria-label":"Context mentions"}});n.append(i,a);let l=[],u=[],f=-1,x=new Map,C=(c,p)=>`${c}\0${p}`,A=c=>`${t}-opt-${c}`,L=c=>`${t}-grp-${c}`,G=(c,p)=>{let m=l[c];m&&(p?m.setAttribute("data-active","true"):m.removeAttribute("data-active"),m.setAttribute("aria-selected",p?"true":"false"),u[c]?.(p))},O=(c,p=!0)=>{f>=0&&f!==c&&G(f,!1),f=c;let m=l[c];m?(G(c,!0),p&&m.scrollIntoView?.({block:"nearest"}),a.setAttribute("aria-activedescendant",m.id),d.setAttribute("aria-activedescendant",m.id)):(a.removeAttribute("aria-activedescendant"),d.removeAttribute("aria-activedescendant"))},k=(c,p)=>{let m=L(p),v=M("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":m}});return v.appendChild(M("div",{className:"persona-mention-group-header",attrs:{id:m},text:c})),v},z=()=>{let c=M("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),p=S("span","persona-mention-option-icon");c.appendChild(p);let m="",v=S("span","persona-mention-option-text"),w=S("span","persona-mention-option-labelline"),I=S("span","persona-mention-option-label");w.appendChild(I),v.appendChild(w),c.appendChild(v);let y=null,b=null,g={el:c,index:0,update:(h,T,P)=>{g.index=T,c.id=A(T),c.setAttribute("aria-setsize",String(P)),c.setAttribute("aria-posinset",String(T+1)),c.removeAttribute("data-active"),c.setAttribute("aria-selected","false");let R=h.iconName??e.chipIconName??"at-sign";if(R!==m){m=R;let N=me(R,15,2);p.replaceChildren(...N?[N]:[])}I.textContent!==h.label&&(I.textContent=h.label);let W=h.commandArgsPlaceholder?`\u2039${h.commandArgsPlaceholder}\u203A`:null;W?(y||(y=S("span","persona-mention-option-arghint"),w.appendChild(y)),y.textContent!==W&&(y.textContent=W)):y&&(y.remove(),y=null),h.description?(b||(b=S("span","persona-mention-option-desc"),v.appendChild(b)),b.textContent!==h.description&&(b.textContent=h.description)):b&&(b.remove(),b=null)}};return c.addEventListener("mousedown",h=>{h.button===0&&(h.preventDefault(),s.onSelectIndex(g.index))}),c.addEventListener("mouseenter",()=>s.onHoverIndex(g.index)),g},de=(c,p,m,v,w)=>{let I=M("div",{className:"persona-mention-option",attrs:{role:"option",id:A(v),"aria-selected":"false","aria-setsize":String(w),"aria-posinset":String(v+1)}}),y=b=>{I.replaceChildren(e.renderMentionItem({item:c,source:p,query:m,active:b,index:v}))};return y(!1),I.addEventListener("mousedown",b=>{b.button===0&&(b.preventDefault(),s.onSelectIndex(v))}),I.addEventListener("mouseenter",()=>s.onHoverIndex(v)),{el:I,paint:y}},ue=c=>{let p=M("div",{className:"persona-mention-status persona-mention-error"});if(p.appendChild(M("span",{className:"persona-mention-error-text",text:`Couldn't load ${c.label}`})),s.onRetry){let m=M("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});m.addEventListener("mousedown",v=>v.preventDefault()),m.addEventListener("click",v=>{v.preventDefault(),s.onRetry(c.id)}),p.appendChild(m)}return p};return{el:n,render:c=>{a.replaceChildren(),l=[],u=[],f=-1;let p=new Set,m=0,v=0,w=0,I=0,y=0,b=c.groups.reduce((g,h)=>h.status==="ready"?g+h.items.length:g,0);for(let g of c.groups)if(g.status==="loading"){w++;let h=k(g.source.label,y++);h.appendChild(M("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),a.appendChild(h)}else if(g.status==="error"){I++;let h=k(g.source.label,y++);h.appendChild(ue(g.source)),a.appendChild(h)}else if(g.status==="ready"&&g.items.length>0){let h=new Map;for(let P of g.items){let R=P.group??g.source.label,W=h.get(R);W?W.push(P):h.set(R,[P])}let T=Array.from(h.entries());T.forEach(([P,R],W)=>{let N=k(P,y++);for(let K of R){let Q=m++,B;if(e.renderMentionItem){let E=de(K,g.source,c.query,Q,b);B=E.el,u.push(E.paint)}else{let E=C(g.source.id,K.id),H=p.has(E)?void 0:x.get(E);H||(H=z(),p.has(E)||x.set(E,H)),p.add(E),H.update(K,Q,b),B=H.el,u.push(null)}l.push(B),N.appendChild(B),v++}g.truncated&&W===T.length-1&&N.appendChild(M("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),a.appendChild(N)})}for(let g of x.keys())p.has(g)||x.delete(g);v===0&&w===0&&I===0&&a.appendChild(M("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),l.length>0?O(Math.min(Math.max(0,c.activeIndex),l.length-1)):(a.removeAttribute("aria-activedescendant"),d.removeAttribute("aria-activedescendant"))},setActiveIndex:O,destroy:()=>{a.replaceChildren(),l=[],x.clear(),n.remove()},showSearch:(c,p)=>{d.value=c,p&&(d.placeholder=p),i.style.display="",d.setAttribute("aria-expanded","true"),d.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{i.style.display!=="none"&&d.focus()})},hideSearch:()=>{i.style.display="none",d.value="",d.setAttribute("aria-expanded","false"),d.removeAttribute("aria-activedescendant")}}}var ge=s=>!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function",fe=0,q=class{#e;#c;#i;#h;#C;#s;#r;#u=null;#x=null;#a=!1;#d="";#n=null;#o=0;#A=null;#v=!1;#I=null;#l=[];#t=[];#m=0;#g=null;#p=null;#w=new Set;#R=new Set;#W=-1;#S=null;#L=null;constructor(e){this.#e=e;let t=e.mentionConfig,n=X(t),i=n.filter(r=>r.sources.length>0);this.#c=i.length>0?i:[n[0]],this.#i=this.#c[0],this.#h=t.maxItemsPerGroup??6,this.#C=t.searchDebounceMs??150,this.#r=`persona-mention-listbox-${++fe}`,this.#s=e.mentionConfig.renderMentionMenu?this.#j():ce({config:e.mentionConfig,listboxId:this.#r,onSelectIndex:r=>this.#D(r),onHoverIndex:r=>this.#y(r,!1),onRetry:r=>this.#J(r),onSearchInput:r=>this.#M(r),onSearchKeydown:r=>{this.handleKeydown(r)}});let o=e.composerInput.element;o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",this.#r)}get input(){return this.#e.composerInput}#j(){let e=document.createElement("div");e.setAttribute("data-persona-mention-menu",""),e.setAttribute("role","listbox"),e.id=this.#r;let t=()=>{let n=this.#e.mentionConfig.renderMentionMenu({query:this.#d,groups:this.#l.map(i=>({source:i.source,items:i.items})),status:Object.fromEntries(this.#l.map(i=>[i.source.id,i.status])),activeIndex:this.#o,select:i=>{let o=this.#l.find(r=>r.items.includes(i));o&&this.#V(o.source,i)},close:()=>this.close()});e.replaceChildren(n)};return{el:e,render:t,setActiveIndex:t,destroy:()=>e.remove()}}isOpen(){return this.#a}openFromButton(e){let t=e&&this.#c.find(r=>r.trigger===e)||this.#c[0],n=this.input.getSelection().start,i=j(this.input.getLogicalText(),n,[t]);if(i){this.#v=!1,this.#n=i.match,this.#a?(this.#E(t),this.#M(i.match.query)):this.#P(i.match.query,t),this.input.focus();return}let o=this.#I;this.#v=!0,this.#I=t.trigger,this.#n=null,this.#a?(o&&o!==t.trigger&&this.#e.onPickerOpenChange?.(!1,o,this.#r),this.#E(t),this.#M("")):this.#P("",t),this.#s.showSearch?this.#s.showSearch("",t.searchPlaceholder):this.input.focus(),this.#e.onPickerOpenChange?.(!0,t.trigger,this.#r)}onInput(){let e=this.input.getSelection().start,t=j(this.input.getLogicalText(),e,this.#c);if(!t){this.#a&&this.close();return}if(this.#te(t.channel,t.match.query)){this.#n=null,this.#a&&this.close(!1);return}this.#n=t.match,this.#a?(this.#E(t.channel),this.#L!==t.match.triggerIndex&&this.#k(),this.#M(t.match.query)):this.#P(t.match.query,t.channel)}#E(e){e!==this.#i&&(this.#i=e,this.#l=[],this.#o=0)}#P(e,t){if(this.#a=!0,this.#i=t,this.#l=[],this.#o=0,this.#W=-1,!this.#u){let n=this.#Q();if(this.#u=te({anchor:this.#e.anchor,content:this.#s.el,placement:"top-start",matchAnchorWidth:!n,offset:6,container:this.#e.popoverContainer,horizontalOffset:n?()=>this.#S?.x??null:void 0,verticalOffset:n?()=>this.#S?.y??null:void 0,onDismiss:()=>this.close(!1)}),n){let i=this.#e.anchor.getBoundingClientRect().width;this.#s.el.style.minWidth=`${Math.min(220,i)}px`}}this.#k(),this.#u.open(),ee(this.#s.el,"persona-mention-menu",ae),this.#U(),this.#e.emit?.("opened",{trigger:t.trigger}),this.#M(e)}#U(){typeof ResizeObserver>"u"||this.#x||(this.#x=new ResizeObserver(()=>{this.#a&&(this.#k(),this.#u?.reposition())}),this.#x.observe(this.#e.anchor))}#O(){this.#x?.disconnect(),this.#x=null}#Q(){return this.#_()&&!!this.input.getLogicalRangeRect}#k(){let e=this.#n,t=this.input.getLogicalRangeRect;if(this.#L=e?.triggerIndex??null,this.#S=null,!e||!t)return;let n=t(e.triggerIndex,e.triggerIndex+1);if(!n)return;let i=this.#e.anchor.getBoundingClientRect(),o=n.top-i.top,r=this.input.element,d=typeof getComputedStyle=="function"&&getComputedStyle(r).direction==="rtl";this.#S={x:d?null:n.left-i.left,y:o}}close(e=!0){this.#a&&(this.#a=!1,this.#O(),this.#p&&clearTimeout(this.#p),this.#g?.abort(),this.#m++,this.#u?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.#v&&(this.#v=!1,this.#s.hideSearch?.(),this.#e.onPickerOpenChange?.(!1,this.#I??this.#i.trigger,this.#r),this.#I=null,e&&this.input.focus()))}#M(e){this.#d=e,this.#o=0,this.#A=null;let t=++this.#m;this.#R.clear(),this.#g?.abort(),this.#g=new AbortController;for(let n of this.#i.sources)this.#w.has(n.id)?this.#b(n.id,"loading"):(this.#R.add(n.id),this.#T(n,t));this.#f(),this.#p&&clearTimeout(this.#p),this.#p=setTimeout(()=>{if(t===this.#m)for(let n of this.#i.sources)this.#w.has(n.id)&&!this.#R.has(n.id)&&this.#T(n,t)},this.#C)}#T(e,t){let n={messages:this.#e.getMessages(),config:this.#e.getConfig(),signal:this.#g.signal},i;try{i=e.search(this.#d,n)}catch{this.#b(e.id,"error"),this.#f();return}ge(i)?(this.#w.add(e.id),this.#b(e.id,"loading"),i.then(o=>{t===this.#m&&(this.#z(e.id,o),this.#f())}).catch(()=>{t===this.#m&&(this.#b(e.id,"error"),this.#f())})):this.#z(e.id,i)}#H(e){let t=this.#l.find(n=>n.source.id===e.id);if(!t){t={source:e,items:[],status:"loading",truncated:!1};let n=this.#i.sources;this.#l.push(t),this.#l.sort((i,o)=>n.findIndex(r=>r.id===i.source.id)-n.findIndex(r=>r.id===o.source.id))}return t}#b(e,t){let n=this.#i.sources.find(i=>i.id===e);n&&(this.#H(n).status=t)}#z(e,t){let n=this.#i.sources.find(o=>o.id===e);if(!n)return;let i=this.#H(n);i.truncated=t.length>this.#h,i.items=t.slice(0,this.#h),i.status=i.items.length===0?"empty":"ready"}#B(e){return JSON.stringify([e.source.id,e.item.id])}#Y(){this.#t=[];for(let e of this.#l)if(e.status==="ready")for(let t of e.items)this.#t.push({source:e.source,item:t});if(this.#A){let e=this.#t.findIndex(t=>this.#B(t)===this.#A);this.#o=e>=0?e:Math.min(this.#o,Math.max(0,this.#t.length-1))}else this.#o>=this.#t.length&&(this.#o=Math.max(0,this.#t.length-1))}#X(){return{query:this.#d,groups:this.#l,activeIndex:this.#o}}#f(){this.#Y(),this.#s.render(this.#X()),this.#$(),this.#u?.reposition();let e=this.#l.some(t=>t.status==="loading");this.#t.length===0&&e||this.#t.length!==this.#W&&(this.#W=this.#t.length,this.#e.announce(this.#t.length===0?"No matches":this.#t.length===1?"1 result":`${this.#t.length} results`),this.#e.emit?.("searched",{query:this.#d,results:this.#t.length}))}#y(e,t=!0){e<0||e>=this.#t.length||(this.#o=e,this.#A=this.#B(this.#t[e]),this.#s.setActiveIndex(e,t),this.#$())}#$(){this.#a&&!this.#v&&this.#o>=0&&this.#o<this.#t.length?this.input.element.setAttribute("aria-activedescendant",`${this.#r}-opt-${this.#o}`):this.input.element.removeAttribute("aria-activedescendant")}#J(e){let t=this.#i.sources.find(n=>n.id===e);!t||!this.#g||(this.#b(e,"loading"),this.#f(),this.#T(t,this.#m),this.#f())}handleKeydown(e){if(!this.#a)return!1;switch(e.key){case"ArrowDown":return this.#t.length===0||(e.preventDefault(),this.#y((this.#o+1)%this.#t.length)),!0;case"ArrowUp":return this.#t.length===0||(e.preventDefault(),this.#y((this.#o-1+this.#t.length)%this.#t.length)),!0;case"Home":return this.#t.length===0||(e.preventDefault(),this.#y(0)),!0;case"End":return this.#t.length===0||(e.preventDefault(),this.#y(this.#t.length-1)),!0;case"Enter":case"Tab":return this.#t.length===0?(this.close(),!1):(e.preventDefault(),this.#D(this.#o),!0);case"Escape":return e.preventDefault(),this.close(),!0;case"Backspace":return this.#d.length===0&&this.close(),!1;default:return!1}}#D(e){let t=this.#t[e];t&&this.#V(t.source,t.item)}#F(e){return _(e).args}#N(e){return e.command==="server"||e.commandArgsPlaceholder!=null}#V(e,t){let n=t.command;if(this.#N(t)){this.#ee(e,t);return}if(n==="action"){let o=this.#F(this.#d);this.#K(),this.close(),this.#G(t,o),this.#e.emit?.("command",{sourceId:e.id,itemId:t.id,kind:"action",args:o}),this.input.focus();return}if(n==="prompt"){let o=this.#F(this.#d),r=this.#ie();this.close(),this.#oe(e,t,o,r),this.#e.emit?.("command",{sourceId:e.id,itemId:t.id,kind:"prompt",args:o});return}if(this.#_()){this.#Z(e,t);return}this.#e.onSelect(e,t,"")&&(this.#K(),this.#e.emit?.("selected",{sourceId:e.id,itemId:t.id,label:t.label})),this.close(),this.input.focus()}#_(){return this.#e.mentionConfig.display==="inline"&&!!this.#e.onInsertMention&&!!this.input.insertMentionAtTrigger}#Z(e,t){if(this.#e.admitMention&&!this.#e.admitMention(e,t)){this.close(),this.input.focus();return}let n=F(e,t),i=this.#n?this.input.insertMentionAtTrigger(n,this.#n):this.input.insertMentionAtSelection?.(n)??null;i?(this.#e.onInsertMention(i,e,t,""),this.#e.emit?.("selected",{sourceId:e.id,itemId:t.id,label:t.label})):(this.#e.mentionConfig.onMentionRejected?.(t,"stale"),this.#e.emit?.("rejected",{sourceId:e.id,itemId:t.id,reason:"stale"})),this.#n=null,this.close(),this.input.focus()}#ee(e,t){let n=`${this.#i.trigger}${t.label} `,i=this.input.getSelection().start,o=this.#n?this.#n.triggerIndex:i;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(o,i,n);else{let r=this.input.getValue();this.input.setValueWithCaret(r.slice(0,o)+n+r.slice(i),o+n.length)}this.#n=null,this.close(),this.#e.emit?.("command",{sourceId:e.id,itemId:t.id,kind:t.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}#te(e,t){let{name:n}=_(t);return!n||t.length<=n.length?!1:e.sources.some(i=>{let o=i.matchCommand?.(n);return!!o&&this.#N(o)})}#ne(e){for(let t of this.#c){if(!t.trigger)continue;let n=t.position==="anywhere"?[e]:t.position==="line-start"?e.split(`
160
+ `):[e.split(`
161
+ `)[0]];for(let i of n){if(!i.startsWith(t.trigger))continue;let{name:o,args:r}=_(i.slice(t.trigger.length));if(o)for(let d of t.sources){let a=d.matchCommand?.(o);if(a&&this.#N(a))return{source:d,item:a,args:r}}}}return null}async dispatchInlineCommand(e){let t=this.#ne(e);if(!t)return null;let{source:n,item:i,args:o}=t,r=i.command??"prompt";if(this.#e.emit?.("command",{sourceId:n.id,itemId:i.id,kind:r,args:o}),r==="action")return this.#G(i,o),{kind:"action"};if(r==="prompt"){let a;try{a=await n.resolve(i,this.#q(o,e))}catch(l){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",l),null}return{kind:"prompt",sendText:a.insertText??a.llmAppend??e}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let a=await n.resolve(i,this.#q(o,e)),l={};return a.context&&(l[n.id]={[i.id]:a.context}),{blocks:[],contentParts:a.contentParts??[],context:l}}}}}#q(e,t){return{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:t,args:e,signal:new AbortController().signal}}#G(e,t){if(e.action)try{Promise.resolve(e.action({args:t,config:this.#e.getConfig(),messages:this.#e.getMessages(),composer:this.input})).catch(n=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",n)})}catch(n){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",n)}}#ie(){return this.#n?{value:this.input.getValue(),start:this.#n.triggerIndex,end:this.input.getSelection().start}:null}async#oe(e,t,n,i){let o=this.input,r;try{r=await e.resolve(t,{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:o.getValue(),args:n,signal:new AbortController().signal})}catch(a){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",a);return}let d=r.insertText??r.llmAppend??"";t.insertMode==="insert-at-caret"&&i?o.replaceLogicalRange?(o.replaceLogicalRange(i.start,i.end,d),o.dispatchInput()):o.setValue(i.value.slice(0,i.start)+d+i.value.slice(i.end)):o.setValue(d),t.submitOnSelect&&o.submit()}#K(){if(!this.#n)return;let e=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.#n.triggerIndex,e,"");else{let t=Y(this.input.getValue(),this.#n,e);this.input.setValueWithCaret(t.value,t.caret)}this.input.dispatchInput(),this.#n=null}destroy(){this.#O(),this.#p&&clearTimeout(this.#p),this.#g?.abort(),this.#u?.destroy(),this.#s.destroy();let e=this.input.element;e.removeAttribute("aria-haspopup"),e.removeAttribute("aria-controls"),e.removeAttribute("aria-activedescendant")}};var Ce={position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"};function U(s,e){let t=document.createElement("div");t.className="persona-sr-only",t.setAttribute("aria-live",s),t.setAttribute("aria-atomic","true"),t.setAttribute("role",s==="assertive"?"alert":"status"),t.setAttribute("data-persona-mention-live-region","");let n=e.getRootNode();typeof ShadowRoot<"u"&&n instanceof ShadowRoot?(Object.assign(t.style,Ce),document.body.appendChild(t)):e.appendChild(t);let o;return{announce:r=>{o!==void 0&&clearTimeout(o),t.textContent="",o=setTimeout(()=>{o=void 0,t.textContent=r},0)},destroy:()=>{o!==void 0&&clearTimeout(o),t.remove()}}}function xe(s){let e=s.composerInput??ne(s.textarea),t=U("polite",s.liveRegionHost),n=U("assertive",s.liveRegionHost),i=l=>t.announce(l),o=l=>n.announce(l),r=new V({mentionConfig:s.mentionConfig,contextRow:s.contextRow,getMessages:s.getMessages,getConfig:s.getConfig,getComposerText:()=>e.getValue(),announce:i,announceError:o,emit:s.emit}),d=()=>new q({mentionConfig:s.mentionConfig,composerInput:e,anchor:s.anchor,getMessages:s.getMessages,getConfig:s.getConfig,onSelect:(l,u,f)=>r.add(l,u,f),onInsertMention:(l,u,f,x)=>r.track(l,u,f,x,C=>e.setMentionStatus?.(l,C)),admitMention:(l,u)=>r.admit(l,u),announce:i,popoverContainer:s.popoverContainer,onPickerOpenChange:s.onPickerOpenChange,emit:s.emit}),a=d();return{openMenu:l=>a.openFromButton(l),isMenuOpen:()=>a.isOpen(),handleInput:()=>a.onInput(),handleKeydown:l=>a.handleKeydown(l),hasMentions:()=>r.hasMentions(),getMentionRefs:()=>r.getRefs(),removeLastChip:()=>r.removeLast(),dispatchInlineCommand:l=>a.dispatchInlineCommand(l),collectForSubmit:()=>r.hasMentions()?r.collectForSubmit():null,untrackMention:l=>r.remove(l),rebindComposer:l=>{l!==e&&(a.destroy(),e=l,a=d())},clear:()=>r.clear(),destroy:()=>{a.destroy(),r.clear(),t.destroy(),n.destroy()}}}export{xe as mountContextMentions,oe as setMentionIconRenderer};
@@ -1,4 +1,4 @@
1
- import{a as X}from"./chunk-R2TMIMDI.js";var ce="@";function O(t){return t.kind==="text"?t.value.length:1}function W(t){let n=[],o=r=>{let c=n[n.length-1];c&&c.kind==="text"?c.value+=r:n.push({kind:"text",value:r})};(t.length===0||t[0].kind!=="text")&&n.push({kind:"text",value:""});for(let r of t){if(r.kind==="text"){o(r.value);continue}let c=n[n.length-1];(!c||c.kind!=="text")&&n.push({kind:"text",value:""}),n.push({kind:"mention",id:r.id,ref:r.ref}),n.push({kind:"text",value:""})}let e=n[n.length-1];return(!e||e.kind!=="text")&&n.push({kind:"text",value:""}),n}function Y(){return{blocks:[{kind:"text",value:""}]}}function B(t){return{blocks:[{kind:"text",value:t}]}}function H(t){return t.blocks.map(n=>n.kind==="text"?n.value:`${ce}${n.ref.label}`).join("")}function R(t){return t.blocks.map(n=>n.kind==="text"?n.value:"\uFFFC").join("")}function L(t){return t.blocks.reduce((n,o)=>n+O(o),0)}function le(t){let n=[];for(let o of t.blocks)o.kind==="mention"&&n.push({id:o.id,ref:o.ref});return n}function I(t,n){let o=[],e=[],r=0;for(let c of t){let a=O(c),p=r+a;if(p<=n)o.push(c);else if(r>=n)e.push(c);else if(c.kind==="text"){let b=n-r;b>0&&o.push({kind:"text",value:c.value.slice(0,b)}),b<a&&e.push({kind:"text",value:c.value.slice(b)})}else e.push(c);r=p}return{left:o,right:e}}function P(t,n,o,e){let r=I(t.blocks,n.start).left,c=I(t.blocks,n.end).right,a=c[0],p=a?.kind==="text"?a.value.charAt(0):"",b=p!==" "&&p!==" "&&p!==`
1
+ import"./chunk-IO5VVUKP.js";import{a as X}from"./chunk-UPO4GUFC.js";var ce="@";function O(t){return t.kind==="text"?t.value.length:1}function W(t){let n=[],o=r=>{let c=n[n.length-1];c&&c.kind==="text"?c.value+=r:n.push({kind:"text",value:r})};(t.length===0||t[0].kind!=="text")&&n.push({kind:"text",value:""});for(let r of t){if(r.kind==="text"){o(r.value);continue}let c=n[n.length-1];(!c||c.kind!=="text")&&n.push({kind:"text",value:""}),n.push({kind:"mention",id:r.id,ref:r.ref}),n.push({kind:"text",value:""})}let e=n[n.length-1];return(!e||e.kind!=="text")&&n.push({kind:"text",value:""}),n}function Y(){return{blocks:[{kind:"text",value:""}]}}function B(t){return{blocks:[{kind:"text",value:t}]}}function H(t){return t.blocks.map(n=>n.kind==="text"?n.value:`${ce}${n.ref.label}`).join("")}function R(t){return t.blocks.map(n=>n.kind==="text"?n.value:"\uFFFC").join("")}function L(t){return t.blocks.reduce((n,o)=>n+O(o),0)}function le(t){let n=[];for(let o of t.blocks)o.kind==="mention"&&n.push({id:o.id,ref:o.ref});return n}function I(t,n){let o=[],e=[],r=0;for(let c of t){let a=O(c),p=r+a;if(p<=n)o.push(c);else if(r>=n)e.push(c);else if(c.kind==="text"){let b=n-r;b>0&&o.push({kind:"text",value:c.value.slice(0,b)}),b<a&&e.push({kind:"text",value:c.value.slice(b)})}else e.push(c);r=p}return{left:o,right:e}}function P(t,n,o,e){let r=I(t.blocks,n.start).left,c=I(t.blocks,n.end).right,a=c[0],p=a?.kind==="text"?a.value.charAt(0):"",b=p!==" "&&p!==" "&&p!==`
2
2
  `,g=W([...r,{kind:"mention",id:e,ref:o},...b?[{kind:"text",value:" "}]:[],...c]),C=n.start+1+(p===`
3
3
  `?0:1);return{doc:{blocks:g},caret:C}}function G(t,n){let o=0,e=0,r=!1;for(let a of t.blocks)a.kind==="mention"&&a.id===n&&(o=e,r=!0),e+=O(a);return r?{doc:{blocks:W(t.blocks.filter(a=>!(a.kind==="mention"&&a.id===n)))},caret:o}:{doc:t,caret:e}}function D(t,n,o,e){let r=L(t),c=Math.max(0,Math.min(n,o,r)),a=Math.min(r,Math.max(n,o,0)),p=I(t.blocks,c).left,b=I(t.blocks,a).right;return{doc:{blocks:W([...p,{kind:"text",value:e},...b])},caret:c+e.length}}function J(t){let n=[];for(let o of t.blocks)o.kind==="text"?o.value.length>0&&n.push({kind:"text",text:o.value}):n.push({kind:"mention",ref:o.ref});return{content:H(t),contextMentions:le(t).map(o=>o.ref),contentSegments:n}}var ae="persona-mention-token-error",y="data-mention-id",A="data-mention-prev-label",_="data-mention-prev-title",U=`
4
4
  `;function T(t){return t.nodeType===1&&t.hasAttribute(y)}function Z(t){return t.nodeType===1&&t.tagName==="BR"}function N(t){return t.nodeType===3?t.data.length:T(t)||Z(t)?1:t.textContent?.length??0}function Q(t,n,o){let e=0;for(let r of Array.from(t.childNodes)){if(r===n)return r.nodeType===3?e+o:e+(o>0?N(r):0);if(r.contains(n))return T(r)?e+1:e+ue(r,n,o);e+=N(r)}if(n===t){let r=0,c=Array.from(t.childNodes);for(let a=0;a<Math.min(o,c.length);a++)r+=N(c[a]);return r}return e}function ue(t,n,o){let e=0,r=c=>{if(c===n)return e+=c.nodeType===3?o:0,!0;if(c.nodeType===3)return e+=c.data.length,!1;for(let a of Array.from(c.childNodes))if(r(a))return!0;return!1};return r(t),e}function v(t,n){let o=0,e=Array.from(t.childNodes);for(let r=0;r<e.length;r++){let c=e[r],a=N(c);if(n<=o+a)return c.nodeType===3?{node:c,offset:n-o}:{node:t,offset:n<=o?r:r+1};o+=a}return{node:t,offset:e.length}}function de(t,n){let o=[];for(let e of Array.from(t.childNodes))if(T(e)){let r=e.getAttribute(y),c=n.get(r);c&&o.push({kind:"mention",id:r,ref:c})}else if(Z(e))o.push({kind:"text",value:U});else if(e.nodeType===3)o.push({kind:"text",value:e.data});else{let r=e.textContent??"";r&&o.push({kind:"text",value:r})}return o.length===0&&o.push({kind:"text",value:""}),{blocks:o}}function ee(t){let n=t.renderToken,o=new Map,e=t.element??document.createElement("div");e.setAttribute("contenteditable","true"),e.setAttribute("data-persona-composer-input",""),e.setAttribute("role","textbox"),e.setAttribute("aria-multiline","true"),e.setAttribute("dir","auto"),e.classList.add("persona-composer-contenteditable"),t.placeholder!=null&&e.setAttribute("data-placeholder",t.placeholder);let r=!1,c=0,a=()=>de(e,o),p=l=>{e.replaceChildren();for(let s of l.blocks)if(s.kind==="text")s.value.length>0&&e.appendChild(document.createTextNode(s.value));else{o.set(s.id,s.ref);let i=n(s.ref);i.setAttribute("contenteditable","false"),i.setAttribute(y,s.id),e.appendChild(i)}},b=()=>{let s=e.getRootNode().activeElement;return s===e||s!=null&&e.contains(s)},g=(l,s)=>{if(c=l,!s?.focus&&!b())return;let i=typeof window<"u"?window.getSelection():null;if(!i)return;let d=v(e,l);try{let u=document.createRange();u.setStart(d.node,d.offset),u.collapse(!0),i.removeAllRanges(),i.addRange(u)}catch{}},C=()=>{e.dispatchEvent(new Event("input",{bubbles:!0}))},k=()=>{let l={start:c,end:c},s=typeof window<"u"?window.getSelection():null;if(!s||s.rangeCount===0)return l;let i=s.getRangeAt(0);if(!e.contains(i.startContainer))return l;let d=Q(e,i.startContainer,i.startOffset),u=i.collapsed?d:Q(e,i.endContainer,i.endOffset);return{start:Math.min(d,u),end:Math.max(d,u)}},M=()=>{let l=new Set;for(let s of Array.from(e.childNodes))T(s)&&l.add(s.getAttribute(y));for(let s of Array.from(o.keys()))l.has(s)||(o.delete(s),t.onMentionRemoved?.(s))},F=()=>{r||o.size!==0&&M()},V=()=>{r=!0},j=()=>{r=!1,M()},$=l=>{l.preventDefault();let s=l.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,s);else{let{start:i,end:d}=k(),u=D(a(),i,d,s);p(u.doc),g(u.caret,{focus:!0}),M()}C()},q=l=>{if(r)return;let s=l.inputType;if(s==="insertParagraph"){l.preventDefault();let{start:x,end:E}=k(),K=D(a(),x,E,U);p(K.doc),g(K.caret,{focus:!0}),o.size>0&&M(),C();return}if(s!=="deleteContentBackward"&&s!=="deleteContentForward"||o.size===0)return;let{start:i,end:d}=k();if(i!==d)return;let u=a(),m=R(u),f=s==="deleteContentBackward"?i-1:i;if(f<0||f>=m.length||m[f]!=="\uFFFC")return;let h=0,S=null;for(let x of u.blocks){let E=x.kind==="text"?x.value.length:1;if(x.kind==="mention"&&f>=h&&f<h+E){S=x.id;break}h+=E}if(!S)return;l.preventDefault();let z=G(u,S);p(z.doc),g(z.caret,{focus:!0}),M(),C()},te=(l,s)=>{p(B(l)),g(s)},ne=(l,s)=>{if(!Number.isFinite(l)||!Number.isFinite(s)||s<=l)return null;try{let i=v(e,l),d=v(e,s),u=document.createRange();u.setStart(i.node,i.offset),u.setEnd(d.node,d.offset);let m=u.getBoundingClientRect();return m.width===0&&m.height===0?null:m}catch{return null}},oe=(l,s,i)=>{let d=D(a(),l,s,i);p(d.doc),g(d.caret,{focus:!0})},re=(l,s)=>{let i=a(),d=R(i),u=s.triggerIndex,m=s.triggerIndex+1+s.query.length;if(u<0||m>d.length||d.slice(u+1,m)!==s.query)return null;let f=t.generateId(),h=P(i,{start:u,end:m},l,f);return p(h.doc),g(h.caret,{focus:!0}),t.onMentionInserted?.(f,l),C(),f},ie=l=>{let s=a(),i=k(),u=typeof window<"u"&&!!window.getSelection()?.rangeCount&&e.contains(window.getSelection().getRangeAt(0).startContainer)?{start:i.start,end:i.end}:{start:L(s),end:L(s)},m=t.generateId(),f=P(s,u,l,m);return p(f.doc),g(f.caret,{focus:!0}),t.onMentionInserted?.(m,l),C(),m},se=(l,s)=>{for(let i of Array.from(e.childNodes))if(T(i)&&i.getAttribute(y)===l){let d=s==="error";if(i.classList.toggle(ae,d),d){i.hasAttribute(A)||(i.setAttribute(A,i.getAttribute("aria-label")??""),i.setAttribute(_,i.getAttribute("title")??""));let u=o.get(l)?.label??"";i.setAttribute("title",`${u}: failed to attach context`),i.setAttribute("aria-label",`${u}, failed to attach context`)}else if(i.hasAttribute(A)){let u=i.getAttribute(A),m=i.getAttribute(_);u?i.setAttribute("aria-label",u):i.removeAttribute("aria-label"),m?i.setAttribute("title",m):i.removeAttribute("title"),i.removeAttribute(A),i.removeAttribute(_)}return}};return e.addEventListener("input",F),e.addEventListener("compositionstart",V),e.addEventListener("compositionend",j),e.addEventListener("paste",$),e.addEventListener("beforeinput",q),p(Y()),{element:e,getValue:()=>H(a()),getLogicalText:()=>R(a()),getDocument:a,getSelection:k,setSelection:(l,s=l)=>{let i=typeof window<"u"?window.getSelection():null;if(i)try{let d=v(e,l),u=v(e,s),m=document.createRange();m.setStart(d.node,d.offset),m.setEnd(u.node,u.offset),i.removeAllRanges(),i.addRange(m)}catch{}},setValueWithCaret:te,getLogicalRangeRect:ne,setValue:l=>{p(B(l)),e.focus(),g(l.length,{focus:!0}),C()},replaceLogicalRange:oe,insertMentionAtTrigger:re,insertMentionAtSelection:ie,setMentionStatus:se,submit:()=>X(e.closest("form")),dispatchInput:C,focus:()=>e.focus(),destroy:()=>{e.removeEventListener("input",F),e.removeEventListener("compositionstart",V),e.removeEventListener("compositionend",j),e.removeEventListener("paste",$),e.removeEventListener("beforeinput",q)}}}var me=0,pe=()=>`pmention-${++me}`;function fe(t,n){n.className=`${t.className} persona-composer-contenteditable`.trim();for(let r=0;r<t.style.length;r++){let c=t.style.item(r);c!=="height"&&n.style.setProperty(c,t.style.getPropertyValue(c),t.style.getPropertyPriority(c))}let o=t.getAttribute("placeholder");o&&(n.setAttribute("data-placeholder",o),n.setAttribute("aria-placeholder",o));let e=t.getAttribute("aria-label")??o;e&&n.setAttribute("aria-label",e)}function ge(t,n,o){Object.defineProperty(t,"value",{configurable:!0,get:()=>n.getValue(),set:e=>{n.setValueWithCaret(e,e.length),n.dispatchInput()}}),Object.defineProperty(t,"placeholder",{configurable:!0,get:()=>t.getAttribute("data-placeholder")??"",set:e=>{e?(t.setAttribute("data-placeholder",e),t.setAttribute("aria-placeholder",e),o||t.setAttribute("aria-label",e)):(t.removeAttribute("data-placeholder"),t.removeAttribute("aria-placeholder"),o||t.removeAttribute("aria-label"))}}),Object.defineProperty(t,"selectionStart",{configurable:!0,get:()=>n.getSelection().start}),Object.defineProperty(t,"selectionEnd",{configurable:!0,get:()=>n.getSelection().end}),t.setSelectionRange=(e,r)=>n.setSelection(e??0,r??e??0)}function be(t){let{textarea:n}=t,o={generateId:pe,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:n.getAttribute("placeholder")??void 0},e=ee(o),r=e.element,c=n.getAttribute("aria-label")!=null;fe(n,r),ge(r,e,c),r.getInlineMessageFields=()=>J(e.getDocument?.()??{blocks:[]});let a=n.selectionStart??n.value.length;return e.setValueWithCaret(n.value,a),{input:e,element:r,destroy:e.destroy}}export{be as mountInlineComposer};