@runtypelabs/persona 4.23.1 → 4.24.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 (158) 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-9Vxm-PPz.d.cts → types-Db61aI9J.d.cts} +25 -2
  4. package/dist/animations/{types-9Vxm-PPz.d.ts → types-Db61aI9J.d.ts} +25 -2
  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 +25 -2
  8. package/dist/animations-extra.d.ts +25 -2
  9. package/dist/approval-ui-3NMYNXBD.js +1 -0
  10. package/dist/approval-ui.cjs +2 -2
  11. package/dist/approval-ui.d.cts +261 -40
  12. package/dist/approval-ui.d.ts +261 -40
  13. package/dist/approval-ui.js +2 -2
  14. package/dist/{artifacts-ui-F4N6VMKF.js → artifacts-ui-IGB5YKLO.js} +4 -4
  15. package/dist/artifacts-ui.d.cts +256 -28
  16. package/dist/artifacts-ui.d.ts +256 -28
  17. package/dist/{chunk-NIKYKSNZ.js → chunk-7CO4T5KB.js} +1 -1
  18. package/dist/codegen.cjs +11 -11
  19. package/dist/codegen.js +13 -13
  20. package/dist/context-mentions.d.cts +256 -28
  21. package/dist/context-mentions.d.ts +256 -28
  22. package/dist/event-stream-view.d.cts +256 -28
  23. package/dist/event-stream-view.d.ts +256 -28
  24. package/dist/forms-ui.d.cts +291 -30
  25. package/dist/forms-ui.d.ts +291 -30
  26. package/dist/history-view.d.cts +25 -2
  27. package/dist/history-view.d.ts +25 -2
  28. package/dist/index.cjs +70 -69
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.d.cts +337 -51
  31. package/dist/index.d.ts +337 -51
  32. package/dist/index.global.js +57 -54
  33. package/dist/index.global.js.map +1 -1
  34. package/dist/index.js +70 -69
  35. package/dist/index.js.map +1 -1
  36. package/dist/install.global.js +1 -1
  37. package/dist/install.global.js.map +1 -1
  38. package/dist/launcher.global.js +2 -2
  39. package/dist/launcher.global.js.map +1 -1
  40. package/dist/session-reconnect.d.cts +256 -28
  41. package/dist/session-reconnect.d.ts +256 -28
  42. package/dist/smart-dom-reader.d.cts +256 -28
  43. package/dist/smart-dom-reader.d.ts +256 -28
  44. package/dist/theme-editor-preview.cjs +74 -73
  45. package/dist/theme-editor-preview.d.cts +263 -28
  46. package/dist/theme-editor-preview.d.ts +263 -28
  47. package/dist/theme-editor-preview.js +51 -50
  48. package/dist/theme-editor.cjs +10 -10
  49. package/dist/theme-editor.d.cts +276 -30
  50. package/dist/theme-editor.d.ts +276 -30
  51. package/dist/theme-editor.js +10 -10
  52. package/dist/theme-reference.cjs +1 -1
  53. package/dist/theme-reference.d.cts +1522 -11
  54. package/dist/theme-reference.d.ts +1522 -11
  55. package/dist/theme-reference.js +1 -1
  56. package/dist/widget.css +1 -1
  57. package/package.json +3 -2
  58. package/src/__fixtures__/defaults-parity.v4.json +776 -0
  59. package/src/approval-ui-entry.ts +0 -1
  60. package/src/approval-ui-loader.ts +5 -4
  61. package/src/approval-ui.ts +0 -1
  62. package/src/client-identity-proof.test.ts +193 -0
  63. package/src/client-session-warm.test.ts +216 -0
  64. package/src/client-visitor-history.test.ts +6 -0
  65. package/src/client.tool-pair-replay.test.ts +325 -0
  66. package/src/client.ts +154 -61
  67. package/src/codegen.test.ts +24 -0
  68. package/src/components/activity-row.test.ts +100 -0
  69. package/src/components/activity-row.ts +136 -0
  70. package/src/components/approval-actions.test.ts +8 -5
  71. package/src/components/approval-actions.ts +19 -6
  72. package/src/components/approval-bubble.test.ts +56 -9
  73. package/src/components/approval-bubble.ts +36 -41
  74. package/src/components/composer-builder.ts +5 -2
  75. package/src/components/composer-parts.ts +10 -2
  76. package/src/components/header-builder.test.ts +32 -0
  77. package/src/components/header-builder.ts +7 -4
  78. package/src/components/header-layouts.test.ts +12 -0
  79. package/src/components/header-layouts.ts +3 -2
  80. package/src/components/launcher.ts +11 -2
  81. package/src/components/message-bubble.test.ts +22 -0
  82. package/src/components/message-bubble.ts +7 -3
  83. package/src/components/panel.test.ts +52 -1
  84. package/src/components/panel.ts +47 -8
  85. package/src/components/pill-composer-builder.test.ts +2 -0
  86. package/src/components/pill-composer-builder.ts +0 -1
  87. package/src/components/reasoning-bubble.ts +29 -17
  88. package/src/components/suggestions.test.ts +1 -0
  89. package/src/components/suggestions.ts +0 -16
  90. package/src/components/tool-bubble.ts +131 -114
  91. package/src/components/tool-details.test.ts +87 -0
  92. package/src/components/tool-details.ts +102 -0
  93. package/src/components/welcome.test.ts +8 -0
  94. package/src/components/welcome.ts +4 -2
  95. package/src/defaults-parity.test.ts +158 -0
  96. package/src/defaults.test.ts +69 -0
  97. package/src/defaults.ts +128 -49
  98. package/src/generated/runtype-openapi-contract.ts +28 -13
  99. package/src/index-core.ts +2 -0
  100. package/src/install.test.ts +24 -0
  101. package/src/install.ts +3 -1
  102. package/src/launcher-global.ts +2 -1
  103. package/src/launcher-variants.test.ts +52 -0
  104. package/src/runtime/init-update-reset.test.ts +21 -0
  105. package/src/session.ts +61 -9
  106. package/src/styles/widget-styles.test.ts +19 -0
  107. package/src/styles/widget.css +295 -23
  108. package/src/theme-editor/index.ts +2 -0
  109. package/src/theme-editor/preview-utils.test.ts +8 -0
  110. package/src/theme-editor/preview-utils.ts +7 -3
  111. package/src/theme-editor/sections.test.ts +31 -0
  112. package/src/theme-editor/sections.ts +55 -1
  113. package/src/theme-editor/state-preferences.test.ts +49 -0
  114. package/src/theme-editor/state.ts +73 -15
  115. package/src/theme-reference.test.ts +20 -0
  116. package/src/theme-reference.ts +11 -5
  117. package/src/tool-call-display-defaults.test.ts +33 -1
  118. package/src/types/theme.ts +80 -3
  119. package/src/types.ts +179 -23
  120. package/src/ui.activity-row.test.ts +91 -0
  121. package/src/ui.approval-plugin.test.ts +63 -0
  122. package/src/ui.composer-compact.test.ts +24 -2
  123. package/src/ui.composer-placement.test.ts +23 -0
  124. package/src/ui.detached-panel.test.ts +33 -6
  125. package/src/ui.docked.test.ts +19 -0
  126. package/src/ui.header-update-stability.test.ts +25 -0
  127. package/src/ui.identity-proof.test.ts +58 -0
  128. package/src/ui.launcher-teaser.test.ts +25 -0
  129. package/src/ui.message-width.test.ts +17 -2
  130. package/src/ui.reasoning-display.test.ts +92 -0
  131. package/src/ui.rebuild-composer.test.ts +20 -3
  132. package/src/ui.scroll.test.ts +32 -0
  133. package/src/ui.session-init.test.ts +312 -0
  134. package/src/ui.status-indicator.test.ts +82 -0
  135. package/src/ui.suggest-replies.test.ts +11 -0
  136. package/src/ui.ts +363 -74
  137. package/src/ui.v5-defaults.test.ts +144 -0
  138. package/src/ui.welcome.test.ts +92 -3
  139. package/src/utils/__snapshots__/tokens-parity.test.ts.snap +811 -140
  140. package/src/utils/code-generators.ts +14 -0
  141. package/src/utils/composer-compact.test.ts +0 -2
  142. package/src/utils/composer-compact.ts +2 -4
  143. package/src/utils/composer-placement.ts +2 -3
  144. package/src/utils/config-merge.test.ts +81 -5
  145. package/src/utils/config-merge.ts +13 -3
  146. package/src/utils/defaults-provenance.ts +67 -0
  147. package/src/utils/dock.ts +7 -1
  148. package/src/utils/launcher-variant.ts +16 -0
  149. package/src/utils/panel-config.ts +97 -0
  150. package/src/utils/status-indicator.ts +39 -0
  151. package/src/utils/theme.test.ts +182 -0
  152. package/src/utils/theme.ts +131 -18
  153. package/src/utils/tokens.test.ts +122 -1
  154. package/src/utils/tokens.ts +177 -17
  155. package/src/utils/tool-pair-replay.ts +100 -0
  156. package/src/welcome.test.ts +23 -0
  157. package/src/welcome.ts +16 -9
  158. package/dist/approval-ui-K7R5Q5OC.js +0 -1
@@ -1,22 +1,22 @@
1
- "use strict";var S0=Object.create;var Gd=Object.defineProperty;var A0=Object.getOwnPropertyDescriptor;var M0=Object.getOwnPropertyNames;var T0=Object.getPrototypeOf,E0=Object.prototype.hasOwnProperty;var be=(t,e)=>()=>(t&&(e=t(t=0)),e);var Vn=(t,e)=>{for(var n in e)Gd(t,n,{get:e[n],enumerable:!0})},pC=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of M0(e))!E0.call(t,r)&&r!==n&&Gd(t,r,{get:()=>e[r],enumerable:!(o=A0(e,r))||o.enumerable});return t};var uC=(t,e,n)=>(n=t!=null?S0(T0(t)):{},pC(e||!t||!t.__esModule?Gd(n,"default",{value:t,enumerable:!0}):n,t)),k0=t=>pC(Gd({},"__esModule",{value:!0}),t);var $t,oo=be(()=>{"use strict";$t=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,s=null;return{setLoader:u=>{o=u,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??e)().then(m=>(r=m,m)).catch(m=>{throw s=null,m}),s),provide:u=>{r=u},getSync:()=>r}}});var yC={};Vn(yC,{DOMPurify:()=>hC.default,Marked:()=>gC.Marked});var gC,hC,bC=be(()=>{"use strict";gC=require("marked"),hC=uC(require("dompurify"),1)});var m1,P0,I0,Df,Yd,vC,CC,ea,_f,Mo,ti=be(()=>{"use strict";oo();({setLoader:m1,load:P0,provide:I0,getSync:Df}=$t({fallbackImport:()=>Promise.resolve().then(()=>(bC(),yC))})),Yd=new Set,vC=()=>{let t=[...Yd];Yd.clear();for(let e of t)try{e()}catch{}},CC=()=>{let t=Df();return t?Promise.resolve(t):P0().then(e=>(vC(),e))},ea=t=>Df()?()=>{}:(Yd.add(t),()=>{Yd.delete(t)}),_f=t=>{I0(t),vC()},Mo=Df});var H0,Nf,Qd,h1,Pr,Xd=be(()=>{"use strict";ti();H0=t=>{if(!t)return;let e={},n=t;if(n.heading){let o=n.heading;e.heading=(r,s,a)=>o({type:"heading",raw:a,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;e.code=(r,s,a)=>o({type:"code",raw:"",text:r,lang:s,escaped:a})}if(n.blockquote){let o=n.blockquote;e.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;e.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;e.link=(r,s,a)=>o({type:"link",raw:"",href:r,title:s??null,text:a,tokens:[]})}if(n.image){let o=n.image;e.image=(r,s,a)=>o({type:"image",raw:"",href:r,title:s??null,text:a})}if(n.list){let o=n.list;e.list=(r,s,a)=>o({type:"list",raw:"",ordered:s,start:a,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;e.listitem=(r,s,a)=>o({type:"list_item",raw:"",task:s,checked:a,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;e.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;e.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;e.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;e.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;e.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;e.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;e.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;e.checkbox=r=>o({checked:r})}return n.hr&&(e.hr=n.hr),n.br&&(e.br=n.br),e},Nf=t=>{let e=null;return n=>{let o=Mo();if(!o)return Pr(n);if(!e){let{Marked:r}=o,s=t?.markedOptions;e=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=H0(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},Qd=t=>t?Nf({markedOptions:t.options,renderer:t.renderer}):Nf(),h1=Nf(),Pr=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")});var R0,W0,B0,Jd,Ff=be(()=>{"use strict";Xd();ti();R0={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},W0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,B0=()=>{let t=null;return e=>{let n=Mo();if(!n)return Pr(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!W0.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,R0)}},Jd=t=>t===!1?null:typeof t=="function"?t:B0()});function HC(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${N0(e.join(""))}`}function PC(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function N0(t){let e=PC(t,0).toString(36),n=PC(t,2654435761).toString(36);return`${e}.${n}`}var Ir,$f,IC,Zd,LC,F0,ta,RC,na=be(()=>{"use strict";Ir="webmcp:",$f=new Map,IC=t=>{$f.clear();for(let e of t){let n=e.title?.trim();n&&$f.set(e.name,n)}},Zd=t=>$f.get(F0(t)),LC=null;F0=t=>t.startsWith(Ir)?t.slice(Ir.length):t,ta=t=>t.startsWith(Ir),RC=()=>LC?LC():import("@mcp-b/webmcp-polyfill")});var WC,V0,ep,np,$0,tp,z0,U0,q0,Vo,j0,K0,G0,Y0,BC=be(()=>{"use strict";WC="webmcp:",V0=t=>t.startsWith(WC)?t.slice(WC.length):t,ep={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},np=class{constructor(e,n){this.config=e;this.deps=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(r){return ep.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.deps.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s=z0(r.annotations);return{name:r.name,description:r.description,parametersSchema:U0(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Vo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return Vo(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=V0(e),a;try{a=await r.getTools()}catch(b){let C=b instanceof Error?b.message:String(b);return Vo(`Failed to read WebMCP registry: ${C}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(b=>b.name===s);if(!l)return Vo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Vo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Vo("Aborted by cancel()");let d=this.deps.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(p))return Vo("User declined the tool call.");if(o?.aborted)return Vo("Aborted by cancel()");let u=new AbortController,m=!1,y=setTimeout(()=>{m=!0,u.abort()},this.timeoutMs),g=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",g,{once:!0}));try{let b=await r.executeTool(l,G0(n),{signal:u.signal});return q0(b)}catch(b){if(m)return Vo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Vo("Aborted by cancel()");let C=b instanceof Error?b.message:String(b);return Vo(C)}finally{clearTimeout(y),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(await this.deps.loadPolyfill()).initializeWebMCPPolyfill(),this.installed=!0}catch(e){ep.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ep.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){let n=this.confirmHandler??j0;try{return await n(e)}catch(o){return ep.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>$0(e,o))}},$0=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},tp={type:"object",properties:{}},z0=t=>{if(!t||typeof t!="object")return;let e={...typeof t.readOnlyHint=="boolean"?{readOnlyHint:t.readOnlyHint}:{},...typeof t.untrustedContentHint=="boolean"?{untrustedContentHint:t.untrustedContentHint}:{}};return Object.keys(e).length>0?e:void 0},U0=t=>{if(t===void 0||t==="")return{...tp};if(typeof t=="object")return t!==null&&!Array.isArray(t)?t:{...tp};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{...tp}}catch{return{...tp}}},q0=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Y0(e)}]}},Vo=t=>({isError:!0,content:[{type:"text",text:t}]}),j0=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=K0(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
1
+ "use strict";var PP=Object.create;var pp=Object.defineProperty;var LP=Object.getOwnPropertyDescriptor;var IP=Object.getOwnPropertyNames;var RP=Object.getPrototypeOf,HP=Object.prototype.hasOwnProperty;var be=(t,e)=>()=>(t&&(e=t(t=0)),e);var $n=(t,e)=>{for(var n in e)pp(t,n,{get:e[n],enumerable:!0})},dw=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of IP(e))!HP.call(t,r)&&r!==n&&pp(t,r,{get:()=>e[r],enumerable:!(o=LP(e,r))||o.enumerable});return t};var pw=(t,e,n)=>(n=t!=null?PP(RP(t)):{},dw(e||!t||!t.__esModule?pp(n,"default",{value:t,enumerable:!0}):n,t)),WP=t=>dw(pp({},"__esModule",{value:!0}),t);var Ge,zn=be(()=>{"use strict";Ge=(t,e=24,n="currentColor",o=2)=>{if(!Array.isArray(t))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let c=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([p,u])=>{p!=="stroke"&&c.setAttribute(p,String(u))}),r.appendChild(c)}),r}});var v,Cw,F,Gt,je=be(()=>{"use strict";v=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Cw=()=>document.createDocumentFragment(),F=(t,e={},...n)=>{let o=document.createElement(t);if(e.className&&(o.className=e.className),e.text!==void 0&&(o.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))o.setAttribute(s,a);if(e.style){let s=o.style,a=e.style;for(let l of Object.keys(a)){let c=a[l];c!=null&&(s[l]=c)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Gt=(...t)=>t.filter(Boolean).join(" ")});var Qt,ro=be(()=>{"use strict";Qt=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,s=null;return{setLoader:u=>{o=u,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??e)().then(m=>(r=m,m)).catch(m=>{throw s=null,m}),s),provide:u=>{r=u},getSync:()=>r}}});var ww={};$n(ww,{EXTRA_LUCIDE_ICONS:()=>FP});var ae,FP,xw=be(()=>{"use strict";ae=require("lucide"),FP={user:ae.User,mail:ae.Mail,phone:ae.Phone,calendar:ae.Calendar,clock:ae.Clock,building:ae.Building,"map-pin":ae.MapPin,lock:ae.Lock,key:ae.Key,"credit-card":ae.CreditCard,hash:ae.Hash,globe:ae.Globe,link:ae.Link,"circle-check":ae.CircleCheck,"circle-x":ae.CircleX,"triangle-alert":ae.TriangleAlert,info:ae.Info,ban:ae.Ban,shield:ae.Shield,house:ae.House,"pen-line":ae.PenLine,save:ae.Save,share:ae.Share,funnel:ae.Funnel,settings:ae.Settings,"rotate-cw":ae.RotateCw,"shopping-cart":ae.ShoppingCart,"shopping-bag":ae.ShoppingBag,package:ae.Package,truck:ae.Truck,tag:ae.Tag,gift:ae.Gift,receipt:ae.Receipt,wallet:ae.Wallet,store:ae.Store,"dollar-sign":ae.DollarSign,percent:ae.Percent,play:ae.Play,pause:ae.Pause,"volume-x":ae.VolumeX,camera:ae.Camera,image:ae.Image,film:ae.Film,headphones:ae.Headphones,"message-circle":ae.MessageCircle,bell:ae.Bell,heart:ae.Heart,"eye-off":ae.EyeOff,bookmark:ae.Bookmark,"calendar-days":ae.CalendarDays,timer:ae.Timer,folder:ae.Folder,"folder-open":ae.FolderOpen,files:ae.Files,"chart-column":ae.ChartColumn,sparkles:ae.Sparkles,zap:ae.Zap,sun:ae.Sun,moon:ae.Moon,flag:ae.Flag,lightbulb:ae.Lightbulb,monitor:ae.Monitor,smartphone:ae.Smartphone}});var VP,$P,Sg,hp,yp=be(()=>{"use strict";ro();({setLoader:VP,load:$P}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(xw(),ww))})),Sg=VP,hp=$P});var me,zP,UP,bp,Ca,Ag,vp,qP,Sw,jP,Mg,KP,GP,ke,Zt=be(()=>{"use strict";zn();yp();me=require("lucide"),zP={activity:me.Activity,"arrow-down":me.ArrowDown,"arrow-up":me.ArrowUp,"arrow-up-right":me.ArrowUpRight,bot:me.Bot,"chevron-down":me.ChevronDown,"chevron-up":me.ChevronUp,"chevron-right":me.ChevronRight,"chevron-left":me.ChevronLeft,check:me.Check,clipboard:me.Clipboard,"clipboard-copy":me.ClipboardCopy,"code-xml":me.CodeXml,copy:me.Copy,file:me.File,"file-code":me.FileCode,"file-spreadsheet":me.FileSpreadsheet,"file-text":me.FileText,"image-plus":me.ImagePlus,loader:me.Loader,"loader-circle":me.LoaderCircle,mic:me.Mic,paperclip:me.Paperclip,quote:me.Quote,"refresh-cw":me.RefreshCw,search:me.Search,send:me.Send,"shield-alert":me.ShieldAlert,"shield-check":me.ShieldCheck,"shield-x":me.ShieldX,square:me.Square,"thumbs-down":me.ThumbsDown,"thumbs-up":me.ThumbsUp,upload:me.Upload,"volume-2":me.Volume2,x:me.X,"at-sign":me.AtSign,"arrow-left":me.ArrowLeft,"arrow-right":me.ArrowRight,"external-link":me.ExternalLink,ellipsis:me.Ellipsis,"ellipsis-vertical":me.EllipsisVertical,menu:me.Menu,"panel-left":me.PanelLeft,plus:me.Plus,minus:me.Minus,pencil:me.Pencil,trash:me.Trash,"trash-2":me.Trash2,download:me.Download,maximize:me.Maximize,minimize:me.Minimize,"message-square":me.MessageSquare,star:me.Star,eye:me.Eye,history:me.History},UP=["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"],bp=new Map(Object.entries(zP)),Ca=new Set,Ag=!1,vp=new Set,qP=t=>{let e=[...vp];t&&vp.clear();for(let n of e)try{n()}catch{}},Sw=t=>Ag?()=>{}:(vp.add(t),()=>{vp.delete(t)}),jP=()=>{let t=0;for(let e of[...Ca]){let n=bp.get(e.name);if(!n)continue;Ca.delete(e),t++;let o=Ge(n,e.size,e.color,e.strokeWidth);if(o)for(e.el.removeAttribute("data-persona-icon-pending");o.firstChild;)e.el.appendChild(o.firstChild)}return t},Mg=!1,KP=()=>{hp().then(t=>{if(!Ag){for(let[e,n]of Object.entries(t.EXTRA_LUCIDE_ICONS))bp.has(e)||bp.set(e,n);Ag=!0,jP(),qP(!0)}}).catch(t=>{Mg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",t)})},GP=(t,e,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",e),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o},ke=(t,e=24,n="currentColor",o=2)=>{let r=bp.get(t);if(r)return Ge(r,e,n,o);if(UP.includes(t)){Mg&&(Mg=!1);let s=GP(e,n,o);if(Ca.size>=500){let a=Ca.values().next().value;a&&Ca.delete(a)}return Ca.add({el:s,name:t,size:e,color:n,strokeWidth:o}),KP(),s}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}});var Lw={};$n(Lw,{DOMPurify:()=>Pw.default,Marked:()=>kw.Marked});var kw,Pw,Iw=be(()=>{"use strict";kw=require("marked"),Pw=pw(require("dompurify"),1)});var pO,tL,nL,kg,kp,Rw,Hw,xa,Pg,Ro,Si=be(()=>{"use strict";ro();({setLoader:pO,load:tL,provide:nL,getSync:kg}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(Iw(),Lw))})),kp=new Set,Rw=()=>{let t=[...kp];kp.clear();for(let e of t)try{e()}catch{}},Hw=()=>{let t=kg();return t?Promise.resolve(t):tL().then(e=>(Rw(),e))},xa=t=>kg()?()=>{}:(kp.add(t),()=>{kp.delete(t)}),Pg=t=>{nL(t),Rw()},Ro=kg});var oL,Lg,Pp,fO,$r,Lp=be(()=>{"use strict";Si();oL=t=>{if(!t)return;let e={},n=t;if(n.heading){let o=n.heading;e.heading=(r,s,a)=>o({type:"heading",raw:a,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;e.code=(r,s,a)=>o({type:"code",raw:"",text:r,lang:s,escaped:a})}if(n.blockquote){let o=n.blockquote;e.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;e.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;e.link=(r,s,a)=>o({type:"link",raw:"",href:r,title:s??null,text:a,tokens:[]})}if(n.image){let o=n.image;e.image=(r,s,a)=>o({type:"image",raw:"",href:r,title:s??null,text:a})}if(n.list){let o=n.list;e.list=(r,s,a)=>o({type:"list",raw:"",ordered:s,start:a,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;e.listitem=(r,s,a)=>o({type:"list_item",raw:"",task:s,checked:a,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;e.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;e.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;e.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;e.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;e.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;e.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;e.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;e.checkbox=r=>o({checked:r})}return n.hr&&(e.hr=n.hr),n.br&&(e.br=n.br),e},Lg=t=>{let e=null;return n=>{let o=Ro();if(!o)return $r(n);if(!e){let{Marked:r}=o,s=t?.markedOptions;e=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=oL(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},Pp=t=>t?Lg({markedOptions:t.options,renderer:t.renderer}):Lg(),fO=Lg(),$r=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")});var rL,sL,iL,Ip,Ig=be(()=>{"use strict";Lp();Si();rL={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},sL=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,iL=()=>{let t=null;return e=>{let n=Ro();if(!n)return $r(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!sL.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,rL)}},Ip=t=>t===!1?null:typeof t=="function"?t:iL()});function qw(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${dL(e.join(""))}`}function zw(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function dL(t){let e=zw(t,0).toString(36),n=zw(t,2654435761).toString(36);return`${e}.${n}`}var zr,Hg,Uw,Rp,$w,pL,Sa,jw,Aa=be(()=>{"use strict";zr="webmcp:",Hg=new Map,Uw=t=>{Hg.clear();for(let e of t){let n=e.title?.trim();n&&Hg.set(e.name,n)}},Rp=t=>Hg.get(pL(t)),$w=null;pL=t=>t.startsWith(zr)?t.slice(zr.length):t,Sa=t=>t.startsWith(zr),jw=()=>$w?$w():import("@mcp-b/webmcp-polyfill")});var Kw,uL,Hp,Bp,mL,Wp,fL,gL,hL,Ko,yL,bL,vL,CL,Gw=be(()=>{"use strict";Kw="webmcp:",uL=t=>t.startsWith(Kw)?t.slice(Kw.length):t,Hp={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},Bp=class{constructor(e,n){this.config=e;this.deps=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(r){return Hp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.deps.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s=fL(r.annotations);return{name:r.name,description:r.description,parametersSchema:gL(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Ko("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return Ko(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=uL(e),a;try{a=await r.getTools()}catch(b){let C=b instanceof Error?b.message:String(b);return Ko(`Failed to read WebMCP registry: ${C}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(b=>b.name===s);if(!l)return Ko(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Ko(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Ko("Aborted by cancel()");let c=this.deps.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...c?{title:c}:{},reason:"gate"};if(!await this.requestConfirm(p))return Ko("User declined the tool call.");if(o?.aborted)return Ko("Aborted by cancel()");let u=new AbortController,m=!1,g=setTimeout(()=>{m=!0,u.abort()},this.timeoutMs),h=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",h,{once:!0}));try{let b=await r.executeTool(l,vL(n),{signal:u.signal});return hL(b)}catch(b){if(m)return Ko(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Ko("Aborted by cancel()");let C=b instanceof Error?b.message:String(b);return Ko(C)}finally{clearTimeout(g),o&&o.removeEventListener("abort",h)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(await this.deps.loadPolyfill()).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Hp.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Hp.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){let n=this.confirmHandler??yL;try{return await n(e)}catch(o){return Hp.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>mL(e,o))}},mL=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},Wp={type:"object",properties:{}},fL=t=>{if(!t||typeof t!="object")return;let e={...typeof t.readOnlyHint=="boolean"?{readOnlyHint:t.readOnlyHint}:{},...typeof t.untrustedContentHint=="boolean"?{untrustedContentHint:t.untrustedContentHint}:{}};return Object.keys(e).length>0?e:void 0},gL=t=>{if(t===void 0||t==="")return{...Wp};if(typeof t=="object")return t!==null&&!Array.isArray(t)?t:{...Wp};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{...Wp}}catch{return{...Wp}}},hL=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:CL(e)}]}},Ko=t=>({isError:!0,content:[{type:"text",text:t}]}),yL=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=bL(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
2
2
 
3
3
  Arguments:
4
4
  ${e}`:"")+(t.description?`
5
5
 
6
- ${t.description}`:"");return window.confirm(n)},K0=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},G0=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Y0=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}});var OC={};Vn(OC,{WebMcpBridge:()=>np});var DC=be(()=>{"use strict";BC()});var v,$C,$,Vt,Ye=be(()=>{"use strict";v=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},$C=()=>document.createDocumentFragment(),$=(t,e={},...n)=>{let o=document.createElement(t);if(e.className&&(o.className=e.className),e.text!==void 0&&(o.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))o.setAttribute(s,a);if(e.style){let s=o.style,a=e.style;for(let l of Object.keys(a)){let d=a[l];d!=null&&(s[l]=d)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Vt=(...t)=>t.filter(Boolean).join(" ")});var ca,rw,us,kL,sw,LL,PL,iw,IL,aw,lp,Hl,cp,Qf,dp,Il,HL,Rl,lw,cw,dw,pw,ri=be(()=>{"use strict";ca=require("partial-json"),rw=t=>t.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),us=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},kL=t=>{let e=t.completedAt??Date.now(),n=t.startedAt??e,r=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},sw=t=>t.status==="complete"?kL(t):t.status==="pending"?"Waiting":"",LL=15e3,PL=1200,iw=(t,e)=>{let n=e?.durationMs??LL,o=e?.chars??PL;return typeof t.durationMs=="number"?t.durationMs<n:(t.chunks??[]).join("").length<o},IL=t=>{let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},aw=t=>t.status==="complete"?IL(t):"Using tool...",lp=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Hl=t=>{let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return lp(e)},cp=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return lp(e)},Qf=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=Hl(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},dp=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Il(o,n.slice(s,a.index),[]),a[1]!==void 0?Il(o,a[1],["bold"]):a[2]!==void 0?Il(o,a[2],["italic"]):a[3]!==void 0&&Il(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Il(o,n.slice(s),[]),o},Il=(t,e,n)=>{let o=e.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&t.push({text:o[r],styles:n}),r<o.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},HL=()=>{let t=null,e=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
6
+ ${t.description}`:"");return window.confirm(n)},bL=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},vL=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},CL=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}});var Yw={};$n(Yw,{WebMcpBridge:()=>Bp});var Qw=be(()=>{"use strict";Gw()});var Ia,hx,mr,nI,yx,oI,rI,bx,sI,vx,Vp,Kl,$p,$g,zp,jl,iI,Gl,Cx,wx,xx,Sx,Ts=be(()=>{"use strict";Ia=require("partial-json"),hx=t=>t.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),mr=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},nI=t=>{let e=t.completedAt??Date.now(),n=t.startedAt??e,r=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},yx=t=>t.status==="complete"?nI(t):t.status==="pending"?"Waiting":"",oI=15e3,rI=1200,bx=(t,e)=>{let n=e?.durationMs??oI,o=e?.chars??rI;return typeof t.durationMs=="number"?t.durationMs<n:(t.chunks??[]).join("").length<o},sI=t=>{let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},vx=t=>t.status==="complete"?sI(t):"Using tool...",Vp=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Kl=t=>{let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return Vp(e)},$p=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return Vp(e)},$g=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=Kl(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},zp=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&jl(o,n.slice(s,a.index),[]),a[1]!==void 0?jl(o,a[1],["bold"]):a[2]!==void 0?jl(o,a[2],["italic"]):a[3]!==void 0&&jl(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&jl(o,n.slice(s),[]),o},jl=(t,e,n)=>{let o=e.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&t.push({text:o[r],styles:n}),r<o.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},iI=()=>{let t=null,e=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
8
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},Rl=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},lw=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},cw=()=>{let t=HL();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},dw=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=(0,ca.parse)(n,ca.STR|ca.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?rw(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=rw(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}},pw=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}}});function qL(t){let e=0;for(let n of t.split(`
10
- `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>e&&(e=o[1].length)}return e}function Dl(t,e){let n="`".repeat(Math.max(3,qL(e)+1));return`${n}${t}
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},Gl=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Cx=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},wx=()=>{let t=iI();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},xx=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=(0,Ia.parse)(n,Ia.STR|Ia.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?hx(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=hx(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}},Sx=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}}});function vI(t){let e=0;for(let n of t.split(`
10
+ `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>e&&(e=o[1].length)}return e}function Jl(t,e){let n="`".repeat(Math.max(3,vI(e)+1));return`${n}${t}
11
11
  ${e}
12
- ${n}`}function jL(t,e,n){return e.includes("</document_content>")?Dl(t,e):`<document index="${n+1}">
12
+ ${n}`}function CI(t,e,n){return e.includes("</document_content>")?Jl(t,e):`<document index="${n+1}">
13
13
  <source>${t}</source>
14
14
  <document_content>
15
15
  ${e}
16
16
  </document_content>
17
- </document>`}function Iw(t,e,n="fenced"){if(typeof n=="function")try{return n(t,e)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),Dl(t.label,t.text)}return n==="document"?jL(t.label,t.text,e):Dl(t.label,t.text)}var eg=be(()=>{"use strict"});function gp(t){return t instanceof ir}var ir,_l=be(()=>{"use strict";ir=class extends Error{constructor(e,n,o){super(n),this.name="HistoryProviderError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}}});var pa,rg=be(()=>{"use strict";pa=class{constructor(e=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=e;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(e*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let r=new Uint8Array(this.remainder.length+e.length);r.set(this.remainder),r.set(e,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,e.length,this.sampleRate);o.getChannelData(0).set(e);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of a)l()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),o=new Float32Array(n),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function ZL(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===JL?new Uint8Array(t,44):new Uint8Array(t)}function eP(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var Bw,YL,QL,XL,JL,ua,sg=be(()=>{"use strict";rg();Bw=16e3,YL=24e3,QL=4096,XL=4,JL=1380533830;ua=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.levelCallbacks=[];this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Bw,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(m=>m.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:Bw});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new pa(YL);if(r!==this.callGeneration){d.destroy(),s.getTracks().forEach(m=>m.stop()),l.close().catch(()=>{});return}this.playback=d,d.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let p=`${eP(o)}/ws/agents/${encodeURIComponent(e)}/voice`,u=new WebSocket(p,["runtype.bearer",n]);u.binaryType="arraybuffer",this.ws=u,u.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,u,r))},u.onmessage=m=>this.handleMessage(m,r),u.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},u.onclose=m=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(m.code!==1e3){let y=m.code?` (code ${m.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}onLevel(e){this.levelCallbacks.push(e)}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(QL,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),p=new Int16Array(d.length),u=0;for(let m=0;m<d.length;m++){let y=Math.max(-1,Math.min(1,d[m]));u+=y*y,p[m]=y<0?y*32768:y*32767}if(o.send(p.buffer),this.levelCallbacks.length>0){let m=Math.sqrt(u/d.length),y=Math.max(0,Math.min(1,m*XL));for(let g of this.levelCallbacks)g(y)}},s.connect(a),a.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let o=ZL(e);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}}});var ms,ig=be(()=>{"use strict";ms=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}}});function Vl(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new ua(t.runtype);case"browser":if(!ms.isSupported())throw new Error("Browser speech recognition not supported");return new ms(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function ag(t){if(t?.type==="custom"&&t.custom)return Vl({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return Vl({type:"runtype",runtype:t.runtype});if(ms.isSupported())return Vl({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ow(t){try{return ag(t),!0}catch{return!1}}var Dw=be(()=>{"use strict";sg();ig()});var _w={};Vn(_w,{BrowserVoiceProvider:()=>ms,RuntypeVoiceProvider:()=>ua,createBestAvailableVoiceProvider:()=>ag,createVoiceProvider:()=>Vl,isVoiceSupported:()=>Ow});var Nw=be(()=>{"use strict";Dw();sg();ig()});function oP(t){return t.replace(/\/+$/,"")}async function rP(t){try{let e=await t.json();return e.detail?`${e.error??`Runtype TTS ${t.status}`}: ${e.detail}`:e.error??`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var yp,Vw=be(()=>{"use strict";rg();yp=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new pa(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(e=>this.player=e))}speak(e,n){let o=++this.generation;this.run(o,e,n)}async run(e,n,o){try{let r=await this.ensurePlayer();if(e!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.generation&&o.onStart?.()}),r.onFinished(()=>{e===this.generation&&o.onEnd?.()});let s=`${oP(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!a.ok||!a.body)throw new Error(await rP(a));let l=a.body.getReader();for(;;){let{done:d,value:p}=await l.read();if(e!==this.generation){await l.cancel().catch(()=>{});return}if(d)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(e!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var bp,$w=be(()=>{"use strict";bp=class{constructor(e,n,o={}){this.primary=e;this.fallback=n;this.options=o;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let o=!1;this.primary.speak(e,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var zw={};Vn(zw,{FallbackSpeechEngine:()=>bp,RuntypeSpeechEngine:()=>yp});var Uw=be(()=>{"use strict";Vw();$w()});var jw={};Vn(jw,{createReconnectController:()=>iP});function iP(t){let e=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},a=()=>{let b=t.getStatus();b!=="resuming"&&b!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},d=()=>{a()},p=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",d),r=!0)},u=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",d),r=!1)},m=b=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},b)}),y=()=>{let b=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,u(),t.setAbortController(null);let C=!1;for(let T of t.getMessages())T.streaming&&(T.streaming=!1,C=!0);let S=t.buildErrorContent("Connection lost and the response could not be resumed.");S?t.appendMessage({id:`reconnect-failed-${b?.executionId??t.nextSequence()}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:t.nextSequence()}):C&&t.notifyMessagesChanged(),t.setStreaming(!1),t.setStatus("idle"),t.onError(new Error("Durable session reconnect failed."))},g=async()=>{let b=t.config.reconnect?.backoffMs??sP,C=t.config.reconnect?.maxAttempts??b.length,S=t.config.reconnectStream;if(!S){t.setReconnecting(!1);return}for(;t.getResumable()&&e<C;){e+=1,t.setStatus("resuming");let T=t.getResumable(),A=T.lastEventId,I=new AbortController;t.setAbortController(I),t.emitReconnect({phase:"resuming",handle:T,attempt:e});let M=null;try{let O=await S({executionId:T.executionId,after:T.lastEventId,signal:I.signal});O&&O.ok&&O.body&&(M=O.body)}catch{M=null}if(I.signal.aborted)return;if(M){let O=t.getMessages().find(B=>B.id===T.assistantMessageId)?.content,k=typeof O=="string"?O:"";try{await t.resumeConnect(M,T.assistantMessageId,k)}catch{}if(I.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,u(),t.emitReconnect({phase:"resumed",handle:T});return}t.getResumable().lastEventId!==A&&(e=0)}if(t.getResumable()&&e<C&&(t.setStatus("paused"),await m(b[Math.min(e-1,b.length-1)]??1e3),I.signal.aborted))return}t.getResumable()&&y()};return{begin(){e=0,p(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,u()},wake:s}}var sP,Kw=be(()=>{"use strict";sP=[1e3,2e3,4e3,8e3,8e3]});var Qe,ro=be(()=>{"use strict";Qe=(t,e=24,n="currentColor",o=2)=>{if(!Array.isArray(t))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([p,u])=>{p!=="stroke"&&d.setAttribute(p,String(u))}),r.appendChild(d)}),r}});var Qw={};Vn(Qw,{EXTRA_LUCIDE_ICONS:()=>pP});var ae,pP,Xw=be(()=>{"use strict";ae=require("lucide"),pP={user:ae.User,mail:ae.Mail,phone:ae.Phone,calendar:ae.Calendar,clock:ae.Clock,building:ae.Building,"map-pin":ae.MapPin,lock:ae.Lock,key:ae.Key,"credit-card":ae.CreditCard,hash:ae.Hash,globe:ae.Globe,link:ae.Link,"circle-check":ae.CircleCheck,"circle-x":ae.CircleX,"triangle-alert":ae.TriangleAlert,info:ae.Info,ban:ae.Ban,shield:ae.Shield,house:ae.House,"pen-line":ae.PenLine,save:ae.Save,share:ae.Share,funnel:ae.Funnel,settings:ae.Settings,"rotate-cw":ae.RotateCw,"shopping-cart":ae.ShoppingCart,"shopping-bag":ae.ShoppingBag,package:ae.Package,truck:ae.Truck,tag:ae.Tag,gift:ae.Gift,receipt:ae.Receipt,wallet:ae.Wallet,store:ae.Store,"dollar-sign":ae.DollarSign,percent:ae.Percent,play:ae.Play,pause:ae.Pause,"volume-x":ae.VolumeX,camera:ae.Camera,image:ae.Image,film:ae.Film,headphones:ae.Headphones,"message-circle":ae.MessageCircle,bell:ae.Bell,heart:ae.Heart,"eye-off":ae.EyeOff,bookmark:ae.Bookmark,"calendar-days":ae.CalendarDays,timer:ae.Timer,folder:ae.Folder,"folder-open":ae.FolderOpen,files:ae.Files,"chart-column":ae.ChartColumn,sparkles:ae.Sparkles,zap:ae.Zap,sun:ae.Sun,moon:ae.Moon,flag:ae.Flag,lightbulb:ae.Lightbulb,monitor:ae.Monitor,smartphone:ae.Smartphone}});var uP,mP,mg,Cp,wp=be(()=>{"use strict";oo();({setLoader:uP,load:mP}=$t({fallbackImport:()=>Promise.resolve().then(()=>(Xw(),Qw))})),mg=uP,Cp=mP});var me,fP,gP,xp,ma,fg,Sp,hP,Jw,yP,gg,bP,vP,Ie,Yt=be(()=>{"use strict";ro();wp();me=require("lucide"),fP={activity:me.Activity,"arrow-down":me.ArrowDown,"arrow-up":me.ArrowUp,"arrow-up-right":me.ArrowUpRight,bot:me.Bot,"chevron-down":me.ChevronDown,"chevron-up":me.ChevronUp,"chevron-right":me.ChevronRight,"chevron-left":me.ChevronLeft,check:me.Check,clipboard:me.Clipboard,"clipboard-copy":me.ClipboardCopy,"code-xml":me.CodeXml,copy:me.Copy,file:me.File,"file-code":me.FileCode,"file-spreadsheet":me.FileSpreadsheet,"file-text":me.FileText,"image-plus":me.ImagePlus,loader:me.Loader,"loader-circle":me.LoaderCircle,mic:me.Mic,paperclip:me.Paperclip,quote:me.Quote,"refresh-cw":me.RefreshCw,search:me.Search,send:me.Send,"shield-alert":me.ShieldAlert,"shield-check":me.ShieldCheck,"shield-x":me.ShieldX,square:me.Square,"thumbs-down":me.ThumbsDown,"thumbs-up":me.ThumbsUp,upload:me.Upload,"volume-2":me.Volume2,x:me.X,"at-sign":me.AtSign,"arrow-left":me.ArrowLeft,"arrow-right":me.ArrowRight,"external-link":me.ExternalLink,ellipsis:me.Ellipsis,"ellipsis-vertical":me.EllipsisVertical,menu:me.Menu,"panel-left":me.PanelLeft,plus:me.Plus,minus:me.Minus,pencil:me.Pencil,trash:me.Trash,"trash-2":me.Trash2,download:me.Download,maximize:me.Maximize,minimize:me.Minimize,"message-square":me.MessageSquare,star:me.Star,eye:me.Eye,history:me.History},gP=["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"],xp=new Map(Object.entries(fP)),ma=new Set,fg=!1,Sp=new Set,hP=t=>{let e=[...Sp];t&&Sp.clear();for(let n of e)try{n()}catch{}},Jw=t=>fg?()=>{}:(Sp.add(t),()=>{Sp.delete(t)}),yP=()=>{let t=0;for(let e of[...ma]){let n=xp.get(e.name);if(!n)continue;ma.delete(e),t++;let o=Qe(n,e.size,e.color,e.strokeWidth);if(o)for(e.el.removeAttribute("data-persona-icon-pending");o.firstChild;)e.el.appendChild(o.firstChild)}return t},gg=!1,bP=()=>{Cp().then(t=>{if(!fg){for(let[e,n]of Object.entries(t.EXTRA_LUCIDE_ICONS))xp.has(e)||xp.set(e,n);fg=!0,yP(),hP(!0)}}).catch(t=>{gg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",t)})},vP=(t,e,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",e),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o},Ie=(t,e=24,n="currentColor",o=2)=>{let r=xp.get(t);if(r)return Qe(r,e,n,o);if(gP.includes(t)){gg&&(gg=!1);let s=vP(e,n,o);if(ma.size>=500){let a=ma.values().next().value;a&&ma.delete(a)}return ma.add({el:s,name:t,size:e,color:n,strokeWidth:o}),bP(),s}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}});var fn,Hn,fa,fs=be(()=>{"use strict";fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Hn=1e5,fa=Hn+1});function gx(t){let e=t.getRootNode?.();return e&&hx(e)||e&&_p(e)?e:t.ownerDocument??document}function Dp(t,e,n){let o=_p(t)?t.head:t,r=e.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let a=(_p(t)?t:t.ownerDocument??document).createElement("style");a.setAttribute("data-persona-plugin-style",e),a.textContent=n,o.appendChild(a)}function Np(t,e,n){if(_p(t)||hx(t)){Dp(t,e,n);return}let o=t;if(o.isConnected){Dp(gx(o),e,n);return}let r=o.ownerDocument??document;Dp(r,e,n),queueMicrotask(()=>{let s=gx(o);s!==r&&Dp(s,e,n)})}function OP(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function gs(t){let{anchor:e,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:l,zIndex:d=2147483e3,onOpen:p,onDismiss:u}=t,m=t.container??OP(e),y=!1,g=null,b=()=>{if(!y)return;let T=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${T.width}px`),a&&(n.style.maxWidth=`${T.width}px`);let A=n.getBoundingClientRect(),I=l?.()??null,M=I!=null?T.top+I:T.top,O=o==="top-start"||o==="top-end"?M-r-A.height:T.bottom+r,B=o==="bottom-end"||o==="top-end"?T.right-A.width:T.left,W=a?.()??null;if(W!=null){let V=Math.max(T.left,T.right-A.width);B=Math.min(Math.max(T.left+W,T.left),V)}n.style.top=`${O}px`,n.style.left=`${B}px`},C=()=>{y&&(y=!1,g&&(g(),g=null),n.remove())},S=()=>{if(y)return;y=!0,d!=null&&(n.style.zIndex=String(d)),m.appendChild(n),b();let T=(e.ownerDocument??document).defaultView??window,A=e.ownerDocument??document,I=()=>{if(!e.isConnected){C(),u?.("anchor-removed");return}b()},M=k=>{let B=typeof k.composedPath=="function"?k.composedPath():[];B.includes(n)||B.includes(e)||(C(),u?.("outside"))},O=T.setTimeout(()=>{A.addEventListener("pointerdown",M,!0)},0);T.addEventListener("scroll",I,!0),T.addEventListener("resize",I),g=()=>{T.clearTimeout(O),A.removeEventListener("pointerdown",M,!0),T.removeEventListener("scroll",I,!0),T.removeEventListener("resize",I)},p?.()};return{get isOpen(){return y},open:S,close:C,toggle:()=>y?C():S(),reposition:b,destroy:C}}function yx(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var _p,hx,ya=be(()=>{"use strict";_p=t=>t.nodeType===Node.DOCUMENT_NODE,hx=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&t.host!==void 0});function ba(t){t.style.display=t.childElementCount>0?"flex":"none"}function Pg(t){let e=t.querySelector(Lg);if(e)return e;let n=$("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=t.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===t?t.insertBefore(n,o):t.appendChild(n),n}var Lg,Fp=be(()=>{"use strict";Ye();Lg="[data-persona-composer-chip-row]"});function jl(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function qx(t){let e=()=>{t.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:t,getValue:()=>t.value,getLogicalText:()=>t.value,getSelection:()=>({start:t.selectionStart??0,end:t.selectionEnd??0}),setSelection:(n,o=n)=>{t.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{t.value=n,t.setSelectionRange(o,o)},setValue:n=>{t.value=n,t.setSelectionRange(n.length,n.length),e(),t.focus()},submit:()=>jl(t.form),dispatchInput:e,focus:()=>t.focus()}}var zp=be(()=>{"use strict"});function iI(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
18
- `:o===""||Yx.test(o)}function aI(t,e,n="@",o="anywhere",r=!1){if(!n||e<=0||e>t.length)return null;let s=e-1;for(;s>=0;){let a=t[s];if(a===n)return iI(t,s,o)?{triggerIndex:s,query:t.slice(s+1,e)}:null;if(a===`
19
- `||a==="\uFFFC"||!r&&Yx.test(a))return null;s--}return null}function Kl(t,e,n){for(let o of n){let r=aI(t,e,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Qx(t){return t?t!=="insertFromPaste"&&t!=="insertFromDrop":!0}function Xx(t,e,n){return{value:t.slice(0,e.triggerIndex)+t.slice(n),caret:e.triggerIndex}}var Yx,Up=be(()=>{"use strict";Yx=/\s/});function qp(t){let e={trigger:t.trigger??"@",position:t.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(t.sources)?t.sources:[],searchPlaceholder:t.searchPlaceholder,showButton:t.showButton!==!1,buttonIconName:t.buttonIconName,buttonTooltipText:t.buttonTooltipText},n=(t.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[e,...n]}var Rg=be(()=>{"use strict"});var Zx,Wg,jp,Kp=be(()=>{"use strict";Zx=null,Wg=t=>{Zx=t},jp=(t,e,n,o)=>Zx?.(t,e,n,o)??null});function tS(t){let{ref:e,config:n,onRemove:o}=t;if(n.renderMentionChip){let g="resolving",b,C=n.renderMentionChip({ref:e,status:g,payload:b,remove:o});return{get el(){return C},setStatus:(T,A)=>{if(T===g&&A===b)return;g=T,b=A;let I=n.renderMentionChip({ref:e,status:g,payload:b,remove:o});C.replaceWith(I),C=I}}}let r=e.iconName??n.chipIconName??"at-sign",s=$("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),a=v("span","persona-mention-chip-icon"),l=g=>{a.replaceChildren();let b=jp(g,13,"currentColor",2);b&&a.appendChild(b)};l(r);let d=v("span","persona-mention-chip-spinner"),p=$("span",{className:"persona-mention-chip-label",text:e.label}),u=$("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),m=Qe(eS.X,11,"currentColor",2.5);return m?u.appendChild(m):u.textContent="\xD7",u.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),o()}),s.appendChild(d),s.appendChild(p),s.appendChild(u),{el:s,setStatus:g=>{s.setAttribute("data-status",g),g==="resolving"?(d.parentNode!==s&&s.insertBefore(d,p),a.parentNode===s&&a.remove(),s.setAttribute("title",e.label)):(d.parentNode===s&&d.remove(),a.parentNode!==s&&s.insertBefore(a,p),g==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${e.label} to context`)):(l(r),s.setAttribute("title",e.label)))}}}var eS,nS=be(()=>{"use strict";Ye();eS=require("lucide");ro();Kp()});function Gp(t,e){return{sourceId:t.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var oS,Yp,Bg=be(()=>{"use strict";nS();Fp();eg();oS=(t,e)=>`${t}\0${e}`,Yp=class{constructor(e){this.mentions=[];this.opts=e,this.updateRowVisibility()}get maxMentions(){return this.opts.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(e,n,o=""){let r=oS(e.id,n.id);if(this.mentions.some(l=>l.key===r))return this.reject(e,n,"duplicate");if(this.atLimit())return this.reject(e,n,"limit");let s=Gp(e,n),a={key:r,source:e,item:n,ref:s,status:"resolving",args:o};return a.chip=tS({ref:s,config:this.opts.mentionConfig,onRemove:()=>this.remove(r)}),a.chip.el.setAttribute("data-persona-chip-enter",""),a.chip.el.addEventListener("animationend",()=>a.chip?.el.removeAttribute("data-persona-chip-enter"),{once:!0}),this.opts.contextRow.appendChild(a.chip.el),this.startPending(a),this.updateRowVisibility(),!0}atLimit(){return this.mentions.length>=this.maxMentions}admit(e,n){return this.atLimit()?this.reject(e,n,"limit"):!0}track(e,n,o,r="",s){let a={key:e,source:n,item:o,ref:Gp(n,o),status:"resolving",args:r,reportStatus:s};this.startPending(a)}reject(e,n,o){return this.opts.mentionConfig.onMentionRejected?.(n,o),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:o}),!1}startPending(e){this.mentions.push(e),e.source.resolveOn==="submit"?(e.status="ready",e.chip?.setStatus("ready"),e.reportStatus?.("resolved")):e.resolvePromise=this.resolvePending(e),this.opts.announce(`Added ${e.ref.label} to context`)}buildResolveContext(e,n,o=this.opts.getComposerText()){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:o,args:n,signal:e}}async resolvePending(e){let n=new AbortController;e.abort=n;try{let o=await e.source.resolve(e.item,this.buildResolveContext(n.signal,e.args));if(n.signal.aborted)return;e.payload=o,e.status="ready",e.chip?.setStatus("ready",o),e.reportStatus?.("resolved")}catch(o){if(n.signal.aborted)return;e.status="error",e.chip?.setStatus("error"),e.reportStatus?.("error"),(this.opts.announceError??this.opts.announce)(`Couldn't attach ${e.ref.label} to context`),this.opts.mentionConfig.onMentionResolveError?.(e.item,o),this.opts.emit?.("resolve-error",{sourceId:e.source.id,itemId:e.item.id})}}remove(e){let n=this.mentions.findIndex(r=>r.key===e);if(n===-1)return;let[o]=this.mentions.splice(n,1);o.abort?.abort(),o.chip?.el.remove(),this.updateRowVisibility(),this.opts.announce(`Removed ${o.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.updateRowVisibility()}collectForSubmit(){let e=[...this.mentions],n=e.map(s=>s.ref),o=this.opts.getComposerText();for(let s of e)s.chip?.el.remove();return this.mentions.length=0,this.updateRowVisibility(),{refs:n,finalize:async()=>{var u;let s=await Promise.all(e.map(async m=>{try{return m.source.resolveOn==="submit"?await m.source.resolve(m.item,this.buildResolveContext(new AbortController().signal,m.args,o)):(m.resolvePromise&&await m.resolvePromise,m.payload??null)}catch(y){try{this.opts.mentionConfig.onMentionResolveError?.(m.item,y)}catch(g){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",g)}return this.opts.emit?.("resolve-error",{sourceId:m.source.id,itemId:m.item.id}),null}})),a=[],l=[],d={},p=new Set;for(let m=0;m<e.length;m++){let y=e[m],g=s[m];if(!g)continue;let b=oS(y.source.id,y.item.id);if(!p.has(b)){if(p.add(b),g.llmAppend&&g.llmAppend.trim())try{a.push(Iw({label:y.ref.label,text:g.llmAppend,ref:y.ref,item:y.item},a.length,this.opts.mentionConfig.llmFormat))}catch(C){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",C)}g.contentParts?.length&&l.push(...g.contentParts),g.context&&((d[u=y.source.id]??(d[u]={}))[y.item.id]=g.context)}}return{blocks:a,contentParts:l,context:d}}}}updateRowVisibility(){ba(this.opts.contextRow)}}});var rS,sS=be(()=>{"use strict";rS=`
17
+ </document>`}function Ux(t,e,n="fenced"){if(typeof n=="function")try{return n(t,e)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),Jl(t.label,t.text)}return n==="document"?CI(t.label,t.text,e):Jl(t.label,t.text)}var Kg=be(()=>{"use strict"});function Gp(t){return t instanceof gr}var gr,Zl=be(()=>{"use strict";gr=class extends Error{constructor(e,n,o){super(n),this.name="HistoryProviderError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}}});var Ha,Xg=be(()=>{"use strict";Ha=class{constructor(e=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=e;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(e*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let r=new Uint8Array(this.remainder.length+e.length);r.set(this.remainder),r.set(e,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,e.length,this.sampleRate);o.getChannelData(0).set(e);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of a)l()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),o=new Float32Array(n),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function EI(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===TI?new Uint8Array(t,44):new Uint8Array(t)}function kI(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var Gx,SI,AI,MI,TI,Wa,Jg=be(()=>{"use strict";Xg();Gx=16e3,SI=24e3,AI=4096,MI=4,TI=1380533830;Wa=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.levelCallbacks=[];this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Gx,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(m=>m.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:Gx});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let c=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ha(SI);if(r!==this.callGeneration){c.destroy(),s.getTracks().forEach(m=>m.stop()),l.close().catch(()=>{});return}this.playback=c,c.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let p=`${kI(o)}/ws/agents/${encodeURIComponent(e)}/voice`,u=new WebSocket(p,["runtype.bearer",n]);u.binaryType="arraybuffer",this.ws=u,u.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,u,r))},u.onmessage=m=>this.handleMessage(m,r),u.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},u.onclose=m=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(m.code!==1e3){let g=m.code?` (code ${m.code})`:"";this.emitError(new Error(`Voice connection closed${g}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}onLevel(e){this.levelCallbacks.push(e)}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(AI,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=l.inputBuffer.getChannelData(0),p=new Int16Array(c.length),u=0;for(let m=0;m<c.length;m++){let g=Math.max(-1,Math.min(1,c[m]));u+=g*g,p[m]=g<0?g*32768:g*32767}if(o.send(p.buffer),this.levelCallbacks.length>0){let m=Math.sqrt(u/c.length),g=Math.max(0,Math.min(1,m*MI));for(let h of this.levelCallbacks)h(g)}},s.connect(a),a.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let o=EI(e);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}}});var Es,Zg=be(()=>{"use strict";Es=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}}});function nc(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Wa(t.runtype);case"browser":if(!Es.isSupported())throw new Error("Browser speech recognition not supported");return new Es(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function eh(t){if(t?.type==="custom"&&t.custom)return nc({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return nc({type:"runtype",runtype:t.runtype});if(Es.isSupported())return nc({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Yx(t){try{return eh(t),!0}catch{return!1}}var Qx=be(()=>{"use strict";Jg();Zg()});var Xx={};$n(Xx,{BrowserVoiceProvider:()=>Es,RuntypeVoiceProvider:()=>Wa,createBestAvailableVoiceProvider:()=>eh,createVoiceProvider:()=>nc,isVoiceSupported:()=>Yx});var Jx=be(()=>{"use strict";Qx();Jg();Zg()});function II(t){return t.replace(/\/+$/,"")}async function RI(t){try{let e=await t.json();return e.detail?`${e.error??`Runtype TTS ${t.status}`}: ${e.detail}`:e.error??`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var Qp,eS=be(()=>{"use strict";Xg();Qp=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Ha(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(e=>this.player=e))}speak(e,n){let o=++this.generation;this.run(o,e,n)}async run(e,n,o){try{let r=await this.ensurePlayer();if(e!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.generation&&o.onStart?.()}),r.onFinished(()=>{e===this.generation&&o.onEnd?.()});let s=`${II(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!a.ok||!a.body)throw new Error(await RI(a));let l=a.body.getReader();for(;;){let{done:c,value:p}=await l.read();if(e!==this.generation){await l.cancel().catch(()=>{});return}if(c)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(e!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var Xp,tS=be(()=>{"use strict";Xp=class{constructor(e,n,o={}){this.primary=e;this.fallback=n;this.options=o;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let o=!1;this.primary.speak(e,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var nS={};$n(nS,{FallbackSpeechEngine:()=>Xp,RuntypeSpeechEngine:()=>Qp});var oS=be(()=>{"use strict";eS();tS()});var sS={};$n(sS,{createReconnectController:()=>WI});function WI(t){let e=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},a=()=>{let b=t.getStatus();b!=="resuming"&&b!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},c=()=>{a()},p=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",c),r=!0)},u=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",c),r=!1)},m=b=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},b)}),g=()=>{let b=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,u(),t.setAbortController(null);let C=!1;for(let E of t.getMessages())E.streaming&&(E.streaming=!1,C=!0);let M=t.buildErrorContent("Connection lost and the response could not be resumed.");M?t.appendMessage({id:`reconnect-failed-${b?.executionId??t.nextSequence()}`,role:"assistant",content:M,createdAt:new Date().toISOString(),streaming:!1,sequence:t.nextSequence()}):C&&t.notifyMessagesChanged(),t.setStreaming(!1),t.setStatus("idle"),t.onError(new Error("Durable session reconnect failed."))},h=async()=>{let b=t.config.reconnect?.backoffMs??HI,C=t.config.reconnect?.maxAttempts??b.length,M=t.config.reconnectStream;if(!M){t.setReconnecting(!1);return}for(;t.getResumable()&&e<C;){e+=1,t.setStatus("resuming");let E=t.getResumable(),T=E.lastEventId,H=new AbortController;t.setAbortController(H),t.emitReconnect({phase:"resuming",handle:E,attempt:e});let A=null;try{let D=await M({executionId:E.executionId,after:E.lastEventId,signal:H.signal});D&&D.ok&&D.body&&(A=D.body)}catch{A=null}if(H.signal.aborted)return;if(A){let D=t.getMessages().find(U=>U.id===E.assistantMessageId)?.content,W=typeof D=="string"?D:"";try{await t.resumeConnect(A,E.assistantMessageId,W)}catch{}if(H.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,u(),t.emitReconnect({phase:"resumed",handle:E});return}t.getResumable().lastEventId!==T&&(e=0)}if(t.getResumable()&&e<C&&(t.setStatus("paused"),await m(b[Math.min(e-1,b.length-1)]??1e3),H.signal.aborted))return}t.getResumable()&&g()};return{begin(){e=0,p(),h()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,u()},wake:s}}var HI,iS=be(()=>{"use strict";HI=[1e3,2e3,4e3,8e3,8e3]});var dn,On,Ba,ks=be(()=>{"use strict";dn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},On=1e5,Ba=On+1});function xS(t){let e=t.getRootNode?.();return e&&SS(e)||e&&uu(e)?e:t.ownerDocument??document}function pu(t,e,n){let o=uu(t)?t.head:t,r=e.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let a=(uu(t)?t:t.ownerDocument??document).createElement("style");a.setAttribute("data-persona-plugin-style",e),a.textContent=n,o.appendChild(a)}function mu(t,e,n){if(uu(t)||SS(t)){pu(t,e,n);return}let o=t;if(o.isConnected){pu(xS(o),e,n);return}let r=o.ownerDocument??document;pu(r,e,n),queueMicrotask(()=>{let s=xS(o);s!==r&&pu(s,e,n)})}function eR(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function Ps(t){let{anchor:e,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:l,zIndex:c=2147483e3,onOpen:p,onDismiss:u}=t,m=t.container??eR(e),g=!1,h=null,b=()=>{if(!g)return;let E=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${E.width}px`),a&&(n.style.maxWidth=`${E.width}px`);let T=n.getBoundingClientRect(),H=l?.()??null,A=H!=null?E.top+H:E.top,D=o==="top-start"||o==="top-end"?A-r-T.height:E.bottom+r,U=o==="bottom-end"||o==="top-end"?E.right-T.width:E.left,B=a?.()??null;if(B!=null){let O=Math.max(E.left,E.right-T.width);U=Math.min(Math.max(E.left+B,E.left),O)}n.style.top=`${D}px`,n.style.left=`${U}px`},C=()=>{g&&(g=!1,h&&(h(),h=null),n.remove())},M=()=>{if(g)return;g=!0,c!=null&&(n.style.zIndex=String(c)),m.appendChild(n),b();let E=(e.ownerDocument??document).defaultView??window,T=e.ownerDocument??document,H=()=>{if(!e.isConnected){C(),u?.("anchor-removed");return}b()},A=W=>{let U=typeof W.composedPath=="function"?W.composedPath():[];U.includes(n)||U.includes(e)||(C(),u?.("outside"))},D=E.setTimeout(()=>{T.addEventListener("pointerdown",A,!0)},0);E.addEventListener("scroll",H,!0),E.addEventListener("resize",H),h=()=>{E.clearTimeout(D),T.removeEventListener("pointerdown",A,!0),E.removeEventListener("scroll",H,!0),E.removeEventListener("resize",H)},p?.()};return{get isOpen(){return g},open:M,close:C,toggle:()=>g?C():M(),reposition:b,destroy:C}}function AS(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var uu,SS,Oa=be(()=>{"use strict";uu=t=>t.nodeType===Node.DOCUMENT_NODE,SS=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&t.host!==void 0});function _a(t){t.style.display=t.childElementCount>0?"flex":"none"}function vh(t){let e=t.querySelector(bh);if(e)return e;let n=F("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=t.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===t?t.insertBefore(n,o):t.appendChild(n),n}var bh,fu=be(()=>{"use strict";je();bh="[data-persona-composer-chip-row]"});function sc(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function JS(t){let e=()=>{t.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:t,getValue:()=>t.value,getLogicalText:()=>t.value,getSelection:()=>({start:t.selectionStart??0,end:t.selectionEnd??0}),setSelection:(n,o=n)=>{t.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{t.value=n,t.setSelectionRange(o,o)},setValue:n=>{t.value=n,t.setSelectionRange(n.length,n.length),e(),t.focus()},submit:()=>sc(t.form),dispatchInput:e,focus:()=>t.focus()}}var yu=be(()=>{"use strict"});function AR(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
18
+ `:o===""||nA.test(o)}function MR(t,e,n="@",o="anywhere",r=!1){if(!n||e<=0||e>t.length)return null;let s=e-1;for(;s>=0;){let a=t[s];if(a===n)return AR(t,s,o)?{triggerIndex:s,query:t.slice(s+1,e)}:null;if(a===`
19
+ `||a==="\uFFFC"||!r&&nA.test(a))return null;s--}return null}function ic(t,e,n){for(let o of n){let r=MR(t,e,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function oA(t){return t?t!=="insertFromPaste"&&t!=="insertFromDrop":!0}function rA(t,e,n){return{value:t.slice(0,e.triggerIndex)+t.slice(n),caret:e.triggerIndex}}var nA,bu=be(()=>{"use strict";nA=/\s/});function vu(t){let e={trigger:t.trigger??"@",position:t.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(t.sources)?t.sources:[],searchPlaceholder:t.searchPlaceholder,showButton:t.showButton!==!1,buttonIconName:t.buttonIconName,buttonTooltipText:t.buttonTooltipText},n=(t.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[e,...n]}var xh=be(()=>{"use strict"});var iA,Sh,Cu,wu=be(()=>{"use strict";iA=null,Sh=t=>{iA=t},Cu=(t,e,n,o)=>iA?.(t,e,n,o)??null});function lA(t){let{ref:e,config:n,onRemove:o}=t;if(n.renderMentionChip){let h="resolving",b,C=n.renderMentionChip({ref:e,status:h,payload:b,remove:o});return{get el(){return C},setStatus:(E,T)=>{if(E===h&&T===b)return;h=E,b=T;let H=n.renderMentionChip({ref:e,status:h,payload:b,remove:o});C.replaceWith(H),C=H}}}let r=e.iconName??n.chipIconName??"at-sign",s=F("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),a=v("span","persona-mention-chip-icon"),l=h=>{a.replaceChildren();let b=Cu(h,13,"currentColor",2);b&&a.appendChild(b)};l(r);let c=v("span","persona-mention-chip-spinner"),p=F("span",{className:"persona-mention-chip-label",text:e.label}),u=F("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),m=Ge(aA.X,11,"currentColor",2.5);return m?u.appendChild(m):u.textContent="\xD7",u.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),o()}),s.appendChild(c),s.appendChild(p),s.appendChild(u),{el:s,setStatus:h=>{s.setAttribute("data-status",h),h==="resolving"?(c.parentNode!==s&&s.insertBefore(c,p),a.parentNode===s&&a.remove(),s.setAttribute("title",e.label)):(c.parentNode===s&&c.remove(),a.parentNode!==s&&s.insertBefore(a,p),h==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${e.label} to context`)):(l(r),s.setAttribute("title",e.label)))}}}var aA,cA=be(()=>{"use strict";je();aA=require("lucide");zn();wu()});function xu(t,e){return{sourceId:t.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var dA,Su,Ah=be(()=>{"use strict";cA();fu();Kg();dA=(t,e)=>`${t}\0${e}`,Su=class{constructor(e){this.mentions=[];this.opts=e,this.updateRowVisibility()}get maxMentions(){return this.opts.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(e,n,o=""){let r=dA(e.id,n.id);if(this.mentions.some(l=>l.key===r))return this.reject(e,n,"duplicate");if(this.atLimit())return this.reject(e,n,"limit");let s=xu(e,n),a={key:r,source:e,item:n,ref:s,status:"resolving",args:o};return a.chip=lA({ref:s,config:this.opts.mentionConfig,onRemove:()=>this.remove(r)}),a.chip.el.setAttribute("data-persona-chip-enter",""),a.chip.el.addEventListener("animationend",()=>a.chip?.el.removeAttribute("data-persona-chip-enter"),{once:!0}),this.opts.contextRow.appendChild(a.chip.el),this.startPending(a),this.updateRowVisibility(),!0}atLimit(){return this.mentions.length>=this.maxMentions}admit(e,n){return this.atLimit()?this.reject(e,n,"limit"):!0}track(e,n,o,r="",s){let a={key:e,source:n,item:o,ref:xu(n,o),status:"resolving",args:r,reportStatus:s};this.startPending(a)}reject(e,n,o){return this.opts.mentionConfig.onMentionRejected?.(n,o),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:o}),!1}startPending(e){this.mentions.push(e),e.source.resolveOn==="submit"?(e.status="ready",e.chip?.setStatus("ready"),e.reportStatus?.("resolved")):e.resolvePromise=this.resolvePending(e),this.opts.announce(`Added ${e.ref.label} to context`)}buildResolveContext(e,n,o=this.opts.getComposerText()){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:o,args:n,signal:e}}async resolvePending(e){let n=new AbortController;e.abort=n;try{let o=await e.source.resolve(e.item,this.buildResolveContext(n.signal,e.args));if(n.signal.aborted)return;e.payload=o,e.status="ready",e.chip?.setStatus("ready",o),e.reportStatus?.("resolved")}catch(o){if(n.signal.aborted)return;e.status="error",e.chip?.setStatus("error"),e.reportStatus?.("error"),(this.opts.announceError??this.opts.announce)(`Couldn't attach ${e.ref.label} to context`),this.opts.mentionConfig.onMentionResolveError?.(e.item,o),this.opts.emit?.("resolve-error",{sourceId:e.source.id,itemId:e.item.id})}}remove(e){let n=this.mentions.findIndex(r=>r.key===e);if(n===-1)return;let[o]=this.mentions.splice(n,1);o.abort?.abort(),o.chip?.el.remove(),this.updateRowVisibility(),this.opts.announce(`Removed ${o.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.updateRowVisibility()}collectForSubmit(){let e=[...this.mentions],n=e.map(s=>s.ref),o=this.opts.getComposerText();for(let s of e)s.chip?.el.remove();return this.mentions.length=0,this.updateRowVisibility(),{refs:n,finalize:async()=>{var u;let s=await Promise.all(e.map(async m=>{try{return m.source.resolveOn==="submit"?await m.source.resolve(m.item,this.buildResolveContext(new AbortController().signal,m.args,o)):(m.resolvePromise&&await m.resolvePromise,m.payload??null)}catch(g){try{this.opts.mentionConfig.onMentionResolveError?.(m.item,g)}catch(h){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",h)}return this.opts.emit?.("resolve-error",{sourceId:m.source.id,itemId:m.item.id}),null}})),a=[],l=[],c={},p=new Set;for(let m=0;m<e.length;m++){let g=e[m],h=s[m];if(!h)continue;let b=dA(g.source.id,g.item.id);if(!p.has(b)){if(p.add(b),h.llmAppend&&h.llmAppend.trim())try{a.push(Ux({label:g.ref.label,text:h.llmAppend,ref:g.ref,item:g.item},a.length,this.opts.mentionConfig.llmFormat))}catch(C){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",C)}h.contentParts?.length&&l.push(...h.contentParts),h.context&&((c[u=g.source.id]??(c[u]={}))[g.item.id]=h.context)}}return{blocks:a,contentParts:l,context:c}}}}updateRowVisibility(){_a(this.opts.contextRow)}}});var pA,uA=be(()=>{"use strict";pA=`
20
20
  .persona-mention-menu {
21
21
  box-sizing: border-box;
22
22
  display: flex;
@@ -174,13 +174,13 @@ ${e}
174
174
  min-height: 36px;
175
175
  }
176
176
  }
177
- `});function Qp(t){let e=t.replace(/^\s+/,""),n=e.search(/\s/);return n===-1?{name:e,args:""}:{name:e.slice(0,n),args:e.slice(n+1).trim()}}var iS=be(()=>{"use strict"});function cS(t){let{config:e,listboxId:n}=t,o=$("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=$("div",{className:"persona-mention-search",style:{display:"none"}}),s=v("span","persona-mention-search-icon"),a=Qe(lS.Search,15,"currentColor",2);a&&s.appendChild(a);let l=$("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":e.searchPlaceholder??"Search context",placeholder:e.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>t.onSearchInput?.(l.value)),l.addEventListener("keydown",R=>t.onSearchKeydown?.(R));let d=$("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,d);let p=[],u=[],m=-1,y=new Map,g=(R,w)=>`${R}\0${w}`,b=R=>`${n}-opt-${R}`,C=R=>`${n}-grp-${R}`,S=(R,w)=>{let E=p[R];E&&(w?E.setAttribute("data-active","true"):E.removeAttribute("data-active"),E.setAttribute("aria-selected",w?"true":"false"),u[R]?.(w))},T=(R,w=!0)=>{m>=0&&m!==R&&S(m,!1),m=R;let E=p[R];E?(S(R,!0),w&&E.scrollIntoView?.({block:"nearest"}),d.setAttribute("aria-activedescendant",E.id),l.setAttribute("aria-activedescendant",E.id)):(d.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},A=(R,w)=>{let E=C(w),H=$("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":E}});return H.appendChild($("div",{className:"persona-mention-group-header",attrs:{id:E},text:R})),H},I=()=>{let R=$("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),w=v("span","persona-mention-option-icon");R.appendChild(w);let E="",H=v("span","persona-mention-option-text"),D=v("span","persona-mention-option-labelline"),G=v("span","persona-mention-option-label");D.appendChild(G),H.appendChild(D),R.appendChild(H);let z=null,K=null,Y={el:R,index:0,update:(re,oe,se)=>{Y.index=oe,R.id=b(oe),R.setAttribute("aria-setsize",String(se)),R.setAttribute("aria-posinset",String(oe+1)),R.removeAttribute("data-active"),R.setAttribute("aria-selected","false");let ce=re.iconName??e.chipIconName??"at-sign";if(ce!==E){E=ce;let ge=lI(ce,15,2);w.replaceChildren(...ge?[ge]:[])}G.textContent!==re.label&&(G.textContent=re.label);let we=re.commandArgsPlaceholder?`\u2039${re.commandArgsPlaceholder}\u203A`:null;we?(z||(z=v("span","persona-mention-option-arghint"),D.appendChild(z)),z.textContent!==we&&(z.textContent=we)):z&&(z.remove(),z=null),re.description?(K||(K=v("span","persona-mention-option-desc"),H.appendChild(K)),K.textContent!==re.description&&(K.textContent=re.description)):K&&(K.remove(),K=null)}};return R.addEventListener("mousedown",re=>{re.button===0&&(re.preventDefault(),t.onSelectIndex(Y.index))}),R.addEventListener("mouseenter",()=>t.onHoverIndex(Y.index)),Y},M=(R,w,E,H,D)=>{let G=$("div",{className:"persona-mention-option",attrs:{role:"option",id:b(H),"aria-selected":"false","aria-setsize":String(D),"aria-posinset":String(H+1)}}),z=K=>{G.replaceChildren(e.renderMentionItem({item:R,source:w,query:E,active:K,index:H}))};return z(!1),G.addEventListener("mousedown",K=>{K.button===0&&(K.preventDefault(),t.onSelectIndex(H))}),G.addEventListener("mouseenter",()=>t.onHoverIndex(H)),{el:G,paint:z}},O=R=>{let w=$("div",{className:"persona-mention-status persona-mention-error"});if(w.appendChild($("span",{className:"persona-mention-error-text",text:`Couldn't load ${R.label}`})),t.onRetry){let E=$("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});E.addEventListener("mousedown",H=>H.preventDefault()),E.addEventListener("click",H=>{H.preventDefault(),t.onRetry(R.id)}),w.appendChild(E)}return w};return{el:o,render:R=>{d.replaceChildren(),p=[],u=[],m=-1;let w=new Set,E=0,H=0,D=0,G=0,z=0,K=R.groups.reduce((Y,re)=>re.status==="ready"?Y+re.items.length:Y,0);for(let Y of R.groups)if(Y.status==="loading"){D++;let re=A(Y.source.label,z++);re.appendChild($("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),d.appendChild(re)}else if(Y.status==="error"){G++;let re=A(Y.source.label,z++);re.appendChild(O(Y.source)),d.appendChild(re)}else if(Y.status==="ready"&&Y.items.length>0){let re=new Map;for(let se of Y.items){let ce=se.group??Y.source.label,we=re.get(ce);we?we.push(se):re.set(ce,[se])}let oe=Array.from(re.entries());oe.forEach(([se,ce],we)=>{let ge=A(se,z++);for(let N of ce){let ye=E++,ke;if(e.renderMentionItem){let nt=M(N,Y.source,R.query,ye,K);ke=nt.el,u.push(nt.paint)}else{let nt=g(Y.source.id,N.id),Ee=w.has(nt)?void 0:y.get(nt);Ee||(Ee=I(),w.has(nt)||y.set(nt,Ee)),w.add(nt),Ee.update(N,ye,K),ke=Ee.el,u.push(null)}p.push(ke),ge.appendChild(ke),H++}Y.truncated&&we===oe.length-1&&ge.appendChild($("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),d.appendChild(ge)})}for(let Y of y.keys())w.has(Y)||y.delete(Y);H===0&&D===0&&G===0&&d.appendChild($("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),p.length>0?T(Math.min(Math.max(0,R.activeIndex),p.length-1)):(d.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:T,destroy:()=>{d.replaceChildren(),p=[],y.clear(),o.remove()},showSearch:(R,w)=>{l.value=R,w&&(l.placeholder=w),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var lS,aS,lI,dS=be(()=>{"use strict";Ye();lS=require("lucide");ro();Kp();aS=new Map,lI=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=aS.get(o);return r===void 0&&(r=jp(t,e,"currentColor",n),aS.set(o,r)),r?r.cloneNode(!0):null}});var cI,dI,Xp,pS=be(()=>{"use strict";ya();sS();Up();Rg();iS();dS();Bg();cI=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",dI=0,Xp=class{constructor(e){this.popover=null;this.resizeObserver=null;this.isOpenState=!1;this.query="";this.triggerMatch=null;this.activeIndex=0;this.activeKey=null;this.pickerMode=!1;this.pickerTrigger=null;this.groups=[];this.flat=[];this.searchToken=0;this.searchAbort=null;this.debounceTimer=null;this.knownAsync=new Set;this.invokedForToken=new Set;this.lastAnnouncedCount=-1;this.triggerAnchorOffset=null;this.measuredTriggerIndex=null;this.opts=e;let n=e.mentionConfig,o=qp(n),r=o.filter(a=>a.sources.length>0);this.channels=r.length>0?r:[o[0]],this.activeChannel=this.channels[0],this.maxPerGroup=n.maxItemsPerGroup??6,this.debounceMs=n.searchDebounceMs??150,this.listboxId=`persona-mention-listbox-${++dI}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():cS({config:e.mentionConfig,listboxId:this.listboxId,onSelectIndex:a=>this.selectIndex(a),onHoverIndex:a=>this.setActiveIndex(a,!1),onRetry:a=>this.retrySource(a),onSearchInput:a=>this.setQuery(a),onSearchKeydown:a=>{this.handleKeydown(a)}});let s=e.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.listboxId)}get input(){return this.opts.composerInput}createHostMenu(){let e=document.createElement("div");e.setAttribute("data-persona-mention-menu",""),e.setAttribute("role","listbox"),e.id=this.listboxId;let n=()=>{let o=this.opts.mentionConfig.renderMentionMenu({query:this.query,groups:this.groups.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.groups.map(r=>[r.source.id,r.status])),activeIndex:this.activeIndex,select:r=>{let s=this.groups.find(a=>a.items.includes(r));s&&this.commit(s.source,r)},close:()=>this.close()});e.replaceChildren(o)};return{el:e,render:n,setActiveIndex:n,destroy:()=>e.remove()}}isOpen(){return this.isOpenState}openFromButton(e){let n=e&&this.channels.find(a=>a.trigger===e)||this.channels[0],o=this.input.getSelection().start,r=Kl(this.input.getLogicalText(),o,[n]);if(r){this.pickerMode=!1,this.triggerMatch=r.match,this.isOpenState?(this.switchChannel(n),this.setQuery(r.match.query)):this.open(r.match.query,n),this.input.focus();return}let s=this.pickerTrigger;this.pickerMode=!0,this.pickerTrigger=n.trigger,this.triggerMatch=null,this.isOpenState?(s&&s!==n.trigger&&this.opts.onPickerOpenChange?.(!1,s,this.listboxId),this.switchChannel(n),this.setQuery("")):this.open("",n),this.menu.showSearch?this.menu.showSearch("",n.searchPlaceholder):this.input.focus(),this.opts.onPickerOpenChange?.(!0,n.trigger,this.listboxId)}onInput(){let e=this.input.getSelection().start,n=Kl(this.input.getLogicalText(),e,this.channels);if(!n){this.isOpenState&&this.close();return}if(this.isInlineArgTail(n.channel,n.match.query)){this.triggerMatch=null,this.isOpenState&&this.close(!1);return}this.triggerMatch=n.match,this.isOpenState?(this.switchChannel(n.channel),this.measuredTriggerIndex!==n.match.triggerIndex&&this.updateTriggerAnchor(),this.setQuery(n.match.query)):this.open(n.match.query,n.channel)}switchChannel(e){e!==this.activeChannel&&(this.activeChannel=e,this.groups=[],this.activeIndex=0)}open(e,n){if(this.isOpenState=!0,this.activeChannel=n,this.groups=[],this.activeIndex=0,this.lastAnnouncedCount=-1,!this.popover){let o=this.canAnchorMenu();if(this.popover=gs({anchor:this.opts.anchor,content:this.menu.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.opts.popoverContainer,horizontalOffset:o?()=>this.triggerAnchorOffset?.x??null:void 0,verticalOffset:o?()=>this.triggerAnchorOffset?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.opts.anchor.getBoundingClientRect().width;this.menu.el.style.minWidth=`${Math.min(220,r)}px`}}this.updateTriggerAnchor(),this.popover.open(),Np(this.menu.el,"persona-mention-menu",rS),this.observeComposerResize(),this.opts.emit?.("opened",{trigger:n.trigger}),this.setQuery(e)}observeComposerResize(){typeof ResizeObserver>"u"||this.resizeObserver||(this.resizeObserver=new ResizeObserver(()=>{this.isOpenState&&(this.updateTriggerAnchor(),this.popover?.reposition())}),this.resizeObserver.observe(this.opts.anchor))}disconnectComposerResize(){this.resizeObserver?.disconnect(),this.resizeObserver=null}canAnchorMenu(){return this.isInlineDisplay()&&!!this.input.getLogicalRangeRect}updateTriggerAnchor(){let e=this.triggerMatch,n=this.input.getLogicalRangeRect;if(this.measuredTriggerIndex=e?.triggerIndex??null,this.triggerAnchorOffset=null,!e||!n)return;let o=n(e.triggerIndex,e.triggerIndex+1);if(!o)return;let r=this.opts.anchor.getBoundingClientRect(),s=o.top-r.top,a=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(a).direction==="rtl";this.triggerAnchorOffset={x:l?null:o.left-r.left,y:s}}close(e=!0){this.isOpenState&&(this.isOpenState=!1,this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.searchToken++,this.popover?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.pickerMode&&(this.pickerMode=!1,this.menu.hideSearch?.(),this.opts.onPickerOpenChange?.(!1,this.pickerTrigger??this.activeChannel.trigger,this.listboxId),this.pickerTrigger=null,e&&this.input.focus()))}setQuery(e){this.query=e,this.activeIndex=0,this.activeKey=null;let n=++this.searchToken;this.invokedForToken.clear(),this.searchAbort?.abort(),this.searchAbort=new AbortController;for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)?this.setGroupStatus(o.id,"loading"):(this.invokedForToken.add(o.id),this.invokeSource(o,n));this.render(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{if(n===this.searchToken)for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)&&!this.invokedForToken.has(o.id)&&this.invokeSource(o,n)},this.debounceMs)}invokeSource(e,n){let o={messages:this.opts.getMessages(),config:this.opts.getConfig(),signal:this.searchAbort.signal},r;try{r=e.search(this.query,o)}catch{this.setGroupStatus(e.id,"error"),this.render();return}cI(r)?(this.knownAsync.add(e.id),this.setGroupStatus(e.id,"loading"),r.then(s=>{n===this.searchToken&&(this.setGroupItems(e.id,s),this.render())}).catch(()=>{n===this.searchToken&&(this.setGroupStatus(e.id,"error"),this.render())})):this.setGroupItems(e.id,r)}getOrCreateGroup(e){let n=this.groups.find(o=>o.source.id===e.id);if(!n){n={source:e,items:[],status:"loading",truncated:!1};let o=this.activeChannel.sources;this.groups.push(n),this.groups.sort((r,s)=>o.findIndex(a=>a.id===r.source.id)-o.findIndex(a=>a.id===s.source.id))}return n}setGroupStatus(e,n){let o=this.activeChannel.sources.find(r=>r.id===e);o&&(this.getOrCreateGroup(o).status=n)}setGroupItems(e,n){let o=this.activeChannel.sources.find(s=>s.id===e);if(!o)return;let r=this.getOrCreateGroup(o);r.truncated=n.length>this.maxPerGroup,r.items=n.slice(0,this.maxPerGroup),r.status=r.items.length===0?"empty":"ready"}keyOf(e){return JSON.stringify([e.source.id,e.item.id])}rebuildFlat(){this.flat=[];for(let e of this.groups)if(e.status==="ready")for(let n of e.items)this.flat.push({source:e.source,item:n});if(this.activeKey){let e=this.flat.findIndex(n=>this.keyOf(n)===this.activeKey);this.activeIndex=e>=0?e:Math.min(this.activeIndex,Math.max(0,this.flat.length-1))}else this.activeIndex>=this.flat.length&&(this.activeIndex=Math.max(0,this.flat.length-1))}viewModel(){return{query:this.query,groups:this.groups,activeIndex:this.activeIndex}}render(){this.rebuildFlat(),this.menu.render(this.viewModel()),this.syncActiveDescendant(),this.popover?.reposition();let e=this.groups.some(n=>n.status==="loading");this.flat.length===0&&e||this.flat.length!==this.lastAnnouncedCount&&(this.lastAnnouncedCount=this.flat.length,this.opts.announce(this.flat.length===0?"No matches":this.flat.length===1?"1 result":`${this.flat.length} results`),this.opts.emit?.("searched",{query:this.query,results:this.flat.length}))}setActiveIndex(e,n=!0){e<0||e>=this.flat.length||(this.activeIndex=e,this.activeKey=this.keyOf(this.flat[e]),this.menu.setActiveIndex(e,n),this.syncActiveDescendant())}syncActiveDescendant(){this.isOpenState&&!this.pickerMode&&this.activeIndex>=0&&this.activeIndex<this.flat.length?this.input.element.setAttribute("aria-activedescendant",`${this.listboxId}-opt-${this.activeIndex}`):this.input.element.removeAttribute("aria-activedescendant")}retrySource(e){let n=this.activeChannel.sources.find(o=>o.id===e);!n||!this.searchAbort||(this.setGroupStatus(e,"loading"),this.render(),this.invokeSource(n,this.searchToken),this.render())}handleKeydown(e){if(!this.isOpenState)return!1;switch(e.key){case"ArrowDown":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex+1)%this.flat.length)),!0;case"ArrowUp":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex-1+this.flat.length)%this.flat.length)),!0;case"Home":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(0)),!0;case"End":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(this.flat.length-1)),!0;case"Enter":case"Tab":return this.flat.length===0?(this.close(),!1):(e.preventDefault(),this.selectIndex(this.activeIndex),!0);case"Escape":return e.preventDefault(),this.close(),!0;case"Backspace":return this.query.length===0&&this.close(),!1;default:return!1}}selectIndex(e){let n=this.flat[e];n&&this.commit(n.source,n.item)}deriveArgs(e){return Qp(e).args}isInlineCommand(e){return e.command==="server"||e.commandArgsPlaceholder!=null}commit(e,n){let o=n.command;if(this.isInlineCommand(n)){this.completeCommandInline(e,n);return}if(o==="action"){let s=this.deriveArgs(this.query);this.stripQuery(),this.close(),this.runAction(n,s),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.deriveArgs(this.query),a=this.captureStripTarget();this.close(),this.runPromptMacro(e,n,s,a),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"prompt",args:s});return}if(this.isInlineDisplay()){this.commitInlineMention(e,n);return}this.opts.onSelect(e,n,"")&&(this.stripQuery(),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}isInlineDisplay(){return this.opts.mentionConfig.display==="inline"&&!!this.opts.onInsertMention&&!!this.input.insertMentionAtTrigger}commitInlineMention(e,n){if(this.opts.admitMention&&!this.opts.admitMention(e,n)){this.close(),this.input.focus();return}let o=Gp(e,n),r=this.triggerMatch?this.input.insertMentionAtTrigger(o,this.triggerMatch):this.input.insertMentionAtSelection?.(o)??null;r?(this.opts.onInsertMention(r,e,n,""),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})):(this.opts.mentionConfig.onMentionRejected?.(n,"stale"),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:"stale"})),this.triggerMatch=null,this.close(),this.input.focus()}completeCommandInline(e,n){let o=`${this.activeChannel.trigger}${n.label} `,r=this.input.getSelection().start,s=this.triggerMatch?this.triggerMatch.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let a=this.input.getValue();this.input.setValueWithCaret(a.slice(0,s)+o+a.slice(r),s+o.length)}this.triggerMatch=null,this.close(),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}isInlineArgTail(e,n){let{name:o}=Qp(n);return!o||n.length<=o.length?!1:e.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.isInlineCommand(s)})}matchInlineCommand(e){for(let n of this.channels){if(!n.trigger)continue;let o=n.position==="anywhere"?[e]:n.position==="line-start"?e.split(`
177
+ `});function Au(t){let e=t.replace(/^\s+/,""),n=e.search(/\s/);return n===-1?{name:e,args:""}:{name:e.slice(0,n),args:e.slice(n+1).trim()}}var mA=be(()=>{"use strict"});function hA(t){let{config:e,listboxId:n}=t,o=F("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=F("div",{className:"persona-mention-search",style:{display:"none"}}),s=v("span","persona-mention-search-icon"),a=Ge(gA.Search,15,"currentColor",2);a&&s.appendChild(a);let l=F("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":e.searchPlaceholder??"Search context",placeholder:e.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>t.onSearchInput?.(l.value)),l.addEventListener("keydown",R=>t.onSearchKeydown?.(R));let c=F("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,c);let p=[],u=[],m=-1,g=new Map,h=(R,S)=>`${R}\0${S}`,b=R=>`${n}-opt-${R}`,C=R=>`${n}-grp-${R}`,M=(R,S)=>{let x=p[R];x&&(S?x.setAttribute("data-active","true"):x.removeAttribute("data-active"),x.setAttribute("aria-selected",S?"true":"false"),u[R]?.(S))},E=(R,S=!0)=>{m>=0&&m!==R&&M(m,!1),m=R;let x=p[R];x?(M(R,!0),S&&x.scrollIntoView?.({block:"nearest"}),c.setAttribute("aria-activedescendant",x.id),l.setAttribute("aria-activedescendant",x.id)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},T=(R,S)=>{let x=C(S),P=F("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":x}});return P.appendChild(F("div",{className:"persona-mention-group-header",attrs:{id:x},text:R})),P},H=()=>{let R=F("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),S=v("span","persona-mention-option-icon");R.appendChild(S);let x="",P=v("span","persona-mention-option-text"),L=v("span","persona-mention-option-labelline"),G=v("span","persona-mention-option-label");L.appendChild(G),P.appendChild(L),R.appendChild(P);let V=null,K=null,ee={el:R,index:0,update:(oe,ne,le)=>{ee.index=ne,R.id=b(ne),R.setAttribute("aria-setsize",String(le)),R.setAttribute("aria-posinset",String(ne+1)),R.removeAttribute("data-active"),R.setAttribute("aria-selected","false");let de=oe.iconName??e.chipIconName??"at-sign";if(de!==x){x=de;let Le=TR(de,15,2);S.replaceChildren(...Le?[Le]:[])}G.textContent!==oe.label&&(G.textContent=oe.label);let ve=oe.commandArgsPlaceholder?`\u2039${oe.commandArgsPlaceholder}\u203A`:null;ve?(V||(V=v("span","persona-mention-option-arghint"),L.appendChild(V)),V.textContent!==ve&&(V.textContent=ve)):V&&(V.remove(),V=null),oe.description?(K||(K=v("span","persona-mention-option-desc"),P.appendChild(K)),K.textContent!==oe.description&&(K.textContent=oe.description)):K&&(K.remove(),K=null)}};return R.addEventListener("mousedown",oe=>{oe.button===0&&(oe.preventDefault(),t.onSelectIndex(ee.index))}),R.addEventListener("mouseenter",()=>t.onHoverIndex(ee.index)),ee},A=(R,S,x,P,L)=>{let G=F("div",{className:"persona-mention-option",attrs:{role:"option",id:b(P),"aria-selected":"false","aria-setsize":String(L),"aria-posinset":String(P+1)}}),V=K=>{G.replaceChildren(e.renderMentionItem({item:R,source:S,query:x,active:K,index:P}))};return V(!1),G.addEventListener("mousedown",K=>{K.button===0&&(K.preventDefault(),t.onSelectIndex(P))}),G.addEventListener("mouseenter",()=>t.onHoverIndex(P)),{el:G,paint:V}},D=R=>{let S=F("div",{className:"persona-mention-status persona-mention-error"});if(S.appendChild(F("span",{className:"persona-mention-error-text",text:`Couldn't load ${R.label}`})),t.onRetry){let x=F("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});x.addEventListener("mousedown",P=>P.preventDefault()),x.addEventListener("click",P=>{P.preventDefault(),t.onRetry(R.id)}),S.appendChild(x)}return S};return{el:o,render:R=>{c.replaceChildren(),p=[],u=[],m=-1;let S=new Set,x=0,P=0,L=0,G=0,V=0,K=R.groups.reduce((ee,oe)=>oe.status==="ready"?ee+oe.items.length:ee,0);for(let ee of R.groups)if(ee.status==="loading"){L++;let oe=T(ee.source.label,V++);oe.appendChild(F("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),c.appendChild(oe)}else if(ee.status==="error"){G++;let oe=T(ee.source.label,V++);oe.appendChild(D(ee.source)),c.appendChild(oe)}else if(ee.status==="ready"&&ee.items.length>0){let oe=new Map;for(let le of ee.items){let de=le.group??ee.source.label,ve=oe.get(de);ve?ve.push(le):oe.set(de,[le])}let ne=Array.from(oe.entries());ne.forEach(([le,de],ve)=>{let Le=T(le,V++);for(let se of de){let _=x++,Te;if(e.renderMentionItem){let He=A(se,ee.source,R.query,_,K);Te=He.el,u.push(He.paint)}else{let He=h(ee.source.id,se.id),ut=S.has(He)?void 0:g.get(He);ut||(ut=H(),S.has(He)||g.set(He,ut)),S.add(He),ut.update(se,_,K),Te=ut.el,u.push(null)}p.push(Te),Le.appendChild(Te),P++}ee.truncated&&ve===ne.length-1&&Le.appendChild(F("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),c.appendChild(Le)})}for(let ee of g.keys())S.has(ee)||g.delete(ee);P===0&&L===0&&G===0&&c.appendChild(F("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),p.length>0?E(Math.min(Math.max(0,R.activeIndex),p.length-1)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:E,destroy:()=>{c.replaceChildren(),p=[],g.clear(),o.remove()},showSearch:(R,S)=>{l.value=R,S&&(l.placeholder=S),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var gA,fA,TR,yA=be(()=>{"use strict";je();gA=require("lucide");zn();wu();fA=new Map,TR=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=fA.get(o);return r===void 0&&(r=Cu(t,e,"currentColor",n),fA.set(o,r)),r?r.cloneNode(!0):null}});var ER,kR,Mu,bA=be(()=>{"use strict";Oa();uA();bu();xh();mA();yA();Ah();ER=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",kR=0,Mu=class{constructor(e){this.popover=null;this.resizeObserver=null;this.isOpenState=!1;this.query="";this.triggerMatch=null;this.activeIndex=0;this.activeKey=null;this.pickerMode=!1;this.pickerTrigger=null;this.groups=[];this.flat=[];this.searchToken=0;this.searchAbort=null;this.debounceTimer=null;this.knownAsync=new Set;this.invokedForToken=new Set;this.lastAnnouncedCount=-1;this.triggerAnchorOffset=null;this.measuredTriggerIndex=null;this.opts=e;let n=e.mentionConfig,o=vu(n),r=o.filter(a=>a.sources.length>0);this.channels=r.length>0?r:[o[0]],this.activeChannel=this.channels[0],this.maxPerGroup=n.maxItemsPerGroup??6,this.debounceMs=n.searchDebounceMs??150,this.listboxId=`persona-mention-listbox-${++kR}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():hA({config:e.mentionConfig,listboxId:this.listboxId,onSelectIndex:a=>this.selectIndex(a),onHoverIndex:a=>this.setActiveIndex(a,!1),onRetry:a=>this.retrySource(a),onSearchInput:a=>this.setQuery(a),onSearchKeydown:a=>{this.handleKeydown(a)}});let s=e.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.listboxId)}get input(){return this.opts.composerInput}createHostMenu(){let e=document.createElement("div");e.setAttribute("data-persona-mention-menu",""),e.setAttribute("role","listbox"),e.id=this.listboxId;let n=()=>{let o=this.opts.mentionConfig.renderMentionMenu({query:this.query,groups:this.groups.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.groups.map(r=>[r.source.id,r.status])),activeIndex:this.activeIndex,select:r=>{let s=this.groups.find(a=>a.items.includes(r));s&&this.commit(s.source,r)},close:()=>this.close()});e.replaceChildren(o)};return{el:e,render:n,setActiveIndex:n,destroy:()=>e.remove()}}isOpen(){return this.isOpenState}openFromButton(e){let n=e&&this.channels.find(a=>a.trigger===e)||this.channels[0],o=this.input.getSelection().start,r=ic(this.input.getLogicalText(),o,[n]);if(r){this.pickerMode=!1,this.triggerMatch=r.match,this.isOpenState?(this.switchChannel(n),this.setQuery(r.match.query)):this.open(r.match.query,n),this.input.focus();return}let s=this.pickerTrigger;this.pickerMode=!0,this.pickerTrigger=n.trigger,this.triggerMatch=null,this.isOpenState?(s&&s!==n.trigger&&this.opts.onPickerOpenChange?.(!1,s,this.listboxId),this.switchChannel(n),this.setQuery("")):this.open("",n),this.menu.showSearch?this.menu.showSearch("",n.searchPlaceholder):this.input.focus(),this.opts.onPickerOpenChange?.(!0,n.trigger,this.listboxId)}onInput(){let e=this.input.getSelection().start,n=ic(this.input.getLogicalText(),e,this.channels);if(!n){this.isOpenState&&this.close();return}if(this.isInlineArgTail(n.channel,n.match.query)){this.triggerMatch=null,this.isOpenState&&this.close(!1);return}this.triggerMatch=n.match,this.isOpenState?(this.switchChannel(n.channel),this.measuredTriggerIndex!==n.match.triggerIndex&&this.updateTriggerAnchor(),this.setQuery(n.match.query)):this.open(n.match.query,n.channel)}switchChannel(e){e!==this.activeChannel&&(this.activeChannel=e,this.groups=[],this.activeIndex=0)}open(e,n){if(this.isOpenState=!0,this.activeChannel=n,this.groups=[],this.activeIndex=0,this.lastAnnouncedCount=-1,!this.popover){let o=this.canAnchorMenu();if(this.popover=Ps({anchor:this.opts.anchor,content:this.menu.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.opts.popoverContainer,horizontalOffset:o?()=>this.triggerAnchorOffset?.x??null:void 0,verticalOffset:o?()=>this.triggerAnchorOffset?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.opts.anchor.getBoundingClientRect().width;this.menu.el.style.minWidth=`${Math.min(220,r)}px`}}this.updateTriggerAnchor(),this.popover.open(),mu(this.menu.el,"persona-mention-menu",pA),this.observeComposerResize(),this.opts.emit?.("opened",{trigger:n.trigger}),this.setQuery(e)}observeComposerResize(){typeof ResizeObserver>"u"||this.resizeObserver||(this.resizeObserver=new ResizeObserver(()=>{this.isOpenState&&(this.updateTriggerAnchor(),this.popover?.reposition())}),this.resizeObserver.observe(this.opts.anchor))}disconnectComposerResize(){this.resizeObserver?.disconnect(),this.resizeObserver=null}canAnchorMenu(){return this.isInlineDisplay()&&!!this.input.getLogicalRangeRect}updateTriggerAnchor(){let e=this.triggerMatch,n=this.input.getLogicalRangeRect;if(this.measuredTriggerIndex=e?.triggerIndex??null,this.triggerAnchorOffset=null,!e||!n)return;let o=n(e.triggerIndex,e.triggerIndex+1);if(!o)return;let r=this.opts.anchor.getBoundingClientRect(),s=o.top-r.top,a=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(a).direction==="rtl";this.triggerAnchorOffset={x:l?null:o.left-r.left,y:s}}close(e=!0){this.isOpenState&&(this.isOpenState=!1,this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.searchToken++,this.popover?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.pickerMode&&(this.pickerMode=!1,this.menu.hideSearch?.(),this.opts.onPickerOpenChange?.(!1,this.pickerTrigger??this.activeChannel.trigger,this.listboxId),this.pickerTrigger=null,e&&this.input.focus()))}setQuery(e){this.query=e,this.activeIndex=0,this.activeKey=null;let n=++this.searchToken;this.invokedForToken.clear(),this.searchAbort?.abort(),this.searchAbort=new AbortController;for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)?this.setGroupStatus(o.id,"loading"):(this.invokedForToken.add(o.id),this.invokeSource(o,n));this.render(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{if(n===this.searchToken)for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)&&!this.invokedForToken.has(o.id)&&this.invokeSource(o,n)},this.debounceMs)}invokeSource(e,n){let o={messages:this.opts.getMessages(),config:this.opts.getConfig(),signal:this.searchAbort.signal},r;try{r=e.search(this.query,o)}catch{this.setGroupStatus(e.id,"error"),this.render();return}ER(r)?(this.knownAsync.add(e.id),this.setGroupStatus(e.id,"loading"),r.then(s=>{n===this.searchToken&&(this.setGroupItems(e.id,s),this.render())}).catch(()=>{n===this.searchToken&&(this.setGroupStatus(e.id,"error"),this.render())})):this.setGroupItems(e.id,r)}getOrCreateGroup(e){let n=this.groups.find(o=>o.source.id===e.id);if(!n){n={source:e,items:[],status:"loading",truncated:!1};let o=this.activeChannel.sources;this.groups.push(n),this.groups.sort((r,s)=>o.findIndex(a=>a.id===r.source.id)-o.findIndex(a=>a.id===s.source.id))}return n}setGroupStatus(e,n){let o=this.activeChannel.sources.find(r=>r.id===e);o&&(this.getOrCreateGroup(o).status=n)}setGroupItems(e,n){let o=this.activeChannel.sources.find(s=>s.id===e);if(!o)return;let r=this.getOrCreateGroup(o);r.truncated=n.length>this.maxPerGroup,r.items=n.slice(0,this.maxPerGroup),r.status=r.items.length===0?"empty":"ready"}keyOf(e){return JSON.stringify([e.source.id,e.item.id])}rebuildFlat(){this.flat=[];for(let e of this.groups)if(e.status==="ready")for(let n of e.items)this.flat.push({source:e.source,item:n});if(this.activeKey){let e=this.flat.findIndex(n=>this.keyOf(n)===this.activeKey);this.activeIndex=e>=0?e:Math.min(this.activeIndex,Math.max(0,this.flat.length-1))}else this.activeIndex>=this.flat.length&&(this.activeIndex=Math.max(0,this.flat.length-1))}viewModel(){return{query:this.query,groups:this.groups,activeIndex:this.activeIndex}}render(){this.rebuildFlat(),this.menu.render(this.viewModel()),this.syncActiveDescendant(),this.popover?.reposition();let e=this.groups.some(n=>n.status==="loading");this.flat.length===0&&e||this.flat.length!==this.lastAnnouncedCount&&(this.lastAnnouncedCount=this.flat.length,this.opts.announce(this.flat.length===0?"No matches":this.flat.length===1?"1 result":`${this.flat.length} results`),this.opts.emit?.("searched",{query:this.query,results:this.flat.length}))}setActiveIndex(e,n=!0){e<0||e>=this.flat.length||(this.activeIndex=e,this.activeKey=this.keyOf(this.flat[e]),this.menu.setActiveIndex(e,n),this.syncActiveDescendant())}syncActiveDescendant(){this.isOpenState&&!this.pickerMode&&this.activeIndex>=0&&this.activeIndex<this.flat.length?this.input.element.setAttribute("aria-activedescendant",`${this.listboxId}-opt-${this.activeIndex}`):this.input.element.removeAttribute("aria-activedescendant")}retrySource(e){let n=this.activeChannel.sources.find(o=>o.id===e);!n||!this.searchAbort||(this.setGroupStatus(e,"loading"),this.render(),this.invokeSource(n,this.searchToken),this.render())}handleKeydown(e){if(!this.isOpenState)return!1;switch(e.key){case"ArrowDown":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex+1)%this.flat.length)),!0;case"ArrowUp":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex-1+this.flat.length)%this.flat.length)),!0;case"Home":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(0)),!0;case"End":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(this.flat.length-1)),!0;case"Enter":case"Tab":return this.flat.length===0?(this.close(),!1):(e.preventDefault(),this.selectIndex(this.activeIndex),!0);case"Escape":return e.preventDefault(),this.close(),!0;case"Backspace":return this.query.length===0&&this.close(),!1;default:return!1}}selectIndex(e){let n=this.flat[e];n&&this.commit(n.source,n.item)}deriveArgs(e){return Au(e).args}isInlineCommand(e){return e.command==="server"||e.commandArgsPlaceholder!=null}commit(e,n){let o=n.command;if(this.isInlineCommand(n)){this.completeCommandInline(e,n);return}if(o==="action"){let s=this.deriveArgs(this.query);this.stripQuery(),this.close(),this.runAction(n,s),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.deriveArgs(this.query),a=this.captureStripTarget();this.close(),this.runPromptMacro(e,n,s,a),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"prompt",args:s});return}if(this.isInlineDisplay()){this.commitInlineMention(e,n);return}this.opts.onSelect(e,n,"")&&(this.stripQuery(),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}isInlineDisplay(){return this.opts.mentionConfig.display==="inline"&&!!this.opts.onInsertMention&&!!this.input.insertMentionAtTrigger}commitInlineMention(e,n){if(this.opts.admitMention&&!this.opts.admitMention(e,n)){this.close(),this.input.focus();return}let o=xu(e,n),r=this.triggerMatch?this.input.insertMentionAtTrigger(o,this.triggerMatch):this.input.insertMentionAtSelection?.(o)??null;r?(this.opts.onInsertMention(r,e,n,""),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})):(this.opts.mentionConfig.onMentionRejected?.(n,"stale"),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:"stale"})),this.triggerMatch=null,this.close(),this.input.focus()}completeCommandInline(e,n){let o=`${this.activeChannel.trigger}${n.label} `,r=this.input.getSelection().start,s=this.triggerMatch?this.triggerMatch.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let a=this.input.getValue();this.input.setValueWithCaret(a.slice(0,s)+o+a.slice(r),s+o.length)}this.triggerMatch=null,this.close(),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}isInlineArgTail(e,n){let{name:o}=Au(n);return!o||n.length<=o.length?!1:e.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.isInlineCommand(s)})}matchInlineCommand(e){for(let n of this.channels){if(!n.trigger)continue;let o=n.position==="anywhere"?[e]:n.position==="line-start"?e.split(`
178
178
  `):[e.split(`
179
- `)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:a}=Qp(r.slice(n.trigger.length));if(s)for(let l of n.sources){let d=l.matchCommand?.(s);if(d&&this.isInlineCommand(d))return{source:l,item:d,args:a}}}}return null}async dispatchInlineCommand(e){let n=this.matchInlineCommand(e);if(!n)return null;let{source:o,item:r,args:s}=n,a=r.command??"prompt";if(this.opts.emit?.("command",{sourceId:o.id,itemId:r.id,kind:a,args:s}),a==="action")return this.runAction(r,s),{kind:"action"};if(a==="prompt"){let d;try{d=await o.resolve(r,this.resolveContext(s,e))}catch(p){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",p),null}return{kind:"prompt",sendText:d.insertText??d.llmAppend??e}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let d=await o.resolve(r,this.resolveContext(s,e)),p={};return d.context&&(p[o.id]={[r.id]:d.context}),{blocks:[],contentParts:d.contentParts??[],context:p}}}}}resolveContext(e,n){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:n,args:e,signal:new AbortController().signal}}runAction(e,n){if(e.action)try{Promise.resolve(e.action({args:n,config:this.opts.getConfig(),messages:this.opts.getMessages(),composer:this.input})).catch(o=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)})}catch(o){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)}}captureStripTarget(){return this.triggerMatch?{value:this.input.getValue(),start:this.triggerMatch.triggerIndex,end:this.input.getSelection().start}:null}async runPromptMacro(e,n,o,r){let s=this.input,a;try{a=await e.resolve(n,{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:s.getValue(),args:o,signal:new AbortController().signal})}catch(d){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",d);return}let l=a.insertText??a.llmAppend??"";n.insertMode==="insert-at-caret"&&r?s.replaceLogicalRange?(s.replaceLogicalRange(r.start,r.end,l),s.dispatchInput()):s.setValue(r.value.slice(0,r.start)+l+r.value.slice(r.end)):s.setValue(l),n.submitOnSelect&&s.submit()}stripQuery(){if(!this.triggerMatch)return;let e=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.triggerMatch.triggerIndex,e,"");else{let n=Xx(this.input.getValue(),this.triggerMatch,e);this.input.setValueWithCaret(n.value,n.caret)}this.input.dispatchInput(),this.triggerMatch=null}destroy(){this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.popover?.destroy(),this.menu.destroy();let e=this.input.element;e.removeAttribute("aria-haspopup"),e.removeAttribute("aria-controls"),e.removeAttribute("aria-activedescendant")}}});function Og(t,e){let n=document.createElement("div");n.className="persona-sr-only",n.setAttribute("aria-live",t),n.setAttribute("aria-atomic","true"),n.setAttribute("role",t==="assertive"?"alert":"status"),n.setAttribute("data-persona-mention-live-region","");let o=e.getRootNode();typeof ShadowRoot<"u"&&o instanceof ShadowRoot?(Object.assign(n.style,pI),document.body.appendChild(n)):e.appendChild(n);let s;return{announce:a=>{s!==void 0&&clearTimeout(s),n.textContent="",s=setTimeout(()=>{s=void 0,n.textContent=a},0)},destroy:()=>{s!==void 0&&clearTimeout(s),n.remove()}}}var pI,uS=be(()=>{"use strict";pI={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 mS(t){let e=t.composerInput??qx(t.textarea),n=Og("polite",t.liveRegionHost),o=Og("assertive",t.liveRegionHost),r=p=>n.announce(p),s=p=>o.announce(p),a=new Yp({mentionConfig:t.mentionConfig,contextRow:t.contextRow,getMessages:t.getMessages,getConfig:t.getConfig,getComposerText:()=>e.getValue(),announce:r,announceError:s,emit:t.emit}),l=()=>new Xp({mentionConfig:t.mentionConfig,composerInput:e,anchor:t.anchor,getMessages:t.getMessages,getConfig:t.getConfig,onSelect:(p,u,m)=>a.add(p,u,m),onInsertMention:(p,u,m,y)=>a.track(p,u,m,y,g=>e.setMentionStatus?.(p,g)),admitMention:(p,u)=>a.admit(p,u),announce:r,popoverContainer:t.popoverContainer,onPickerOpenChange:t.onPickerOpenChange,emit:t.emit}),d=l();return{openMenu:p=>d.openFromButton(p),isMenuOpen:()=>d.isOpen(),handleInput:()=>d.onInput(),handleKeydown:p=>d.handleKeydown(p),hasMentions:()=>a.hasMentions(),getMentionRefs:()=>a.getRefs(),removeLastChip:()=>a.removeLast(),dispatchInlineCommand:p=>d.dispatchInlineCommand(p),collectForSubmit:()=>a.hasMentions()?a.collectForSubmit():null,untrackMention:p=>a.remove(p),rebindComposer:p=>{p!==e&&(d.destroy(),e=p,d=l())},clear:()=>a.clear(),destroy:()=>{d.destroy(),a.clear(),n.destroy(),o.destroy()}}}var fS=be(()=>{"use strict";Bg();pS();zp();uS();Kp()});var gS={};Vn(gS,{mountContextMentions:()=>mS,setMentionIconRenderer:()=>Wg});var hS=be(()=>{"use strict";fS()});function Ng(t){return t.kind==="text"?t.value.length:1}function Fg(t){let e=[],n=r=>{let s=e[e.length-1];s&&s.kind==="text"?s.value+=r:e.push({kind:"text",value:r})};(t.length===0||t[0].kind!=="text")&&e.push({kind:"text",value:""});for(let r of t){if(r.kind==="text"){n(r.value);continue}let s=e[e.length-1];(!s||s.kind!=="text")&&e.push({kind:"text",value:""}),e.push({kind:"mention",id:r.id,ref:r.ref}),e.push({kind:"text",value:""})}let o=e[e.length-1];return(!o||o.kind!=="text")&&e.push({kind:"text",value:""}),e}function yS(){return{blocks:[{kind:"text",value:""}]}}function Vg(t){return{blocks:[{kind:"text",value:t}]}}function $g(t){return t.blocks.map(e=>e.kind==="text"?e.value:`${mI}${e.ref.label}`).join("")}function Zp(t){return t.blocks.map(e=>e.kind==="text"?e.value:"\uFFFC").join("")}function eu(t){return t.blocks.reduce((e,n)=>e+Ng(n),0)}function fI(t){let e=[];for(let n of t.blocks)n.kind==="mention"&&e.push({id:n.id,ref:n.ref});return e}function Jp(t,e){let n=[],o=[],r=0;for(let s of t){let a=Ng(s),l=r+a;if(l<=e)n.push(s);else if(r>=e)o.push(s);else if(s.kind==="text"){let d=e-r;d>0&&n.push({kind:"text",value:s.value.slice(0,d)}),d<a&&o.push({kind:"text",value:s.value.slice(d)})}else o.push(s);r=l}return{left:n,right:o}}function zg(t,e,n,o){let r=Jp(t.blocks,e.start).left,s=Jp(t.blocks,e.end).right,a=s[0],l=a?.kind==="text"?a.value.charAt(0):"",d=l!==" "&&l!==" "&&l!==`
180
- `,p=Fg([...r,{kind:"mention",id:o,ref:n},...d?[{kind:"text",value:" "}]:[],...s]),u=e.start+1+(l===`
181
- `?0:1);return{doc:{blocks:p},caret:u}}function bS(t,e){let n=0,o=0,r=!1;for(let a of t.blocks)a.kind==="mention"&&a.id===e&&(n=o,r=!0),o+=Ng(a);return r?{doc:{blocks:Fg(t.blocks.filter(a=>!(a.kind==="mention"&&a.id===e)))},caret:n}:{doc:t,caret:o}}function tu(t,e,n,o){let r=eu(t),s=Math.max(0,Math.min(e,n,r)),a=Math.min(r,Math.max(e,n,0)),l=Jp(t.blocks,s).left,d=Jp(t.blocks,a).right;return{doc:{blocks:Fg([...l,{kind:"text",value:o},...d])},caret:s+o.length}}function vS(t){let e=[];for(let n of t.blocks)n.kind==="text"?n.value.length>0&&e.push({kind:"text",text:n.value}):e.push({kind:"mention",ref:n.ref});return{content:$g(t),contextMentions:fI(t).map(n=>n.ref),contentSegments:e}}var mI,Ug=be(()=>{"use strict";Up();mI="@"});function Xl(t){return t.nodeType===1&&t.hasAttribute(Ql)}function xS(t){return t.nodeType===1&&t.tagName==="BR"}function nu(t){return t.nodeType===3?t.data.length:Xl(t)||xS(t)?1:t.textContent?.length??0}function CS(t,e,n){let o=0;for(let r of Array.from(t.childNodes)){if(r===e)return r.nodeType===3?o+n:o+(n>0?nu(r):0);if(r.contains(e))return Xl(r)?o+1:o+hI(r,e,n);o+=nu(r)}if(e===t){let r=0,s=Array.from(t.childNodes);for(let a=0;a<Math.min(n,s.length);a++)r+=nu(s[a]);return r}return o}function hI(t,e,n){let o=0,r=s=>{if(s===e)return o+=s.nodeType===3?n:0,!0;if(s.nodeType===3)return o+=s.data.length,!1;for(let a of Array.from(s.childNodes))if(r(a))return!0;return!1};return r(t),o}function Yl(t,e){let n=0,o=Array.from(t.childNodes);for(let r=0;r<o.length;r++){let s=o[r],a=nu(s);if(e<=n+a)return s.nodeType===3?{node:s,offset:e-n}:{node:t,offset:e<=n?r:r+1};n+=a}return{node:t,offset:o.length}}function yI(t,e){let n=[];for(let o of Array.from(t.childNodes))if(Xl(o)){let r=o.getAttribute(Ql),s=e.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(xS(o))n.push({kind:"text",value:wS});else if(o.nodeType===3)n.push({kind:"text",value:o.data});else{let r=o.textContent??"";r&&n.push({kind:"text",value:r})}return n.length===0&&n.push({kind:"text",value:""}),{blocks:n}}function SS(t){let e=t.renderToken,n=new Map,o=t.element??document.createElement("div");o.setAttribute("contenteditable","true"),o.setAttribute("data-persona-composer-input",""),o.setAttribute("role","textbox"),o.setAttribute("aria-multiline","true"),o.setAttribute("dir","auto"),o.classList.add("persona-composer-contenteditable"),t.placeholder!=null&&o.setAttribute("data-placeholder",t.placeholder);let r=!1,s=0,a=()=>yI(o,n),l=W=>{o.replaceChildren();for(let V of W.blocks)if(V.kind==="text")V.value.length>0&&o.appendChild(document.createTextNode(V.value));else{n.set(V.id,V.ref);let R=e(V.ref);R.setAttribute("contenteditable","false"),R.setAttribute(Ql,V.id),o.appendChild(R)}},d=()=>{let V=o.getRootNode().activeElement;return V===o||V!=null&&o.contains(V)},p=(W,V)=>{if(s=W,!V?.focus&&!d())return;let R=typeof window<"u"?window.getSelection():null;if(!R)return;let w=Yl(o,W);try{let E=document.createRange();E.setStart(w.node,w.offset),E.collapse(!0),R.removeAllRanges(),R.addRange(E)}catch{}},u=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},m=()=>{let W={start:s,end:s},V=typeof window<"u"?window.getSelection():null;if(!V||V.rangeCount===0)return W;let R=V.getRangeAt(0);if(!o.contains(R.startContainer))return W;let w=CS(o,R.startContainer,R.startOffset),E=R.collapsed?w:CS(o,R.endContainer,R.endOffset);return{start:Math.min(w,E),end:Math.max(w,E)}},y=()=>{let W=new Set;for(let V of Array.from(o.childNodes))Xl(V)&&W.add(V.getAttribute(Ql));for(let V of Array.from(n.keys()))W.has(V)||(n.delete(V),t.onMentionRemoved?.(V))},g=()=>{r||n.size!==0&&y()},b=()=>{r=!0},C=()=>{r=!1,y()},S=W=>{W.preventDefault();let V=W.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,V);else{let{start:R,end:w}=m(),E=tu(a(),R,w,V);l(E.doc),p(E.caret,{focus:!0}),y()}u()},T=W=>{if(r)return;let V=W.inputType;if(V==="insertParagraph"){W.preventDefault();let{start:Y,end:re}=m(),oe=tu(a(),Y,re,wS);l(oe.doc),p(oe.caret,{focus:!0}),n.size>0&&y(),u();return}if(V!=="deleteContentBackward"&&V!=="deleteContentForward"||n.size===0)return;let{start:R,end:w}=m();if(R!==w)return;let E=a(),H=Zp(E),D=V==="deleteContentBackward"?R-1:R;if(D<0||D>=H.length||H[D]!=="\uFFFC")return;let G=0,z=null;for(let Y of E.blocks){let re=Y.kind==="text"?Y.value.length:1;if(Y.kind==="mention"&&D>=G&&D<G+re){z=Y.id;break}G+=re}if(!z)return;W.preventDefault();let K=bS(E,z);l(K.doc),p(K.caret,{focus:!0}),y(),u()},A=(W,V)=>{l(Vg(W)),p(V)},I=(W,V)=>{if(!Number.isFinite(W)||!Number.isFinite(V)||V<=W)return null;try{let R=Yl(o,W),w=Yl(o,V),E=document.createRange();E.setStart(R.node,R.offset),E.setEnd(w.node,w.offset);let H=E.getBoundingClientRect();return H.width===0&&H.height===0?null:H}catch{return null}},M=(W,V,R)=>{let w=tu(a(),W,V,R);l(w.doc),p(w.caret,{focus:!0})},O=(W,V)=>{let R=a(),w=Zp(R),E=V.triggerIndex,H=V.triggerIndex+1+V.query.length;if(E<0||H>w.length||w.slice(E+1,H)!==V.query)return null;let D=t.generateId(),G=zg(R,{start:E,end:H},W,D);return l(G.doc),p(G.caret,{focus:!0}),t.onMentionInserted?.(D,W),u(),D},k=W=>{let V=a(),R=m(),E=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:R.start,end:R.end}:{start:eu(V),end:eu(V)},H=t.generateId(),D=zg(V,E,W,H);return l(D.doc),p(D.caret,{focus:!0}),t.onMentionInserted?.(H,W),u(),H},B=(W,V)=>{for(let R of Array.from(o.childNodes))if(Xl(R)&&R.getAttribute(Ql)===W){let w=V==="error";if(R.classList.toggle(gI,w),w){R.hasAttribute(Gl)||(R.setAttribute(Gl,R.getAttribute("aria-label")??""),R.setAttribute(qg,R.getAttribute("title")??""));let E=n.get(W)?.label??"";R.setAttribute("title",`${E}: failed to attach context`),R.setAttribute("aria-label",`${E}, failed to attach context`)}else if(R.hasAttribute(Gl)){let E=R.getAttribute(Gl),H=R.getAttribute(qg);E?R.setAttribute("aria-label",E):R.removeAttribute("aria-label"),H?R.setAttribute("title",H):R.removeAttribute("title"),R.removeAttribute(Gl),R.removeAttribute(qg)}return}};return o.addEventListener("input",g),o.addEventListener("compositionstart",b),o.addEventListener("compositionend",C),o.addEventListener("paste",S),o.addEventListener("beforeinput",T),l(yS()),{element:o,getValue:()=>$g(a()),getLogicalText:()=>Zp(a()),getDocument:a,getSelection:m,setSelection:(W,V=W)=>{let R=typeof window<"u"?window.getSelection():null;if(R)try{let w=Yl(o,W),E=Yl(o,V),H=document.createRange();H.setStart(w.node,w.offset),H.setEnd(E.node,E.offset),R.removeAllRanges(),R.addRange(H)}catch{}},setValueWithCaret:A,getLogicalRangeRect:I,setValue:W=>{l(Vg(W)),o.focus(),p(W.length,{focus:!0}),u()},replaceLogicalRange:M,insertMentionAtTrigger:O,insertMentionAtSelection:k,setMentionStatus:B,submit:()=>jl(o.closest("form")),dispatchInput:u,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",g),o.removeEventListener("compositionstart",b),o.removeEventListener("compositionend",C),o.removeEventListener("paste",S),o.removeEventListener("beforeinput",T)}}}var gI,Ql,Gl,qg,wS,AS=be(()=>{"use strict";Ug();zp();gI="persona-mention-token-error",Ql="data-mention-id",Gl="data-mention-prev-label",qg="data-mention-prev-title",wS=`
182
- `});function CI(t,e){e.className=`${t.className} persona-composer-contenteditable`.trim();for(let r=0;r<t.style.length;r++){let s=t.style.item(r);s!=="height"&&e.style.setProperty(s,t.style.getPropertyValue(s),t.style.getPropertyPriority(s))}let n=t.getAttribute("placeholder");n&&(e.setAttribute("data-placeholder",n),e.setAttribute("aria-placeholder",n));let o=t.getAttribute("aria-label")??n;o&&e.setAttribute("aria-label",o)}function wI(t,e,n){Object.defineProperty(t,"value",{configurable:!0,get:()=>e.getValue(),set:o=>{e.setValueWithCaret(o,o.length),e.dispatchInput()}}),Object.defineProperty(t,"placeholder",{configurable:!0,get:()=>t.getAttribute("data-placeholder")??"",set:o=>{o?(t.setAttribute("data-placeholder",o),t.setAttribute("aria-placeholder",o),n||t.setAttribute("aria-label",o)):(t.removeAttribute("data-placeholder"),t.removeAttribute("aria-placeholder"),n||t.removeAttribute("aria-label"))}}),Object.defineProperty(t,"selectionStart",{configurable:!0,get:()=>e.getSelection().start}),Object.defineProperty(t,"selectionEnd",{configurable:!0,get:()=>e.getSelection().end}),t.setSelectionRange=(o,r)=>e.setSelection(o??0,r??o??0)}function MS(t){let{textarea:e}=t,n={generateId:vI,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:e.getAttribute("placeholder")??void 0},o=SS(n),r=o.element,s=e.getAttribute("aria-label")!=null;CI(e,r),wI(r,o,s),r.getInlineMessageFields=()=>vS(o.getDocument?.()??{blocks:[]});let a=e.selectionStart??e.value.length;return o.setValueWithCaret(e.value,a),{input:o,element:r,destroy:o.destroy}}var bI,vI,TS=be(()=>{"use strict";AS();Ug();bI=0,vI=()=>`pmention-${++bI}`});var ES={};Vn(ES,{mountInlineComposer:()=>MS});var kS=be(()=>{"use strict";TS()});function YS(t){return t.role!=="assistant"||t.variant==="tool"||t.variant==="reasoning"?!1:t.variant==="approval"?!0:!!(t.content?.trim()||t.rawContent?.trim()||t.contentParts?.length)}function pu(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function cr(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function Wr(t,e){return cr(t)-t.scrollTop<=e}function uu(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:p=!1}=t,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!e&&r&&(!p||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:e&&l&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:e&&d&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function mu(t){let{following:e,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=t;return e&&n<0?"pause":!e&&r&&n>0&&o?"resume":"none"}function QS(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Xg(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight+(t.slack??0));return{targetScrollTop:e,spacerHeight:n}}function XS(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var Jg=be(()=>{"use strict"});var nc,VI,fu,$I,th,ZS,ii,oc,gu,zI,UI,Zg,qI,jI,KI,rc,hu,sc,JS,GI,eh,YI,eA,ic,ac=be(()=>{"use strict";nc={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},VI=["pre","code","a","script","style"],fu=t=>({type:t?.type??nc.type,placeholder:t?.placeholder??nc.placeholder,speed:t?.speed??nc.speed,duration:t?.duration??nc.duration,buffer:t?.buffer??nc.buffer}),$I=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],th=new Map;for(let t of $I)th.set(t.name,t);ZS=["wipe","glyph-cycle"],ii=t=>{th.set(t.name,t)},oc=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:th.get(t)??null,gu=(t,e,n,o,r)=>{if(!r)return t;if(n?.bufferContent)return n.bufferContent(t,o);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
183
- `);return s<0?"":t.slice(0,s)}return t},zI=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=e,r},UI=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=e,r},Zg=/\s/,qI=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(e.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},jI=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Zg.test(s[l])){let d=l;for(;d<s.length&&Zg.test(s[d]);)d+=1;a.appendChild(o.createTextNode(s.slice(l,d))),l=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let p=l;for(;p<s.length&&!Zg.test(s[p]);)d.appendChild(zI(o,s[p],e,n.value)),n.value+=1,p+=1;a.appendChild(d),l=p}r.replaceChild(a,t)},KI=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let d of l)d&&(/^\s+$/.test(d)?a.appendChild(o.createTextNode(d)):(a.appendChild(UI(o,d,e,n.value)),n.value+=1));r.replaceChild(a,t)},rc=(t,e,n,o)=>{if(!t||typeof document>"u")return t;let r=document.createElement("div");r.innerHTML=t;let s=new Set((o?.skipTags??VI).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)qI(d,s)||l.push(d),d=a.nextNode();let p={value:o?.startIndex??0},u=e==="char"?jI:KI;for(let m of l)u(m,n,p);return r.innerHTML},hu=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},sc=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},JS=new WeakMap,GI=(t,e)=>{if(!t.styles)return;let n=JS.get(e);if(n||(n=new Set,JS.set(e,n)),n.has(t.name)){let s=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(t.name)}n.add(t.name);let r=(e instanceof ShadowRoot?e.ownerDocument:e.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",t.name),r.textContent=t.styles,e.appendChild(r)},eh=new WeakMap,YI=(t,e)=>{if(!t.onAttach)return;let n=eh.get(e);if(n||(n=new Map,eh.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},eA=t=>{let e=eh.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},ic=(t,e)=>{GI(t,e),YI(t,e)}});var QI,tA,nA,oA=be(()=>{"use strict";ac();QI=`
179
+ `)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:a}=Au(r.slice(n.trigger.length));if(s)for(let l of n.sources){let c=l.matchCommand?.(s);if(c&&this.isInlineCommand(c))return{source:l,item:c,args:a}}}}return null}async dispatchInlineCommand(e){let n=this.matchInlineCommand(e);if(!n)return null;let{source:o,item:r,args:s}=n,a=r.command??"prompt";if(this.opts.emit?.("command",{sourceId:o.id,itemId:r.id,kind:a,args:s}),a==="action")return this.runAction(r,s),{kind:"action"};if(a==="prompt"){let c;try{c=await o.resolve(r,this.resolveContext(s,e))}catch(p){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",p),null}return{kind:"prompt",sendText:c.insertText??c.llmAppend??e}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let c=await o.resolve(r,this.resolveContext(s,e)),p={};return c.context&&(p[o.id]={[r.id]:c.context}),{blocks:[],contentParts:c.contentParts??[],context:p}}}}}resolveContext(e,n){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:n,args:e,signal:new AbortController().signal}}runAction(e,n){if(e.action)try{Promise.resolve(e.action({args:n,config:this.opts.getConfig(),messages:this.opts.getMessages(),composer:this.input})).catch(o=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)})}catch(o){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)}}captureStripTarget(){return this.triggerMatch?{value:this.input.getValue(),start:this.triggerMatch.triggerIndex,end:this.input.getSelection().start}:null}async runPromptMacro(e,n,o,r){let s=this.input,a;try{a=await e.resolve(n,{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:s.getValue(),args:o,signal:new AbortController().signal})}catch(c){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",c);return}let l=a.insertText??a.llmAppend??"";n.insertMode==="insert-at-caret"&&r?s.replaceLogicalRange?(s.replaceLogicalRange(r.start,r.end,l),s.dispatchInput()):s.setValue(r.value.slice(0,r.start)+l+r.value.slice(r.end)):s.setValue(l),n.submitOnSelect&&s.submit()}stripQuery(){if(!this.triggerMatch)return;let e=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.triggerMatch.triggerIndex,e,"");else{let n=rA(this.input.getValue(),this.triggerMatch,e);this.input.setValueWithCaret(n.value,n.caret)}this.input.dispatchInput(),this.triggerMatch=null}destroy(){this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.popover?.destroy(),this.menu.destroy();let e=this.input.element;e.removeAttribute("aria-haspopup"),e.removeAttribute("aria-controls"),e.removeAttribute("aria-activedescendant")}}});function Mh(t,e){let n=document.createElement("div");n.className="persona-sr-only",n.setAttribute("aria-live",t),n.setAttribute("aria-atomic","true"),n.setAttribute("role",t==="assertive"?"alert":"status"),n.setAttribute("data-persona-mention-live-region","");let o=e.getRootNode();typeof ShadowRoot<"u"&&o instanceof ShadowRoot?(Object.assign(n.style,PR),document.body.appendChild(n)):e.appendChild(n);let s;return{announce:a=>{s!==void 0&&clearTimeout(s),n.textContent="",s=setTimeout(()=>{s=void 0,n.textContent=a},0)},destroy:()=>{s!==void 0&&clearTimeout(s),n.remove()}}}var PR,vA=be(()=>{"use strict";PR={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 CA(t){let e=t.composerInput??JS(t.textarea),n=Mh("polite",t.liveRegionHost),o=Mh("assertive",t.liveRegionHost),r=p=>n.announce(p),s=p=>o.announce(p),a=new Su({mentionConfig:t.mentionConfig,contextRow:t.contextRow,getMessages:t.getMessages,getConfig:t.getConfig,getComposerText:()=>e.getValue(),announce:r,announceError:s,emit:t.emit}),l=()=>new Mu({mentionConfig:t.mentionConfig,composerInput:e,anchor:t.anchor,getMessages:t.getMessages,getConfig:t.getConfig,onSelect:(p,u,m)=>a.add(p,u,m),onInsertMention:(p,u,m,g)=>a.track(p,u,m,g,h=>e.setMentionStatus?.(p,h)),admitMention:(p,u)=>a.admit(p,u),announce:r,popoverContainer:t.popoverContainer,onPickerOpenChange:t.onPickerOpenChange,emit:t.emit}),c=l();return{openMenu:p=>c.openFromButton(p),isMenuOpen:()=>c.isOpen(),handleInput:()=>c.onInput(),handleKeydown:p=>c.handleKeydown(p),hasMentions:()=>a.hasMentions(),getMentionRefs:()=>a.getRefs(),removeLastChip:()=>a.removeLast(),dispatchInlineCommand:p=>c.dispatchInlineCommand(p),collectForSubmit:()=>a.hasMentions()?a.collectForSubmit():null,untrackMention:p=>a.remove(p),rebindComposer:p=>{p!==e&&(c.destroy(),e=p,c=l())},clear:()=>a.clear(),destroy:()=>{c.destroy(),a.clear(),n.destroy(),o.destroy()}}}var wA=be(()=>{"use strict";Ah();bA();yu();vA();wu()});var xA={};$n(xA,{mountContextMentions:()=>CA,setMentionIconRenderer:()=>Sh});var SA=be(()=>{"use strict";wA()});function kh(t){return t.kind==="text"?t.value.length:1}function Ph(t){let e=[],n=r=>{let s=e[e.length-1];s&&s.kind==="text"?s.value+=r:e.push({kind:"text",value:r})};(t.length===0||t[0].kind!=="text")&&e.push({kind:"text",value:""});for(let r of t){if(r.kind==="text"){n(r.value);continue}let s=e[e.length-1];(!s||s.kind!=="text")&&e.push({kind:"text",value:""}),e.push({kind:"mention",id:r.id,ref:r.ref}),e.push({kind:"text",value:""})}let o=e[e.length-1];return(!o||o.kind!=="text")&&e.push({kind:"text",value:""}),e}function AA(){return{blocks:[{kind:"text",value:""}]}}function Lh(t){return{blocks:[{kind:"text",value:t}]}}function Ih(t){return t.blocks.map(e=>e.kind==="text"?e.value:`${IR}${e.ref.label}`).join("")}function Eu(t){return t.blocks.map(e=>e.kind==="text"?e.value:"\uFFFC").join("")}function ku(t){return t.blocks.reduce((e,n)=>e+kh(n),0)}function RR(t){let e=[];for(let n of t.blocks)n.kind==="mention"&&e.push({id:n.id,ref:n.ref});return e}function Tu(t,e){let n=[],o=[],r=0;for(let s of t){let a=kh(s),l=r+a;if(l<=e)n.push(s);else if(r>=e)o.push(s);else if(s.kind==="text"){let c=e-r;c>0&&n.push({kind:"text",value:s.value.slice(0,c)}),c<a&&o.push({kind:"text",value:s.value.slice(c)})}else o.push(s);r=l}return{left:n,right:o}}function Rh(t,e,n,o){let r=Tu(t.blocks,e.start).left,s=Tu(t.blocks,e.end).right,a=s[0],l=a?.kind==="text"?a.value.charAt(0):"",c=l!==" "&&l!==" "&&l!==`
180
+ `,p=Ph([...r,{kind:"mention",id:o,ref:n},...c?[{kind:"text",value:" "}]:[],...s]),u=e.start+1+(l===`
181
+ `?0:1);return{doc:{blocks:p},caret:u}}function MA(t,e){let n=0,o=0,r=!1;for(let a of t.blocks)a.kind==="mention"&&a.id===e&&(n=o,r=!0),o+=kh(a);return r?{doc:{blocks:Ph(t.blocks.filter(a=>!(a.kind==="mention"&&a.id===e)))},caret:n}:{doc:t,caret:o}}function Pu(t,e,n,o){let r=ku(t),s=Math.max(0,Math.min(e,n,r)),a=Math.min(r,Math.max(e,n,0)),l=Tu(t.blocks,s).left,c=Tu(t.blocks,a).right;return{doc:{blocks:Ph([...l,{kind:"text",value:o},...c])},caret:s+o.length}}function TA(t){let e=[];for(let n of t.blocks)n.kind==="text"?n.value.length>0&&e.push({kind:"text",text:n.value}):e.push({kind:"mention",ref:n.ref});return{content:Ih(t),contextMentions:RR(t).map(n=>n.ref),contentSegments:e}}var IR,Hh=be(()=>{"use strict";bu();IR="@"});function dc(t){return t.nodeType===1&&t.hasAttribute(cc)}function PA(t){return t.nodeType===1&&t.tagName==="BR"}function Lu(t){return t.nodeType===3?t.data.length:dc(t)||PA(t)?1:t.textContent?.length??0}function EA(t,e,n){let o=0;for(let r of Array.from(t.childNodes)){if(r===e)return r.nodeType===3?o+n:o+(n>0?Lu(r):0);if(r.contains(e))return dc(r)?o+1:o+WR(r,e,n);o+=Lu(r)}if(e===t){let r=0,s=Array.from(t.childNodes);for(let a=0;a<Math.min(n,s.length);a++)r+=Lu(s[a]);return r}return o}function WR(t,e,n){let o=0,r=s=>{if(s===e)return o+=s.nodeType===3?n:0,!0;if(s.nodeType===3)return o+=s.data.length,!1;for(let a of Array.from(s.childNodes))if(r(a))return!0;return!1};return r(t),o}function lc(t,e){let n=0,o=Array.from(t.childNodes);for(let r=0;r<o.length;r++){let s=o[r],a=Lu(s);if(e<=n+a)return s.nodeType===3?{node:s,offset:e-n}:{node:t,offset:e<=n?r:r+1};n+=a}return{node:t,offset:o.length}}function BR(t,e){let n=[];for(let o of Array.from(t.childNodes))if(dc(o)){let r=o.getAttribute(cc),s=e.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(PA(o))n.push({kind:"text",value:kA});else if(o.nodeType===3)n.push({kind:"text",value:o.data});else{let r=o.textContent??"";r&&n.push({kind:"text",value:r})}return n.length===0&&n.push({kind:"text",value:""}),{blocks:n}}function LA(t){let e=t.renderToken,n=new Map,o=t.element??document.createElement("div");o.setAttribute("contenteditable","true"),o.setAttribute("data-persona-composer-input",""),o.setAttribute("role","textbox"),o.setAttribute("aria-multiline","true"),o.setAttribute("dir","auto"),o.classList.add("persona-composer-contenteditable"),t.placeholder!=null&&o.setAttribute("data-placeholder",t.placeholder);let r=!1,s=0,a=()=>BR(o,n),l=B=>{o.replaceChildren();for(let O of B.blocks)if(O.kind==="text")O.value.length>0&&o.appendChild(document.createTextNode(O.value));else{n.set(O.id,O.ref);let R=e(O.ref);R.setAttribute("contenteditable","false"),R.setAttribute(cc,O.id),o.appendChild(R)}},c=()=>{let O=o.getRootNode().activeElement;return O===o||O!=null&&o.contains(O)},p=(B,O)=>{if(s=B,!O?.focus&&!c())return;let R=typeof window<"u"?window.getSelection():null;if(!R)return;let S=lc(o,B);try{let x=document.createRange();x.setStart(S.node,S.offset),x.collapse(!0),R.removeAllRanges(),R.addRange(x)}catch{}},u=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},m=()=>{let B={start:s,end:s},O=typeof window<"u"?window.getSelection():null;if(!O||O.rangeCount===0)return B;let R=O.getRangeAt(0);if(!o.contains(R.startContainer))return B;let S=EA(o,R.startContainer,R.startOffset),x=R.collapsed?S:EA(o,R.endContainer,R.endOffset);return{start:Math.min(S,x),end:Math.max(S,x)}},g=()=>{let B=new Set;for(let O of Array.from(o.childNodes))dc(O)&&B.add(O.getAttribute(cc));for(let O of Array.from(n.keys()))B.has(O)||(n.delete(O),t.onMentionRemoved?.(O))},h=()=>{r||n.size!==0&&g()},b=()=>{r=!0},C=()=>{r=!1,g()},M=B=>{B.preventDefault();let O=B.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,O);else{let{start:R,end:S}=m(),x=Pu(a(),R,S,O);l(x.doc),p(x.caret,{focus:!0}),g()}u()},E=B=>{if(r)return;let O=B.inputType;if(O==="insertParagraph"){B.preventDefault();let{start:ee,end:oe}=m(),ne=Pu(a(),ee,oe,kA);l(ne.doc),p(ne.caret,{focus:!0}),n.size>0&&g(),u();return}if(O!=="deleteContentBackward"&&O!=="deleteContentForward"||n.size===0)return;let{start:R,end:S}=m();if(R!==S)return;let x=a(),P=Eu(x),L=O==="deleteContentBackward"?R-1:R;if(L<0||L>=P.length||P[L]!=="\uFFFC")return;let G=0,V=null;for(let ee of x.blocks){let oe=ee.kind==="text"?ee.value.length:1;if(ee.kind==="mention"&&L>=G&&L<G+oe){V=ee.id;break}G+=oe}if(!V)return;B.preventDefault();let K=MA(x,V);l(K.doc),p(K.caret,{focus:!0}),g(),u()},T=(B,O)=>{l(Lh(B)),p(O)},H=(B,O)=>{if(!Number.isFinite(B)||!Number.isFinite(O)||O<=B)return null;try{let R=lc(o,B),S=lc(o,O),x=document.createRange();x.setStart(R.node,R.offset),x.setEnd(S.node,S.offset);let P=x.getBoundingClientRect();return P.width===0&&P.height===0?null:P}catch{return null}},A=(B,O,R)=>{let S=Pu(a(),B,O,R);l(S.doc),p(S.caret,{focus:!0})},D=(B,O)=>{let R=a(),S=Eu(R),x=O.triggerIndex,P=O.triggerIndex+1+O.query.length;if(x<0||P>S.length||S.slice(x+1,P)!==O.query)return null;let L=t.generateId(),G=Rh(R,{start:x,end:P},B,L);return l(G.doc),p(G.caret,{focus:!0}),t.onMentionInserted?.(L,B),u(),L},W=B=>{let O=a(),R=m(),x=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:R.start,end:R.end}:{start:ku(O),end:ku(O)},P=t.generateId(),L=Rh(O,x,B,P);return l(L.doc),p(L.caret,{focus:!0}),t.onMentionInserted?.(P,B),u(),P},U=(B,O)=>{for(let R of Array.from(o.childNodes))if(dc(R)&&R.getAttribute(cc)===B){let S=O==="error";if(R.classList.toggle(HR,S),S){R.hasAttribute(ac)||(R.setAttribute(ac,R.getAttribute("aria-label")??""),R.setAttribute(Wh,R.getAttribute("title")??""));let x=n.get(B)?.label??"";R.setAttribute("title",`${x}: failed to attach context`),R.setAttribute("aria-label",`${x}, failed to attach context`)}else if(R.hasAttribute(ac)){let x=R.getAttribute(ac),P=R.getAttribute(Wh);x?R.setAttribute("aria-label",x):R.removeAttribute("aria-label"),P?R.setAttribute("title",P):R.removeAttribute("title"),R.removeAttribute(ac),R.removeAttribute(Wh)}return}};return o.addEventListener("input",h),o.addEventListener("compositionstart",b),o.addEventListener("compositionend",C),o.addEventListener("paste",M),o.addEventListener("beforeinput",E),l(AA()),{element:o,getValue:()=>Ih(a()),getLogicalText:()=>Eu(a()),getDocument:a,getSelection:m,setSelection:(B,O=B)=>{let R=typeof window<"u"?window.getSelection():null;if(R)try{let S=lc(o,B),x=lc(o,O),P=document.createRange();P.setStart(S.node,S.offset),P.setEnd(x.node,x.offset),R.removeAllRanges(),R.addRange(P)}catch{}},setValueWithCaret:T,getLogicalRangeRect:H,setValue:B=>{l(Lh(B)),o.focus(),p(B.length,{focus:!0}),u()},replaceLogicalRange:A,insertMentionAtTrigger:D,insertMentionAtSelection:W,setMentionStatus:U,submit:()=>sc(o.closest("form")),dispatchInput:u,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",h),o.removeEventListener("compositionstart",b),o.removeEventListener("compositionend",C),o.removeEventListener("paste",M),o.removeEventListener("beforeinput",E)}}}var HR,cc,ac,Wh,kA,IA=be(()=>{"use strict";Hh();yu();HR="persona-mention-token-error",cc="data-mention-id",ac="data-mention-prev-label",Wh="data-mention-prev-title",kA=`
182
+ `});function _R(t,e){e.className=`${t.className} persona-composer-contenteditable`.trim();for(let r=0;r<t.style.length;r++){let s=t.style.item(r);s!=="height"&&e.style.setProperty(s,t.style.getPropertyValue(s),t.style.getPropertyPriority(s))}let n=t.getAttribute("placeholder");n&&(e.setAttribute("data-placeholder",n),e.setAttribute("aria-placeholder",n));let o=t.getAttribute("aria-label")??n;o&&e.setAttribute("aria-label",o)}function NR(t,e,n){Object.defineProperty(t,"value",{configurable:!0,get:()=>e.getValue(),set:o=>{e.setValueWithCaret(o,o.length),e.dispatchInput()}}),Object.defineProperty(t,"placeholder",{configurable:!0,get:()=>t.getAttribute("data-placeholder")??"",set:o=>{o?(t.setAttribute("data-placeholder",o),t.setAttribute("aria-placeholder",o),n||t.setAttribute("aria-label",o)):(t.removeAttribute("data-placeholder"),t.removeAttribute("aria-placeholder"),n||t.removeAttribute("aria-label"))}}),Object.defineProperty(t,"selectionStart",{configurable:!0,get:()=>e.getSelection().start}),Object.defineProperty(t,"selectionEnd",{configurable:!0,get:()=>e.getSelection().end}),t.setSelectionRange=(o,r)=>e.setSelection(o??0,r??o??0)}function RA(t){let{textarea:e}=t,n={generateId:OR,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:e.getAttribute("placeholder")??void 0},o=LA(n),r=o.element,s=e.getAttribute("aria-label")!=null;_R(e,r),NR(r,o,s),r.getInlineMessageFields=()=>TA(o.getDocument?.()??{blocks:[]});let a=e.selectionStart??e.value.length;return o.setValueWithCaret(e.value,a),{input:o,element:r,destroy:o.destroy}}var DR,OR,HA=be(()=>{"use strict";IA();Hh();DR=0,OR=()=>`pmention-${++DR}`});var WA={};$n(WA,{mountInlineComposer:()=>RA});var BA=be(()=>{"use strict";HA()});function nM(t){return t.role!=="assistant"||t.variant==="tool"||t.variant==="reasoning"?!1:t.variant==="approval"?!0:!!(t.content?.trim()||t.rawContent?.trim()||t.contentParts?.length)}function $u(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function br(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function jr(t,e){return br(t)-t.scrollTop<=e}function zu(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:p=!1}=t,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!e&&r&&(!p||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:e&&l&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:e&&c&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function Uu(t){let{following:e,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=t;return e&&n<0?"pause":!e&&r&&n>0&&o?"resume":"none"}function oM(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function zh(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight+(t.slack??0));return{targetScrollTop:e,spacerHeight:n}}function rM(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var Uh=be(()=>{"use strict"});var bc,fH,qu,gH,Kh,iM,Ei,vc,ju,hH,yH,qh,bH,vH,CH,Cc,Ku,wc,sM,wH,jh,xH,aM,xc,Sc=be(()=>{"use strict";bc={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},fH=["pre","code","a","script","style"],qu=t=>({type:t?.type??bc.type,placeholder:t?.placeholder??bc.placeholder,speed:t?.speed??bc.speed,duration:t?.duration??bc.duration,buffer:t?.buffer??bc.buffer}),gH=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Kh=new Map;for(let t of gH)Kh.set(t.name,t);iM=["wipe","glyph-cycle"],Ei=t=>{Kh.set(t.name,t)},vc=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:Kh.get(t)??null,ju=(t,e,n,o,r)=>{if(!r)return t;if(n?.bufferContent)return n.bufferContent(t,o);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
183
+ `);return s<0?"":t.slice(0,s)}return t},hH=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=e,r},yH=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=e,r},qh=/\s/,bH=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(e.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},vH=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(qh.test(s[l])){let c=l;for(;c<s.length&&qh.test(s[c]);)c+=1;a.appendChild(o.createTextNode(s.slice(l,c))),l=c}else{let c=o.createElement("span");c.className="persona-stream-word-group";let p=l;for(;p<s.length&&!qh.test(s[p]);)c.appendChild(hH(o,s[p],e,n.value)),n.value+=1,p+=1;a.appendChild(c),l=p}r.replaceChild(a,t)},CH=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let c of l)c&&(/^\s+$/.test(c)?a.appendChild(o.createTextNode(c)):(a.appendChild(yH(o,c,e,n.value)),n.value+=1));r.replaceChild(a,t)},Cc=(t,e,n,o)=>{if(!t||typeof document>"u")return t;let r=document.createElement("div");r.innerHTML=t;let s=new Set((o?.skipTags??fH).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],c=a.nextNode();for(;c;)bH(c,s)||l.push(c),c=a.nextNode();let p={value:o?.startIndex??0},u=e==="char"?vH:CH;for(let m of l)u(m,n,p);return r.innerHTML},Ku=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},wc=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},sM=new WeakMap,wH=(t,e)=>{if(!t.styles)return;let n=sM.get(e);if(n||(n=new Set,sM.set(e,n)),n.has(t.name)){let s=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(t.name)}n.add(t.name);let r=(e instanceof ShadowRoot?e.ownerDocument:e.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",t.name),r.textContent=t.styles,e.appendChild(r)},jh=new WeakMap,xH=(t,e)=>{if(!t.onAttach)return;let n=jh.get(e);if(n||(n=new Map,jh.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},aM=t=>{let e=jh.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},xc=(t,e)=>{wH(t,e),xH(t,e)}});var SH,lM,cM,dM=be(()=>{"use strict";Sc();SH=`
184
184
  @keyframes persona-stream-wipe {
185
185
  from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
186
186
  to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
@@ -216,7 +216,7 @@ ${e}
216
216
  mask-image: none !important;
217
217
  }
218
218
  }
219
- `.trim(),tA={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:QI};ii(tA);nA=tA});var XI,lc,JI,ZI,nh,eH,tH,nH,pA,oh,oH,rA,sA,iA,rH,aA,lA,cA,sH,wa,iH,aH,lH,uA,cH,dA,dH,mA,fA,gA=be(()=>{"use strict";ac();XI=`
219
+ `.trim(),lM={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:SH};Ei(lM);cM=lM});var AH,Ac,MH,TH,Gh,EH,kH,PH,bM,Yh,LH,pM,uM,mM,IH,fM,gM,hM,RH,Fa,HH,WH,BH,vM,DH,yM,OH,CM,wM,xM=be(()=>{"use strict";Sc();AH=`
220
220
  [data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
221
221
  animation: persona-stream-glyph-cycle-fade
222
222
  calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
@@ -234,13 +234,13 @@ ${e}
234
234
  opacity: 1 !important;
235
235
  }
236
236
  }
237
- `.trim(),lc="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",JI=10,ZI=120,nh=120,eH=.4,tH=50,nH=t=>{if(!t)return nh;let n=(t.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):nh},pA=t=>{let e=t.closest(".persona-stream-glyph-cycle"),n=nH(e);return ZI*n/nh},oh=t=>{let e=lc[Math.floor(Math.random()*lc.length)];return t&&e===t&&(e=lc[(lc.indexOf(e)+1)%lc.length]),e},oH=t=>{let e=t.closest(".persona-stream-glyph-cycle");if(!e)return;let n=e.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===t){o=!0;continue}o&&Math.random()<eH&&(r.textContent=oh())}},rA=new WeakMap,sA=25,iA=.5,rH=6,aA=.25,lA=new WeakMap,cA=new WeakMap,sH=(t,e)=>{if(!t)return sA*iA;let n=lA.get(t);lA.set(t,e);let o=cA.get(t)??sA;if(n!==void 0){let r=e-n;r>1&&(o=o*(1-aA)+r*aA,cA.set(t,o))}return Math.max(rH,o*iA)},wa=new Map,iH=t=>t.closest("[data-message-id]")?.dataset.messageId??null,aH=t=>{t&&wa.set(t,(wa.get(t)??0)+1)},lH=t=>{if(!t)return;let e=wa.get(t)??0;e<=1?wa.delete(t):wa.set(t,e-1)},uA=t=>{if(t.dataset.glyphCycleScheduled==="true")return;let e=t.textContent??"";if(!e||/\s/.test(e))return;t.dataset.glyphCycleScheduled="true",t.dataset.glyphCycleFinal=e,t.setAttribute("data-preserve-runtime","stream-glyph-cycle"),t.textContent=oh();let n=iH(t);n&&(t.dataset.glyphCycleMessageId=n),aH(n);let o=t.closest(".persona-stream-glyph-cycle"),r=Date.now(),s=sH(o,r),a=pA(t),l=JI*a,d=r+l;if(o){let p=rA.get(o);p!==void 0&&(d=Math.max(d,p)),rA.set(o,d+s)}cH(t,e,d)},cH=(t,e,n)=>{if(t.dataset.glyphCycleStarted==="true")return;t.dataset.glyphCycleStarted="true";let o=pA(t),r=t.textContent??void 0,s=()=>{if(!t.isConnected)return;if(Date.now()>=n){t.textContent=e,t.removeAttribute("data-preserve-runtime"),delete t.dataset.glyphCycleStarted,delete t.dataset.glyphCycleFinal,lH(t.dataset.glyphCycleMessageId??null),delete t.dataset.glyphCycleMessageId;return}let a=oh(r);t.textContent=a,r=a,oH(t),setTimeout(s,o)};setTimeout(s,o)},dA=t=>{let e=t.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(e)for(let n of Array.from(e))uA(n)},dH=t=>t.nodeType===1,mA={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:XI,bufferContent(t){if(t.length<tH)return"";let e=0,n=-1,o=0;for(;o<t.length;){if(t[o]==="*"&&t[o+1]==="*"){e+=1,o+=2;continue}/\s/.test(t[o])&&e%2===0&&(n=o),o+=1}return n<0?"":t.slice(0,n)},isAnimating(t){return(wa.get(t.id)??0)>0},onAttach(t){dA(t);let e=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))dH(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?uA(r):dA(r))});return e.observe(t,{childList:!0,subtree:!0}),()=>e.disconnect()}};ii(mA);fA=mA});var hA={};Vn(hA,{glyphCycle:()=>fA,wipe:()=>nA});var yA=be(()=>{"use strict";oA();gA()});function fc(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=t,l=v("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(fa)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let b of e){if(b.dividerBefore){let T=document.createElement("hr");l.appendChild(T)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",b.id),b.destructive&&C.setAttribute("data-destructive",""),b.icon){let T=Ie(b.icon,16,"currentColor",1.5);T&&C.appendChild(T)}let S=document.createElement("span");S.textContent=b.label,C.appendChild(S),C.addEventListener("click",T=>{T.stopPropagation(),m(),n(b.id)}),l.appendChild(C)}let d=null;function p(){if(!s)return;let b=o.getBoundingClientRect();l.style.top=`${b.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-b.right}px`,l.style.left="auto"):(l.style.left=`${b.left}px`,l.style.right="auto")}function u(){let b=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),b&&a?.(!0),requestAnimationFrame(()=>{let C=S=>{!l.contains(S.target)&&!o.contains(S.target)&&m()};document.addEventListener("click",C,!0),d=()=>document.removeEventListener("click",C,!0)})}function m(){let b=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,b&&a?.(!1)}function y(){l.classList.contains("persona-hidden")?u():m()}function g(){m(),l.remove()}return s&&s.appendChild(l),{element:l,show:u,hide:m,toggle:y,destroy:g}}var dh=be(()=>{"use strict";Ye();Yt();fs()});function gn(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=t,p=v("button",Vt(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=Ie(e,o??16,"currentColor",r??2);if(u&&p.appendChild(u),l&&p.addEventListener("click",l),d)for(let[m,y]of Object.entries(d))p.setAttribute(m,y);return p}function ci(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:d}=t,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let u=v("button",p);if(u.type="button",u.setAttribute("aria-label",n),e){let y=Ie(e,s??14,"currentColor",2);y&&u.appendChild(y)}let m=v("span");if(m.textContent=n,u.appendChild(m),l&&u.addEventListener("click",l),d)for(let[y,g]of Object.entries(d))u.setAttribute(y,g);return u}function bu(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=v("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function d(){for(let u of l)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of e){let m;u.icon?m=gn({icon:u.icon,label:u.label,className:u.className,onClick:()=>{a=u.id,d(),o(u.id)}}):(m=v("button","persona-icon-btn"+(u.className?" "+u.className:"")),m.type="button",m.setAttribute("aria-label",u.label),m.title=u.label,m.textContent=u.label,m.addEventListener("click",()=>{a=u.id,d(),o(u.id)})),m.setAttribute("aria-pressed",u.id===a?"true":"false"),l.push({id:u.id,btn:m}),s.appendChild(m)}function p(u){a=u,d()}return{element:s,setSelected:p}}function xA(t){let{label:e,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:a,onPrimary:l,position:d="bottom-left",portal:p,chevronLabel:u="More options",chevronIconSize:m,className:y,primaryClassName:g,chevronClassName:b}=t,C=v("div","persona-split-btn"+(y?" "+y:"")),S={label:e,className:"persona-split-btn-primary"+(g?" "+g:""),onClick:l},T=r&&n?gn({...S,icon:n,size:o??14}):ci({...S,icon:n,iconSize:o??14}),A=gn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(b?" "+b:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});C.append(T,A);let I=null,M=()=>{if(I)return I;let O=(typeof p=="function"?p():p)??void 0;return I=fc({items:s,onSelect:a,anchor:C,position:d,portal:O,onOpenChange:k=>{A.setAttribute("aria-expanded",k?"true":"false")}}),O||C.appendChild(I.element),I};return C.isConnected?M():requestAnimationFrame(()=>{I||M()}),A.addEventListener("click",O=>{O.stopPropagation(),M().toggle()}),{element:C,primaryButton:T,chevronButton:A,openMenu:()=>M().show(),closeMenu:()=>I?.hide(),toggleMenu:()=>M().toggle(),destroy:()=>{I?.destroy(),C.remove()}}}function SA(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:d}=t,p=v("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",e);let u=v("span","persona-combo-btn-label");u.textContent=e,p.appendChild(u);let m=Ie(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",p.appendChild(m)),d&&(p.style.borderRadius=d.borderRadius??"10px",p.style.padding=d.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=d.background??"",p.style.borderColor=d.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let y=fc({items:o,onSelect:b=>{p.setAttribute("aria-expanded","false"),r(b)},anchor:p,position:s,portal:a});a||p.appendChild(y.element);let g=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",b=>{if(b.stopPropagation(),g())return;let C=!y.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",C?"false":"true"),y.toggle()}),p.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),p.click())}),{element:p,setLabel:b=>{u.textContent=b,p.setAttribute("aria-label",b)},open:()=>{p.setAttribute("aria-expanded","true"),y.show()},close:()=>{p.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let b=!y.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",b?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),p.remove()}}}var di=be(()=>{"use strict";Ye();Yt();dh()});var vs,Tu=be(()=>{"use strict";Ye();vs=(t,e,n)=>{let o=n;for(let r of e){let s=v("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o}});var JA,kh,Wu,Bu=be(()=>{"use strict";JA=()=>{},kh=t=>{JA=t.webMcpToolTitle},Wu=t=>JA(t)});var Po,pi,ui,ZA,eM,tM,Lh,Ph,Ih=be(()=>{"use strict";Ye();ri();Bu();Po=require("lucide");ro();na();pi=new Map,ui=t=>{let n=(t.startsWith(Ir)?t.slice(Ir.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},ZA=t=>t?.approval!==!1?t?.approval:void 0,eM=(t,e)=>{let n=ZA(e)?.detailsDisplay??"collapsed";return pi.get(t)??n==="expanded"},tM=(t,e,n)=>{let o=ZA(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=Qe(e?Po.ChevronUp:Po.ChevronDown,14,"currentColor",2);a&&s.appendChild(a)}},Lh=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=eM(t,n);tM(o,s,n),r.style.display=s?"":"none"},Ph=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=v("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let d=n.status==="denied"?Po.ShieldX:n.status==="timeout"?Po.ShieldAlert:Po.ShieldCheck,p=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",u=Qe(d,20,p,2);u&&l.appendChild(u);let m=v("div","persona-flex-1 persona-min-w-0"),y=v("div","persona-flex persona-items-center persona-gap-2"),g=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",y.appendChild(g),!r){let B=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");B.setAttribute("data-approval-status",n.status),n.status==="approved"?(B.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",B.style.color="var(--persona-palette-colors-success-700, #15803d)",B.textContent="Approved"):n.status==="denied"?(B.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",B.style.color="var(--persona-palette-colors-error-700, #b91c1c)",B.textContent="Denied"):n.status==="timeout"&&(B.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",B.style.color="var(--persona-palette-colors-warning-700, #b45309)",B.textContent="Timeout"),y.appendChild(B)}m.appendChild(y);let C=n.toolType==="webmcp"||n.toolName.startsWith(Ir)?Wu(n.toolName):void 0,S=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),T=!n.toolName,A=S||(T?n.description:`The assistant wants to use \u201C${C??ui(n.toolName)}\u201D.`),I=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(I.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(I.style.color=o.descriptionColor),I.textContent=A,m.appendChild(I),n.reason){let B=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");B.setAttribute("data-approval-reason","true"),o?.reasonColor?B.style.color=o.reasonColor:o?.descriptionColor&&(B.style.color=o.descriptionColor);let W=v("span","persona-font-medium");W.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,B.appendChild(W),B.appendChild(document.createTextNode(n.reason)),m.appendChild(B)}let M=o?.detailsDisplay??"collapsed",O=!!n.description&&!T,k=O||!!n.parameters;if(M!=="hidden"&&k){let B=eM(t.id,e),W=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");W.type="button",W.setAttribute("data-expand-header","true"),W.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(W.style.color=o.descriptionColor);let V=v("span");V.setAttribute("data-approval-details-label","true");let R=v("span","persona-inline-flex persona-items-center");R.setAttribute("data-approval-details-chevron","true"),W.append(V,R),tM(W,B,e),m.appendChild(W);let w=v("div");if(w.setAttribute("data-approval-details","true"),w.style.display=B?"":"none",O){let E=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(E.style.color=o.descriptionColor),E.textContent=n.description,w.appendChild(E)}if(n.parameters){let E=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(E.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(E.style.color=o.parameterTextColor),E.style.fontSize="0.75rem",E.style.lineHeight="1rem",E.textContent=us(n.parameters),w.appendChild(E)}m.appendChild(w)}if(r){let B=v("div","persona-flex persona-gap-2 persona-mt-2");B.setAttribute("data-approval-buttons","true");let W=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");W.type="button",W.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",W.style.color=o?.approveButtonTextColor??"#ffffff",W.setAttribute("data-approval-action","approve");let V=Qe(Po.ShieldCheck,14,o?.approveButtonTextColor??"#ffffff",2);V&&(V.style.marginRight="4px",W.appendChild(V));let R=document.createTextNode(o?.approveLabel??"Approve");W.appendChild(R);let w=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");w.type="button",w.style.backgroundColor=o?.denyButtonColor??"transparent",w.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",w.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,w.setAttribute("data-approval-action","deny");let E=Qe(Po.ShieldX,14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);E&&(E.style.marginRight="4px",w.appendChild(E));let H=document.createTextNode(o?.denyLabel??"Deny");w.appendChild(H),B.append(W,w),m.appendChild(B)}return a.append(l,m),s.appendChild(a),s}});var fi,mR,nM,mi,fR,gR,Hh,hR,yR,bR,Rh,oM=be(()=>{"use strict";Ye();Bu();fi=require("lucide");ro();ri();na();ya();Ih();mR=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),nM=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},mi=(t,e)=>{nM(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},fR=t=>t?.approval!==!1?t?.approval:void 0,gR=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return pi.get(t)??n==="expanded"},Hh=t=>{let e=v("span","persona-approval-kbd");return e.textContent=t,e},hR=(t,e)=>{let n=v("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(Ir)?Wu(t.toolName):void 0,s=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=r??ui(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),l){n.append(" from ");let p=document.createElement("strong");p.textContent=l,n.appendChild(p)}return n},yR=t=>{let e=v("div","persona-approval-resolved"),n=Qe(fi.Ban,15,"currentColor",2);n&&e.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=t.toolName?ui(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},bR=(t,e,n,o,r,s,a)=>{let l=v("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${e.id}`,l.setAttribute("data-message-id",e.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let d=o?.detailsDisplay??"collapsed",p=!!n.description&&d!=="hidden",u=n.parameters!=null&&d!=="hidden",m=p||u,y=m&&gR(e.id,o),g=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",C=v("button","persona-approval-head");C.type="button",m?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",y?"true":"false"),C.setAttribute("aria-label",y?b:g)):C.setAttribute("data-static","true");let S=v("span","persona-approval-logo"),T=Qe(fi.ShieldCheck,16,"currentColor",2);T&&S.appendChild(T),C.appendChild(S);let A=hR(n,o);if(m){let W=v("span","persona-approval-toggle");W.setAttribute("aria-hidden","true");let V=Qe(fi.ChevronDown,14,"currentColor",2);V&&W.appendChild(V),A.append(" "),A.appendChild(W)}C.appendChild(A),l.appendChild(C);let I=v("div","persona-approval-body");if(m){let W=v("div","persona-approval-details");if(W.setAttribute("data-role","params"),W.hidden=!y,p){let V=v("p","persona-approval-desc");o?.descriptionColor&&(V.style.color=o.descriptionColor),V.textContent=n.description,W.appendChild(V)}if(u){let V=v("pre","persona-approval-params");o?.parameterBackgroundColor&&(V.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(V.style.color=o.parameterTextColor),V.textContent=us(n.parameters),W.appendChild(V)}I.appendChild(W)}if(n.reason){let W=v("p","persona-approval-reason");o?.reasonColor?W.style.color=o.reasonColor:o?.descriptionColor&&(W.style.color=o.descriptionColor);let V=v("span","persona-approval-reason-label");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,W.append(V,document.createTextNode(n.reason)),I.appendChild(W)}let M=v("div","persona-approval-actions"),O=null,k=W=>{o?.approveButtonColor&&(W.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(W.style.color=o.approveButtonTextColor)},B=v("button","persona-approval-deny");if(B.type="button",B.setAttribute("data-action","deny"),o?.denyButtonColor&&(B.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(B.style.color=o.denyButtonTextColor),B.append(o?.denyLabel??"Deny"),a){let W=v("div","persona-approval-split"),V=v("button","persona-approval-primary");V.type="button",V.setAttribute("data-action","always"),k(V),V.append(o?.approveLabel??"Always allow",Hh("\u23CE"));let R=v("button","persona-approval-caret");R.type="button",R.setAttribute("data-action","toggle-menu"),R.setAttribute("aria-label","More options"),k(R);let w=Qe(fi.ChevronDown,15,"currentColor",2);w&&R.appendChild(w),W.append(V,R),M.append(W,B),B.append(Hh("Esc"));let E=v("div","persona-approval-menu"),H=v("button","persona-approval-menu-item");H.type="button",H.append("Allow once",Hh("\u2318\u23CE")),E.appendChild(H),O=gs({anchor:W,content:E,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,O),H.addEventListener("click",()=>{mi(t,e.id),r()})}else{let W=v("button","persona-approval-primary persona-approval-primary--solo");W.type="button",W.setAttribute("data-action","allow"),k(W),W.append(o?.approveLabel??"Allow"),M.append(W,B)}return I.appendChild(M),l.appendChild(I),l.addEventListener("click",W=>{let V=W.target instanceof Element?W.target.closest("[data-action]"):null;if(!V)return;let R=V.getAttribute("data-action");if(R==="toggle-params"){let w=l.querySelector('[data-role="params"]');if(w){let E=w.hidden;w.hidden=!E,C.setAttribute("aria-expanded",E?"true":"false"),C.setAttribute("aria-label",E?b:g),pi.set(e.id,E)}return}if(R==="toggle-menu"){O?.toggle();return}if(R==="always"){mi(t,e.id),r({remember:!0});return}if(R==="allow"){mi(t,e.id),r();return}if(R==="deny"){mi(t,e.id),s();return}}),l},Rh=()=>{let t=mR();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let l=o?.approval;if(!l)return null;let d=fR(a);if(l.status!=="pending"){if(mi(t,o.id),l.status==="approved"){let m=document.createElement("div");return m.style.display="none",m}return yR(l)}nM(t,o.id);let p=d?.enableAlwaysAllow===!0,u=bR(t,o,l,d,r,s,p);if(p){t.pendingOrder.includes(o.id)||t.pendingOrder.push(o.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let m=y=>{yx(y)||o.id===t.latestPendingApprovalId&&(y.key!=="Escape"&&y.key!=="Enter"||(y.preventDefault(),y.stopImmediatePropagation(),mi(t,o.id),y.key==="Escape"?s():y.metaKey||y.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,m),document.addEventListener("keydown",m)}return u}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])mi(t,o);t.latestPendingApprovalId=null}}}});var rM=be(()=>{"use strict";Ih();oM();Bu()});var sM={};Vn(sM,{approvalDetailsExpansionState:()=>pi,createApprovalBubble:()=>Ph,createBuiltInApprovalPlugin:()=>Rh,humanizeToolName:()=>ui,initApprovalUi:()=>kh,updateApprovalDetailsUI:()=>Lh});var iM=be(()=>{"use strict";rM()});function ka(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}function cM(t,e){if(e[t])return e[t];for(let n of Object.keys(e))if(n.endsWith("_")&&t.startsWith(n))return e[n]}function AR(t,e){return(e&&cM(t,e))??cM(t,Or)??wR}function MR(t){return/^#[0-9a-fA-F]{6}$/.test(t)?`${t}50`:`color-mix(in srgb, ${t} 31%, transparent)`}function TR(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function ER(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),r=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function kR(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let o of e){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function LR(t){return navigator.clipboard?.writeText?navigator.clipboard.writeText(t):new Promise(e=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),e()})}function PR(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function IR(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function HR(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function RR(t,e,n){let o,r;try{r=JSON.parse(t.payload),o=JSON.stringify(r,null,2)}catch{r=t.payload,o=t.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,l.appendChild(d),l}}function Wh(t,e,n,o,r,s,a,l){let d=r.has(t.id),p=v("div","persona-border-b persona-border-persona-divider persona-text-xs");ka(p,o.classNames?.eventRow);let u=a.find(y=>y.renderEventStreamRow);if(u?.renderEventStreamRow&&l){let y=u.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>s(t.id)});if(y)return p.appendChild(y),p}return p.appendChild(m()),p;function m(){let y=v("div",""),g=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");g.setAttribute("data-event-id",t.id);let b=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=Qe(d?En.ChevronDown:En.ChevronRight,"14px","currentColor",2);C&&b.appendChild(C);let S=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),T=o.timestampFormat??"relative";S.textContent=T==="relative"?TR(t.timestamp,n):ER(t.timestamp);let A=null;o.showSequenceNumbers!==!1&&(A=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),A.textContent=String(e+1));let I=AR(t.type,o.badgeColors),M=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");M.style.backgroundColor=I.bg,M.style.color=I.text,M.style.borderColor=MR(I.text),M.textContent=t.type;let O=o.descriptionFields??xR,k=kR(t.payload,O),B=null;k&&(B=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),B.textContent=k);let W=v("div","persona-flex-1 persona-min-w-0"),V=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),R=Qe(En.Clipboard,"12px","currentColor",1.5);return R&&V.appendChild(R),V.addEventListener("click",async w=>{w.stopPropagation(),await LR(PR(t)),V.innerHTML="";let E=Qe(En.Check,"12px","currentColor",1.5);E&&V.appendChild(E),setTimeout(()=>{V.innerHTML="";let H=Qe(En.Clipboard,"12px","currentColor",1.5);H&&V.appendChild(H)},1500)}),g.appendChild(b),g.appendChild(S),A&&g.appendChild(A),g.appendChild(M),B&&g.appendChild(B),g.appendChild(W),g.appendChild(V),y.appendChild(g),d&&y.appendChild(RR(t,a,l)),y}}function Bh(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=t,l=t.renderIconByName??(()=>null),d=r?.features?.scrollToBottom,p=d?.enabled!==!1,u=d?.iconName??"arrow-down",m=d?.label??"",y=r?.features?.eventStream??{},g=s.find(C=>C.renderEventStreamView);if(g?.renderEventStreamView&&r){let C=g.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>b().element,onClose:o});if(C)return{element:C,update:()=>{},destroy:()=>{}}}return b();function b(){let C=y.classNames,S=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ka(S,C?.panel);let T=[],A="",I="",M=null,O=[],k={},B=0,W=pu(),V=0,R=0,w=!1,E=null,H=!1,D=0,G=new Set,z=new Map,K="",Y="",re=null,oe,se,ce,we,ge=null,N=null,ye=null;function ke(){let ve=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Se=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(ka(Se,C?.headerBar),a){N=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),N.style.cursor="help",ge=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ge.textContent="-- tok/s",ye=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ye.style.display="none",ye.style.pointerEvents="none";let Rn=N,tn=ye,it=()=>{if(!tn.textContent)return;let Kt=Rn.getBoundingClientRect(),Ze=ve.getBoundingClientRect();tn.style.left=`${Kt.left-Ze.left}px`,tn.style.top=`${Kt.bottom-Ze.top+4}px`,tn.style.display="block"},_e=()=>{tn.style.display="none"};N.addEventListener("mouseenter",it),N.addEventListener("mouseleave",_e),N.appendChild(ge)}let Ke=v("div","persona-flex-1");oe=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let ut=v("option","");ut.value="",ut.textContent="All events (0)",oe.appendChild(ut),se=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),se.type="button",se.title="Copy All";let Cn=Qe(En.ClipboardCopy,"12px","currentColor",1.5);Cn&&se.appendChild(Cn);let wn=v("span","persona-event-copy-all persona-text-xs");wn.textContent="Copy All",se.appendChild(wn),N&&Se.appendChild(N),Se.appendChild(Ke),Se.appendChild(oe),Se.appendChild(se);let Wt=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ka(Wt,C?.searchBar);let St=Qe(En.Search,"14px","var(--persona-muted, #9ca3af)",1.5),Et=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");St&&Et.appendChild(St),ce=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),ka(ce,C?.searchInput),ce.type="text",ce.placeholder="Search event payloads...",we=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),we.type="button",we.style.display="none";let sn=Qe(En.X,"12px","currentColor",2);return sn&&we.appendChild(sn),Wt.appendChild(Et),Wt.appendChild(ce),Wt.appendChild(we),ve.appendChild(Se),ve.appendChild(Wt),ye&&ve.appendChild(ye),ve}let nt,Ee=s.find(ve=>ve.renderEventStreamToolbar);Ee?.renderEventStreamToolbar&&r?nt=Ee.renderEventStreamToolbar({config:r,defaultRenderer:()=>ke(),eventCount:e.getSize(),filteredCount:0,onFilterChange:Se=>{A=Se,Q(),Te()},onSearchChange:Se=>{I=Se,Q(),Te()}})??ke():nt=ke();let Ne=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Ne.style.display="none";function Pe(){if(!a||!ge||!N)return;let ve=a(),Se=IR(ve);ge.textContent=Se;let Ke=HR(ve);ye&&(ye.textContent=Ke,Ke||(ye.style.display="none")),N.setAttribute("aria-label",Ke?`Throughput: ${Se}, ${Ke}`:`Throughput: ${Se}`)}let dt=v("div","persona-flex-1 persona-min-h-0 persona-relative"),Xe=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Xe.style.height="100%";let xt=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ka(xt,C?.scrollIndicator),xt.style.display="none",xt.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Ge=l(u,"14px","currentColor",2);Ge&&xt.appendChild(Ge);let yt=v("span","");yt.textContent=m,xt.appendChild(yt);let X=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");X.style.display="none",dt.appendChild(Xe),dt.appendChild(X),dt.appendChild(xt),S.setAttribute("tabindex","0"),S.appendChild(nt),S.appendChild(Ne),S.appendChild(dt);function P(){let ve=e.getAll(),Se={};for(let Wt of ve)Se[Wt.type]=(Se[Wt.type]||0)+1;let Ke=Object.keys(Se).sort(),ut=Ke.length!==O.length||!Ke.every((Wt,St)=>Wt===O[St]),vn=!ut&&Ke.some(Wt=>Se[Wt]!==k[Wt]),Cn=ve.length!==Object.values(k).reduce((Wt,St)=>Wt+St,0);if(!ut&&!vn&&!Cn||(O=Ke,k=Se,!oe))return;let wn=oe.value;if(oe.options[0].textContent=`All events (${ve.length})`,ut){for(;oe.options.length>1;)oe.remove(1);for(let Wt of Ke){let St=v("option","");St.value=Wt,St.textContent=`${Wt} (${Se[Wt]||0})`,oe.appendChild(St)}wn&&Ke.includes(wn)?oe.value=wn:wn&&(oe.value="",A="")}else for(let Wt=1;Wt<oe.options.length;Wt++){let St=oe.options[Wt];St.textContent=`${St.value} (${Se[St.value]||0})`}}function j(){let ve=e.getAll();if(A&&(ve=ve.filter(Se=>Se.type===A)),I){let Se=I.toLowerCase();ve=ve.filter(Ke=>Ke.type.toLowerCase().includes(Se)||Ke.payload.toLowerCase().includes(Se))}return ve}function J(){return A!==""||I!==""}function Q(){B=0,V=0,W.resume(),xt.style.display="none"}function de(ve){G.has(ve)?G.delete(ve):G.add(ve),re=ve;let Se=Xe.scrollTop,Ke=W.isFollowing();H=!0,W.pause(),Te(),Xe.scrollTop=Se,Ke&&W.resume(),H=!1}function Me(){return Wr(Xe,50)}function Te(){R=Date.now(),w=!1,Pe(),P();let ve=e.getEvictedCount();ve>0?(Ne.textContent=`${ve.toLocaleString()} older events truncated`,Ne.style.display=""):Ne.style.display="none",T=j();let Se=T.length,Ke=e.getSize()>0;Se===0&&Ke&&J()?(X.textContent=I?`No events matching '${I}'`:"No events matching filter",X.style.display="",Xe.style.display="none"):(X.style.display="none",Xe.style.display=""),se&&(se.title=J()?`Copy Filtered (${Se})`:"Copy All"),p&&!W.isFollowing()&&Se>B&&(V+=Se-B,yt.textContent=m?`${m}${V>0?` (${V})`:""}`:"",xt.style.display=""),B=Se;let ut=e.getAll(),vn=ut.length>0?ut[0].timestamp:0,Cn=new Set(T.map(St=>St.id));for(let St of G)Cn.has(St)||G.delete(St);let wn=A!==K||I!==Y,Wt=z.size===0&&T.length>0;if(wn||Wt||T.length===0){Xe.innerHTML="",z.clear();let St=document.createDocumentFragment();for(let Et=0;Et<T.length;Et++){let sn=Wh(T[Et],Et,vn,y,G,de,s,r);z.set(T[Et].id,sn),St.appendChild(sn)}Xe.appendChild(St),K=A,Y=I,re=null}else{if(re!==null){let Et=z.get(re);if(Et&&Et.parentNode===Xe){let sn=T.findIndex(Rn=>Rn.id===re);if(sn>=0){let Rn=Wh(T[sn],sn,vn,y,G,de,s,r);Xe.insertBefore(Rn,Et),Et.remove(),z.set(re,Rn)}}re=null}let St=new Set(T.map(Et=>Et.id));for(let[Et,sn]of z)St.has(Et)||(sn.remove(),z.delete(Et));for(let Et=0;Et<T.length;Et++){let sn=T[Et];if(!z.has(sn.id)){let Rn=Wh(sn,Et,vn,y,G,de,s,r);z.set(sn.id,Rn),Xe.appendChild(Rn)}}}W.isFollowing()&&(Xe.scrollTop=Xe.scrollHeight)}function Fe(){if(Date.now()-R>=SR){E!==null&&(cancelAnimationFrame(E),E=null),Te();return}w||(w=!0,E=requestAnimationFrame(()=>{E=null,Te()}))}let je=(ve,Se)=>{if(!se)return;se.innerHTML="";let Ke=Qe(ve,"12px","currentColor",1.5);Ke&&se.appendChild(Ke);let ut=v("span","persona-text-xs");ut.textContent="Copy All",se.appendChild(ut),setTimeout(()=>{se.innerHTML="";let vn=Qe(En.ClipboardCopy,"12px","currentColor",1.5);vn&&se.appendChild(vn);let Cn=v("span","persona-text-xs");Cn.textContent="Copy All",se.appendChild(Cn),se.disabled=!1},Se)},lt=async()=>{if(se){se.disabled=!0;try{let ve;J()?ve=T:n?(ve=await n(),ve.length===0&&(ve=e.getAll())):ve=e.getAll();let Se=ve.map(Ke=>{try{return JSON.parse(Ke.payload)}catch{return Ke.payload}});await navigator.clipboard.writeText(JSON.stringify(Se,null,2)),je(En.Check,1500)}catch{je(En.X,1500)}}},ot=()=>{oe&&(A=oe.value,Q(),Te())},Je=()=>{!ce||!we||(we.style.display=ce.value?"":"none",M&&clearTimeout(M),M=setTimeout(()=>{I=ce.value,Q(),Te()},150))},mt=()=>{!ce||!we||(ce.value="",I="",we.style.display="none",M&&clearTimeout(M),Q(),Te())},Tt=()=>{if(H)return;let ve=Xe.scrollTop,{action:Se,nextLastScrollTop:Ke}=uu({following:W.isFollowing(),currentScrollTop:ve,lastScrollTop:D,nearBottom:Me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});D=Ke,Se==="resume"?(W.resume(),V=0,xt.style.display="none"):Se==="pause"&&(W.pause(),p&&(yt.textContent=m,xt.style.display=""))},ee=ve=>{let Se=mu({following:W.isFollowing(),deltaY:ve.deltaY,nearBottom:Me(),resumeWhenNearBottom:!0});Se==="pause"?(W.pause(),p&&(yt.textContent=m,xt.style.display="")):Se==="resume"&&(W.resume(),V=0,xt.style.display="none")},Oe=()=>{p&&(Xe.scrollTop=Xe.scrollHeight,W.resume(),V=0,xt.style.display="none")},$e=ve=>{let Se=ve.target;if(!Se||Se.closest("button"))return;let Ke=Se.closest("[data-event-id]");if(!Ke)return;let ut=Ke.getAttribute("data-event-id");ut&&de(ut)},pt=ve=>{if((ve.metaKey||ve.ctrlKey)&&ve.key==="f"){ve.preventDefault(),ce?.focus(),ce?.select();return}ve.key==="Escape"&&(ce&&document.activeElement===ce?(mt(),ce.blur(),S.focus()):o&&o())};se&&se.addEventListener("click",lt),oe&&oe.addEventListener("change",ot),ce&&ce.addEventListener("input",Je),we&&we.addEventListener("click",mt),Xe.addEventListener("scroll",Tt),Xe.addEventListener("wheel",ee,{passive:!0}),Xe.addEventListener("click",$e),xt.addEventListener("click",Oe),S.addEventListener("keydown",pt);function _t(){M&&clearTimeout(M),E!==null&&(cancelAnimationFrame(E),E=null),w=!1,z.clear(),se&&se.removeEventListener("click",lt),oe&&oe.removeEventListener("change",ot),ce&&ce.removeEventListener("input",Je),we&&we.removeEventListener("click",mt),Xe.removeEventListener("scroll",Tt),Xe.removeEventListener("wheel",ee),Xe.removeEventListener("click",$e),xt.removeEventListener("click",Oe),S.removeEventListener("keydown",pt)}return{element:S,update:Fe,destroy:_t}}}var En,Or,wR,xR,SR,dM=be(()=>{"use strict";Ye();En=require("lucide");ro();Jg();Or={flow_:{bg:"var(--persona-event-badge-flow-bg, #dcfce7)",text:"var(--persona-event-badge-flow-fg, #15803d)"},step_:{bg:"var(--persona-event-badge-step-bg, #f5f5f5)",text:"var(--persona-event-badge-step-fg, #0a0a0a)"},reasoning_:{bg:"var(--persona-event-badge-reasoning-bg, #fef9c3)",text:"var(--persona-event-badge-reasoning-fg, #a16207)"},tool_:{bg:"var(--persona-event-badge-tool-bg, #f3e8ff)",text:"var(--persona-event-badge-tool-fg, #6b21a8)"},agent_:{bg:"var(--persona-event-badge-agent-bg, #ccfbf1)",text:"var(--persona-event-badge-agent-fg, #115e59)"},error:{bg:"var(--persona-event-badge-error-bg, #fee2e2)",text:"var(--persona-event-badge-error-fg, #b91c1c)"}};Or.execution_error=Or.error;Or.execution_=Or.flow_;Or.turn_=Or.agent_;Or.text_=Or.agent_;wR={bg:"var(--persona-event-badge-default-bg, #f3f4f6)",text:"var(--persona-event-badge-default-fg, #4b5563)"},xR=["flowName","stepName","reasoningText","text","name","tool","toolName"],SR=100});var bc,pM=be(()=>{"use strict";bc=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),this.store?.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}}});var vc,uM=be(()=>{"use strict";vc=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}}});function Oh(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function Ou(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function OR(t,e){return typeof e.type=="string"?e.type:t}function fM(t){let e=mM(t,"tokens")??mM(t,"totalTokens");return e?hM(e.output):void 0}function DR(t){return hM(t.durationMs)}function _R(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var WR,BR,gM,hM,mM,Cc,yM=be(()=>{"use strict";WR=new Set(["step_start","turn_start"]),BR=new Set(["step_complete","turn_complete"]),gM=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),hM=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,mM=(t,e)=>{let n=t[e];return gM(n)?n:void 0};Cc=class{constructor(e=_R){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Ou(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){if(!gM(n)){e==="execution_error"&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=OR(e,n),r=this.now();if(o==="execution_start"){this.startRun(r);return}if(WR.has(o)){this.run||this.startRun(r);return}if(o==="text_delta"){let s=typeof n.delta=="string"?n.delta:"";if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+Oh(a.visibleCharCount),d=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ou(l,d),outputTokens:l,durationMs:d,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(BR.has(o)){if(!this.run)return;let s=this.run,a=fM(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,d=s.exactOutputTokens+Oh(s.visibleCharCount),p=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Ou(d,p),outputTokens:d,durationMs:p,source:l?"usage":"estimate"};return}if(o==="execution_complete"){if(!this.run)return;let s=this.run,a=fM(n),l=a??s.exactOutputTokens+Oh(s.visibleCharCount),d=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Ou(l,p),outputTokens:l,durationMs:p,source:d},this.run=null;return}if(o==="execution_error"||o==="error"&&n.recoverable===!1){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:DR(n)??o-e.startedAt}}});var bM=be(()=>{"use strict";dM();pM();uM();yM()});var vM={};Vn(vM,{EventStreamBuffer:()=>bc,EventStreamStore:()=>vc,ThroughputTracker:()=>Cc,createEventStreamView:()=>Bh});var CM=be(()=>{"use strict";bM()});var _h,zo,wc=be(()=>{"use strict";_h=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},zo=new _h});function dr(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function wM(t){let e=dr(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function Du(t){if(typeof t!="string")return"";let e=t.indexOf(`
237
+ `.trim(),Ac="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",MH=10,TH=120,Gh=120,EH=.4,kH=50,PH=t=>{if(!t)return Gh;let n=(t.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):Gh},bM=t=>{let e=t.closest(".persona-stream-glyph-cycle"),n=PH(e);return TH*n/Gh},Yh=t=>{let e=Ac[Math.floor(Math.random()*Ac.length)];return t&&e===t&&(e=Ac[(Ac.indexOf(e)+1)%Ac.length]),e},LH=t=>{let e=t.closest(".persona-stream-glyph-cycle");if(!e)return;let n=e.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===t){o=!0;continue}o&&Math.random()<EH&&(r.textContent=Yh())}},pM=new WeakMap,uM=25,mM=.5,IH=6,fM=.25,gM=new WeakMap,hM=new WeakMap,RH=(t,e)=>{if(!t)return uM*mM;let n=gM.get(t);gM.set(t,e);let o=hM.get(t)??uM;if(n!==void 0){let r=e-n;r>1&&(o=o*(1-fM)+r*fM,hM.set(t,o))}return Math.max(IH,o*mM)},Fa=new Map,HH=t=>t.closest("[data-message-id]")?.dataset.messageId??null,WH=t=>{t&&Fa.set(t,(Fa.get(t)??0)+1)},BH=t=>{if(!t)return;let e=Fa.get(t)??0;e<=1?Fa.delete(t):Fa.set(t,e-1)},vM=t=>{if(t.dataset.glyphCycleScheduled==="true")return;let e=t.textContent??"";if(!e||/\s/.test(e))return;t.dataset.glyphCycleScheduled="true",t.dataset.glyphCycleFinal=e,t.setAttribute("data-preserve-runtime","stream-glyph-cycle"),t.textContent=Yh();let n=HH(t);n&&(t.dataset.glyphCycleMessageId=n),WH(n);let o=t.closest(".persona-stream-glyph-cycle"),r=Date.now(),s=RH(o,r),a=bM(t),l=MH*a,c=r+l;if(o){let p=pM.get(o);p!==void 0&&(c=Math.max(c,p)),pM.set(o,c+s)}DH(t,e,c)},DH=(t,e,n)=>{if(t.dataset.glyphCycleStarted==="true")return;t.dataset.glyphCycleStarted="true";let o=bM(t),r=t.textContent??void 0,s=()=>{if(!t.isConnected)return;if(Date.now()>=n){t.textContent=e,t.removeAttribute("data-preserve-runtime"),delete t.dataset.glyphCycleStarted,delete t.dataset.glyphCycleFinal,BH(t.dataset.glyphCycleMessageId??null),delete t.dataset.glyphCycleMessageId;return}let a=Yh(r);t.textContent=a,r=a,LH(t),setTimeout(s,o)};setTimeout(s,o)},yM=t=>{let e=t.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(e)for(let n of Array.from(e))vM(n)},OH=t=>t.nodeType===1,CM={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:AH,bufferContent(t){if(t.length<kH)return"";let e=0,n=-1,o=0;for(;o<t.length;){if(t[o]==="*"&&t[o+1]==="*"){e+=1,o+=2;continue}/\s/.test(t[o])&&e%2===0&&(n=o),o+=1}return n<0?"":t.slice(0,n)},isAnimating(t){return(Fa.get(t.id)??0)>0},onAttach(t){yM(t);let e=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))OH(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?vM(r):yM(r))});return e.observe(t,{childList:!0,subtree:!0}),()=>e.disconnect()}};Ei(CM);wM=CM});var SM={};$n(SM,{glyphCycle:()=>wM,wipe:()=>cM});var AM=be(()=>{"use strict";dM();xM()});function Lc(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=t,l=v("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(Ba)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let b of e){if(b.dividerBefore){let E=document.createElement("hr");l.appendChild(E)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",b.id),b.destructive&&C.setAttribute("data-destructive",""),b.icon){let E=ke(b.icon,16,"currentColor",1.5);E&&C.appendChild(E)}let M=document.createElement("span");M.textContent=b.label,C.appendChild(M),C.addEventListener("click",E=>{E.stopPropagation(),m(),n(b.id)}),l.appendChild(C)}let c=null;function p(){if(!s)return;let b=o.getBoundingClientRect();l.style.top=`${b.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-b.right}px`,l.style.left="auto"):(l.style.left=`${b.left}px`,l.style.right="auto")}function u(){let b=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),b&&a?.(!0),requestAnimationFrame(()=>{let C=M=>{!l.contains(M.target)&&!o.contains(M.target)&&m()};document.addEventListener("click",C,!0),c=()=>document.removeEventListener("click",C,!0)})}function m(){let b=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),c?.(),c=null,b&&a?.(!1)}function g(){l.classList.contains("persona-hidden")?u():m()}function h(){m(),l.remove()}return s&&s.appendChild(l),{element:l,show:u,hide:m,toggle:g,destroy:h}}var ny=be(()=>{"use strict";je();Zt();ks()});function vn(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:c}=t,p=v("button",Gt(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=ke(e,o??16,"currentColor",r??2);if(u&&p.appendChild(u),l&&p.addEventListener("click",l),c)for(let[m,g]of Object.entries(c))p.setAttribute(m,g);return p}function Li(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:c}=t,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let u=v("button",p);if(u.type="button",u.setAttribute("aria-label",n),e){let g=ke(e,s??14,"currentColor",2);g&&u.appendChild(g)}let m=v("span");if(m.textContent=n,u.appendChild(m),l&&u.addEventListener("click",l),c)for(let[g,h]of Object.entries(c))u.setAttribute(g,h);return u}function Yu(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=v("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function c(){for(let u of l)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of e){let m;u.icon?m=vn({icon:u.icon,label:u.label,className:u.className,onClick:()=>{a=u.id,c(),o(u.id)}}):(m=v("button","persona-icon-btn"+(u.className?" "+u.className:"")),m.type="button",m.setAttribute("aria-label",u.label),m.title=u.label,m.textContent=u.label,m.addEventListener("click",()=>{a=u.id,c(),o(u.id)})),m.setAttribute("aria-pressed",u.id===a?"true":"false"),l.push({id:u.id,btn:m}),s.appendChild(m)}function p(u){a=u,c()}return{element:s,setSelected:p}}function PM(t){let{label:e,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:a,onPrimary:l,position:c="bottom-left",portal:p,chevronLabel:u="More options",chevronIconSize:m,className:g,primaryClassName:h,chevronClassName:b}=t,C=v("div","persona-split-btn"+(g?" "+g:"")),M={label:e,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},E=r&&n?vn({...M,icon:n,size:o??14}):Li({...M,icon:n,iconSize:o??14}),T=vn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(b?" "+b:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});C.append(E,T);let H=null,A=()=>{if(H)return H;let D=(typeof p=="function"?p():p)??void 0;return H=Lc({items:s,onSelect:a,anchor:C,position:c,portal:D,onOpenChange:W=>{T.setAttribute("aria-expanded",W?"true":"false")}}),D||C.appendChild(H.element),H};return C.isConnected?A():requestAnimationFrame(()=>{H||A()}),T.addEventListener("click",D=>{D.stopPropagation(),A().toggle()}),{element:C,primaryButton:E,chevronButton:T,openMenu:()=>A().show(),closeMenu:()=>H?.hide(),toggleMenu:()=>A().toggle(),destroy:()=>{H?.destroy(),C.remove()}}}function LM(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:c}=t,p=v("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",e);let u=v("span","persona-combo-btn-label");u.textContent=e,p.appendChild(u);let m=ke(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",p.appendChild(m)),c&&(p.style.borderRadius=c.borderRadius??"10px",p.style.padding=c.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=c.background??"",p.style.borderColor=c.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let g=Lc({items:o,onSelect:b=>{p.setAttribute("aria-expanded","false"),r(b)},anchor:p,position:s,portal:a});a||p.appendChild(g.element);let h=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",b=>{if(b.stopPropagation(),h())return;let C=!g.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",C?"false":"true"),g.toggle()}),p.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),p.click())}),{element:p,setLabel:b=>{u.textContent=b,p.setAttribute("aria-label",b)},open:()=>{p.setAttribute("aria-expanded","true"),g.show()},close:()=>{p.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let b=!g.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",b?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),p.remove()}}}var Ii=be(()=>{"use strict";je();Zt();ny()});var Hs,rm=be(()=>{"use strict";je();Hs=(t,e,n)=>{let o=n;for(let r of e){let s=v("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o}});var aT,xy,sm,im=be(()=>{"use strict";aT=()=>{},xy=t=>{aT=t.webMcpToolTitle},sm=t=>aT(t)});var Oo,Hi,lT,cT,dT,Sy,Ay,My=be(()=>{"use strict";je();Ts();im();Oo=require("lucide");zn();Aa();Hi=t=>{let n=(t.startsWith(zr)?t.slice(zr.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},lT=t=>t?.approval!==!1?t?.approval:void 0,cT=(t,e,n)=>{let o=lT(n)?.detailsDisplay??"collapsed";return e.get(t)??o==="expanded"},dT=(t,e,n)=>{let o=lT(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=Ge(e?Oo.ChevronUp:Oo.ChevronDown,14,"currentColor",2);a&&s.appendChild(a)}},Sy=(t,e,n,o=new Map)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),s=e.querySelector("[data-approval-details]");if(!r||!s)return;let a=cT(t,o,n);dT(r,a,n),s.style.display=a?"":"none"},Ay=(t,e,n=new Map)=>{let o=t.approval,r=e?.approval!==!1?e?.approval:void 0,s=o?.status==="pending",a=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${t.id}`,a.setAttribute("data-message-id",t.id),a.style.backgroundColor=r?.backgroundColor??"var(--persona-approval-bg)",a.style.borderColor=r?.borderColor??"var(--persona-approval-border)",a.style.boxShadow=r?.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow)",!o)return a;let l=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),c=v("div","persona-flex-shrink-0 persona-mt-0.5");c.setAttribute("data-approval-icon","true");let p=o.status==="denied"?Oo.ShieldX:o.status==="timeout"?Oo.ShieldAlert:Oo.ShieldCheck,u=o.status==="approved"?"var(--persona-feedback-success, var(--persona-palette-colors-success-600))":o.status==="denied"?"var(--persona-feedback-error, var(--persona-palette-colors-error-600))":o.status==="timeout"?"var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))":r?.titleColor??"currentColor",m=Ge(p,20,u,2);m&&c.appendChild(m);let g=v("div","persona-flex-1 persona-min-w-0"),h=v("div","persona-flex persona-items-center persona-gap-2"),b=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r?.titleColor&&(b.style.color=r.titleColor),b.textContent=r?.title??"Approval Required",h.appendChild(b),!s){let B=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");B.setAttribute("data-approval-status",o.status),o.status==="approved"?(B.style.backgroundColor="var(--persona-palette-colors-success-100)",B.style.color="var(--persona-palette-colors-success-700)",B.textContent="Approved"):o.status==="denied"?(B.style.backgroundColor="var(--persona-palette-colors-error-100)",B.style.color="var(--persona-palette-colors-error-700)",B.textContent="Denied"):o.status==="timeout"&&(B.style.backgroundColor="var(--persona-palette-colors-warning-100)",B.style.color="var(--persona-palette-colors-warning-700)",B.textContent="Timeout"),h.appendChild(B)}g.appendChild(h);let M=o.toolType==="webmcp"||o.toolName.startsWith(zr)?sm(o.toolName):void 0,E=r?.formatDescription?.({toolName:o.toolName,toolType:o.toolType,description:o.description,parameters:o.parameters,...M?{displayTitle:M}:{},...o.reason?{reason:o.reason}:{}}),T=!o.toolName,H=E||(T?o.description:`The assistant wants to use \u201C${M??Hi(o.toolName)}\u201D.`),A=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(A.setAttribute("data-approval-summary","true"),r?.descriptionColor&&(A.style.color=r.descriptionColor),A.textContent=H,g.appendChild(A),o.reason){let B=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");B.setAttribute("data-approval-reason","true"),r?.reasonColor?B.style.color=r.reasonColor:r?.descriptionColor&&(B.style.color=r.descriptionColor);let O=v("span","persona-font-medium");O.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,B.appendChild(O),B.appendChild(document.createTextNode(o.reason)),g.appendChild(B)}let D=r?.detailsDisplay??"collapsed",W=!!o.description&&!T,U=W||!!o.parameters;if(D!=="hidden"&&U){let B=cT(t.id,n,e),O=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");O.type="button",O.setAttribute("data-expand-header","true"),O.setAttribute("data-bubble-type","approval"),r?.descriptionColor&&(O.style.color=r.descriptionColor);let R=v("span");R.setAttribute("data-approval-details-label","true");let S=v("span","persona-inline-flex persona-items-center");S.setAttribute("data-approval-details-chevron","true"),O.append(R,S),dT(O,B,e),g.appendChild(O);let x=v("div");if(x.setAttribute("data-approval-details","true"),x.style.display=B?"":"none",W){let P=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r?.descriptionColor&&(P.style.color=r.descriptionColor),P.textContent=o.description,x.appendChild(P)}if(o.parameters){let P=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r?.parameterBackgroundColor&&(P.style.backgroundColor=r.parameterBackgroundColor),r?.parameterTextColor&&(P.style.color=r.parameterTextColor),P.style.fontSize="0.75rem",P.style.lineHeight="1rem",P.textContent=mr(o.parameters),x.appendChild(P)}g.appendChild(x)}if(s){let B=v("div","persona-flex persona-gap-2 persona-mt-2");B.setAttribute("data-approval-buttons","true");let O=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");O.type="button",O.style.backgroundColor=r?.approveButtonColor??"var(--persona-approval-approve-bg)",O.style.color=r?.approveButtonTextColor??"var(--persona-button-primary-fg)",O.setAttribute("data-approval-action","approve");let R=Ge(Oo.ShieldCheck,14,r?.approveButtonTextColor??"var(--persona-button-primary-fg)",2);R&&(R.style.marginRight="4px",O.appendChild(R));let S=document.createTextNode(r?.approveLabel??"Approve");O.appendChild(S);let x=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");x.type="button",x.style.backgroundColor=r?.denyButtonColor??"transparent",x.style.color=r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",x.style.border=`1px solid ${r?.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200)"}`,x.setAttribute("data-approval-action","deny");let P=Ge(Oo.ShieldX,14,r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",2);P&&(P.style.marginRight="4px",x.appendChild(P));let L=document.createTextNode(r?.denyLabel??"Deny");x.appendChild(L),B.append(O,x),g.appendChild(B)}return l.append(c,g),a.appendChild(l),a}});var Bi,_W,pT,Wi,NW,FW,Ty,VW,$W,zW,Ey,uT=be(()=>{"use strict";je();im();Bi=require("lucide");zn();Ts();Aa();Oa();My();_W=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),pT=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},Wi=(t,e)=>{pT(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},NW=t=>t?.approval!==!1?t?.approval:void 0,FW=(t,e,n)=>{let o=n?.detailsDisplay??"collapsed";return e.get(t)??o==="expanded"},Ty=t=>{let e=v("span","persona-approval-kbd");return e.textContent=t,e},VW=(t,e)=>{let n=v("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(zr)?sm(t.toolName):void 0,s=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=r??Hi(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let c=document.createElement("strong");if(c.textContent=a,n.appendChild(c),l){n.append(" from ");let p=document.createElement("strong");p.textContent=l,n.appendChild(p)}return n},$W=t=>{let e=v("div","persona-approval-resolved"),n=Ge(Bi.Ban,15,"currentColor",2);n&&e.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=t.toolName?Hi(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},zW=(t,e,n,o,r,s,a,l)=>{let c=v("div","persona-approval-card persona-shadow-sm");c.id=`bubble-${n.id}`,c.setAttribute("data-message-id",n.id),c.setAttribute("data-bubble-type","approval"),r?.backgroundColor&&(c.style.background=r.backgroundColor),r?.borderColor&&(c.style.borderColor=r.borderColor),r?.shadow!==void 0&&(c.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let p=r?.detailsDisplay??"collapsed",u=!!o.description&&p!=="hidden",m=o.parameters!=null&&p!=="hidden",g=u||m,h=g&&FW(n.id,e,r),b=r?.showDetailsLabel??"Show details",C=r?.hideDetailsLabel??"Hide details",M=v("button","persona-approval-head");M.type="button",g?(M.setAttribute("data-action","toggle-params"),M.setAttribute("aria-expanded",h?"true":"false"),M.setAttribute("aria-label",h?C:b)):M.setAttribute("data-static","true");let E=v("span","persona-approval-logo"),T=Ge(Bi.ShieldCheck,16,"currentColor",2);T&&E.appendChild(T),M.appendChild(E);let H=VW(o,r);if(g){let O=v("span","persona-approval-toggle");O.setAttribute("aria-hidden","true");let R=Ge(Bi.ChevronDown,14,"currentColor",2);R&&O.appendChild(R),H.append(" "),H.appendChild(O)}M.appendChild(H),c.appendChild(M);let A=v("div","persona-approval-body");if(g){let O=v("div","persona-approval-details");if(O.setAttribute("data-role","params"),O.hidden=!h,u){let R=v("p","persona-approval-desc");r?.descriptionColor&&(R.style.color=r.descriptionColor),R.textContent=o.description,O.appendChild(R)}if(m){let R=v("pre","persona-approval-params");r?.parameterBackgroundColor&&(R.style.background=r.parameterBackgroundColor),r?.parameterTextColor&&(R.style.color=r.parameterTextColor),R.textContent=mr(o.parameters),O.appendChild(R)}A.appendChild(O)}if(o.reason){let O=v("p","persona-approval-reason");r?.reasonColor?O.style.color=r.reasonColor:r?.descriptionColor&&(O.style.color=r.descriptionColor);let R=v("span","persona-approval-reason-label");R.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,O.append(R,document.createTextNode(o.reason)),A.appendChild(O)}let D=v("div","persona-approval-actions"),W=null,U=O=>{r?.approveButtonColor&&(O.style.background=r.approveButtonColor),r?.approveButtonTextColor&&(O.style.color=r.approveButtonTextColor)},B=v("button","persona-approval-deny");if(B.type="button",B.setAttribute("data-action","deny"),r?.denyButtonColor&&(B.style.background=r.denyButtonColor),r?.denyButtonTextColor&&(B.style.color=r.denyButtonTextColor),B.append(r?.denyLabel??"Deny"),l){let O=v("div","persona-approval-split"),R=v("button","persona-approval-primary");R.type="button",R.setAttribute("data-action","always"),U(R),R.append(r?.approveLabel??"Always allow",Ty("\u23CE"));let S=v("button","persona-approval-caret");S.type="button",S.setAttribute("data-action","toggle-menu"),S.setAttribute("aria-label","More options"),U(S);let x=Ge(Bi.ChevronDown,15,"currentColor",2);x&&S.appendChild(x),O.append(R,S),D.append(O,B),B.append(Ty("Esc"));let P=v("div","persona-approval-menu"),L=v("button","persona-approval-menu-item");L.type="button",L.append("Allow once",Ty("\u2318\u23CE")),P.appendChild(L),W=Ps({anchor:O,content:P,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(n.id,W),L.addEventListener("click",()=>{Wi(t,n.id),s()})}else{let O=v("button","persona-approval-primary persona-approval-primary--solo");O.type="button",O.setAttribute("data-action","allow"),U(O),O.append(r?.approveLabel??"Allow"),D.append(O,B)}return A.appendChild(D),c.appendChild(A),c.addEventListener("click",O=>{let R=O.target instanceof Element?O.target.closest("[data-action]"):null;if(!R)return;let S=R.getAttribute("data-action");if(S==="toggle-params"){let x=c.querySelector('[data-role="params"]');if(x){let P=x.hidden;x.hidden=!P,M.setAttribute("aria-expanded",P?"true":"false"),M.setAttribute("aria-label",P?C:b),e.set(n.id,P)}return}if(S==="toggle-menu"){W?.toggle();return}if(S==="always"){Wi(t,n.id),s({remember:!0});return}if(S==="allow"){Wi(t,n.id),s();return}if(S==="deny"){Wi(t,n.id),a();return}}),c},Ey=(t=new Map)=>{let e=_W();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:s,deny:a,config:l})=>{let c=r?.approval;if(!c)return null;let p=NW(l);if(c.status!=="pending"){if(Wi(e,r.id),c.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return $W(c)}pT(e,r.id);let u=p?.enableAlwaysAllow===!0,m=zW(e,t,r,c,p,s,a,u);if(u){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let g=h=>{AS(h)||r.id===e.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),Wi(e,r.id),h.key==="Escape"?a():h.metaKey||h.ctrlKey?s():s({remember:!0})))};e.keyHandlers.set(r.id,g),document.addEventListener("keydown",g)}return m}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])Wi(e,r);e.latestPendingApprovalId=null}}}});var mT=be(()=>{"use strict";My();uT();im()});var fT={};$n(fT,{createApprovalBubble:()=>Ay,createBuiltInApprovalPlugin:()=>Ey,humanizeToolName:()=>Hi,initApprovalUi:()=>xy,updateApprovalDetailsUI:()=>Sy});var gT=be(()=>{"use strict";mT()});function qa(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}function bT(t,e){if(e[t])return e[t];for(let n of Object.keys(e))if(n.endsWith("_")&&t.startsWith(n))return e[n]}function YW(t,e){return(e&&bT(t,e))??bT(t,Kr)??jW}function QW(t){return/^#[0-9a-fA-F]{6}$/.test(t)?`${t}50`:`color-mix(in srgb, ${t} 31%, transparent)`}function XW(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function JW(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),r=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function ZW(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let o of e){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function eB(t){return navigator.clipboard?.writeText?navigator.clipboard.writeText(t):new Promise(e=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),e()})}function tB(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function nB(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function oB(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function rB(t,e,n){let o,r;try{r=JSON.parse(t.payload),o=JSON.stringify(r,null,2)}catch{r=t.payload,o=t.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),c=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,l.appendChild(c),l}}function ky(t,e,n,o,r,s,a,l){let c=r.has(t.id),p=v("div","persona-border-b persona-border-persona-divider persona-text-xs");qa(p,o.classNames?.eventRow);let u=a.find(g=>g.renderEventStreamRow);if(u?.renderEventStreamRow&&l){let g=u.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>m(),isExpanded:c,onToggleExpand:()=>s(t.id)});if(g)return p.appendChild(g),p}return p.appendChild(m()),p;function m(){let g=v("div",""),h=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");h.setAttribute("data-event-id",t.id);let b=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=Ge(c?Wn.ChevronDown:Wn.ChevronRight,"14px","currentColor",2);C&&b.appendChild(C);let M=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),E=o.timestampFormat??"relative";M.textContent=E==="relative"?XW(t.timestamp,n):JW(t.timestamp);let T=null;o.showSequenceNumbers!==!1&&(T=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),T.textContent=String(e+1));let H=YW(t.type,o.badgeColors),A=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");A.style.backgroundColor=H.bg,A.style.color=H.text,A.style.borderColor=QW(H.text),A.textContent=t.type;let D=o.descriptionFields??KW,W=ZW(t.payload,D),U=null;W&&(U=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),U.textContent=W);let B=v("div","persona-flex-1 persona-min-w-0"),O=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),R=Ge(Wn.Clipboard,"12px","currentColor",1.5);return R&&O.appendChild(R),O.addEventListener("click",async S=>{S.stopPropagation(),await eB(tB(t)),O.innerHTML="";let x=Ge(Wn.Check,"12px","currentColor",1.5);x&&O.appendChild(x),setTimeout(()=>{O.innerHTML="";let P=Ge(Wn.Clipboard,"12px","currentColor",1.5);P&&O.appendChild(P)},1500)}),h.appendChild(b),h.appendChild(M),T&&h.appendChild(T),h.appendChild(A),U&&h.appendChild(U),h.appendChild(B),h.appendChild(O),g.appendChild(h),c&&g.appendChild(rB(t,a,l)),g}}function Py(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=t,l=t.renderIconByName??(()=>null),c=r?.features?.scrollToBottom,p=c?.enabled!==!1,u=c?.iconName??"arrow-down",m=c?.label??"",g=r?.features?.eventStream??{},h=s.find(C=>C.renderEventStreamView);if(h?.renderEventStreamView&&r){let C=h.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>b().element,onClose:o});if(C)return{element:C,update:()=>{},destroy:()=>{}}}return b();function b(){let C=g.classNames,M=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");qa(M,C?.panel);let E=[],T="",H="",A=null,D=[],W={},U=0,B=$u(),O=0,R=0,S=!1,x=null,P=!1,L=0,G=new Set,V=new Map,K="",ee="",oe=null,ne,le,de,ve,Le=null,se=null,_=null;function Te(){let Ie=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Be=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(qa(Be,C?.headerBar),a){se=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),se.style.cursor="help",Le=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Le.textContent="-- tok/s",_=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),_.style.display="none",_.style.pointerEvents="none";let ao=se,Gn=_,Zc=()=>{if(!Gn.textContent)return;let Qo=ao.getBoundingClientRect(),Cn=Ie.getBoundingClientRect();Gn.style.left=`${Qo.left-Cn.left}px`,Gn.style.top=`${Qo.bottom-Cn.top+4}px`,Gn.style.display="block"},_s=()=>{Gn.style.display="none"};se.addEventListener("mouseenter",Zc),se.addEventListener("mouseleave",_s),se.appendChild(Le)}let qe=v("div","persona-flex-1");ne=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Tt=v("option","");Tt.value="",Tt.textContent="All events (0)",ne.appendChild(Tt),le=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),le.type="button",le.title="Copy All";let xt=Ge(Wn.ClipboardCopy,"12px","currentColor",1.5);xt&&le.appendChild(xt);let Mn=v("span","persona-event-copy-all persona-text-xs");Mn.textContent="Copy All",le.appendChild(Mn),se&&Be.appendChild(se),Be.appendChild(qe),Be.appendChild(ne),Be.appendChild(le);let ft=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");qa(ft,C?.searchBar);let _t=Ge(Wn.Search,"14px","var(--persona-muted, #9ca3af)",1.5),Vt=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");_t&&Vt.appendChild(_t),de=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),qa(de,C?.searchInput),de.type="text",de.placeholder="Search event payloads...",ve=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ve.type="button",ve.style.display="none";let pn=Ge(Wn.X,"12px","currentColor",2);return pn&&ve.appendChild(pn),ft.appendChild(Vt),ft.appendChild(de),ft.appendChild(ve),Ie.appendChild(Be),Ie.appendChild(ft),_&&Ie.appendChild(_),Ie}let He,ut=s.find(Ie=>Ie.renderEventStreamToolbar);ut?.renderEventStreamToolbar&&r?He=ut.renderEventStreamToolbar({config:r,defaultRenderer:()=>Te(),eventCount:e.getSize(),filteredCount:0,onFilterChange:Be=>{T=Be,Y(),Ee()},onSearchChange:Be=>{H=Be,Y(),Ee()}})??Te():He=Te();let At=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");At.style.display="none";function Wt(){if(!a||!Le||!se)return;let Ie=a(),Be=nB(Ie);Le.textContent=Be;let qe=oB(Ie);_&&(_.textContent=qe,qe||(_.style.display="none")),se.setAttribute("aria-label",qe?`Throughput: ${Be}, ${qe}`:`Throughput: ${Be}`)}let bt=v("div","persona-flex-1 persona-min-h-0 persona-relative"),xe=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");xe.style.height="100%";let Ne=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");qa(Ne,C?.scrollIndicator),Ne.style.display="none",Ne.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Ae=l(u,"14px","currentColor",2);Ae&&Ne.appendChild(Ae);let vt=v("span","");vt.textContent=m,Ne.appendChild(vt);let X=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");X.style.display="none",bt.appendChild(xe),bt.appendChild(X),bt.appendChild(Ne),M.setAttribute("tabindex","0"),M.appendChild(He),M.appendChild(At),M.appendChild(bt);function I(){let Ie=e.getAll(),Be={};for(let ft of Ie)Be[ft.type]=(Be[ft.type]||0)+1;let qe=Object.keys(Be).sort(),Tt=qe.length!==D.length||!qe.every((ft,_t)=>ft===D[_t]),mt=!Tt&&qe.some(ft=>Be[ft]!==W[ft]),xt=Ie.length!==Object.values(W).reduce((ft,_t)=>ft+_t,0);if(!Tt&&!mt&&!xt||(D=qe,W=Be,!ne))return;let Mn=ne.value;if(ne.options[0].textContent=`All events (${Ie.length})`,Tt){for(;ne.options.length>1;)ne.remove(1);for(let ft of qe){let _t=v("option","");_t.value=ft,_t.textContent=`${ft} (${Be[ft]||0})`,ne.appendChild(_t)}Mn&&qe.includes(Mn)?ne.value=Mn:Mn&&(ne.value="",T="")}else for(let ft=1;ft<ne.options.length;ft++){let _t=ne.options[ft];_t.textContent=`${_t.value} (${Be[_t.value]||0})`}}function j(){let Ie=e.getAll();if(T&&(Ie=Ie.filter(Be=>Be.type===T)),H){let Be=H.toLowerCase();Ie=Ie.filter(qe=>qe.type.toLowerCase().includes(Be)||qe.payload.toLowerCase().includes(Be))}return Ie}function J(){return T!==""||H!==""}function Y(){U=0,O=0,B.resume(),Ne.style.display="none"}function ie(Ie){G.has(Ie)?G.delete(Ie):G.add(Ie),oe=Ie;let Be=xe.scrollTop,qe=B.isFollowing();P=!0,B.pause(),Ee(),xe.scrollTop=Be,qe&&B.resume(),P=!1}function Me(){return jr(xe,50)}function Ee(){R=Date.now(),S=!1,Wt(),I();let Ie=e.getEvictedCount();Ie>0?(At.textContent=`${Ie.toLocaleString()} older events truncated`,At.style.display=""):At.style.display="none",E=j();let Be=E.length,qe=e.getSize()>0;Be===0&&qe&&J()?(X.textContent=H?`No events matching '${H}'`:"No events matching filter",X.style.display="",xe.style.display="none"):(X.style.display="none",xe.style.display=""),le&&(le.title=J()?`Copy Filtered (${Be})`:"Copy All"),p&&!B.isFollowing()&&Be>U&&(O+=Be-U,vt.textContent=m?`${m}${O>0?` (${O})`:""}`:"",Ne.style.display=""),U=Be;let Tt=e.getAll(),mt=Tt.length>0?Tt[0].timestamp:0,xt=new Set(E.map(_t=>_t.id));for(let _t of G)xt.has(_t)||G.delete(_t);let Mn=T!==K||H!==ee,ft=V.size===0&&E.length>0;if(Mn||ft||E.length===0){xe.innerHTML="",V.clear();let _t=document.createDocumentFragment();for(let Vt=0;Vt<E.length;Vt++){let pn=ky(E[Vt],Vt,mt,g,G,ie,s,r);V.set(E[Vt].id,pn),_t.appendChild(pn)}xe.appendChild(_t),K=T,ee=H,oe=null}else{if(oe!==null){let Vt=V.get(oe);if(Vt&&Vt.parentNode===xe){let pn=E.findIndex(ao=>ao.id===oe);if(pn>=0){let ao=ky(E[pn],pn,mt,g,G,ie,s,r);xe.insertBefore(ao,Vt),Vt.remove(),V.set(oe,ao)}}oe=null}let _t=new Set(E.map(Vt=>Vt.id));for(let[Vt,pn]of V)_t.has(Vt)||(pn.remove(),V.delete(Vt));for(let Vt=0;Vt<E.length;Vt++){let pn=E[Vt];if(!V.has(pn.id)){let ao=ky(pn,Vt,mt,g,G,ie,s,r);V.set(pn.id,ao),xe.appendChild(ao)}}}B.isFollowing()&&(xe.scrollTop=xe.scrollHeight)}function Oe(){if(Date.now()-R>=GW){x!==null&&(cancelAnimationFrame(x),x=null),Ee();return}S||(S=!0,x=requestAnimationFrame(()=>{x=null,Ee()}))}let Ct=(Ie,Be)=>{if(!le)return;le.innerHTML="";let qe=Ge(Ie,"12px","currentColor",1.5);qe&&le.appendChild(qe);let Tt=v("span","persona-text-xs");Tt.textContent="Copy All",le.appendChild(Tt),setTimeout(()=>{le.innerHTML="";let mt=Ge(Wn.ClipboardCopy,"12px","currentColor",1.5);mt&&le.appendChild(mt);let xt=v("span","persona-text-xs");xt.textContent="Copy All",le.appendChild(xt),le.disabled=!1},Be)},Ot=async()=>{if(le){le.disabled=!0;try{let Ie;J()?Ie=E:n?(Ie=await n(),Ie.length===0&&(Ie=e.getAll())):Ie=e.getAll();let Be=Ie.map(qe=>{try{return JSON.parse(qe.payload)}catch{return qe.payload}});await navigator.clipboard.writeText(JSON.stringify(Be,null,2)),Ct(Wn.Check,1500)}catch{Ct(Wn.X,1500)}}},rt=()=>{ne&&(T=ne.value,Y(),Ee())},Ze=()=>{!de||!ve||(ve.style.display=de.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{H=de.value,Y(),Ee()},150))},ct=()=>{!de||!ve||(de.value="",H="",ve.style.display="none",A&&clearTimeout(A),Y(),Ee())},Rt=()=>{if(P)return;let Ie=xe.scrollTop,{action:Be,nextLastScrollTop:qe}=zu({following:B.isFollowing(),currentScrollTop:Ie,lastScrollTop:L,nearBottom:Me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});L=qe,Be==="resume"?(B.resume(),O=0,Ne.style.display="none"):Be==="pause"&&(B.pause(),p&&(vt.textContent=m,Ne.style.display=""))},Z=Ie=>{let Be=Uu({following:B.isFollowing(),deltaY:Ie.deltaY,nearBottom:Me(),resumeWhenNearBottom:!0});Be==="pause"?(B.pause(),p&&(vt.textContent=m,Ne.style.display="")):Be==="resume"&&(B.resume(),O=0,Ne.style.display="none")},Fe=()=>{p&&(xe.scrollTop=xe.scrollHeight,B.resume(),O=0,Ne.style.display="none")},Re=Ie=>{let Be=Ie.target;if(!Be||Be.closest("button"))return;let qe=Be.closest("[data-event-id]");if(!qe)return;let Tt=qe.getAttribute("data-event-id");Tt&&ie(Tt)},nt=Ie=>{if((Ie.metaKey||Ie.ctrlKey)&&Ie.key==="f"){Ie.preventDefault(),de?.focus(),de?.select();return}Ie.key==="Escape"&&(de&&document.activeElement===de?(ct(),de.blur(),M.focus()):o&&o())};le&&le.addEventListener("click",Ot),ne&&ne.addEventListener("change",rt),de&&de.addEventListener("input",Ze),ve&&ve.addEventListener("click",ct),xe.addEventListener("scroll",Rt),xe.addEventListener("wheel",Z,{passive:!0}),xe.addEventListener("click",Re),Ne.addEventListener("click",Fe),M.addEventListener("keydown",nt);function Bt(){A&&clearTimeout(A),x!==null&&(cancelAnimationFrame(x),x=null),S=!1,V.clear(),le&&le.removeEventListener("click",Ot),ne&&ne.removeEventListener("change",rt),de&&de.removeEventListener("input",Ze),ve&&ve.removeEventListener("click",ct),xe.removeEventListener("scroll",Rt),xe.removeEventListener("wheel",Z),xe.removeEventListener("click",Re),Ne.removeEventListener("click",Fe),M.removeEventListener("keydown",nt)}return{element:M,update:Oe,destroy:Bt}}}var Wn,Kr,jW,KW,GW,vT=be(()=>{"use strict";je();Wn=require("lucide");zn();Uh();Kr={flow_:{bg:"var(--persona-event-badge-flow-bg, #dcfce7)",text:"var(--persona-event-badge-flow-fg, #15803d)"},step_:{bg:"var(--persona-event-badge-step-bg, #f5f5f5)",text:"var(--persona-event-badge-step-fg, #0a0a0a)"},reasoning_:{bg:"var(--persona-event-badge-reasoning-bg, #fef9c3)",text:"var(--persona-event-badge-reasoning-fg, #a16207)"},tool_:{bg:"var(--persona-event-badge-tool-bg, #f3e8ff)",text:"var(--persona-event-badge-tool-fg, #6b21a8)"},agent_:{bg:"var(--persona-event-badge-agent-bg, #ccfbf1)",text:"var(--persona-event-badge-agent-fg, #115e59)"},error:{bg:"var(--persona-event-badge-error-bg, #fee2e2)",text:"var(--persona-event-badge-error-fg, #b91c1c)"}};Kr.execution_error=Kr.error;Kr.execution_=Kr.flow_;Kr.turn_=Kr.agent_;Kr.text_=Kr.agent_;jW={bg:"var(--persona-event-badge-default-bg, #f3f4f6)",text:"var(--persona-event-badge-default-fg, #4b5563)"},KW=["flowName","stepName","reasoningText","text","name","tool","toolName"],GW=100});var Wc,CT=be(()=>{"use strict";Wc=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),this.store?.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}}});var Bc,wT=be(()=>{"use strict";Bc=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}}});function Ly(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function am(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function aB(t,e){return typeof e.type=="string"?e.type:t}function ST(t){let e=xT(t,"tokens")??xT(t,"totalTokens");return e?MT(e.output):void 0}function lB(t){return MT(t.durationMs)}function cB(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var sB,iB,AT,MT,xT,Dc,TT=be(()=>{"use strict";sB=new Set(["step_start","turn_start"]),iB=new Set(["step_complete","turn_complete"]),AT=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),MT=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,xT=(t,e)=>{let n=t[e];return AT(n)?n:void 0};Dc=class{constructor(e=cB){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:am(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){if(!AT(n)){e==="execution_error"&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=aB(e,n),r=this.now();if(o==="execution_start"){this.startRun(r);return}if(sB.has(o)){this.run||this.startRun(r);return}if(o==="text_delta"){let s=typeof n.delta=="string"?n.delta:"";if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+Ly(a.visibleCharCount),c=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:am(l,c),outputTokens:l,durationMs:c,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(iB.has(o)){if(!this.run)return;let s=this.run,a=ST(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,c=s.exactOutputTokens+Ly(s.visibleCharCount),p=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:am(c,p),outputTokens:c,durationMs:p,source:l?"usage":"estimate"};return}if(o==="execution_complete"){if(!this.run)return;let s=this.run,a=ST(n),l=a??s.exactOutputTokens+Ly(s.visibleCharCount),c=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:am(l,p),outputTokens:l,durationMs:p,source:c},this.run=null;return}if(o==="execution_error"||o==="error"&&n.recoverable===!1){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:lB(n)??o-e.startedAt}}});var ET=be(()=>{"use strict";vT();CT();wT();TT()});var kT={};$n(kT,{EventStreamBuffer:()=>Wc,EventStreamStore:()=>Bc,ThroughputTracker:()=>Dc,createEventStreamView:()=>Py});var PT=be(()=>{"use strict";ET()});var Ry,Yo,Oc=be(()=>{"use strict";Ry=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},Yo=new Ry});function vr(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function LT(t){let e=vr(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function lm(t){if(typeof t!="string")return"";let e=t.indexOf(`
238
238
  `);if(e===-1||!t.slice(0,e).startsWith("```"))return t;let o=t.slice(e+1),r=o.lastIndexOf(`
239
- `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function gi(t){let e=wM(t.path);if(e)return e==="html"||e==="htm"?"html":e==="svg"?"svg":e==="md"||e==="mdx"?"markdown":"other";let n=(t.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Cs(t){switch(gi(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=wM(t.path);return e?e.toUpperCase():"File"}}}function xc(t){let e=t.markdown??"";return t.file?{filename:dr(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:Du(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}function Sc(t){let e=new Blob([t.content],{type:t.mime}),n=URL.createObjectURL(e),o=document.createElement("a");o.href=n,o.download=t.filename,o.click(),URL.revokeObjectURL(n)}var hi=be(()=>{"use strict"});function La(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+_u+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+_u+(n?" persona-artifact-doc-icon-btn":"");o=v("button",r)}o.type="button",o.setAttribute("aria-label",t.label),o.title=t.label;try{let r=t.icon();r&&o.appendChild(r)}catch{}if(t.showLabel){let r=v("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=ci({icon:t.icon,label:t.label,className:_u+(n?" persona-artifact-doc-copy-btn":"")}):o=gn({icon:t.icon,label:t.label,className:_u+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function Ac(t){if(!t)return null;let e={artifactId:t.id,title:t.title??"",artifactType:t.artifactType};return t.artifactType==="markdown"?(e.markdown=t.markdown??"",t.file&&(e.file=t.file)):e.jsonPayload=JSON.stringify({component:t.component,props:t.props},null,2),e}var _u,Nu=be(()=>{"use strict";di();Ye();_u="persona-artifact-custom-action-btn"});function xM(t){let e=document.createElementNS(Nh,"svg");e.setAttribute("class",Vt("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(Nh,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Nh,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),e.appendChild(n),e.appendChild(o),e}var Nh,SM=be(()=>{"use strict";Ye();Nh="http://www.w3.org/2000/svg"});function AM(t,e,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){t.textContent=e;return}if(o==="pulse"){t.setAttribute("data-preserve-animation","true"),t.classList.add("persona-tool-loading-pulse"),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),t.textContent=e;return}t.setAttribute("data-preserve-animation","true"),t.classList.add(`persona-tool-loading-${o}`),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&t.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&t.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),vs(t,e,0)}var MM=be(()=>{"use strict";Tu()});function Pa(t){t&&Vh.delete(t)}function FR(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?Cs(e):t.artifactType==="component"?"Component":"Document"}function Ia(t,e,n){let o=FR(t),r=`Generating ${o.toLowerCase()}...`,s=e?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=t.id,l=Vh.get(a);t.status!=="complete"&&l===void 0&&(l=kM(),Vh.set(a,l));let d=l===void 0?0:Math.max(0,kM()-l),p=t.artifactType==="component",u=!p&&typeof t.markdown=="string"?t.markdown:"",m=p?0:u.length,y=p||u===""?0:u.split(`
240
- `).length,g=t.artifactType==="markdown"?t.file:void 0,b={artifactId:a,artifactType:t.artifactType,title:t.title,typeLabel:o,file:g,chars:m,lines:y,elapsedMs:d,content:()=>p?"":u,surface:n};try{let C=s(b);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function VR(t){t.className=Fh,t.removeAttribute("data-preserve-animation"),t.style.removeProperty("--persona-tool-anim-duration"),t.style.removeProperty("--persona-tool-anim-color"),t.style.removeProperty("--persona-tool-anim-secondary-color"),t.replaceChildren()}function yi(t,e,n){let o=t.querySelector(`:scope > .${Fh}`);o||(o=v("span",Fh),t.appendChild(o)),o.getAttribute(EM)!==e.label&&(VR(o),AM(o,e.label,n),o.setAttribute(EM,e.label));let r=t.querySelector(`:scope > .${TM}`),s=e.detail;s?(r||(r=v("span",TM),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var Fh,TM,EM,Vh,kM,Fu=be(()=>{"use strict";Ye();hi();MM();Fh="persona-artifact-status-label",TM="persona-artifact-status-detail",EM="data-artifact-status-label",Vh=new Map,kM=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()});function UR(t,e){let n=(t||"").trim().toLowerCase();if(n&&Vu[n])return Vu[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(Vu[r])return Vu[r]}}return null}function $u(t,e){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:t.slice(r,a)})};for(;o<t.length;){let a=!1;for(let l of e){l.re.lastIndex=o;let d=l.re.exec(t);if(d&&d.index===o&&d[0].length>0){s(o);let p=l.map?l.map(d[0]):l.type;n.push({type:p,value:d[0]}),o+=d[0].length,r=o,a=!0;break}}a||(o+=1)}return s(t.length),n}function LM(t){return $u(t,jR)}function GR(t){let e=$u(t,KR);for(let n=0;n<e.length;n+=1){if(e[n].type!=="string")continue;let o=n+1;for(;o<e.length&&e[o].value.trim()==="";)o+=1;let r=e[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(e[n].type="property")}return e}function PM(t){let e=$u(t,YR),n="";for(let o=0;o<e.length;o+=1){let r=e[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<e.length&&e[a].value.trim()==="";)a+=1;let l=e[a];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return e}function XR(t){let e=[],n=(s,a)=>{a&&e.push({type:s,value:a})},o=t.length,r=0;for(;r<o;){if(t.startsWith("<!--",r)){let a=t.indexOf("-->",r+4),l=a===-1?o:a+3;n("comment",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&t[r+1]==="!"){let a=t.indexOf(">",r),l=a===-1?o:a+1;n("tag",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&/[A-Za-z/]/.test(t[r+1]||"")){let a=t.indexOf(">",r),l=a===-1?o:a+1,d=t.slice(r,l);for(let u of $u(d,QR))e.push(u);r=l;let p=/^<\s*(script|style)\b/i.exec(d);if(p&&!/\/>\s*$/.test(d)){let u=p[1].toLowerCase(),y=new RegExp("</\\s*"+u+"\\s*>","i").exec(t.slice(r)),g=y?r+y.index:o,b=t.slice(r,g),C=u==="script"?LM(b):PM(b);for(let S of C)e.push(S);r=g}continue}let s=t.indexOf("<",r);if(s===r)n("plain",t[r]),r+=1;else{let a=s===-1?o:s;n("plain",t.slice(r,a)),r=a}}return e}function JR(t,e){switch(e){case"html":return XR(t);case"css":return PM(t);case"js":return LM(t);case"json":return GR(t)}}function ZR(t){let e=$C(),n=v("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=$R[r];if(a){let l=v("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
239
+ `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Di(t){let e=LT(t.path);if(e)return e==="html"||e==="htm"?"html":e==="svg"?"svg":e==="md"||e==="mdx"?"markdown":"other";let n=(t.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Ws(t){switch(Di(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=LT(t.path);return e?e.toUpperCase():"File"}}}function _c(t){let e=t.markdown??"";return t.file?{filename:vr(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:lm(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}function Nc(t){let e=new Blob([t.content],{type:t.mime}),n=URL.createObjectURL(e),o=document.createElement("a");o.href=n,o.download=t.filename,o.click(),URL.revokeObjectURL(n)}var Oi=be(()=>{"use strict"});function ja(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+cm+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+cm+(n?" persona-artifact-doc-icon-btn":"");o=v("button",r)}o.type="button",o.setAttribute("aria-label",t.label),o.title=t.label;try{let r=t.icon();r&&o.appendChild(r)}catch{}if(t.showLabel){let r=v("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=Li({icon:t.icon,label:t.label,className:cm+(n?" persona-artifact-doc-copy-btn":"")}):o=vn({icon:t.icon,label:t.label,className:cm+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function Fc(t){if(!t)return null;let e={artifactId:t.id,title:t.title??"",artifactType:t.artifactType};return t.artifactType==="markdown"?(e.markdown=t.markdown??"",t.file&&(e.file=t.file)):e.jsonPayload=JSON.stringify({component:t.component,props:t.props},null,2),e}var cm,dm=be(()=>{"use strict";Ii();je();cm="persona-artifact-custom-action-btn"});function IT(t){let e=document.createElementNS(Hy,"svg");e.setAttribute("class",Gt("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(Hy,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Hy,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),e.appendChild(n),e.appendChild(o),e}var Hy,RT=be(()=>{"use strict";je();Hy="http://www.w3.org/2000/svg"});function HT(t,e,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){t.textContent=e;return}if(o==="pulse"){t.setAttribute("data-preserve-animation","true"),t.classList.add("persona-tool-loading-pulse"),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),t.textContent=e;return}t.setAttribute("data-preserve-animation","true"),t.classList.add(`persona-tool-loading-${o}`),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&t.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&t.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),Hs(t,e,0)}var WT=be(()=>{"use strict";rm()});function Ka(t){t&&By.delete(t)}function pB(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?Ws(e):t.artifactType==="component"?"Component":"Document"}function Ga(t,e,n){let o=pB(t),r=`Generating ${o.toLowerCase()}...`,s=e?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=t.id,l=By.get(a);t.status!=="complete"&&l===void 0&&(l=OT(),By.set(a,l));let c=l===void 0?0:Math.max(0,OT()-l),p=t.artifactType==="component",u=!p&&typeof t.markdown=="string"?t.markdown:"",m=p?0:u.length,g=p||u===""?0:u.split(`
240
+ `).length,h=t.artifactType==="markdown"?t.file:void 0,b={artifactId:a,artifactType:t.artifactType,title:t.title,typeLabel:o,file:h,chars:m,lines:g,elapsedMs:c,content:()=>p?"":u,surface:n};try{let C=s(b);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function uB(t){t.className=Wy,t.removeAttribute("data-preserve-animation"),t.style.removeProperty("--persona-tool-anim-duration"),t.style.removeProperty("--persona-tool-anim-color"),t.style.removeProperty("--persona-tool-anim-secondary-color"),t.replaceChildren()}function _i(t,e,n){let o=t.querySelector(`:scope > .${Wy}`);o||(o=v("span",Wy),t.appendChild(o)),o.getAttribute(DT)!==e.label&&(uB(o),HT(o,e.label,n),o.setAttribute(DT,e.label));let r=t.querySelector(`:scope > .${BT}`),s=e.detail;s?(r||(r=v("span",BT),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var Wy,BT,DT,By,OT,pm=be(()=>{"use strict";je();Oi();WT();Wy="persona-artifact-status-label",BT="persona-artifact-status-detail",DT="data-artifact-status-label",By=new Map,OT=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()});function gB(t,e){let n=(t||"").trim().toLowerCase();if(n&&um[n])return um[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(um[r])return um[r]}}return null}function mm(t,e){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:t.slice(r,a)})};for(;o<t.length;){let a=!1;for(let l of e){l.re.lastIndex=o;let c=l.re.exec(t);if(c&&c.index===o&&c[0].length>0){s(o);let p=l.map?l.map(c[0]):l.type;n.push({type:p,value:c[0]}),o+=c[0].length,r=o,a=!0;break}}a||(o+=1)}return s(t.length),n}function _T(t){return mm(t,yB)}function vB(t){let e=mm(t,bB);for(let n=0;n<e.length;n+=1){if(e[n].type!=="string")continue;let o=n+1;for(;o<e.length&&e[o].value.trim()==="";)o+=1;let r=e[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(e[n].type="property")}return e}function NT(t){let e=mm(t,CB),n="";for(let o=0;o<e.length;o+=1){let r=e[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<e.length&&e[a].value.trim()==="";)a+=1;let l=e[a];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return e}function xB(t){let e=[],n=(s,a)=>{a&&e.push({type:s,value:a})},o=t.length,r=0;for(;r<o;){if(t.startsWith("<!--",r)){let a=t.indexOf("-->",r+4),l=a===-1?o:a+3;n("comment",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&t[r+1]==="!"){let a=t.indexOf(">",r),l=a===-1?o:a+1;n("tag",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&/[A-Za-z/]/.test(t[r+1]||"")){let a=t.indexOf(">",r),l=a===-1?o:a+1,c=t.slice(r,l);for(let u of mm(c,wB))e.push(u);r=l;let p=/^<\s*(script|style)\b/i.exec(c);if(p&&!/\/>\s*$/.test(c)){let u=p[1].toLowerCase(),g=new RegExp("</\\s*"+u+"\\s*>","i").exec(t.slice(r)),h=g?r+g.index:o,b=t.slice(r,h),C=u==="script"?_T(b):NT(b);for(let M of C)e.push(M);r=h}continue}let s=t.indexOf("<",r);if(s===r)n("plain",t[r]),r+=1;else{let a=s===-1?o:s;n("plain",t.slice(r,a)),r=a}}return e}function SB(t,e){switch(e){case"html":return xB(t);case"css":return NT(t);case"js":return _T(t);case"json":return vB(t)}}function AB(t){let e=Cw(),n=v("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=mB[r];if(a){let l=v("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
241
241
  `);for(let a=0;a<s.length;a+=1)a>0&&(e.appendChild(n),e.appendChild(document.createTextNode(`
242
- `)),n=v("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function IM(t,e,n){let o=t.length<=zR?UR(e,n):null,r=o?JR(t,o):[{type:"plain",value:t}];return ZR(r)}var $R,zR,Vu,qR,jR,KR,YR,QR,HM=be(()=>{"use strict";Ye();$R={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},zR=15e4,Vu={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};qR=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),jR=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:t=>qR.has(t)?"keyword":"plain"}];KR=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:t=>t==="true"||t==="false"||t==="null"?"keyword":"plain"}];YR=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];QR=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}]});var RM,$h,WM,zh=be(()=>{"use strict";RM=null,$h=t=>{RM=t.componentRegistry},WM=()=>RM});function Mc(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?Du(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}function eW(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function BM(t,e,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(e!=="auto"||!t||typeof r!="function"||Uh||s){o();return}Uh=!0;let a=eW(n);t.style.setProperty("view-transition-name",a);let l=()=>{Uh=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}function oW(t){let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=v("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(t.props??{},null,2),e.appendChild(n),e.appendChild(o),e}function rW(t){if(t===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let e=t&&typeof t=="object"?t:void 0;return{enabled:!0,delayMs:e?.delayMs??200,minVisibleMs:e?.minVisibleMs??300,timeoutMs:e?.timeoutMs??8e3,injectReadySignal:e?.injectReadySignal!==!1,label:e?.label===!1?!1:e?.label??"Starting preview...",labelDelayMs:e?.labelDelayMs??2e3,renderIndicator:e?.renderIndicator}}function iW(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(2);return crypto.getRandomValues(t),t[0].toString(36)+t[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function aW(t){return`
243
- <script>(function(){var d=false;var t=`+JSON.stringify(t)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function lW(t,e,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:t,config:e});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(xM());let s=null;return n.label!==!1&&(s=v("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function cW(t,e,n,o,r,s){let a=null,l=0,d=!1,p=new Set,u=()=>{p.forEach(I=>clearTimeout(I)),p.clear()},m=(I,M)=>{let O=setTimeout(()=>{p.delete(O),!(typeof document>"u")&&I()},M);p.add(O)},y=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||d)return;let I=lW(r,s,o);a=I.el,t.appendChild(a),l=Date.now(),o.label!==!1&&m(I.revealLabel,o.labelDelayMs)},b=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),m(y,sW))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",T):e.removeEventListener("load",A)},S=()=>{if(d||(d=!0,C(),u(),!a))return;let I=Math.max(0,o.minVisibleMs-(Date.now()-l));I>0?m(b,I):b()};function T(I){if(n===null)return;let M=I.data;!M||M.persona!=="artifact-preview-ready"||M.token!==n||I.source===e.contentWindow&&S()}function A(){let I=M=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>M()):setTimeout(M,0)};I(()=>I(()=>S()))}return m(g,o.delayMs),m(S,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",T):e.addEventListener("load",A),()=>{d=!0,u(),C(),y()}}function zu(t,e){let{config:n}=e,o=e.registry??WM()??zo,r=e.bodyLayout,s=n.markdown?Qd(n.markdown):null,a=Jd(n.sanitize),l=t,d=!1,p=K=>{let Y=Mo()!==null;s&&!Y&&!d&&(d=!0,ea(()=>z(l)));let re=s?s(K):Pr(K);return s&&Y&&a?a(re):re},u=v("div","persona-artifact-preview-body"),m=null,y=null,g=null,b=()=>{g&&(g(),g=null),m=null,y=null},C=null,S=null,T=null,A=!1,I=()=>{C=null,S=null,T=null,A=!1},M=null,O=null,k=()=>{M=null,O=null},B=40,W=0,V=K=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>K()):setTimeout(K,0),R=K=>K.scrollHeight-K.clientHeight-K.scrollTop<=B,w=K=>{if(!r)return;let Y=K.scrollHeight-K.clientHeight>1,re=K.scrollHeight-K.clientHeight-K.scrollTop;K.classList.toggle("persona-artifact-fade-top",r.fadeTop&&Y&&K.scrollTop>1),K.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&Y&&re>1)},E=K=>{W||(W=V(()=>{W=0,K.scrollTop=K.scrollHeight,w(K)}))},H=(K,Y,re,oe)=>{let se=!!r,ce=re.id+"|"+(se?"w":"p");if(!C||T!==ce||C.parentElement!==u){b(),k(),u.replaceChildren();let N=v("pre",tW+" persona-code-pre"),ye=v("code","persona-code");if(N.appendChild(ye),se){let ke=v("div","persona-artifact-source-window");if(ke.appendChild(N),u.appendChild(ke),!(r?.overflow==="clip")&&typeof ke.addEventListener=="function"){let Ee=()=>ke.scrollHeight-ke.clientHeight>1;ke.addEventListener("scroll",()=>{R(ke)&&(A=!1),w(ke)},{passive:!0}),ke.addEventListener("wheel",Ne=>{Ee()&&Ne.deltaY<0&&(A=!0)},{passive:!0}),ke.addEventListener("touchmove",()=>{Ee()&&(A=!0)},{passive:!0})}C=ke}else u.appendChild(N),C=N;S=ye,T=ce}let we=se?C:null;we&&(we.classList.toggle("persona-artifact-source-window--fixed",oe),we.classList.toggle("persona-artifact-source-window--clip",oe&&r?.overflow==="clip"));let ge=we?R(we):!0;if(S.replaceChildren(IM(K,Y?.language,Y?.path)),we){let N=re.status!=="complete";oe&&N&&r?.followOutput&&!A&&ge?E(we):N||(A=!1),w(we)}},D=K=>{b(),I(),k(),u.replaceChildren();let Y=v("div",nW);Y.innerHTML=p(K),u.appendChild(Y)},G=K=>{let Y=K.id,re=n.features?.artifacts,oe=Ia(K,re,"status-body");if(M&&O===Y&&M.parentElement===u){let we=M.querySelector(".persona-artifact-status-view-text");we&&yi(we,oe,re);return}b(),I(),u.replaceChildren();let se=v("div","persona-artifact-status-view"),ce=v("div","persona-artifact-status-view-text");yi(ce,oe,re),se.appendChild(ce),u.appendChild(se),M=se,O=Y},z=K=>{l=K;let Y=e.resolveViewMode?.(K)??r?.viewMode??"rendered",re=K.artifactType==="markdown"?K.file:void 0,oe=K.status!=="complete";oe||Pa(K.id);let se=oe?r?.streamingHeight:r?.completeHeight,ce=!!r&&typeof se=="number";if(r?.streamingView==="status"&&oe){G(K);return}if(re){let ge=Du(K.markdown??""),N=gi(re),ye=n.features?.artifacts?.filePreview?.enabled!==!1;if(!oe&&Y==="rendered"&&ye&&(N==="html"||N==="svg")){let nt=K.id+"\0"+ge;if(m&&y===nt&&m.parentElement===u)return;I(),k(),b(),u.replaceChildren();let Ee=n.features?.artifacts?.filePreview,Ne=Ee?.iframeSandbox??"allow-scripts";!Ee?.dangerouslyAllowSameOrigin&&Ne.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Ne=Ne.split(/\s+/).filter(Ge=>Ge&&Ge!=="allow-same-origin").join(" "));let Pe=rW(Ee?.loading),dt=v("div","persona-artifact-frame"),Xe=v("iframe","persona-artifact-iframe");Xe.setAttribute("sandbox",Ne),Xe.setAttribute("data-artifact-id",K.id);let xt=null;Pe.enabled&&Pe.injectReadySignal?(xt=iW(),Xe.srcdoc=ge+aW(xt)):Xe.srcdoc=ge,dt.appendChild(Xe),u.appendChild(dt),Pe.enabled&&(g=cW(dt,Xe,xt,Pe,K.id,n)),m=dt,y=nt;return}if(b(),!oe&&N==="markdown"&&Y==="rendered"){D(ge);return}H(ge,{language:re.language,path:re.path},K,ce);return}if(K.artifactType==="markdown"){if(Y==="source"){b(),H(K.markdown??"",void 0,K,ce);return}D(K.markdown??"");return}b(),I(),k(),u.replaceChildren();let we=K.component?o.get(K.component):void 0;if(we){let N={message:{id:K.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let ye=we(K.props??{},N);if(ye){u.appendChild(ye);return}}catch{}}u.appendChild(oW(K))};return z(t),{el:u,update(K){z(K)},destroy(){b()}}}var Uh,tW,nW,sW,Uu=be(()=>{"use strict";Ye();SM();hi();Fu();HM();Xd();ti();Ff();wc();zh();Uh=!1;tW="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",nW="persona-text-sm persona-leading-relaxed persona-markdown-bubble";sW=220});function OM(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.setAttribute("role","tablist");let s=[],a=!1,l=m=>{typeof m.scrollIntoView=="function"&&m.scrollIntoView({block:"nearest",inline:"nearest"})},d=m=>{let y=m;return s.findIndex(g=>g===y||g.contains(y))},p=m=>{let y=d(m.target);if(y<0)return;let g=y;if(m.key===r)g=Math.min(y+1,s.length-1);else if(m.key===o)g=Math.max(y-1,0);else if(m.key==="Home")g=0;else if(m.key==="End")g=s.length-1;else return;m.preventDefault(),g!==y&&e.onSelect(g)},u=m=>{let y=d(m.target);y>=0&&l(s[y])};return t.addEventListener("keydown",p),t.addEventListener("focusin",u),{beforeRender(){a=typeof document<"u"&&t.contains(document.activeElement)},render(m,y){if(s=m,m.forEach((g,b)=>{g.setAttribute("role","tab");let C=b===y;g.setAttribute("aria-selected",C?"true":"false"),g.tabIndex=C||y<0&&b===0?0:-1}),a){let g=(y>=0?m[y]:void 0)??m[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){t.removeEventListener("keydown",p),t.removeEventListener("focusin",u)}}}var DM=be(()=>{"use strict"});function qh(t,e){let n=t.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),d=n?.tabFadeSize?.trim(),p=ee=>({start:ee===!1?!1:typeof ee=="object"&&ee?ee.start!==!1:!0,end:ee===!1?!1:typeof ee=="object"&&ee?ee.end!==!1:!0}),{start:u,end:m}=p(n?.tabFade),y=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{y?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),w?.closeMenu()};y&&y.addEventListener("click",()=>{g(),e.onDismiss?.()});let b=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let C=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let S=v("span","persona-text-xs persona-font-medium persona-truncate");S.textContent=s;let T=gn({icon:"x",label:a});T.addEventListener("click",()=>{g(),e.onDismiss?.()});let A="rendered",I=bu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:ee=>{A=ee==="source"?"source":"rendered",Je()}}),M=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),O=n?.documentToolbarShowCopyLabel===!0,k=n?.documentToolbarShowCopyChevron===!0,B=n?.documentToolbarCopyMenuItems,W=!!(k&&B&&B.length>0),V=null,R,w=null;if(r&&(O||k)&&!W){if(R=O?ci({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):gn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k){let ee=Qe(ws.ChevronDown,14,"currentColor",2);ee&&R.appendChild(ee)}}else r&&W?(w=xA({label:"Copy",icon:"copy",iconSize:14,iconOnly:!O,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(B??[]).map(ee=>({id:ee.id,label:ee.label})),position:"bottom-right",portal:()=>b.closest("[data-persona-root]")??document.body,onSelect:ee=>{we(ee)}}),V=w.element,R=w.primaryButton):r?R=gn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(R=gn({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&R.classList.add("persona-hidden"));let E=r?gn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):gn({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||E.classList.add("persona-hidden");let H=r?gn({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):gn({icon:"x",label:a}),D=gn({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&D.classList.add("persona-hidden");let G=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),z=t.features?.artifacts?.toolbarActions??[],K=()=>{let ee=Ge.find(Ke=>Ke.id===yt)??Ge[Ge.length-1],Oe=ee?.id??null,$e=ee?.artifactType==="markdown"?ee.markdown??"":"",pt=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"",{filename:_t,mime:ve,content:Se}=xc({title:ee?.title,markdown:ee?.markdown??"",file:ee?.file});return{markdown:$e,jsonPayload:pt,id:Oe,file:ee?.file,suggestedFilename:_t,mime:ve,content:Se}},Y=()=>{let{suggestedFilename:ee,mime:Oe,content:$e}=K();$e&&Sc({filename:ee,mime:Oe,content:$e})},re=ee=>{let{id:Oe,...$e}=K();return{actionId:ee,artifactId:Oe,...$e}},oe=async()=>{let ee=Ge.find(Oe=>Oe.id===yt)??Ge[Ge.length-1];try{return await navigator.clipboard.writeText(Mc(ee)),!0}catch{return!1}},se=null,ce=()=>{se?.();let ee=R.querySelector("svg"),Oe=Number(ee?.getAttribute("width"))||16,$e=Qe(ws.Check,Oe,"currentColor",2);if(!ee||!$e)return;ee.replaceWith($e);let pt=R.querySelector("span");pt&&(pt.textContent="Copied");let _t=setTimeout(()=>se?.(),2e3);se=()=>{clearTimeout(_t),$e.replaceWith(ee),pt&&(pt.textContent="Copy"),se=null}};R.addEventListener("click",async()=>{let ee=n?.onDocumentToolbarCopyMenuSelect;if(ee&&W){try{if(await ee(re("primary"))===!1){await oe()&&ce();return}ce()}catch{}return}await oe()&&ce()});async function we(ee){let Oe=n?.onDocumentToolbarCopyMenuSelect;try{if(Oe&&await Oe(re(ee))!==!1)return;if(ee==="download"){Y();return}let{markdown:$e,jsonPayload:pt}=K();ee==="markdown"||ee==="md"?await navigator.clipboard.writeText($e):ee==="json"||ee==="source"?await navigator.clipboard.writeText(pt):await navigator.clipboard.writeText($e||pt),ce()}catch{}}E.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Je()}),H.addEventListener("click",()=>{g(),e.onDismiss?.()});let ge=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),V?M.append(V,E,H):M.append(R,E,H),M.insertBefore(G,H),M.insertBefore(D,H),C.append(I.element,ge,M);else{let ee=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ee.append(R,G,D,T),C.appendChild(S),C.appendChild(ee)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let N=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");d&&N.style.setProperty("--persona-artifact-tab-fade-size",d);let ye=t.features?.artifacts?.renderTabBar,ke=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),nt=OM(N,{onSelect:ee=>e.onSelect(Ge[ee].id)}),Ee=ee=>{let Oe=ee.scrollWidth-ee.clientWidth,$e=Oe>1,pt=Math.abs(ee.scrollLeft);ee.classList.toggle("persona-artifact-tab-fade-start",u&&$e&&pt>1),ee.classList.toggle("persona-artifact-tab-fade-end",m&&$e&&pt<Oe-1)},Ne=0,Pe=()=>{if(Ne)return;let ee=()=>{Ne=0,Ee(N)};Ne=typeof requestAnimationFrame=="function"?requestAnimationFrame(ee):setTimeout(ee,0)};N.addEventListener("scroll",()=>Pe(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Ee(N)).observe(N);let dt=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Xe=()=>{dt.scrollLeft=0},xt=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Xe):setTimeout(Xe,0)};if(l){for(let ee of[N,ke])ee.style.paddingLeft=l,ee.style.paddingRight=l;dt.style.padding=l}b.appendChild(C),b.appendChild(N),b.appendChild(ke),b.appendChild(dt);let Ge=[],yt=null,X=!1,P=!1,j=!0,J=!1,Q=null,de="",Me=null,Te=!1,Fe=ee=>ee.artifactType==="markdown"&&!!ee.file||r?A:"rendered",je=ee=>{r||(ee&&!Te?(C.insertBefore(I.element,S),Te=!0):!ee&&Te&&(I.element.remove(),Te=!1))},lt=()=>yt&&Ge.find(ee=>ee.id===yt)||Ge[Ge.length-1],ot=()=>{let ee=Ac(lt());if(!ee){G.replaceChildren();return}let Oe=z.filter($e=>$e.visible===void 0||$e.visible(ee)).map($e=>La($e,{documentChrome:r,onClick:()=>{let pt=Ac(lt());if(pt)try{Promise.resolve($e.onClick(pt)).catch(()=>{})}catch{}}}));G.replaceChildren(...Oe)},Je=()=>{ot();let ee=r&&Ge.length<=1,Oe=!!ye;if(N.classList.toggle("persona-hidden",ee||Oe),ke.classList.toggle("persona-hidden",ee||!Oe),Oe&&ye){let _t=Ge.map(ve=>ve.id).join("|")+" "+(yt??"");if(_t!==de){de=_t;let ve=ye({records:Ge,selectedId:yt,onSelect:e.onSelect});ke.firstElementChild!==ve&&ke.replaceChildren(ve)}}else{nt.beforeRender(),N.replaceChildren();let _t=[],ve=-1;for(let[Se,Ke]of Ge.entries()){let ut=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ut.type="button";let vn=Ke.artifactType==="markdown"?Ke.file:void 0,Cn=vn?dr(vn.path):Ke.title||Ke.id.slice(0,8),wn=vn?.path||Ke.title||Cn;ut.textContent=Cn,ut.title=wn,ut.setAttribute("aria-label",wn),Ke.id===yt&&(ut.classList.add("persona-bg-persona-container","persona-border-persona-border"),ve=Se),ut.addEventListener("click",()=>e.onSelect(Ke.id)),N.appendChild(ut),_t.push(ut)}if(nt.render(_t,ve),ve>=0&&yt!==Q){Q=yt;let Se=_t[ve];typeof Se.scrollIntoView=="function"&&Se.scrollIntoView({block:"nearest",inline:"nearest"})}Ee(N)}let $e=yt&&Ge.find(_t=>_t.id===yt)||Ge[Ge.length-1];if(!$e){dt.replaceChildren(),Me?.destroy(),Me=null,je(!1);return}let pt=$e.artifactType==="markdown"?$e.file:void 0;if(je(!!pt&&gi(pt)!=="other"),r){let _t=pt?Cs(pt):$e.artifactType==="markdown"?"MD":$e.component??"Component",ve=($e.title||"Document").trim(),Se=pt?dr(pt.path):ve.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ge.textContent=`${Se} \xB7 ${_t}`}else S.textContent=pt?dr(pt.path):s;Me?(Me.el.parentElement!==dt&&dt.replaceChildren(Me.el),Me.update($e)):(Me=zu($e,{config:t,resolveViewMode:Fe}),dt.replaceChildren(Me.el)),dt.classList.toggle("persona-artifact-content-flush",!!dt.querySelector(".persona-code-pre"))},mt=()=>{let ee=Ge.length>0;if(b.classList.toggle("persona-hidden",!ee),y){let pt=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ee&&pt&&X?(y.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(y.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},Tt=()=>{J=!1,Je(),mt()};return{element:b,backdrop:y,update(ee){let Oe=ee.selectedId??ee.artifacts[ee.artifacts.length-1]?.id??null,$e=Oe!==yt;Ge=ee.artifacts,yt=Oe,Ge.length>0&&(X=!0),J=!0,j&&Tt(),$e&&Xe()},setMobileOpen(ee){X=ee,!ee&&y?(y.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):mt()},setExpanded(ee){ee!==P&&(P=ee,xt());let Oe=Qe(ee?ws.Minimize:ws.Maximize,16,"currentColor",2);Oe&&D.replaceChildren(Oe);let $e=ee?"Collapse artifacts panel":"Expand artifacts panel";D.setAttribute("aria-label",$e),D.title=$e},setExpandToggleVisible(ee){D.classList.toggle("persona-hidden",!ee)},setCopyButtonVisible(ee){r||R.classList.toggle("persona-hidden",!ee)},setRefreshButtonVisible(ee){E.classList.toggle("persona-hidden",!ee)},setCustomActions(ee){z=ee,ot()},setTabFade(ee){let Oe=p(ee);Oe.start===u&&Oe.end===m||(u=Oe.start,m=Oe.end,Ee(N))},setRenderTabBar(ee){ee!==ye&&(ye=ee,de="",Je())},setVisible(ee){ee!==j&&(j=ee,ee&&J&&Tt())},destroy(){Me?.destroy(),Me=null}}}var ws,_M=be(()=>{"use strict";Ye();hi();Nu();Uu();ws=require("lucide");ro();di();DM()});function NM(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?dr(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",a=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",d=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0,p=n?Cs(n):l==="component"?"Component":"Document",u=document.createElement("div");u.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",u.tabIndex=0,u.setAttribute("role","button"),u.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&u.setAttribute("data-open-artifact",s);let m=document.createElement("div");m.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",m.style.border="1px solid var(--persona-border, #e5e7eb)",m.style.color="var(--persona-muted, #9ca3af)",m.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let y=document.createElement("div");y.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let b=document.createElement("div");if(b.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",b.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=e?.config?.features?.artifacts,S={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{},...d?{presentation:d}:{}},T=Ia(S,C,"card");yi(b,T,C)}else s&&Pa(s),b.textContent=p;if(y.append(g,b),u.append(m,y),a==="complete"){let C=e?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let T={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let A of C)try{if(A.visible===void 0||A.visible(T)){let I=La(A);I.setAttribute("data-artifact-custom-action",A.id),I.className=`${I.className} persona-flex-shrink-0`,u.append(I)}}catch{}}let S=ci({label:"Download",className:"persona-flex-shrink-0"});S.title=`Download ${r}`,S.setAttribute("data-download-artifact",s),u.append(S)}return u}var Tc,jh=be(()=>{"use strict";hi();Fu();di();Nu();Tc=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>NM(t,e)});if(l)return l}return NM(t,e)}});function Kh(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=xs.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function Gh(t){return xs.has(t)}function dW(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete",r=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0;if(t.artifactType==="component"){let a=t.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:l,...r?{presentation:r}:{}}}let s=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function FM(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?dr(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?Cs(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function pW(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}function bW(t,e,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!e||!t.isConnected||s||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let a=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:VM,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let T of a)T.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let d=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!d||Math.abs(d-e)<1){l(),r();return}let p=Math.abs(e-d),u=Math.round(Math.min(gW,Math.max(fW,uW+p*mW))),m=Math.round(u*yW),y=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,g=y?y.animate([{opacity:0},{opacity:1}],{duration:$M,delay:m,easing:"ease-out",fill:"backwards"}):null,b=t.animate([{height:`${e}px`},{height:`${d}px`}],{duration:u,easing:hW});t.style.height=`${d}px`;let C=!1,S=()=>{C||(C=!0,l(),r())};Promise.allSettled([b.finished,g?.finished].filter(Boolean)).then(S),window.setTimeout(S,Math.max(u,m+$M)+120)},VM)}function vW(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}function CW(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,s=320,a=e?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",d=l==="clip"?!1:e?.followOutput!==!1,p,u,m=e?.fadeMask;m===!0?(p=!0,u=!0):m===!1?(p=!1,u=!1):m&&typeof m=="object"?(p=m.top===!0,u=m.bottom===!0):l==="clip"?(p=!1,u=!0):(p=!0,u=!0);let y=e?.transition==="none"?"none":"auto",g=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:d,overflow:l,fadeTop:p,fadeBottom:u,transition:y,completeDisplay:g}}function zM(t,e){let n=dW(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=vW(o),d=o?.inlineActions??[],p=CW(o),u=p.completeDisplay==="card",m=null,y=n,g=v("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let b=oe=>Tc(pW(oe),e),C=null,S=oe=>{C?.destroy(),C=null,g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(Ec),g.replaceChildren(b(oe)),xs.set(g,se=>{g.replaceChildren(b(se))})};if(u&&n.status==="complete")return S(n),g;let T=zu(n,{config:e.config,bodyLayout:p,resolveViewMode:()=>m??p.viewMode});C=T;let A=v("div","persona-artifact-inline-body");A.appendChild(T.el);let I=oe=>{let se=oe.status!=="complete",ce=se?p.streamingHeight:p.completeHeight,we=typeof ce=="number";we?g.style.setProperty(Ec,`${ce}px`):g.style.removeProperty(Ec);let ge=!!T.el.querySelector(".persona-code-pre"),N=!!T.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");A.classList.toggle("persona-artifact-content-flush",ge),A.classList.toggle("persona-artifact-inline-body--sized",we&&N),A.classList.toggle("persona-artifact-inline-body--cap",!se&&!N&&typeof p.completeHeight=="number")},M=n.status,O=(oe,se)=>{M!=="complete"&&oe.status==="complete"?(typeof p.completeHeight=="number"?g.style.setProperty(Ec,`${p.completeHeight}px`):g.style.removeProperty(Ec),BM(A,se?.suppressTransition?"none":p.transition,oe.id,()=>{T.update(oe),I(oe)})):T.update(oe),I(oe),M=oe.status};I(n);let k=p.overflow==="clip"&&a&&!!n.id;if(k&&(A.setAttribute("data-expand-artifact-inline",n.id),A.setAttribute("role","button"),A.setAttribute("tabindex","0"),A.classList.add("persona-cursor-pointer"),A.setAttribute("aria-label",`Open ${FM(n).title} in panel`)),!r)return g.appendChild(A),xs.set(g,O),g;let B=v("div","persona-artifact-inline-chrome");B.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let W=v("div","persona-artifact-inline-chrome-lead"),V=v("span","persona-flex persona-items-center persona-flex-shrink-0"),R=Qe(UM.FileText,16,"currentColor",2);R&&V.appendChild(R);let w=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),E=v("span","persona-artifact-inline-type");W.append(V,w,E);let H=v("div","persona-artifact-inline-chrome-actions"),D=v("span","persona-flex persona-items-center persona-gap-1"),G=()=>m??p.viewMode,z=l?bu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:G(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:oe=>{let se=oe==="source"?"source":"rendered";se!==G()&&(m=se,T.update(y),I(y))}}):null,K=s?gn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;K&&n.id&&K.setAttribute("data-copy-artifact",n.id);let Y=a?gn({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Y&&n.id&&Y.setAttribute("data-expand-artifact-inline",n.id),H.appendChild(D),z&&H.appendChild(z.element),K&&H.appendChild(K),Y&&H.appendChild(Y),B.append(W,H),g.append(B,A);let re=oe=>{let{title:se,typeLabel:ce}=FM(oe);w.textContent=se,w.title=se,k&&A.setAttribute("aria-label",`Open ${se} in panel`);let we=oe.status!=="complete";if(we){E.classList.contains("persona-artifact-inline-status")||(E.className="persona-artifact-inline-status",E.removeAttribute("data-preserve-animation"),E.replaceChildren());let ge=Ia(oe,o,"inline-chrome");yi(E,ge,o)}else Pa(oe.id),E.className="persona-artifact-inline-type",E.removeAttribute("data-preserve-animation"),E.replaceChildren(),E.textContent=ce;if(K&&K.classList.toggle("persona-hidden",we),z){let ge=oe.artifactType==="markdown"?oe.file:void 0,N=!1;if(!we&&ge&&p.viewMode!=="source"){let ye=gi(ge);ye==="markdown"?N=!0:(ye==="html"||ye==="svg")&&(N=o?.filePreview?.enabled!==!1)}z.element.classList.toggle("persona-hidden",!N),z.setSelected(G())}if(D.replaceChildren(),!we&&d.length>0){let ge=Ac(oe);if(ge)for(let N of d)try{if(N.visible===void 0||N.visible(ge)){let ye=La(N,{documentChrome:!0});ye.setAttribute("data-artifact-custom-action",N.id),ye.classList.add("persona-flex-shrink-0"),D.appendChild(ye)}}catch{}}};return re(n),xs.set(g,(oe,se)=>{if(u&&M!=="complete"&&oe.status==="complete"){let ce=g.isConnected?g.getBoundingClientRect().height:0;M="complete";let we=oe,ge=!1,N=ye=>{we=ye,ge=!0};xs.set(g,N),bW(g,ce,{swap:()=>{S(we),ge=!1,xs.set(g,N)},onSettled:()=>{ge?S(we):xs.set(g,ye=>{g.replaceChildren(b(ye))})}});return}(oe.status!=="complete"||oe.id!==y.id)&&(m=null),y=oe,O(oe,se),re(oe)}),g}var UM,xs,VM,uW,mW,fW,gW,hW,$M,yW,Ec,Yh,qM=be(()=>{"use strict";Ye();hi();Fu();Nu();di();UM=require("lucide");ro();Uu();jh();xs=new WeakMap;VM=180,uW=240,mW=.8,fW=300,gW=500,hW="cubic-bezier(0.2, 0, 0, 1)",$M=240,yW=.35;Ec="--persona-artifact-inline-body-height";Yh=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>zM(t,e)});if(l)return l}return zM(t,e)}});var jM=be(()=>{"use strict";_M();qM();jh();Uu();hi();zh();ti();wp()});var KM={};Vn(KM,{PersonaArtifactCard:()=>Tc,PersonaArtifactInline:()=>Yh,__provideMarkdownParsers:()=>_f,__setIconsExtraLoader:()=>mg,artifactCopyText:()=>Mc,createArtifactPane:()=>qh,downloadInfoFor:()=>xc,hasLiveInlineArtifactBlock:()=>Gh,initArtifactsUi:()=>$h,triggerArtifactDownload:()=>Sc,updateInlineArtifactBlocks:()=>Kh});var GM=be(()=>{"use strict";jM()});var Yu,sT,iT=be(()=>{"use strict";Ye();Yu={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},sT=(t,e,n,o)=>{let r=t.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=Yu[a]??Yu.init;s.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),p=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(p.textContent=l.title,d.appendChild(p),l.description){let b=v("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,d.appendChild(b)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let C=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${a}-${b.name}`;let S=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");S.textContent=b.label,C.appendChild(S);let T=b.type??"text",A;T==="textarea"?(A=document.createElement("textarea"),A.rows=3):(A=document.createElement("input"),A.type=T),A.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",A.id=`${e.id}-${a}-${b.name}`,A.name=b.name,A.placeholder=b.placeholder??"",b.required&&(A.required=!0),C.appendChild(A),u.appendChild(C)});let m=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=l.submitLabel??"Submit",m.appendChild(y),m.appendChild(g),u.appendChild(m),s.replaceChildren(d,u),u.addEventListener("submit",async b=>{b.preventDefault();let C=n.formEndpoint??"/form",S=new FormData(u),T={};S.forEach((A,I)=>{T[I]=A}),T.type=a,g.disabled=!0,y.textContent="Submitting\u2026";try{let A=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(T)});if(!A.ok)throw new Error(`Form submission failed (${A.status})`);let I=await A.json();y.textContent=I.message??"Thanks! We'll be in touch soon.",I.success&&I.nextPrompt&&await o.sendMessage(String(I.nextPrompt))}catch(A){y.textContent=A instanceof Error?A.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})}});var aT={};Vn(aT,{enhanceWithForms:()=>sT,formDefinitions:()=>Yu});var lT=be(()=>{"use strict";iT()});function vT(){let t=document.createElement("div");t.className="persona-history-sr-only",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t.setAttribute("data-persona-history-live-region","");let e;return{element:t,announce(n){e!==void 0&&clearTimeout(e),t.textContent="",e=setTimeout(()=>{e=void 0,t.textContent=n},0)},destroy(){e!==void 0&&clearTimeout(e),t.remove()}}}var CT=be(()=>{"use strict"});var wT,xT=be(()=>{"use strict";wT=`
242
+ `)),n=v("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function FT(t,e,n){let o=t.length<=fB?gB(e,n):null,r=o?SB(t,o):[{type:"plain",value:t}];return AB(r)}var mB,fB,um,hB,yB,bB,CB,wB,VT=be(()=>{"use strict";je();mB={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},fB=15e4,um={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};hB=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),yB=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:t=>hB.has(t)?"keyword":"plain"}];bB=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:t=>t==="true"||t==="false"||t==="null"?"keyword":"plain"}];CB=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];wB=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}]});var $T,Dy,zT,Oy=be(()=>{"use strict";$T=null,Dy=t=>{$T=t.componentRegistry},zT=()=>$T});function Vc(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?lm(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}function MB(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function UT(t,e,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(e!=="auto"||!t||typeof r!="function"||_y||s){o();return}_y=!0;let a=MB(n);t.style.setProperty("view-transition-name",a);let l=()=>{_y=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}function kB(t){let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=v("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(t.props??{},null,2),e.appendChild(n),e.appendChild(o),e}function PB(t){if(t===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let e=t&&typeof t=="object"?t:void 0;return{enabled:!0,delayMs:e?.delayMs??200,minVisibleMs:e?.minVisibleMs??300,timeoutMs:e?.timeoutMs??8e3,injectReadySignal:e?.injectReadySignal!==!1,label:e?.label===!1?!1:e?.label??"Starting preview...",labelDelayMs:e?.labelDelayMs??2e3,renderIndicator:e?.renderIndicator}}function IB(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(2);return crypto.getRandomValues(t),t[0].toString(36)+t[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function RB(t){return`
243
+ <script>(function(){var d=false;var t=`+JSON.stringify(t)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function HB(t,e,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:t,config:e});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(IT());let s=null;return n.label!==!1&&(s=v("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function WB(t,e,n,o,r,s){let a=null,l=0,c=!1,p=new Set,u=()=>{p.forEach(H=>clearTimeout(H)),p.clear()},m=(H,A)=>{let D=setTimeout(()=>{p.delete(D),!(typeof document>"u")&&H()},A);p.add(D)},g=()=>{a&&a.parentElement&&a.remove(),a=null},h=()=>{if(a||c)return;let H=HB(r,s,o);a=H.el,t.appendChild(a),l=Date.now(),o.label!==!1&&m(H.revealLabel,o.labelDelayMs)},b=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),m(g,LB))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",E):e.removeEventListener("load",T)},M=()=>{if(c||(c=!0,C(),u(),!a))return;let H=Math.max(0,o.minVisibleMs-(Date.now()-l));H>0?m(b,H):b()};function E(H){if(n===null)return;let A=H.data;!A||A.persona!=="artifact-preview-ready"||A.token!==n||H.source===e.contentWindow&&M()}function T(){let H=A=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>A()):setTimeout(A,0)};H(()=>H(()=>M()))}return m(h,o.delayMs),m(M,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",E):e.addEventListener("load",T),()=>{c=!0,u(),C(),g()}}function fm(t,e){let{config:n}=e,o=e.registry??zT()??Yo,r=e.bodyLayout,s=n.markdown?Pp(n.markdown):null,a=Ip(n.sanitize),l=t,c=!1,p=K=>{let ee=Ro()!==null;s&&!ee&&!c&&(c=!0,xa(()=>V(l)));let oe=s?s(K):$r(K);return s&&ee&&a?a(oe):oe},u=v("div","persona-artifact-preview-body"),m=null,g=null,h=null,b=()=>{h&&(h(),h=null),m=null,g=null},C=null,M=null,E=null,T=!1,H=()=>{C=null,M=null,E=null,T=!1},A=null,D=null,W=()=>{A=null,D=null},U=40,B=0,O=K=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>K()):setTimeout(K,0),R=K=>K.scrollHeight-K.clientHeight-K.scrollTop<=U,S=K=>{if(!r)return;let ee=K.scrollHeight-K.clientHeight>1,oe=K.scrollHeight-K.clientHeight-K.scrollTop;K.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ee&&K.scrollTop>1),K.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ee&&oe>1)},x=K=>{B||(B=O(()=>{B=0,K.scrollTop=K.scrollHeight,S(K)}))},P=(K,ee,oe,ne)=>{let le=!!r,de=oe.id+"|"+(le?"w":"p");if(!C||E!==de||C.parentElement!==u){b(),W(),u.replaceChildren();let se=v("pre",TB+" persona-code-pre"),_=v("code","persona-code");if(se.appendChild(_),le){let Te=v("div","persona-artifact-source-window");if(Te.appendChild(se),u.appendChild(Te),!(r?.overflow==="clip")&&typeof Te.addEventListener=="function"){let ut=()=>Te.scrollHeight-Te.clientHeight>1;Te.addEventListener("scroll",()=>{R(Te)&&(T=!1),S(Te)},{passive:!0}),Te.addEventListener("wheel",At=>{ut()&&At.deltaY<0&&(T=!0)},{passive:!0}),Te.addEventListener("touchmove",()=>{ut()&&(T=!0)},{passive:!0})}C=Te}else u.appendChild(se),C=se;M=_,E=de}let ve=le?C:null;ve&&(ve.classList.toggle("persona-artifact-source-window--fixed",ne),ve.classList.toggle("persona-artifact-source-window--clip",ne&&r?.overflow==="clip"));let Le=ve?R(ve):!0;if(M.replaceChildren(FT(K,ee?.language,ee?.path)),ve){let se=oe.status!=="complete";ne&&se&&r?.followOutput&&!T&&Le?x(ve):se||(T=!1),S(ve)}},L=K=>{b(),H(),W(),u.replaceChildren();let ee=v("div",EB);ee.innerHTML=p(K),u.appendChild(ee)},G=K=>{let ee=K.id,oe=n.features?.artifacts,ne=Ga(K,oe,"status-body");if(A&&D===ee&&A.parentElement===u){let ve=A.querySelector(".persona-artifact-status-view-text");ve&&_i(ve,ne,oe);return}b(),H(),u.replaceChildren();let le=v("div","persona-artifact-status-view"),de=v("div","persona-artifact-status-view-text");_i(de,ne,oe),le.appendChild(de),u.appendChild(le),A=le,D=ee},V=K=>{l=K;let ee=e.resolveViewMode?.(K)??r?.viewMode??"rendered",oe=K.artifactType==="markdown"?K.file:void 0,ne=K.status!=="complete";ne||Ka(K.id);let le=ne?r?.streamingHeight:r?.completeHeight,de=!!r&&typeof le=="number";if(r?.streamingView==="status"&&ne){G(K);return}if(oe){let Le=lm(K.markdown??""),se=Di(oe),_=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ne&&ee==="rendered"&&_&&(se==="html"||se==="svg")){let He=K.id+"\0"+Le;if(m&&g===He&&m.parentElement===u)return;H(),W(),b(),u.replaceChildren();let ut=n.features?.artifacts?.filePreview,At=ut?.iframeSandbox??"allow-scripts";!ut?.dangerouslyAllowSameOrigin&&At.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),At=At.split(/\s+/).filter(Ae=>Ae&&Ae!=="allow-same-origin").join(" "));let Wt=PB(ut?.loading),bt=v("div","persona-artifact-frame"),xe=v("iframe","persona-artifact-iframe");xe.setAttribute("sandbox",At),xe.setAttribute("data-artifact-id",K.id);let Ne=null;Wt.enabled&&Wt.injectReadySignal?(Ne=IB(),xe.srcdoc=Le+RB(Ne)):xe.srcdoc=Le,bt.appendChild(xe),u.appendChild(bt),Wt.enabled&&(h=WB(bt,xe,Ne,Wt,K.id,n)),m=bt,g=He;return}if(b(),!ne&&se==="markdown"&&ee==="rendered"){L(Le);return}P(Le,{language:oe.language,path:oe.path},K,de);return}if(K.artifactType==="markdown"){if(ee==="source"){b(),P(K.markdown??"",void 0,K,de);return}L(K.markdown??"");return}b(),H(),W(),u.replaceChildren();let ve=K.component?o.get(K.component):void 0;if(ve){let se={message:{id:K.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let _=ve(K.props??{},se);if(_){u.appendChild(_);return}}catch{}}u.appendChild(kB(K))};return V(t),{el:u,update(K){V(K)},destroy(){b()}}}var _y,TB,EB,LB,gm=be(()=>{"use strict";je();RT();Oi();pm();VT();Lp();Si();Ig();Oc();Oy();_y=!1;TB="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",EB="persona-text-sm persona-leading-relaxed persona-markdown-bubble";LB=220});function qT(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.setAttribute("role","tablist");let s=[],a=!1,l=m=>{typeof m.scrollIntoView=="function"&&m.scrollIntoView({block:"nearest",inline:"nearest"})},c=m=>{let g=m;return s.findIndex(h=>h===g||h.contains(g))},p=m=>{let g=c(m.target);if(g<0)return;let h=g;if(m.key===r)h=Math.min(g+1,s.length-1);else if(m.key===o)h=Math.max(g-1,0);else if(m.key==="Home")h=0;else if(m.key==="End")h=s.length-1;else return;m.preventDefault(),h!==g&&e.onSelect(h)},u=m=>{let g=c(m.target);g>=0&&l(s[g])};return t.addEventListener("keydown",p),t.addEventListener("focusin",u),{beforeRender(){a=typeof document<"u"&&t.contains(document.activeElement)},render(m,g){if(s=m,m.forEach((h,b)=>{h.setAttribute("role","tab");let C=b===g;h.setAttribute("aria-selected",C?"true":"false"),h.tabIndex=C||g<0&&b===0?0:-1}),a){let h=(g>=0?m[g]:void 0)??m[0];h&&typeof h.focus=="function"&&(l(h),h.focus())}},destroy(){t.removeEventListener("keydown",p),t.removeEventListener("focusin",u)}}}var jT=be(()=>{"use strict"});function Ny(t,e){let n=t.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),c=n?.tabFadeSize?.trim(),p=Z=>({start:Z===!1?!1:typeof Z=="object"&&Z?Z.start!==!1:!0,end:Z===!1?!1:typeof Z=="object"&&Z?Z.end!==!1:!0}),{start:u,end:m}=p(n?.tabFade),g=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,h=()=>{g?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),S?.closeMenu()};g&&g.addEventListener("click",()=>{h(),e.onDismiss?.()});let b=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let C=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let M=v("span","persona-text-xs persona-font-medium persona-truncate");M.textContent=s;let E=vn({icon:"x",label:a});E.addEventListener("click",()=>{h(),e.onDismiss?.()});let T="rendered",H=Yu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:Z=>{T=Z==="source"?"source":"rendered",Ze()}}),A=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=n?.documentToolbarShowCopyLabel===!0,W=n?.documentToolbarShowCopyChevron===!0,U=n?.documentToolbarCopyMenuItems,B=!!(W&&U&&U.length>0),O=null,R,S=null;if(r&&(D||W)&&!B){if(R=D?Li({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let Z=Ge(Bs.ChevronDown,14,"currentColor",2);Z&&R.appendChild(Z)}}else r&&B?(S=PM({label:"Copy",icon:"copy",iconSize:14,iconOnly:!D,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(U??[]).map(Z=>({id:Z.id,label:Z.label})),position:"bottom-right",portal:()=>b.closest("[data-persona-root]")??document.body,onSelect:Z=>{ve(Z)}}),O=S.element,R=S.primaryButton):r?R=vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(R=vn({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&R.classList.add("persona-hidden"));let x=r?vn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):vn({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||x.classList.add("persona-hidden");let P=r?vn({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):vn({icon:"x",label:a}),L=vn({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&L.classList.add("persona-hidden");let G=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),V=t.features?.artifacts?.toolbarActions??[],K=()=>{let Z=Ae.find(qe=>qe.id===vt)??Ae[Ae.length-1],Fe=Z?.id??null,Re=Z?.artifactType==="markdown"?Z.markdown??"":"",nt=Z?JSON.stringify({component:Z.component,props:Z.props},null,2):"",{filename:Bt,mime:Ie,content:Be}=_c({title:Z?.title,markdown:Z?.markdown??"",file:Z?.file});return{markdown:Re,jsonPayload:nt,id:Fe,file:Z?.file,suggestedFilename:Bt,mime:Ie,content:Be}},ee=()=>{let{suggestedFilename:Z,mime:Fe,content:Re}=K();Re&&Nc({filename:Z,mime:Fe,content:Re})},oe=Z=>{let{id:Fe,...Re}=K();return{actionId:Z,artifactId:Fe,...Re}},ne=async()=>{let Z=Ae.find(Fe=>Fe.id===vt)??Ae[Ae.length-1];try{return await navigator.clipboard.writeText(Vc(Z)),!0}catch{return!1}},le=null,de=()=>{le?.();let Z=R.querySelector("svg"),Fe=Number(Z?.getAttribute("width"))||16,Re=Ge(Bs.Check,Fe,"currentColor",2);if(!Z||!Re)return;Z.replaceWith(Re);let nt=R.querySelector("span");nt&&(nt.textContent="Copied");let Bt=setTimeout(()=>le?.(),2e3);le=()=>{clearTimeout(Bt),Re.replaceWith(Z),nt&&(nt.textContent="Copy"),le=null}};R.addEventListener("click",async()=>{let Z=n?.onDocumentToolbarCopyMenuSelect;if(Z&&B){try{if(await Z(oe("primary"))===!1){await ne()&&de();return}de()}catch{}return}await ne()&&de()});async function ve(Z){let Fe=n?.onDocumentToolbarCopyMenuSelect;try{if(Fe&&await Fe(oe(Z))!==!1)return;if(Z==="download"){ee();return}let{markdown:Re,jsonPayload:nt}=K();Z==="markdown"||Z==="md"?await navigator.clipboard.writeText(Re):Z==="json"||Z==="source"?await navigator.clipboard.writeText(nt):await navigator.clipboard.writeText(Re||nt),de()}catch{}}x.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Ze()}),P.addEventListener("click",()=>{h(),e.onDismiss?.()});let Le=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),O?A.append(O,x,P):A.append(R,x,P),A.insertBefore(G,P),A.insertBefore(L,P),C.append(H.element,Le,A);else{let Z=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");Z.append(R,G,L,E),C.appendChild(M),C.appendChild(Z)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let se=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");c&&se.style.setProperty("--persona-artifact-tab-fade-size",c);let _=t.features?.artifacts?.renderTabBar,Te=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),He=qT(se,{onSelect:Z=>e.onSelect(Ae[Z].id)}),ut=Z=>{let Fe=Z.scrollWidth-Z.clientWidth,Re=Fe>1,nt=Math.abs(Z.scrollLeft);Z.classList.toggle("persona-artifact-tab-fade-start",u&&Re&&nt>1),Z.classList.toggle("persona-artifact-tab-fade-end",m&&Re&&nt<Fe-1)},At=0,Wt=()=>{if(At)return;let Z=()=>{At=0,ut(se)};At=typeof requestAnimationFrame=="function"?requestAnimationFrame(Z):setTimeout(Z,0)};se.addEventListener("scroll",()=>Wt(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ut(se)).observe(se);let bt=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),xe=()=>{bt.scrollLeft=0},Ne=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(xe):setTimeout(xe,0)};if(l){for(let Z of[se,Te])Z.style.paddingLeft=l,Z.style.paddingRight=l;bt.style.padding=l}b.appendChild(C),b.appendChild(se),b.appendChild(Te),b.appendChild(bt);let Ae=[],vt=null,X=!1,I=!1,j=!0,J=!1,Y=null,ie="",Me=null,Ee=!1,Oe=Z=>Z.artifactType==="markdown"&&!!Z.file||r?T:"rendered",Ct=Z=>{r||(Z&&!Ee?(C.insertBefore(H.element,M),Ee=!0):!Z&&Ee&&(H.element.remove(),Ee=!1))},Ot=()=>vt&&Ae.find(Z=>Z.id===vt)||Ae[Ae.length-1],rt=()=>{let Z=Fc(Ot());if(!Z){G.replaceChildren();return}let Fe=V.filter(Re=>Re.visible===void 0||Re.visible(Z)).map(Re=>ja(Re,{documentChrome:r,onClick:()=>{let nt=Fc(Ot());if(nt)try{Promise.resolve(Re.onClick(nt)).catch(()=>{})}catch{}}}));G.replaceChildren(...Fe)},Ze=()=>{rt();let Z=r&&Ae.length<=1,Fe=!!_;if(se.classList.toggle("persona-hidden",Z||Fe),Te.classList.toggle("persona-hidden",Z||!Fe),Fe&&_){let Bt=Ae.map(Ie=>Ie.id).join("|")+" "+(vt??"");if(Bt!==ie){ie=Bt;let Ie=_({records:Ae,selectedId:vt,onSelect:e.onSelect});Te.firstElementChild!==Ie&&Te.replaceChildren(Ie)}}else{He.beforeRender(),se.replaceChildren();let Bt=[],Ie=-1;for(let[Be,qe]of Ae.entries()){let Tt=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");Tt.type="button";let mt=qe.artifactType==="markdown"?qe.file:void 0,xt=mt?vr(mt.path):qe.title||qe.id.slice(0,8),Mn=mt?.path||qe.title||xt;Tt.textContent=xt,Tt.title=Mn,Tt.setAttribute("aria-label",Mn),qe.id===vt&&(Tt.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ie=Be),Tt.addEventListener("click",()=>e.onSelect(qe.id)),se.appendChild(Tt),Bt.push(Tt)}if(He.render(Bt,Ie),Ie>=0&&vt!==Y){Y=vt;let Be=Bt[Ie];typeof Be.scrollIntoView=="function"&&Be.scrollIntoView({block:"nearest",inline:"nearest"})}ut(se)}let Re=vt&&Ae.find(Bt=>Bt.id===vt)||Ae[Ae.length-1];if(!Re){bt.replaceChildren(),Me?.destroy(),Me=null,Ct(!1);return}let nt=Re.artifactType==="markdown"?Re.file:void 0;if(Ct(!!nt&&Di(nt)!=="other"),r){let Bt=nt?Ws(nt):Re.artifactType==="markdown"?"MD":Re.component??"Component",Ie=(Re.title||"Document").trim(),Be=nt?vr(nt.path):Ie.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Le.textContent=`${Be} \xB7 ${Bt}`}else M.textContent=nt?vr(nt.path):s;Me?(Me.el.parentElement!==bt&&bt.replaceChildren(Me.el),Me.update(Re)):(Me=fm(Re,{config:t,resolveViewMode:Oe}),bt.replaceChildren(Me.el)),bt.classList.toggle("persona-artifact-content-flush",!!bt.querySelector(".persona-code-pre"))},ct=()=>{let Z=Ae.length>0;if(b.classList.toggle("persona-hidden",!Z),g){let nt=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;Z&&nt&&X?(g.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(g.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},Rt=()=>{J=!1,Ze(),ct()};return{element:b,backdrop:g,update(Z){let Fe=Z.selectedId??Z.artifacts[Z.artifacts.length-1]?.id??null,Re=Fe!==vt;Ae=Z.artifacts,vt=Fe,Ae.length>0&&(X=!0),J=!0,j&&Rt(),Re&&xe()},setMobileOpen(Z){X=Z,!Z&&g?(g.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):ct()},setExpanded(Z){Z!==I&&(I=Z,Ne());let Fe=Ge(Z?Bs.Minimize:Bs.Maximize,16,"currentColor",2);Fe&&L.replaceChildren(Fe);let Re=Z?"Collapse artifacts panel":"Expand artifacts panel";L.setAttribute("aria-label",Re),L.title=Re},setExpandToggleVisible(Z){L.classList.toggle("persona-hidden",!Z)},setCopyButtonVisible(Z){r||R.classList.toggle("persona-hidden",!Z)},setRefreshButtonVisible(Z){x.classList.toggle("persona-hidden",!Z)},setCustomActions(Z){V=Z,rt()},setTabFade(Z){let Fe=p(Z);Fe.start===u&&Fe.end===m||(u=Fe.start,m=Fe.end,ut(se))},setRenderTabBar(Z){Z!==_&&(_=Z,ie="",Ze())},setVisible(Z){Z!==j&&(j=Z,Z&&J&&Rt())},destroy(){Me?.destroy(),Me=null}}}var Bs,KT=be(()=>{"use strict";je();Oi();dm();gm();Bs=require("lucide");zn();Ii();jT()});function GT(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?vr(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",a=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",c=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0,p=n?Ws(n):l==="component"?"Component":"Document",u=document.createElement("div");u.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",u.tabIndex=0,u.setAttribute("role","button"),u.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&u.setAttribute("data-open-artifact",s);let m=document.createElement("div");m.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",m.style.border="1px solid var(--persona-border, #e5e7eb)",m.style.color="var(--persona-muted, #9ca3af)",m.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let g=document.createElement("div");g.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let h=document.createElement("div");h.className="persona-truncate persona-text-sm persona-font-medium",h.style.color="var(--persona-text, #1f2937)",h.textContent=r;let b=document.createElement("div");if(b.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",b.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=e?.config?.features?.artifacts,M={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{},...c?{presentation:c}:{}},E=Ga(M,C,"card");_i(b,E,C)}else s&&Ka(s),b.textContent=p;if(g.append(h,b),u.append(m,g),a==="complete"){let C=e?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let E={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let T of C)try{if(T.visible===void 0||T.visible(E)){let H=ja(T);H.setAttribute("data-artifact-custom-action",T.id),H.className=`${H.className} persona-flex-shrink-0`,u.append(H)}}catch{}}let M=Li({label:"Download",className:"persona-flex-shrink-0"});M.title=`Download ${r}`,M.setAttribute("data-download-artifact",s),u.append(M)}return u}var $c,Fy=be(()=>{"use strict";Oi();pm();Ii();dm();$c=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>GT(t,e)});if(l)return l}return GT(t,e)}});function Vy(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=Ds.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function $y(t){return Ds.has(t)}function BB(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete",r=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0;if(t.artifactType==="component"){let a=t.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:l,...r?{presentation:r}:{}}}let s=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function YT(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?vr(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?Ws(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function DB(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}function zB(t,e,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!e||!t.isConnected||s||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let a=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:QT,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let E of a)E.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let c=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!c||Math.abs(c-e)<1){l(),r();return}let p=Math.abs(e-c),u=Math.round(Math.min(FB,Math.max(NB,OB+p*_B))),m=Math.round(u*$B),g=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,h=g?g.animate([{opacity:0},{opacity:1}],{duration:XT,delay:m,easing:"ease-out",fill:"backwards"}):null,b=t.animate([{height:`${e}px`},{height:`${c}px`}],{duration:u,easing:VB});t.style.height=`${c}px`;let C=!1,M=()=>{C||(C=!0,l(),r())};Promise.allSettled([b.finished,h?.finished].filter(Boolean)).then(M),window.setTimeout(M,Math.max(u,m+XT)+120)},QT)}function UB(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}function qB(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,s=320,a=e?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",c=l==="clip"?!1:e?.followOutput!==!1,p,u,m=e?.fadeMask;m===!0?(p=!0,u=!0):m===!1?(p=!1,u=!1):m&&typeof m=="object"?(p=m.top===!0,u=m.bottom===!0):l==="clip"?(p=!1,u=!0):(p=!0,u=!0);let g=e?.transition==="none"?"none":"auto",h=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:c,overflow:l,fadeTop:p,fadeBottom:u,transition:g,completeDisplay:h}}function JT(t,e){let n=BB(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=UB(o),c=o?.inlineActions??[],p=qB(o),u=p.completeDisplay==="card",m=null,g=n,h=v("div","persona-artifact-inline persona-w-full persona-max-w-full");h.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&h.setAttribute("data-artifact-inline",n.id);let b=ne=>$c(DB(ne),e),C=null,M=ne=>{C?.destroy(),C=null,h.classList.add("persona-artifact-inline--card"),h.style.removeProperty(zc),h.replaceChildren(b(ne)),Ds.set(h,le=>{h.replaceChildren(b(le))})};if(u&&n.status==="complete")return M(n),h;let E=fm(n,{config:e.config,bodyLayout:p,resolveViewMode:()=>m??p.viewMode});C=E;let T=v("div","persona-artifact-inline-body");T.appendChild(E.el);let H=ne=>{let le=ne.status!=="complete",de=le?p.streamingHeight:p.completeHeight,ve=typeof de=="number";ve?h.style.setProperty(zc,`${de}px`):h.style.removeProperty(zc);let Le=!!E.el.querySelector(".persona-code-pre"),se=!!E.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");T.classList.toggle("persona-artifact-content-flush",Le),T.classList.toggle("persona-artifact-inline-body--sized",ve&&se),T.classList.toggle("persona-artifact-inline-body--cap",!le&&!se&&typeof p.completeHeight=="number")},A=n.status,D=(ne,le)=>{A!=="complete"&&ne.status==="complete"?(typeof p.completeHeight=="number"?h.style.setProperty(zc,`${p.completeHeight}px`):h.style.removeProperty(zc),UT(T,le?.suppressTransition?"none":p.transition,ne.id,()=>{E.update(ne),H(ne)})):E.update(ne),H(ne),A=ne.status};H(n);let W=p.overflow==="clip"&&a&&!!n.id;if(W&&(T.setAttribute("data-expand-artifact-inline",n.id),T.setAttribute("role","button"),T.setAttribute("tabindex","0"),T.classList.add("persona-cursor-pointer"),T.setAttribute("aria-label",`Open ${YT(n).title} in panel`)),!r)return h.appendChild(T),Ds.set(h,D),h;let U=v("div","persona-artifact-inline-chrome");U.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let B=v("div","persona-artifact-inline-chrome-lead"),O=v("span","persona-flex persona-items-center persona-flex-shrink-0"),R=Ge(ZT.FileText,16,"currentColor",2);R&&O.appendChild(R);let S=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),x=v("span","persona-artifact-inline-type");B.append(O,S,x);let P=v("div","persona-artifact-inline-chrome-actions"),L=v("span","persona-flex persona-items-center persona-gap-1"),G=()=>m??p.viewMode,V=l?Yu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:G(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ne=>{let le=ne==="source"?"source":"rendered";le!==G()&&(m=le,E.update(g),H(g))}}):null,K=s?vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;K&&n.id&&K.setAttribute("data-copy-artifact",n.id);let ee=a?vn({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ee&&n.id&&ee.setAttribute("data-expand-artifact-inline",n.id),P.appendChild(L),V&&P.appendChild(V.element),K&&P.appendChild(K),ee&&P.appendChild(ee),U.append(B,P),h.append(U,T);let oe=ne=>{let{title:le,typeLabel:de}=YT(ne);S.textContent=le,S.title=le,W&&T.setAttribute("aria-label",`Open ${le} in panel`);let ve=ne.status!=="complete";if(ve){x.classList.contains("persona-artifact-inline-status")||(x.className="persona-artifact-inline-status",x.removeAttribute("data-preserve-animation"),x.replaceChildren());let Le=Ga(ne,o,"inline-chrome");_i(x,Le,o)}else Ka(ne.id),x.className="persona-artifact-inline-type",x.removeAttribute("data-preserve-animation"),x.replaceChildren(),x.textContent=de;if(K&&K.classList.toggle("persona-hidden",ve),V){let Le=ne.artifactType==="markdown"?ne.file:void 0,se=!1;if(!ve&&Le&&p.viewMode!=="source"){let _=Di(Le);_==="markdown"?se=!0:(_==="html"||_==="svg")&&(se=o?.filePreview?.enabled!==!1)}V.element.classList.toggle("persona-hidden",!se),V.setSelected(G())}if(L.replaceChildren(),!ve&&c.length>0){let Le=Fc(ne);if(Le)for(let se of c)try{if(se.visible===void 0||se.visible(Le)){let _=ja(se,{documentChrome:!0});_.setAttribute("data-artifact-custom-action",se.id),_.classList.add("persona-flex-shrink-0"),L.appendChild(_)}}catch{}}};return oe(n),Ds.set(h,(ne,le)=>{if(u&&A!=="complete"&&ne.status==="complete"){let de=h.isConnected?h.getBoundingClientRect().height:0;A="complete";let ve=ne,Le=!1,se=_=>{ve=_,Le=!0};Ds.set(h,se),zB(h,de,{swap:()=>{M(ve),Le=!1,Ds.set(h,se)},onSettled:()=>{Le?M(ve):Ds.set(h,_=>{h.replaceChildren(b(_))})}});return}(ne.status!=="complete"||ne.id!==g.id)&&(m=null),g=ne,D(ne,le),oe(ne)}),h}var ZT,Ds,QT,OB,_B,NB,FB,VB,XT,$B,zc,zy,eE=be(()=>{"use strict";je();Oi();pm();dm();Ii();ZT=require("lucide");zn();gm();Fy();Ds=new WeakMap;QT=180,OB=240,_B=.8,NB=300,FB=500,VB="cubic-bezier(0.2, 0, 0, 1)",XT=240,$B=.35;zc="--persona-artifact-inline-body-height";zy=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>JT(t,e)});if(l)return l}return JT(t,e)}});var tE=be(()=>{"use strict";KT();eE();Fy();gm();Oi();Oy();Si();yp()});var nE={};$n(nE,{PersonaArtifactCard:()=>$c,PersonaArtifactInline:()=>zy,__provideMarkdownParsers:()=>Pg,__setIconsExtraLoader:()=>Sg,artifactCopyText:()=>Vc,createArtifactPane:()=>Ny,downloadInfoFor:()=>_c,hasLiveInlineArtifactBlock:()=>$y,initArtifactsUi:()=>Dy,triggerArtifactDownload:()=>Nc,updateInlineArtifactBlocks:()=>Vy});var oE=be(()=>{"use strict";tE()});var Cm,fE,gE=be(()=>{"use strict";je();Cm={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},fE=(t,e,n,o)=>{let r=t.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=Cm[a]??Cm.init;s.classList.add("persona-form-card","persona-space-y-4");let c=v("div","persona-space-y-1"),p=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(p.textContent=l.title,c.appendChild(p),l.description){let b=v("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,c.appendChild(b)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let C=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${a}-${b.name}`;let M=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=b.label,C.appendChild(M);let E=b.type??"text",T;E==="textarea"?(T=document.createElement("textarea"),T.rows=3):(T=document.createElement("input"),T.type=E),T.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",T.id=`${e.id}-${a}-${b.name}`,T.name=b.name,T.placeholder=b.placeholder??"",b.required&&(T.required=!0),C.appendChild(T),u.appendChild(C)});let m=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),h=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");h.type="submit",h.textContent=l.submitLabel??"Submit",m.appendChild(g),m.appendChild(h),u.appendChild(m),s.replaceChildren(c,u),u.addEventListener("submit",async b=>{b.preventDefault();let C=n.formEndpoint??"/form",M=new FormData(u),E={};M.forEach((T,H)=>{E[H]=T}),E.type=a,h.disabled=!0,g.textContent="Submitting\u2026";try{let T=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let H=await T.json();g.textContent=H.message??"Thanks! We'll be in touch soon.",H.success&&H.nextPrompt&&await o.sendMessage(String(H.nextPrompt))}catch(T){g.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{h.disabled=!1}})})}});var hE={};$n(hE,{enhanceWithForms:()=>fE,formDefinitions:()=>Cm});var yE=be(()=>{"use strict";gE()});function kE(){let t=document.createElement("div");t.className="persona-history-sr-only",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t.setAttribute("data-persona-history-live-region","");let e;return{element:t,announce(n){e!==void 0&&clearTimeout(e),t.textContent="",e=setTimeout(()=>{e=void 0,t.textContent=n},0)},destroy(){e!==void 0&&clearTimeout(e),t.remove()}}}var PE=be(()=>{"use strict"});var LE,IE=be(()=>{"use strict";LE=`
244
244
  .persona-history-view {
245
245
  --persona-history-surface-bg: var(--persona-surface, #ffffff);
246
246
  --persona-history-topbar-bg: var(--persona-header-bg, var(--persona-surface, #ffffff));
@@ -1137,25 +1137,25 @@ ${e}
1137
1137
  .persona-history-view .persona-history-skeleton-bar { animation: none; }
1138
1138
  .persona-history-rail-host { transition: none; }
1139
1139
  }
1140
- `});function ly(t){if(!t)return Qu;let e={...Qu};for(let n of QW){let o=t[n];typeof o=="string"&&o.length>0&&(e[n]=o)}return e}var QW,Qu,cy=be(()=>{"use strict";QW=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],Qu={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."}});function Hc(t){if(!t)return Ic;let e={...Ic};for(let[n,o]of Object.entries(t))typeof o=="string"&&o.length>0&&(e[n]=o);return e}function ur(t,e){return t.replace(/\{(\w+)\}/g,(n,o)=>o in e?String(e[o]):n)}var Ic,Rc=be(()=>{"use strict";cy();Ic={...Qu,emptyTitle:"No conversations yet",emptyDescription:"Start a conversation and it will show up here.",errorTitle:"Could not load conversations",errorDescription:"Something went wrong. Please try again.",retryLabel:"Retry",rateLimitedTitle:"Too many requests",rateLimitedDescription:"Please wait a moment before trying again.",groupStarred:"Starred",groupToday:"Today",groupYesterday:"Yesterday",groupPrevious7Days:"Previous 7 days",groupPrevious30Days:"Previous 30 days",groupMonthYear:"{month} {year}",browserOnlyTitle:"On this device",browserOnlyDescription:"Another browser or device keeps its own separate history.",verifyingTitle:"Checking your account",verifyingDescription:"Looking for messages linked to your account.",verifiedTitle:"Available across signed-in devices",verifiedDescription:"This list refreshes when the chat opens rather than syncing live.",authenticationRequiredTitle:"Sign in to see your messages",authenticationRequiredDescription:"Your session expired. Sign in again to load account history.",identityProviderFailedTitle:"Account history is unavailable",identityProviderFailedDescription:"We could not verify your account, so account history is not shown here.",proofNotAdmittedTitle:"Account history is unavailable",proofNotAdmittedDescription:"This assistant is not set up to accept your account identity.",retryIdentityLabel:"Try again",backLabel:"Back to conversation",closeLabel:"Close conversation list",loadingLabel:"Loading conversations",loadMoreLabel:"Load more",loadingMoreLabel:"Loading more conversations",conversationsTitle:"Conversations",rowActionsLabel:"Conversation options",listOptionsLabel:"Conversation options",deleteConversationLabel:"Delete",clearHistoryLabel:"Delete all conversations",resetIdentityLabel:"Forget this device",messageCountLabel:"{count} messages",messageCountLabelOne:"1 message",conversationRemovedNotice:"Conversation deleted.",historyClearedNotice:"All conversations were deleted.",unavailableTitle:"Conversation history is unavailable",unavailableDescription:"Try again later.",newConversationRequiredTitle:"Start a new conversation",newConversationRequiredDescription:"The previous conversation is gone. Start a new one to keep chatting.",rateLimitedWaitDescription:"You can try again in {seconds} seconds.",openFailedLabel:"Could not open that conversation.",deleteFailedLabel:"Could not delete that conversation.",relativeNow:"now",relativeMinutes:"{value}m",relativeHours:"{value}h",relativeDays:"{value}d",relativeWeeks:"{value}w",relativeYears:"{value}y"}});function XW(t){let e=new Date(t);return e.setHours(0,0,0,0),e.getTime()}function py(t,e){let n=Date.parse(t);return Number.isFinite(n)?n:e}function JW(t,e){let n=py(t,e),o=XW(e);if(n>=o)return"today";if(n>=o-dy)return"yesterday";if(n>=o-7*dy)return"previous-7-days";if(n>=o-30*dy)return"previous-30-days";let r=new Date(n);return`month:${r.getFullYear()}-${r.getMonth()}`}function ZW(t,e,n,o){if(t==="today")return o.groupToday;if(t==="yesterday")return o.groupYesterday;if(t==="previous-7-days")return o.groupPrevious7Days;if(t==="previous-30-days")return o.groupPrevious30Days;let r=new Date(py(e,n));return ur(o.groupMonthYear,{month:r.toLocaleString(void 0,{month:"long"}),year:r.getFullYear()})}function ST(t,e,n,o="time"){let r=t.filter(a=>a.starred),s=r.length>0?[{key:"starred",label:n.groupStarred,items:r}]:[];if(o==="none"){let a=t.filter(l=>!l.starred);return a.length>0&&s.push({key:"recent",label:n.conversationsTitle,items:a}),s}for(let a of t){if(a.starred)continue;let l=JW(a.updatedAt,e),d=s[s.length-1];if(d&&d.key===l){d.items.push(a);continue}s.push({key:l,label:ZW(l,a.updatedAt,e,n),items:[a]})}return s}function AT(t,e,n){let o=Math.max(0,e-py(t,e)),r=Math.floor(o/6e4);if(r<1)return n.relativeNow;if(r<60)return ur(n.relativeMinutes,{value:r});let s=Math.floor(r/60);if(s<24)return ur(n.relativeHours,{value:s});let a=Math.floor(s/24);if(a<7)return ur(n.relativeDays,{value:a});let l=Math.floor(a/7);return a<365?ur(n.relativeWeeks,{value:l}):ur(n.relativeYears,{value:Math.floor(a/365)})}function MT(t,e){return t===1?e.messageCountLabelOne:ur(e.messageCountLabel,{count:t})}var dy,uy=be(()=>{"use strict";Rc();dy=864e5});function Ss(t,e=20){let n=document.createElementNS(Xu,"svg");if(n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","2"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),t==="ellipsis"){for(let r of[12,19,5]){let s=document.createElementNS(Xu,"circle");s.setAttribute("cx",String(r)),s.setAttribute("cy","12"),s.setAttribute("r","1"),n.appendChild(s)}return n}let o=tB[t];if(o){let r=document.createElementNS(Xu,"rect");r.setAttribute("x",String(o[0])),r.setAttribute("y",String(o[1])),r.setAttribute("width",String(o[2])),r.setAttribute("height",String(o[3])),r.setAttribute("rx","2"),n.appendChild(r)}for(let r of eB[t]){let s=document.createElementNS(Xu,"path");s.setAttribute("d",r),n.appendChild(s)}return n}var Xu,eB,tB,my=be(()=>{"use strict";Xu="http://www.w3.org/2000/svg",eB={"arrow-left":["m12 19-7-7 7-7","M19 12H5"],plus:["M5 12h14","M12 5v14"],star:["m12 2 2.9 6.2 6.8.7-5.1 4.5 1.4 6.6-6-3.4-6 3.4 1.4-6.6-5.1-4.5 6.8-.7z"],x:["M18 6 6 18","m6 6 12 12"],"panel-left":["M9 3v18"],monitor:["M8 21h8","M12 17v4"],ellipsis:[]},tB={"panel-left":[3,3,18,18],monitor:[2,3,20,14]}});function oB(t){let e=$("span",{className:"persona-history-row-avatar",attrs:{"aria-hidden":"true"}});return nB.test(t)?e.appendChild($("img",{attrs:{src:t,alt:"",loading:"lazy"}})):e.textContent=t,e}function TT(t){let{conversation:e,copy:n,busy:o,pending:r}=t,s=o||r!==null,a=e.title.trim().length>0,l=e.starred?(()=>{let g=Ss("star",11);return g.setAttribute("fill","currentColor"),g.setAttribute("stroke-width","1"),$("span",{className:"persona-history-row-star"},g,$("span",{className:"persona-history-sr-only",text:n.groupStarred}))})():null,d=$("div",{className:"persona-history-row-head"},$("span",{className:"persona-history-row-title persona-history-truncate",text:a?e.title:e.preview??""}),l,$("time",{className:"persona-history-row-time",attrs:{datetime:e.updatedAt},text:AT(e.updatedAt,t.nowMs,n)})),p=a&&e.preview?$("span",{className:"persona-history-row-preview persona-history-truncate",text:e.preview}):null,u=$("button",{className:Vt("persona-history-row",t.active&&"persona-history-row--active",r&&`persona-history-row--${r}`),attrs:{type:"button","data-persona-history-focus":rB(e.id),"data-persona-history-conversation":e.id,...t.active?{"aria-current":"page"}:{},...s?{"aria-disabled":"true"}:{},...r?{"aria-busy":"true"}:{}}},t.avatar?oB(t.avatar):null,$("div",{className:"persona-history-row-body"},d,p,$("span",{className:"persona-history-row-count persona-history-sr-only",text:MT(e.messageCount,n)})));u.addEventListener("click",()=>{s||t.onOpen()});let m=t.showDelete?fy({className:"persona-history-row-menu-button",label:`${n.rowActionsLabel}: ${e.title}`,focusKey:sB(e.id),open:t.menuOpen,inert:s,onToggle:t.onToggleMenu}):null;return $("li",{className:Vt("persona-history-item",!t.showDelete&&"persona-history-item--no-menu"),attrs:{"data-persona-history-item":e.id}},u,m,t.menuOpen&&t.showDelete?iB(t):null,t.error?aB(t.error,n,e.id):null)}function iB(t){let{conversation:e,copy:n}=t;return gy({label:`${n.rowActionsLabel}: ${e.title}`,items:[{label:n.deleteConversationLabel,focusKey:Wc(e.id),danger:!0,onSelect:t.onDelete}],onCloseMenu:t.onCloseMenu})}function fy(t){let e=$("button",{className:Vt("persona-history-icon-button",t.className),attrs:{type:"button","aria-label":t.label,"aria-haspopup":"menu","aria-expanded":t.open?"true":"false","data-persona-history-focus":t.focusKey,...t.inert?{"aria-disabled":"true"}:{}}});e.appendChild(Ss("ellipsis",t.iconSize));let n=()=>e.getAttribute("aria-disabled")==="true";return e.addEventListener("click",o=>{o.stopPropagation(),!n()&&t.onToggle()}),e.addEventListener("keydown",o=>{o.key!=="ArrowDown"&&o.key!=="ArrowUp"||(o.preventDefault(),!(n()||e.getAttribute("aria-expanded")==="true")&&t.onToggle())}),e}function gy(t){let e=$("div",{className:"persona-history-menu",attrs:{role:"menu","aria-label":t.label}});for(let n of t.items){let o=$("button",{className:Vt("persona-history-menu-item",n.danger&&"persona-history-menu-item--danger"),text:n.label,attrs:{type:"button",role:"menuitem",tabindex:"0","data-persona-history-focus":n.focusKey}});o.addEventListener("click",()=>{t.onCloseMenu(),n.onSelect()}),e.appendChild(o)}return e.addEventListener("keydown",n=>{let o=Array.from(e.querySelectorAll('[role="menuitem"]'));if(o.length===0)return;let r=o.indexOf(document.activeElement);if(n.key==="Tab"){t.onCloseMenu({restoreFocus:!0});return}if(n.key==="ArrowDown"){n.preventDefault(),o[(r+1+o.length)%o.length]?.focus();return}if(n.key==="ArrowUp"){n.preventDefault(),o[(r-1+o.length)%o.length]?.focus();return}if(n.key==="Home"){n.preventDefault(),o[0]?.focus();return}n.key==="End"&&(n.preventDefault(),o[o.length-1]?.focus())}),e}function aB(t,e,n){let o=$("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":`row-retry:${n}`}});return o.addEventListener("click",t.retry),$("div",{className:"persona-history-row-error",attrs:{role:"alert"}},$("span",{text:t.message}),o)}var nB,rB,sB,Wc,ET=be(()=>{"use strict";Ye();my();uy();nB=/^(https?:|\/|data:)/i;rB=t=>`row:${t}`,sB=t=>`menu:${t}`,Wc=t=>`menu-item:${t}`});function lB(t){switch(t){case"authentication_failed":case"authentication_required":case"identity_provider_failed":case"proof_not_admitted":case"unsupported_scope":case"unavailable":return t;default:return"unknown"}}function kT(t){if(gp(t)){if(t.code==="rate_limited")return{kind:"rate_limited",retryAfterSeconds:t.retryAfterSeconds??0};let e=lB(t.code);return{kind:"error",reason:e,retryable:e!=="unsupported_scope"}}return{kind:"error",reason:"unknown",retryable:!0}}function cB(t,e){switch(t.state){case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};default:return null}}function dB(t,e){switch(t){case"authentication_required":case"authentication_failed":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"proof_not_admitted":case"unsupported_scope":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription};default:return{title:e.errorTitle,description:e.errorDescription}}}function Ju(t,e,n,o){let r=$("button",{className:"persona-history-secondary persona-history-state-action",text:t,attrs:{type:"button","data-persona-history-focus":e,...n?{"aria-disabled":"true"}:{}}});return r.addEventListener("click",()=>{n||o()}),r}function Bc(t,e,n,o,r){return $("div",{className:"persona-history-state",attrs:{"data-persona-history-state":t,...r?{role:"alert"}:{role:"status"}}},$("p",{className:"persona-history-state-title",text:e}),$("p",{className:"persona-history-state-description",text:n}),o)}function pB(t){let e=["42%","58%","34%"],n=["94%","78%","88%"],o=[0,1,2].map(r=>$("div",{className:"persona-history-skeleton-row",attrs:{"aria-hidden":"true"}},$("div",{className:"persona-history-skeleton-head"},$("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--title",style:{width:e[r]}}),$("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--time"})),$("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--preview",style:{width:n[r]}})));return $("div",{className:"persona-history-view-loading",attrs:{"data-persona-history-state":"loading",role:"status","aria-label":t.loadingLabel}},...o)}function LT(t){let{state:e,copy:n,busy:o}=t;if(e.kind==="loading")return pB(n);if(e.kind==="empty"){let l=cB(t.identityStatus,n);return l?Bc("identity",l.title,l.description,t.onRetry?Ju(n.retryIdentityLabel,"state-retry",o,t.onRetry):null,!0):Bc("empty",n.emptyTitle,n.emptyDescription,null,!1)}if(e.kind==="rate_limited"){let l=e.retryAfterSeconds>0?ur(n.rateLimitedWaitDescription,{seconds:e.retryAfterSeconds}):n.rateLimitedDescription;return Bc("rate_limited",n.rateLimitedTitle,l,t.onRetry?Ju(n.retryLabel,"state-retry",o,t.onRetry):null,!1)}if(e.kind==="new_conversation_required")return Bc("new_conversation_required",n.newConversationRequiredTitle,n.newConversationRequiredDescription,t.onStartNew?Ju(n.newConversationLabel,"state-retry",o,t.onStartNew):null,!0);let{title:r,description:s}=dB(e.reason,n),a=e.reason==="authentication_required"||e.reason==="authentication_failed"||e.reason==="identity_provider_failed"?n.retryIdentityLabel:n.retryLabel;return Bc("error",r,s,e.retryable&&t.onRetry?Ju(a,"state-retry",o,t.onRetry):null,!0)}var PT=be(()=>{"use strict";Ye();Rc();_l()});function Zu(t){return`${t.state}:${"reason"in t?t.reason:""}`}function HT(t,e){switch(t.state){case"verified":return{title:e.verifiedTitle,description:e.verifiedDescription,pending:!1};case"verifying":case"resetting":return{title:e.verifyingTitle,description:e.verifyingDescription,pending:!0};case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription,pending:!1};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription,pending:!1};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription,pending:!1};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription,pending:!1};default:return{title:e.browserOnlyTitle,description:e.browserOnlyDescription,pending:!1}}}function vB(t){return t.state==="verified"||t.state==="browser_only"}function CB(t){return t.state==="authentication_required"||t.state==="identity_provider_failed"||t.state==="configuration_error"}function hy(t){let e=Hc(t.copy),n=t.now??(()=>Date.now()),o=t.pageSize??uB,r=`persona-history-title-${Math.random().toString(36).slice(2,8)}`,s=[],a=null,l={kind:"loading",phase:"initial"},d=null,p=t.activeConversationId,u=t.provider.getIdentityStatus(),m=Zu(u),y=null,g=!1,b=!1,C=0,S=t.presentation,T=t.collapsible!==!1,A=t.collapsed===!0,I=t.railSide==="right",M=t.renderDom!==!1,O=new Map,k=null,B=vT(),W=F=>{!M&&t.onAnnounce?t.onAnnounce(F):B.announce(F)},V=()=>d!==null,R=`${r}-body`,w=$("button",{className:"persona-history-icon-button persona-history-back",attrs:{type:"button"}}),E=()=>S==="rail"&&T,H,D=()=>{if(t.railBrand){if(!E()){w.classList.remove("persona-history-back--branded");return}if(H===void 0){let F=t.railBrand(!0);H=F?$("span",{className:"persona-history-brand-mark persona-history-toggle-brand",attrs:{"aria-hidden":"true"}},F):null}H&&(w.classList.add("persona-history-back--branded"),w.appendChild(H))}},G=()=>{let F=E(),le=S==="rail";w.setAttribute("data-persona-history-focus",F?"collapse":"close"),w.setAttribute("aria-label",F?A?e.expandLabel:e.collapseLabel:le?e.closeLabel:e.backLabel),F?(w.setAttribute("aria-expanded",A?"false":"true"),w.setAttribute("aria-controls",R),t.collapseShortcut?.aria&&w.setAttribute("aria-keyshortcuts",t.collapseShortcut.aria)):(w.removeAttribute("aria-expanded"),w.removeAttribute("aria-controls"),w.removeAttribute("aria-keyshortcuts")),w.replaceChildren(Ss(F?"panel-left":le?"x":"arrow-left")),D()};G(),w.addEventListener("click",()=>{E()?t.onToggleCollapse?.():t.onClose()});let z=$("h2",{className:"persona-history-title",text:e.viewTitle,attrs:{id:r}}),K=$("span",{className:"persona-history-scope-title"}),Y=$("p",{className:"persona-history-scope"},$("span",{className:"persona-history-scope-icon",attrs:{"aria-hidden":"true"}},Ss("monitor",14)),K),re=$("div",{className:"persona-history-heading-group"},z),oe=!1,se,ce=()=>{let F=S==="rail",le=F?t.renderRailHeader:void 0,Be=null,et=le!==void 0;if(le)try{Be=le({collapsed:A,defaultTitle:e.viewTitle})}catch(he){et=!1,oe||(oe=!0,console.warn("[persona] history rail renderHeader threw",he))}if(!et&&F&&t.railBrand){if(se===void 0){let he=t.railBrand(!1);se=he?$("span",{className:"persona-history-heading-brand",attrs:{"aria-hidden":"true"}},$("span",{className:"persona-history-brand-mark"},he),$("span",{className:"persona-history-wordmark",text:e.viewTitle})):null}se&&(et=!0,Be=se)}z.classList.toggle("persona-history-sr-only",et),re.replaceChildren(z),Be&&re.appendChild(Be)};ce();let we=$("button",{className:"persona-history-icon-button persona-history-new-icon",attrs:{type:"button","data-persona-history-focus":"new-icon","aria-label":e.newConversationLabel}});we.appendChild(Ss("plus")),we.addEventListener("click",()=>{an()});let ge=[w,we].map(F=>t.attachTooltip?.({anchor:F,text:()=>F.getAttribute("aria-label")??"",...F===w&&t.collapseShortcut?{hint:()=>E()?t.collapseShortcut.hint:""}:{}})),N=$("div",{className:"persona-history-topbar"}),ye=null,ke=()=>{let F=S==="rail",le=F?I?"rail-right":"rail":"panel";le!==ye&&(ye=le,le==="rail"?N.append(re,w):N.append(w,re),F?we.remove():N.appendChild(we),Q.classList.toggle("persona-history-view--rail-right",le==="rail-right"))},nt=$("div",{className:"persona-history-scope-alert"}),Ee=`${r}-scope`,Ne=Ss("plus",18),Pe=$("button",{className:"persona-history-new",attrs:{type:"button","data-persona-history-focus":"new"}},Ne,$("span",{text:e.newConversationLabel}));Pe.addEventListener("click",()=>{an()});let dt=$("div",{className:"persona-history-list-region"}),Xe=t.showDeleteAll!==!1,xt=!!t.provider.resetDevice,Ge=t.listActions??[],yt=Xe||xt||Ge.length>0?fy({className:"persona-history-list-options",label:e.listOptionsLabel,focusKey:`menu:${Ci}`,open:!1,inert:!0,iconSize:16,onToggle:()=>wi(Ci)}):null,X=$("h3",{className:"persona-history-conversations-title",text:e.conversationsTitle}),P=$("div",{className:"persona-history-caption",attrs:{"data-persona-history-item":Ci}},X,t.showScopeStatus?Y:null,yt),j=$("div",{className:"persona-history-body",attrs:{id:R}},t.showScopeStatus?nt:null,Pe,P,dt),J=t.headerPlacement??"inline";J==="external"&&N.classList.add("persona-history-topbar--shell","persona-history-topbar--shell-enter");let Q=$("div",{className:Vt("persona-history-view",`persona-history-view--${t.presentation}`,"persona-history-view--enter"),attrs:{role:"region","aria-labelledby":r,"data-persona-history-presentation":t.presentation}},B.element,J==="inline"?N:null,j),de=()=>{Q.classList.toggle("persona-history-view--rail-collapsed",A&&E())};de(),ke();let Me=(F,le)=>{let Be=`${r}-s${le}`,et=$("div",{className:Vt("persona-history-nav",F.placement==="footer"&&"persona-history-nav--footer"),attrs:{role:"group","data-persona-rail-section":F.id,...F.title?{"aria-labelledby":Be}:{"aria-label":F.id}}});F.title&&et.appendChild($("h3",{className:"persona-history-group-heading",text:F.title,attrs:{id:Be}}));for(let he of F.items){let We=he.iconNode?.()??null,Uo=$("button",{className:Vt("persona-history-nav-item",We&&"persona-history-nav-item--icon"),attrs:{type:"button","aria-label":he.label,"data-persona-rail-item":he.id}},We?$("span",{className:"persona-history-nav-icon"},We):null,$("span",{className:"persona-history-nav-label persona-history-truncate",text:he.label}),he.badge?$("span",{className:"persona-history-nav-badge",text:he.badge}):null);Uo.addEventListener("click",()=>he.onSelect()),et.appendChild(Uo)}return et},Te=null,Fe=null,je=()=>{!Te||!M||S!=="rail"||A===Fe||(Fe=A,t.railSections.forEach((F,le)=>{if(!F.render)return;let Be=Te[le],et=F.title?Be.firstElementChild:null,he=null;try{he=F.render(A)}catch(We){F.render=void 0,console.warn("[persona] history rail section threw",F.id,We)}Be.replaceChildren(...et?[et]:[],...he?[he]:[]),Be.hidden=!he}))},lt=()=>{let F=t.railSections;if(Q.classList.toggle("persona-history-view--has-nav",S==="rail"&&!!F?.some(le=>le.placement==="above-conversations")),!!F?.length){if(S!=="rail"){Te?.forEach(le=>le.remove());return}Te??(Te=F.map(Me));for(let le of["above-conversations","below-conversations","footer"]){let Be=le==="above-conversations"?P.parentNode===j?P:dt:null;F.forEach((et,he)=>{et.placement===le&&j.insertBefore(Te[he],Be)})}je()}};lt(),Np(Q,"persona-history-view",wT);let ot=(F,le)=>{let Be=Q.ownerDocument.defaultView?.getComputedStyle(Q).getPropertyValue(F),et=Number.parseFloat(Be??"");return Number.isFinite(et)&&et>=0?et:le},Je=(F,le)=>Q.ownerDocument.defaultView?.getComputedStyle(Q).getPropertyValue(F).trim()||le,mt=null,Tt=()=>{mt!==null&&(clearTimeout(mt),mt=null),Q.removeEventListener("animationend",Tt),Q.classList.remove("persona-history-view--enter")};Q.addEventListener("animationend",Tt),mt=setTimeout(()=>{mt=setTimeout(Tt,ot("--persona-history-enter-ms",mB)+60)},0);let ee=null,Oe=()=>{ee!==null&&(clearTimeout(ee),ee=null),N.classList.remove("persona-history-topbar--shell-enter")},$e=()=>{Oe(),N.classList.add("persona-history-topbar--shell-enter"),ee=setTimeout(Oe,IT+60)};J==="external"&&(ee=setTimeout(Oe,IT+60));let pt=[],_t=null,ve=()=>{if(_t)return _t;if(b||yB()||typeof Q.animate!="function")return Tt(),null;let F=Q.ownerDocument.defaultView?.getComputedStyle(j).opacity||"1";Tt(),Q.style.pointerEvents="none",Ke.style.pointerEvents="none";let le={duration:ot("--persona-history-exit-ms",fB),easing:Je("--persona-history-exit-easing",gB),fill:"forwards"},Be=hB[S];return pt=[j.animate([{opacity:F,transform:"none"},{opacity:0,transform:`translateX(${Be}px)`}],le)],_t=Promise.all(pt.map(bB)).then(()=>{}),_t},Se=(F,le)=>{F&&(le?F.setAttribute("aria-disabled","true"):F.removeAttribute("aria-disabled"))},Ke=N,ut=null,vn=()=>{let F=t.slots?.header;if(!F)return;let le=`${S}|${Zu(u)}|${d?`${d.kind}:${"conversationId"in d?d.conversationId:""}`:""}`;if(le===ut)return;ut=le;let Be=F({identityStatus:u,pendingAction:d,copy:e,defaultRenderer:()=>N})??N;Be!==Ke&&(Ke.replaceWith(Be),Ke=Be)},Cn=null,wn=()=>{if(!t.showScopeStatus)return;let F=Zu(u);if(F===Cn)return;Cn=F;let le=HT(u,e);K.textContent=le.title;let Be=vB(u);if(Y.hidden=!Be,nt.replaceChildren(...Be?[]:[$("span",{className:"persona-history-scope-alert-title",text:le.title})],$("span",{className:"persona-history-scope-description",text:le.description,attrs:{id:Ee}})),nt.setAttribute("data-persona-history-scope-tone",Be?"ambient":"attention"),Be?Y.setAttribute("aria-describedby",Ee):Y.removeAttribute("aria-describedby"),le.pending?nt.setAttribute("role","status"):nt.removeAttribute("role"),nt.setAttribute("data-persona-history-identity",u.state),Y.setAttribute("data-persona-history-identity",u.state),CB(u)){let et=$("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryIdentityLabel,attrs:{type:"button","data-persona-history-focus":"identity-retry"}});et.addEventListener("click",()=>{V()||Ae("refresh")}),nt.appendChild(et)}},Wt=F=>d?d.kind==="open"&&d.conversationId===F?"opening":d.kind==="delete"&&d.conversationId===F?"deleting":null:null,St=()=>{let F=document.activeElement;return!(F instanceof HTMLElement)||!Q.contains(F)?null:F.getAttribute("data-persona-history-focus")},Et=F=>{if(g&&y){g=!1;let le=Q.querySelector(`[data-persona-history-focus="${Wc(y)}"]`);if(le){le.focus();return}}F&&Q.querySelector(`[data-persona-history-focus="${F}"]`)?.focus()},sn=()=>{if(!k)return null;let F=$("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":"action-retry"}}),le=k;return F.addEventListener("click",()=>{V()||le.retry()}),$("div",{className:"persona-history-row-error",attrs:{role:"alert"}},$("span",{text:le.message}),F)},Rn=()=>ST(s,n(),e,t.grouping).map((F,le)=>{let Be=`${r}-g${le}`,et=$("ul",{className:"persona-history-list",attrs:{"aria-labelledby":Be}});for(let he of F.items){let We=()=>TT({conversation:he,active:he.id===p,pending:Wt(he.id),busy:V(),menuOpen:y===he.id,error:O.get(he.id)??null,avatar:t.rowAvatar,showDelete:t.showDelete!==!1,nowMs:n(),copy:e,onOpen:()=>{Wn(he.id)},onToggleMenu:()=>wi(he.id),onCloseMenu:$r=>Re($r),onDelete:()=>{bt(he.id)}}),qo=t.slots?.conversation?.({conversation:he,active:he.id===p,pending:Wt(he.id),open:()=>Wn(he.id),requestDelete:()=>bt(he.id),defaultRenderer:We})??We();et.appendChild(qo instanceof HTMLLIElement?qo:$("li",{className:"persona-history-item"},qo))}return $("div",{className:"persona-history-group",attrs:{"data-persona-history-group":F.key}},$("h3",{className:Vt("persona-history-group-heading",F.key==="recent"&&"persona-history-sr-only"),text:F.label,attrs:{id:Be}}),et)}),tn=()=>{if(!a)return null;let F=d?.kind==="load-more"||l.kind==="loading"&&l.phase==="load-more",le=$("button",{className:"persona-history-secondary persona-history-load-more",text:F?e.loadingMoreLabel:e.loadMoreLabel,attrs:{type:"button","data-persona-history-focus":"load-more",...F?{"aria-busy":"true","aria-disabled":"true"}:{},...V()&&!F?{"aria-disabled":"true"}:{}}});return le.addEventListener("click",()=>{V()||Ae("load-more")}),le},it=()=>{let F=St(),le=[sn()],Be=s.length>0;if(Be&&(le.push(...Rn()),le.push(tn())),l.kind!=="ready"&&!(l.kind==="loading"&&l.phase!=="initial"&&Be)){let he=l,We=he.kind==="loading"?void 0:()=>Ae("refresh"),Uo=he.kind==="new_conversation_required"?()=>an():void 0,qo=()=>LT({state:he,copy:e,identityStatus:u,busy:V(),...We?{onRetry:()=>{We()}}:{},...Uo?{onStartNew:()=>{Uo()}}:{}}),$r=t.slots?.state?.({state:he,identityStatus:u,copy:e,...We?{retry:We}:{},...Uo?{startNewConversation:Uo}:{},defaultRenderer:qo});le.push($r??qo())}dt.replaceChildren(...le.filter(he=>!!he)),Et(F)},_e=()=>{let F=l.kind==="loading"&&s.length===0,le=[],Be=()=>le.length===0?Wc(Ci):`${Wc(Ci)}-${le.length}`;if(!F)for(let et of Ge)le.push({label:et.label,focusKey:Be(),danger:et.danger===!0,onSelect:()=>{et.onSelect({conversations:[...s]})}});return Xe&&!(s.length===0&&(l.kind==="empty"||F))&&le.push({label:e.clearHistoryLabel,focusKey:Be(),danger:!0,onSelect:()=>{_a()}}),xt&&!F&&le.push({label:e.resetIdentityLabel,focusKey:Be(),danger:!0,onSelect:()=>{Na()}}),le},Kt=()=>{if(Se(Pe,V()),Se(we,V()),yt){let F=_e(),le=l.kind==="loading"&&s.length===0;yt.hidden=F.length===0&&!le,Se(yt,V()||F.length===0),yt.setAttribute("aria-expanded",y===Ci?"true":"false");let Be=P.querySelector(".persona-history-menu");if(y!==Ci||F.length===0)Be?.remove();else{let et=gy({label:e.listOptionsLabel,items:F,onCloseMenu:he=>Re(he)});Be?Be.replaceWith(et):P.appendChild(et)}}P.hidden=S!=="rail"&&(!yt||yt.hidden)&&(!t.showScopeStatus||Y.hidden)},Ze,Le=()=>{let F=t.onActiveConversationChange;if(!F)return;let le=s.find(et=>et.id===p)??null,Be=le?`${le.id}\0${le.title}\0${le.starred?1:0}`:"";Be!==Ze&&(Ze=Be,F(le))},ie=()=>{if(!b){if(Le(),!M){t.onModelChange?.();return}vn(),wn(),Kt(),it(),je()}},Re=F=>{if(!y)return;let le=y;y=null,g=!1,ie(),F?.restoreFocus&&Q.querySelector(`[data-persona-history-focus="menu:${le}"]`)?.focus()},wi=F=>{if(y===F){Re({restoreFocus:!0});return}y=F,g=!0,ie()},Vr=F=>{if(!y)return;let le=F.target;le instanceof Node&&Q.contains(le)&&le.closest?.(`[data-persona-history-item="${y}"]`)||Re()};document.addEventListener("pointerdown",Vr,!0);let Io=F=>{F.key!=="Escape"||!y||(F.stopPropagation(),Re({restoreFocus:!0}))};Q.addEventListener("keydown",Io);async function Ae(F){if(b)return;let le=++C,Be=F==="load-more"?a:null;if(!(F==="load-more"&&!Be)){d={kind:F==="load-more"?"load-more":"refresh"},l={kind:"loading",phase:F},F!=="load-more"&&(O.clear(),k=null),Re(),ie();try{let et=await t.provider.list({limit:o,context:t.context,...Be?{cursor:Be}:{},...t.targetId?{targetId:t.targetId}:{}});if(b||le!==C)return;s=Be?[...s,...et.items]:et.items,a=et.nextCursor,l=s.length===0?{kind:"empty"}:{kind:"ready"}}catch(et){if(b||le!==C)return;l=kT(et)}finally{!b&&le===C&&(d=null,ie())}}}let Ve=F=>{s=s.filter(le=>le.id!==F),O.delete(F),p===F&&(p=null),s.length===0&&!a&&(l={kind:"empty"})};async function Wn(F){if(!(V()||b)){O.delete(F),Re(),d={kind:"open",conversationId:F},ie();try{if(await t.onSelect(F),b)return;p=F}catch{if(b)return;O.set(F,{message:e.openFailedLabel,retry:()=>{Wn(F)}})}finally{b||(d=null,ie())}}}async function bt(F){if(V()||b)return"cancelled";O.delete(F),d={kind:"delete",conversationId:F},ie();try{let le=await t.onRequestDeleteConversation(F);return b||le==="deleted"&&(Ve(F),W(e.conversationRemovedNotice)),le}catch(le){return b||(gp(le)&&le.code==="not_found"?Ve(F):O.set(F,{message:e.deleteFailedLabel,retry:()=>{bt(F)}})),"cancelled"}finally{b||(d=null,ie())}}async function an(){if(!(V()||b)){k=null,Re(),d={kind:"start-new"},ie();try{if(await t.onStartNew(),b)return;l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"})}catch{if(b)return;k={message:e.errorDescription,retry:()=>{an()}}}finally{b||(d=null,ie())}}}async function _a(){if(V()||b)return"cancelled";k=null,Re(),d={kind:"clear"},ie();try{let F=await t.onRequestClearHistory();return b||F==="cleared"&&(s=[],a=null,p=null,l={kind:"empty"},W(e.historyClearedNotice)),F}catch{return b||(k={message:e.errorDescription,retry:()=>{_a()}}),"cancelled"}finally{b||(d=null,ie())}}let kn={outcome:"cancelled"};async function Na(){if(V()||b||!t.onRequestResetIdentity)return kn;k=null,Re(),d={kind:"reset"},ie();try{let F=await t.onRequestResetIdentity();return b||F.outcome==="reset"&&(W(F.remoteRevocationConfirmed?e.identityResetNotice:e.identityResetUnconfirmedNotice),d=null,await Ae("refresh")),F}catch{return b||(k={message:e.errorDescription,retry:()=>{Na()}}),kn}finally{!b&&d?.kind==="reset"&&(d=null,ie())}}let om=t.provider.subscribeIdentityStatus(F=>{if(b)return;let le=Zu(F),Be=le!==m;u=F,m=le,ie(),Be&&F.state!=="verifying"&&W(HT(F,e).title)}),rm=t.provider.subscribeAvailability?.(F=>{if(!b){if(F){Ae("refresh");return}s=[],a=null,l={kind:"error",reason:"unavailable",retryable:!1},ie()}});return ie(),Ae("initial"),{element:Q,copy:e,getModel:()=>({conversations:s,activeConversationId:p,state:l,pendingAction:d,identityStatus:u,nextCursor:a}),operations:{refresh:async()=>{V()||await Ae("refresh")},loadMore:async()=>{V()||await Ae("load-more")},openConversation:F=>Wn(F),startNewConversation:()=>an(),requestDeleteConversation:F=>bt(F),requestClearConversationHistory:()=>_a(),requestResetHistoryIdentity:()=>Na()},setDomRenderEnabled:F=>{F!==M&&(M=F,F&&ie())},refresh:()=>{Ae("refresh")},setPresentation:F=>{if(F===S)return;Tt(),S=F,ut=null;let le=F==="rail";Q.classList.toggle("persona-history-view--panel",!le),Q.classList.toggle("persona-history-view--rail",le),Q.setAttribute("data-persona-history-presentation",F),G(),de(),ke(),ce(),lt(),ie()},setCollapsed:F=>{F!==A&&(A=F,de(),G(),ce(),je())},setRailSide:F=>{I=F==="right",ke()},getHeaderElement:()=>Ke,setHeaderPlacement:F=>{if(F===J)return;J=F;let le=F==="external";if(N.classList.toggle("persona-history-topbar--shell",le),le){$e(),Ke.remove();return}Oe(),Q.insertBefore(Ke,j)},setActiveConversationId:F=>{p!==F&&(p=F,ie())},applyConversationSummary:F=>{let le=s.findIndex(Be=>Be.id===F.id);le!==-1&&(s[le]=F,ie())},removeConversationSummary:F=>{s.some(le=>le.id===F)&&(Ve(F),ie())},setNewConversationRequired:F=>{F?l={kind:"new_conversation_required"}:l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"}),ie()},playExit:ve,destroy:()=>{b=!0,C+=1,Tt(),Oe(),ge.forEach(F=>F?.destroy()),Ke.remove(),pt.forEach(F=>F.cancel()),pt=[],om(),rm?.(),document.removeEventListener("pointerdown",Vr,!0),Q.removeEventListener("keydown",Io),B.destroy(),Q.remove(),Q.replaceChildren()}}}var uB,Ci,mB,IT,fB,gB,hB,yB,bB,RT=be(()=>{"use strict";ya();Ye();CT();xT();Rc();uy();my();ET();PT();_l();uB=25,Ci="persona:list-options",mB=180,IT=120,fB=160,gB="cubic-bezier(0.4, 0, 1, 1)",hB={panel:20,rail:12},yB=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,bB=t=>t.finished?t.finished.then(()=>{},()=>{}):Promise.resolve()});var yy=be(()=>{"use strict";RT();Rc()});var WT={};Vn(WT,{HISTORY_VIEW_COPY_DEFAULTS:()=>Ic,createHistoryView:()=>hy,resolveHistoryViewCopy:()=>Hc});var BT=be(()=>{"use strict";yy();yy()});var o1={};Vn(o1,{createThemePreview:()=>aE});module.exports=k0(o1);function mC(t,e){let n=t.voiceRecognition,o=e.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||t.agentId!==e.agentId||t.clientToken!==e.clientToken||t.apiUrl!==e.apiUrl}function no(t){return t?.type==="runtype"||t?.type==="custom"}var L0=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function fC(t){try{if(t?.type==="custom"&&t.custom){let e=t.custom,n=typeof e=="function"?e():e;return!!n&&typeof n.startListening=="function"}return t?.type==="runtype"&&t.runtype?!0:L0()}catch{return!1}}Xd();Ff();var wC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,xC=t=>t.includes("|"),SC=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},O0=t=>`| ${t.join(" | ")} |`,D0=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,_0=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),AC=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
1141
- `),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!xC(r)||wC.test(r)||!wC.test(s))continue;let a=SC(r).length;if(a<1)continue;let l=D0(a);e[o+1]!==l&&(e[o+1]=l,n=!0);let d=o+2;for(;d<e.length;d++){let p=e[d];if(p.trim()===""||!xC(p))break;let u=O0(_0(SC(p),a));e[d]!==u&&(e[d]=u,n=!0)}o=d-1}return n?e.join(`
1142
- `):t};var MC="var(--persona-md-table-scroll-fade, 24px)",TC=new WeakSet;function kC(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function EC(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,r=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":MC),t.style.setProperty("--persona-fade-r",r<=1?"0px":MC)}function Vf(t){TC.has(t)||(TC.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&EC(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(EC)}ti();na();oo();var{setLoader:E1,load:Q0}=$t({fallbackImport:()=>Promise.resolve().then(()=>(DC(),OC))});var _C=Q0;function To(t){return t==="card"?"collapsed":t}function oa(t){return t.split(";",1)[0].trim().toLowerCase()}function X0(t,e){if(!t)return;let n=Object.entries(t);for(let[r,s]of n)if(oa(r)===e)return{mode:To(s),selector:oa(r)};let o=`${e.split("/",1)[0]}/*`;for(let[r,s]of n)if(oa(r)===o)return{mode:To(s),selector:o}}function J0(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:To(o.files),matchedBy:{type:"files"}};let l=e.file.mimeType?oa(e.file.mimeType):void 0,d=l?X0(o.files.byMediaType,l):void 0;if(l&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:l,selector:d.selector}};if(o.files.default)return{mode:To(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[e.artifactType];if(r)return{mode:To(r),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let s=o.byType?.[e.artifactType];if(s)return{mode:To(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let a=e.presentation?.preferredMode;return a?{mode:To(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:To(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function is(t,e){return J0(t,e).mode}function El(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var Z0="agent_",eL="flow_";function NC(t){return t.startsWith(Z0)?{kind:"agentId",agentId:t}:t.startsWith(eL)?{kind:"flowId",flowId:t}:null}function FC(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let p=NC(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let d=e?.[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(l).payload}}let r=NC(n);if(r)return r;let s=e?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function op(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ra(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function VC(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var as=require("partial-json");Ye();var zf="ask_user_question",kl=8,sa="data-persona-ask-sheet-for",tL="Other",nL="Other\u2026",UC="Type your own answer here",qC="Send",oL="Next",rL="Back",sL="Submit all",iL="Skip",aL=3,Uf="data-ask-current-index",qf="data-ask-question-count",jC="data-ask-answers",jf="data-ask-grouped",KC="data-ask-layout",lL=t=>t.layout==="pills"?"pills":"rows",cL=t=>t.getAttribute(KC)==="pills"?"pills":"rows",zC=!1,GC=t=>t.replace(/["\\]/g,"\\$&"),ni=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===zf,Kf=t=>t?.features?.askUserQuestion??{},ia=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,as.parse)(r,as.STR|as.OBJ|as.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Ll=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>kl&&!zC&&(zC=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${kl}.`)),e.slice(0,kl)},dL=t=>Ll(t)[0]??null,pL=(t,e)=>Ll(t)[e]??null,uL=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},YC=(t,e,n)=>{if(t!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},mL=(t,e,n,o)=>{let s=v("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=t.label,a.appendChild(l),t.description){let p=v("span","persona-ask-row-description");p.textContent=t.description,a.appendChild(p)}s.appendChild(a);let d=YC(n,o,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},fL=t=>{let n=v("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},gL=(t,e,n,o)=>{let s=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!t?.multiSelect,d=(Array.isArray(t?.options)?t.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<aL;u++)s.appendChild(fL(o));return s}if(d.forEach((u,m)=>{s.appendChild(mL(u,m,o,a))}),t?.allowFreeText!==!1){let u=o==="rows"?tL:nL;if(o==="rows"){let m=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(d.length)),m.setAttribute("data-ask-other-row","true");let y=v("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=e.freeTextPlaceholder??UC,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",e.freeTextLabel??u),y.appendChild(g),m.appendChild(y);let b=YC(o,a,d.length);b&&m.appendChild(b),s.appendChild(m)}else{let m=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=e.freeTextLabel??u,s.appendChild(m)}}return s},QC=(t,e)=>{let o=v("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=t.freeTextPlaceholder??UC,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=v("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??qC,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},hL=t=>{let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??qC,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},yL=(t,e,n)=>{let o=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??rL,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??iL,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=t===e-1;return l.textContent=d?n.submitAllLabel??sL:n.nextLabel??oL,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},oi=t=>{let e=t.getAttribute(jC);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},XC=(t,e)=>{t.setAttribute(jC,JSON.stringify(e))},Eo=t=>{let e=Number(t.getAttribute(Uf)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},bL=(t,e)=>{t.setAttribute(Uf,String(Math.max(0,Math.floor(e))))},aa=t=>{let e=Number(t.getAttribute(qf)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},ls=t=>t.getAttribute(jf)==="true",vL=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},CL=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},rp=(t,e)=>{let{payload:n}=ia(e),o=Ll(n),r=oi(t),s={},a=new Set;return o.forEach((l,d)=>{let p=typeof l?.question=="string"?l.question:"";p&&(a.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),a.add(p),Object.prototype.hasOwnProperty.call(r,d)&&(s[p]=r[d]))}),s},JC=t=>{let e=oi(t),n=Eo(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{let p=d.getAttribute("data-option-label")??"",u=r.has(p);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>d.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},ZC=t=>{if(!ls(t))return;let e=oi(t),n=Eo(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Gf=(t,e,n)=>{let o=Kf(n),r=cL(t),{payload:s,complete:a}=ia(e),l=ls(t),d=Eo(t),p=aa(t),u=l?pL(s,d):dL(s),m=!!u?.multiSelect,y=t.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=l?`${d+1}/${p}`:"");let g=t.querySelector('[data-ask-stepper="true"]');g&&g.remove();let b=t.querySelector('[data-ask-question="true"]');if(b){let A=typeof u?.question=="string"?u.question:"";b.textContent=A,b.classList.toggle("persona-ask-question-skeleton",!A&&!a)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let A=gL(u,o,a,r);C.replaceWith(A)}if(r!=="rows"){let A=t.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(QC(o,r))}let S=t.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!S?t.appendChild(hL(o)):(!m||l)&&S&&S.remove(),t.setAttribute("data-multi-select",m?"true":"false");let T=t.querySelector('[data-ask-nav-row="true"]');if(l){let A=yL(d,p,o);T?T.replaceWith(A):t.appendChild(A)}else T&&T.remove();JC(t),ZC(t)},wL=(t,e,n)=>{let o=Kf(e),r=lL(o),s=t.toolCall.id,a=Ll(n),l=Math.max(1,a.length),d=l>1,p=vL(t,a),u=d?CL(t,l):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(sa,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(qf,String(l)),m.setAttribute(Uf,String(u)),m.setAttribute(jf,d?"true":"false"),m.setAttribute(KC,r),XC(m,p),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),uL(m,o);let y=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=v("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",y.appendChild(g);let b=v("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",y.appendChild(b),m.appendChild(y);let S=v("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),m.appendChild(S),r!=="rows"&&m.appendChild(QC(o,r)),Gf(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},xL=(t,e,n)=>{let{payload:o}=ia(e),r=Math.max(1,Ll(o).length);r>aa(t)&&(t.setAttribute(qf,String(r)),r>1&&!ls(t)&&t.setAttribute(jf,"true")),Gf(t,e,n)};var sp=(t,e,n)=>{if(!n||!ni(t)||Kf(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${sa}]`).forEach(p=>{p.getAttribute(sa)!==r&&p.remove()});let a=n.querySelector(`[${sa}="${GC(r)}"]`);if(a){xL(a,t,e);return}let{payload:l}=ia(t),d=wL(t,e,l);n.appendChild(d)},la=(t,e)=>{if(!t)return;let n=e?`[${sa}="${GC(e)}"]`:`[${sa}]`;t.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Yf=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),cs=(t,e)=>{let n=oi(t),o=Eo(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,XC(t,n),JC(t),ZC(t)},ip=(t,e,n,o)=>{let r=aa(t),s=Math.max(0,Math.min(r-1,o));bL(t,s),Gf(t,e,n)};var ds="suggest_replies";var SL={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},tw={name:ds,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:SL,origin:"sdk",annotations:{readOnlyHint:!0}},nw=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Pl=t=>t.variant==="tool"&&t.toolCall?.name===ds,AL=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},ow=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!Pl(n))continue;let o=AL(n.toolCall?.args);return o.length>0?o:null}return null},ew=new Set,ML=(t,e,n)=>{let o=`${t}:${e}:${n}`;ew.has(o)||(ew.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},ps=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=a=>{let l=e?.[a],d=n?.[a];l===void 0||d===void 0||l!==d&&ML(a,d,l)};t&&(o("enabled"),o("expose"));let r=e?.enabled??n?.enabled??!0,s=r?e?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var TL={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:kl,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},EL={name:zf,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:TL,origin:"sdk",annotations:{readOnlyHint:!0}},ap=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(EL),ps(t).expose&&e.push(tw),e};ri();var uw="4.23.1";var si=uw;var da="[Image]";function mw(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function pp(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function sr(t){return{type:"text",text:t}}function fw(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var gw=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],WL=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Hr=[...gw,...WL];function BL(t){return gw.includes(t)||t.startsWith("image/")}function up(t){return BL(t.type)}function hw(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function yw(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;up(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function bw(t,e=Hr,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function OL(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function vw(t,e){let n=OL(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||n||"FILE"}var DL=["user","assistant","system"],_L=0;function Cw(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function mp(t){return typeof t=="string"?t:void 0}function NL(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?sr(e.text):null;case"image":return typeof e.image=="string"?fw(e.image,{mimeType:mp(e.mimeType),alt:mp(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?hw(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...mp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...mp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function FL(t,e){let n=Cw(e),o=t.map(a=>Cw(a.timestamp)),r=new Array(t.length),s=0;for(;s<o.length;){let a=o[s];if(a!==null){r[s]=a,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let d=l-s+1,p=s>0?r[s-1]:null,u=l+1<o.length?o[l+1]:null,m=u!==null&&n!==null?Math.min(u,n):u??n;for(let y=0;y<d;y+=1)r[s+y]=m!==null?m-(d-y):p!==null?p+y+1:_L+y;s=l+1}return r.map(a=>new Date(a).toISOString())}function ww(t,e){let n=FL(t,e?.beforeCreatedAt),o=[];return t.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!DL.includes(r.role))return;let a=r.role,l=n[s];if(r.displayAvailable===!1){let d={historyDisplayUnavailable:!0};o.push({id:r.id,role:a,content:"",createdAt:l,agentMetadata:d});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:a,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:a,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let d=r.content.map(NL).filter(u=>u!==null),p=mw(d);o.push({id:r.id,role:a,content:p||(pp(d)?da:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Wl(t){let e=t.content;if(typeof e!="string"||e==="")return;let n=t.contentParts??t.llmContent??t.rawContent??e;if(!(typeof n=="string"&&n===e))return e}function Bl(t,e){let n=new Map;for(let o of t)n.set(o.id,o);for(let o of e)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),a=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(a)&&s!==a)return s-a;let l=o.sequence??0,d=r.sequence??0;return l!==d?l-d:o.id.localeCompare(r.id)})}var VL="https://api.runtype.com/v1/dispatch",xw="https://api.runtype.com",at=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Sw=32768,Xf=49152,Aw=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:n,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:""}},Mw=t=>"reason"in t?t.reason:void 0,Tw="The identity proof was not admitted; account history is unavailable",Ew="The identity proof was rejected",kw="The request carried no visitor credential",Lw="The stored visitor belongs to a different signed-in user",Jf=(t,e)=>t instanceof at&&t.code===e;function $L(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Zf=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function zL(t){switch(t){case"json":return dw;case"regex-json":return cw;case"xml":return pw;default:return lw}}var Pw=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function UL(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=Pw(n);if(!Pw(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Rl(t);return Rl(e)!==null&&a===null?e:t}var Ol=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??VL,this.headers={"Content-Type":"application/json","X-Persona-Version":si,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??zL(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,e.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(e.webmcp))}createWebMcpBridge(e){return _C().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:IC,getToolDisplayTitle:Zd,loadPolyfill:RC});return this.pendingWebMcpConfirmHandler!==void 0&&o.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=o,o}).catch(n=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}getWebMcpBridge(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.webMcpBridgePromise||(this.webMcpBridgePromise=this.createWebMcpBridge(this.config.webmcp)),this.webMcpBridgePromise)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.pendingWebMcpConfirmHandler=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=FC(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||xw}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new at("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:e.after}),d=await fetch(`${a}?${l}`,{method:"GET",headers:{"X-Persona-Version":si,"X-Visitor-Token":s},signal:e.signal});if(d.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(d),null,!0);continue}if(!d.ok)throw await this.historyErrorFor(d,!0);return d}}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.historyAvailabilitySubscribers])e(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(e){return this.historyIdentitySubscribers.add(e),()=>{this.historyIdentitySubscribers.delete(e)}}subscribeHistoryAvailability(e){return this.historyAvailabilitySubscribers.add(e),this.historyUnavailable&&e(!1),()=>{this.historyAvailabilitySubscribers.delete(e)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let e=this.historyIdentityStatus;return e?.state==="browser_only"?e:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&Mw(n)===Mw(e);if(this.historyIdentityStatus=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let r of[...this.historyIdentitySubscribers])r(e)}}async createClientSession(e){let n=this.isHistoryCapable()&&!e.omitVisitorFields,o=!e.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.routing(),a=s.agentId??s.flowId,l=n||e.durableResume?e.conversationId:void 0,d={token:this.config.clientToken,...a&&{flowId:a},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...l?{conversationId:l}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":si},body:JSON.stringify(d),signal:e.signal});if(!p.ok){let m=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new at("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw p.status===403&&m.error==="durable_recovery_disabled"?new at("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&m.error==="visitor_required"?new at("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new at("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):p.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let u=await p.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let r=await this.createClientSession({conversationId:e,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,e,!1)}catch(r){if(!Jf(r,"not_found")&&!Jf(r,"visitor_required")&&!Jf(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(e,n)):this.doOrdinaryInit(e,n)}async doOrdinaryInit(e,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,e,n)}async reinitWithProof(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:e}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),s}async claimFirstConversation(e){if(!e.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.claimInFlight=!1}}finishInit(e,n,o){let r=e.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}prepared(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new at("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new at("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:e,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.createClientSession({});return this.prepared(e)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":si},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}historyUrl(e,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${e}${r?`?${r}`:""}`}resolveHistoryScope(e){if(e)return e;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(e,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new at("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(e.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new at("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(e,n,o){if(e.visitor?.endUserId!=null)return e;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new at("proof_not_admitted",Tw);return r}async readErrorCode(e){let n=await e.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(e,n,o){let r=e.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new at("invalid_identity_proof",Ew);if(r.includes("visitor token required"))throw new at("visitor_token_missing",kw);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new at("visitor_identity_mismatch",Lw);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new at("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new at("not_found","Conversation not found");if(e.status===429){let r=Number.parseInt(e.headers.get("Retry-After")??"",10);return new at("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(e.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new at("proof_not_admitted",Tw);if(e.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new at("invalid_identity_proof",Ew)):r.includes("visitor token required")?new at("visitor_token_missing",kw):r.includes("visitor_identity_mismatch")?new at("visitor_identity_mismatch",Lw):new at("unauthorized",o||"History request was not authorized")}return new at("request_failed",o||`History request failed (${e.status})`)}commitIdentityAcknowledgement(e,n,o){let r=e?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new at("identity_contract_violation","Server reported an ignored identity proof on a success response"):new at("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new at("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(e,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let a=this.historyInternals.visitorStore,l=!1;for(;;){let d=a?.revision()??0,p=await this.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new at("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(e,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":si,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(u),s,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),y=await u.json().catch(()=>{});if(a&&a.revision()!==d)throw new at("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,s!==null,o),y}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new at("history_disabled","Visitor history is disabled for this surface")}async listConversations(e){let n=await this.historyFetch("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(n?.data)?n.data:[]).map(Aw),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Aw(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(e,n){this.assertHistoryUsable();let o=0;for(let d of n){let p=d.displayContent.length;if(p>Sw)throw new at("payload_too_large",`displayContent exceeds the ${Sw} character limit`);o+=p}if(o>Xf)throw new at("payload_too_large",`Display projection batch exceeds the ${Xf} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,s=r?.revision()??0,a=await this.historyFetch(`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=Xf,trackIdentity:!1}),l=typeof a?.conversationRevision=="string"?a.conversationRevision:null;return l&&this.clientSession?.conversationId===e&&(r?.revision()??0)===s&&this.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async deleteConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(e){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){let o=VC();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=()=>{if(e.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();a();let d=async()=>{a();let T=l,A=T.durableRecovery?.enabled===!0;if(A&&(!T.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");a();let I=await this.createClientSession({...A||this.isHistoryCapable()?{conversationId:T.conversationId,durableResume:A}:{storedSessionId:T.sessionId},signal:e.signal});if(a(),T.conversationId&&I.conversationId!==T.conversationId||A&&I.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.finishInit(I,T.conversationId??null,!1),this.clientSession=l,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await d();let p=await this.buildPayload(e.messages),u=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([T])=>T!=="sessionId"&&T!=="session_id")):void 0,m=this.isHistoryCapable(),y={sessionId:l.sessionId,messages:e.messages.filter(Zf).map(T=>{let A=m?Wl(T):void 0;return{id:T.id,role:T.role,content:T.contentParts??T.llmContent??T.rawContent??T.content,...A!==void 0&&{displayContent:A}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},g=async()=>{a();let T=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return a(),this.sendWithClientToolsDiff(l.sessionId,p.clientTools,A=>{let I={...y,sessionId:l.sessionId,...A};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",I),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":si,...T?{"X-Visitor-Token":T}:{}},body:JSON.stringify(I),signal:e.signal})})},b=await g();if(a(),b.response.status===401){let T=await b.response.clone().json().catch(()=>null);a(),T?.error==="Session not found or expired"&&(await d(),b=await g(),a())}let{response:C,commit:S}=b;if(!C.ok){let T=await C.json().catch(()=>({error:"Chat request failed"}));if(C.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let I=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:I}),I}if(C.status===429){let I=new Error(T.hint||"Message limit reached for this session.");throw s({type:"error",error:I}),I}if(C.status===410&&T.error==="conversation_deleted"){let I=new at("conversation_deleted","This conversation was deleted");throw s({type:"error",error:I}),I}let A=new Error(T.error||"Failed to send message");throw s({type:"error",error:A}),A}if(!C.body){let T=new Error("No response body received");throw s({type:"error",error:T}),T}S(),s({type:"status",status:"connected"});try{await this.streamResponse(C.body,s,e.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof at)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let o=`${this.clientApiBase()}/v1/agents/${e.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),a=s?HC(n):void 0,l=this.clientToolsFingerprintSessionId===e,d=s&&l&&this.lastSentClientToolsFingerprint===a,p=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,u=!1,m;for(let y=0;;y++){if(m=await o({...s&&(u||!d)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),m.status===409&&y===0&&s&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:p&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||xw}/resume`,a,l=null;if(r){let u=await this.initSession();a=u.sessionId,u.durableRecovery?.enabled===!0&&(l=await this.readVisitorToken())}let d={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...this.headers};this.getHeaders&&Object.assign(d,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(a&&(p.sessionId=a),r&&a){let u=[...ap(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:y}=await this.sendWithClientToolsDiff(a,u,g=>{let b={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token resume",b),fetch(s,{method:"POST",headers:d,body:JSON.stringify(b),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&y(),m}return fetch(s,{method:"POST",headers:d,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:e,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(s=>s.id===o)?{...e,model:o}:e}async buildAgentPayload(e,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Zf).filter(p=>p.role==="user"||p.role==="assistant"||p.role==="system").filter(p=>!p.variant||p.variant==="assistant").sort((p,u)=>{let m=new Date(p.createdAt).getTime(),y=new Date(u.createdAt).getTime();return m-y}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),s=this.normalizeComposerOptions(n),a={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(a.composerOptions=s);let l=[...ap(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(a.clientTools=l);let d=await this.buildContextAggregate(e);return d&&(a.context=d),a}async buildPayload(e,n){let o=e.slice().filter(Zf).sort((p,u)=>{let m=new Date(p.createdAt).getTime(),y=new Date(u.createdAt).getTime();return m-y}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),r=this.routing(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,u]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=u);let a=[...ap(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(s.clientTools=a);let l=await this.buildContextAggregate(e);l&&(s.context=l);let d=this.normalizeComposerOptions(n);if(d&&(s.composerOptions=d),this.requestMiddleware)try{let p=await this.requestMiddleware({payload:{...s},config:this.config});if(p&&typeof p=="object"){let u=p;return s.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=s.clientTools),u}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async handleCustomSSEEvent(e,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=m,r(m),m},p=u=>o.current?o.current:d(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=p(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,r(u)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),a=new TextDecoder,l="",d=Date.now(),p=0,u=()=>d+p++,m=X=>{let P=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,j=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,J=X.tools?X.tools.map(Q=>({...Q,chunks:Q.chunks?[...Q.chunks]:void 0})):void 0;return{...X,reasoning:P,toolCall:j,tools:J}},y=X=>{if(X.role!=="assistant"||X.variant)return!0;let P=Array.isArray(X.contentParts)&&X.contentParts.length>0,j=typeof X.rawContent=="string"&&X.rawContent.trim()!=="";return typeof X.content=="string"&&X.content.trim()!==""||P||j||!!X.stopReason},g=X=>{y(X)&&n({type:"message",message:m(X)})},b=null,C=null,S={current:null},T={current:null},A=null,I="",M=new Map,O=new Map,k=new Map,B=new Map,W=new Map,V=o,R=!1,w=()=>{if(b)return b;let X,P="",j=A;return!R&&V?(X=V,R=!0,P=r??""):V&&j?X=`${V}_${j}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:X,role:"assistant",content:P,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},g(b),b},E=X=>{let P=B.get(X);if(P)return P;let j={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:X,status:"streaming",chunks:[]}};return B.set(X,j),g(j),j},H=new Set,D=new Map,G=new Set,z=new Map,K=X=>{if(!X)return!1;let P=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return P==="emit_artifact_markdown"||P==="emit_artifact_component"},Y=X=>{let P=W.get(X);if(P)return P;let j={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:X,status:"pending"}};return W.set(X,j),g(j),j},re=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let P=Number(X);if(!Number.isNaN(P)&&Number.isFinite(P))return P;let j=Date.parse(X);if(!Number.isNaN(j))return j}return Date.now()},oe=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},se=new Map,ce=new Map,we=(X,P)=>{let j=oe(P),J=ce.get(X.id),Q=UL(J,j);X.rawContent=Q;let de=se.get(X.id),Me=ot=>{let Je=X.content??"";ot.trim()!==""&&(Je.trim().length===0||ot.startsWith(Je)||ot.trimStart().startsWith(Je.trim()))&&(X.content=ot)},Te=()=>{if(de){let ot=de.close?.();ot instanceof Promise&&ot.catch(()=>{})}se.delete(X.id),ce.delete(X.id),X.streaming=!1,g(X)};if(!de){Me(j),Te();return}let Fe=Rl(Q);if(Fe!==null&&Fe.trim()!==""){Me(Fe),Te();return}let je=ot=>{let Je=typeof ot=="string"?ot:ot?.text??null;if(Je!==null&&Je.trim()!=="")return Je;let mt=de.getExtractedText();return mt!==null&&mt.trim()!==""?mt:j},lt;try{lt=de.processChunk(Q)}catch{Me(j),Te();return}if(lt instanceof Promise){lt.then(ot=>{Me(je(ot)),Te()}).catch(()=>{Me(j),Te()});return}Me(je(lt)),Te()},ge=null,N=(X,P,j,J)=>{X.rawContent=P,se.has(X.id)||se.set(X.id,this.createStreamParser());let Q=se.get(X.id),de=P.trim().startsWith("{")||P.trim().startsWith("[");if(de&&ce.set(X.id,P),Q.__isPlainTextParser===!0){X.content=J!==void 0?P:X.content+j,ce.delete(X.id),se.delete(X.id),X.rawContent=void 0,g(X);return}let Te=Q.processChunk(P);if(Te instanceof Promise)Te.then(Fe=>{let je=typeof Fe=="string"?Fe:Fe?.text??null;je!==null&&je.trim()!==""?(X.content=je,g(X)):!de&&!P.trim().startsWith("<")&&(X.content=J!==void 0?P:X.content+j,ce.delete(X.id),se.delete(X.id),X.rawContent=void 0,g(X))}).catch(()=>{X.content=J!==void 0?P:X.content+j,ce.delete(X.id),se.delete(X.id),X.rawContent=void 0,g(X)});else{let Fe=typeof Te=="string"?Te:Te?.text??null;Fe!==null&&Fe.trim()!==""?(X.content=Fe,g(X)):!de&&!P.trim().startsWith("<")&&(X.content=J!==void 0?P:X.content+j,ce.delete(X.id),se.delete(X.id),X.rawContent=void 0,g(X))}},ye=(X,P)=>{let j=P??X.content;if(j==null||j===""){X.streaming=!1,g(X);return}let Q=ce.get(X.id)??oe(j);X.rawContent=Q;let de=se.get(X.id),Me=null,Te=!1;if(de&&(Me=de.getExtractedText(),Me===null&&(Me=Rl(Q)),Me===null)){let Fe=de.processChunk(Q);Fe instanceof Promise?(Te=!0,Fe.then(je=>{let lt=typeof je=="string"?je:je?.text??null;lt!==null&&(X.content=lt,X.streaming=!1,se.delete(X.id),ce.delete(X.id),g(X))}).catch(()=>{})):Me=typeof Fe=="string"?Fe:Fe?.text??null}if(!Te){Me!==null&&Me.trim()!==""?X.content=Me:ce.has(X.id)||(X.content=oe(j));let Fe=se.get(X.id);if(Fe){let je=Fe.close?.();je instanceof Promise&&je.catch(()=>{}),se.delete(X.id)}ce.delete(X.id),X.streaming=!1,g(X)}},ke=(X,P,j)=>{let J=O.get(X);if(J)return J;let Q={id:`nested-${P}-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...j?{variant:j}:{},...j==="reasoning"?{reasoning:{id:X,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:P}};return O.set(X,Q),g(Q),Q},nt=[],Ee,Ne=new Map,Pe=0,dt="agent",Xe=!1,xt=null,Ge=null,yt=this.config.iterationDisplay??"separate";for(Ee=()=>{for(let X=0;X<nt.length;X++){let P=nt[X];if(!Xe&&dt!=="flow"&&typeof P.stepType=="string"&&(dt="flow"),P.type==="reasoning_start"){let j=typeof P.id=="string"?P.id:null,J=typeof P.parentToolCallId=="string"&&P.parentToolCallId?P.parentToolCallId:null;if(j&&J){M.set(j,J),ke(j,J,"reasoning");continue}let Q=P.id,de=E(Q);de.reasoning=de.reasoning??{id:Q,status:"streaming",chunks:[]},de.reasoning.startedAt=de.reasoning.startedAt??Date.now(),de.reasoning.completedAt=void 0,de.reasoning.durationMs=void 0,(P.scope==="loop"||P.scope==="turn")&&(de.reasoning.scope=P.scope),de.streaming=!0,de.reasoning.status="streaming",g(de)}else if(P.type==="reasoning_delta"){let j=typeof P.id=="string"?P.id:null;if(j&&M.has(j)&&O.has(j)){let de=O.get(j),Me=P.delta;Me&&de.reasoning&&(de.reasoning.chunks.push(String(Me)),g(de));continue}let J=P.id,Q=E(J);Q.reasoning=Q.reasoning??{id:J,status:"streaming",chunks:[]},Q.reasoning.startedAt=Q.reasoning.startedAt??Date.now(),P.delta&&Q.reasoning.chunks.push(P.delta),Q.reasoning.status="streaming",Q.streaming=!0,g(Q)}else if(P.type==="reasoning_complete"){let j=typeof P.id=="string"?P.id:null;if(j&&M.has(j)&&O.has(j)){let Me=O.get(j);if(Me.reasoning){let Te=typeof P.text=="string"?P.text:"";Te&&Me.reasoning.chunks.length===0&&Me.reasoning.chunks.push(Te),Me.reasoning.status="complete",Me.streaming=!1,g(Me)}M.delete(j),O.delete(j);continue}let J=P.id,Q=typeof P.text=="string"?P.text:"";!B.get(J)&&(Q||P.scope==="loop")&&E(J);let de=B.get(J);if(de?.reasoning){(P.scope==="loop"||P.scope==="turn")&&(de.reasoning.scope=P.scope),Q&&de.reasoning.chunks.length===0&&de.reasoning.chunks.push(Q),de.reasoning.status="complete",de.reasoning.completedAt=Date.now();let Me=de.reasoning.startedAt??Date.now();de.reasoning.durationMs=Math.max(0,(de.reasoning.completedAt??Date.now())-Me),de.streaming=!1,g(de)}}else if(P.type==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof P.iteration=="number"&&(Pe=P.iteration);let j=P.toolCallId,J=P.toolName;if(K(J)){H.add(j);continue}let Q=Y(j),de=Q.toolCall??{id:j,status:"pending"};de.name=J??de.name,de.status="running",de.success=void 0,de.error=void 0,de.duration=void 0,P.parameters!==void 0&&(de.args=P.parameters),de.startedAt=de.startedAt??re(P.startedAt),de.completedAt=void 0,de.durationMs=void 0,Q.toolCall=de,Q.streaming=!0,P.executionId&&(Q.agentMetadata={executionId:P.executionId,iteration:P.iteration}),g(Q)}else if(P.type==="tool_output_delta"){let j=P.toolCallId;if(H.has(j))continue;let J=Y(j),Q=J.toolCall??{id:j,status:"running"};Q.startedAt=Q.startedAt??Date.now();let de=P.delta;de&&(Q.chunks=Q.chunks??[],Q.chunks.push(String(de))),Q.status="running",J.toolCall=Q,J.streaming=!0,P.executionId&&(J.agentMetadata=J.agentMetadata??{executionId:P.executionId,iteration:Pe}),g(J)}else if(P.type==="tool_complete"){let j=P.toolCallId;if(H.has(j)){H.delete(j);continue}let J=Y(j),Q=J.toolCall??{id:j,status:"running"};Q.status="complete",P.result!==void 0&&(Q.result=P.result),Q.name=P.toolName??Q.name,Q.success=P.success,Q.error=P.error,Q.completedAt=Date.now();let de=P.executionTime;if(typeof de=="number")Q.durationMs=de,Q.duration=de;else{let Me=Q.startedAt??Date.now();Q.durationMs=Math.max(0,(Q.completedAt??Date.now())-Me)}J.toolCall=Q,J.streaming=!1,P.executionId&&(J.agentMetadata=J.agentMetadata??{executionId:P.executionId,iteration:P.iteration??Pe}),g(J)}else if(P.type==="await"&&P.toolName){let j=typeof P.toolCallId=="string"&&P.toolCallId.length>0?P.toolCallId:void 0,J=j??P.toolId??`local-${u()}`,Q=Y(J),de=P.toolName,Me=P.origin==="webmcp"&&!ta(de)?`webmcp:${de}`:de,Te=ta(Me),Fe=Q.toolCall??{id:J,status:"pending"};Fe.name=Me,Fe.args=P.parameters,Fe.status=Te?"running":"complete",Fe.chunks=Fe.chunks??[],Fe.startedAt=Fe.startedAt??re(P.awaitedAt),Te?(Fe.completedAt=void 0,Fe.duration=void 0,Fe.durationMs=void 0):Fe.completedAt=Fe.completedAt??Fe.startedAt,Q.toolCall=Fe,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:P.executionId??Q.agentMetadata?.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},g(Q)}else if(P.type==="text_start"){let j=typeof P.id=="string"?P.id:null,J=typeof P.parentToolCallId=="string"&&P.parentToolCallId?P.parentToolCallId:null;if(j&&J){M.set(j,J);continue}let Q=b;Q&&(dt==="flow"?(ye(Q),ge=Q):(Q.streaming=!1,g(Q)),b=null),A=typeof P.id=="string"?P.id:A,I=""}else if(P.type==="text_delta"){let j=typeof P.id=="string"?P.id:null,J=j?M.get(j):void 0;if(j&&J){let Me=typeof P.delta=="string"?P.delta:"",Te=(k.get(j)??"")+Me;if(k.set(j,Te),Te.trim()==="")continue;let Fe=ke(j,J);Fe.agentMetadata={...Fe.agentMetadata,executionId:P.executionId,parentToolId:J},N(Fe,Te,Me,void 0);continue}if(A=typeof P.id=="string"?P.id:A,dt==="flow"){let Me=typeof P.delta=="string"?P.delta:"";if(I+=Me,I.trim()==="")continue;let Te=w();Te.agentMetadata={executionId:P.executionId,iteration:Pe},N(Te,I,Me,void 0),C=Te;continue}let Q=typeof P.delta=="string"?P.delta:"";I+=Q;let de=w();de.agentMetadata={executionId:P.executionId,iteration:Pe,turnId:xt??void 0,agentName:Ge?.agentName},N(de,I,Q,void 0),C=de}else if(P.type==="text_complete"){let j=typeof P.id=="string"?P.id:null;if(j&&M.has(j)){let Q=O.get(j);Q&&ye(Q),M.delete(j),k.delete(j),O.delete(j);continue}let J=b;J&&(dt==="flow"?(ye(J),ge=J):((J.content??"")===""&&typeof P.text=="string"&&(J.content=P.text),J.streaming=!1,g(J)),b=null),A=null,I=""}else if(P.type==="step_complete"){if(P.stepType==="tool")continue;if(P.success===!1){let j=P.error||"Step failed";n({type:"error",error:new Error(j)});let J=b;J&&J.streaming&&(J.streaming=!1,g(J)),n({type:"status",status:"idle"});continue}{let j=ge;ge=null;let J=P.stopReason,de=(P.result&&typeof P.result=="object"?P.result:null)?.response;if(j)J&&(j.stopReason=J),de!=null?we(j,de):j.streaming!==!1&&(se.delete(j.id),ce.delete(j.id),j.streaming=!1,g(j));else{let Me=de!=null&&de!=="";if(Me||J){let Te=w();J&&(Te.stopReason=J),Me?ye(Te,de):(Te.streaming=!1,g(Te))}}continue}}else if(P.type==="execution_start")dt=P.kind==="flow"?"flow":"agent",Xe=!0,dt==="agent"&&(Ge={executionId:P.executionId,agentId:P.agentId??"virtual",agentName:P.agentName??""});else if(P.type==="turn_start"){let j=typeof P.iteration=="number"?P.iteration:Pe;if(j!==Pe){if(yt==="separate"&&j>1){let J=b;J&&(J.streaming=!1,g(J),b=null)}Pe=j}xt=typeof P.id=="string"?P.id:null,C=null}else if(P.type==="tool_input_delta"){let j=P.toolCallId;if(j){let J=W.get(j);J?.toolCall&&(J.toolCall.chunks=J.toolCall.chunks??[],J.toolCall.chunks.push(P.delta??""),g(J))}}else if(P.type==="tool_input_complete"){if(H.has(P.toolCallId))continue;let j=Y(P.toolCallId),J=j.toolCall;J.args=P.parameters,J.name=P.toolName??J.name,g(j)}else if(P.type==="turn_complete"){let j=P.stopReason,J=b??C;if(j&&J!==null){let Q=P.id;(!Q||J.agentMetadata?.turnId===Q)&&(J.stopReason=j,g(J))}xt===P.id&&(xt=null)}else if(P.type==="media_start"){let j=String(P.id);Ne.set(j,{mediaType:typeof P.mediaType=="string"?P.mediaType:void 0,toolCallId:P.toolCallId,parts:[]})}else if(P.type==="media_delta"){let j=Ne.get(String(P.id));j&&typeof P.delta=="string"&&j.parts.push(P.delta)}else if(P.type==="media_complete"){let j=String(P.id),J=Ne.get(j);Ne.delete(j);let Q=(typeof P.mediaType=="string"?P.mediaType:void 0)??J?.mediaType??"application/octet-stream",de=typeof P.data=="string"?P.data:void 0,Me=typeof P.url=="string"?P.url:J&&J.parts.length>0?J.parts.join(""):void 0,Te=null;if(de)Te={type:"media",data:de,mediaType:Q};else if(Me){let ot=Q.toLowerCase();Te={type:ot==="image"||ot.startsWith("image/")?"image-url":"file-url",url:Me,mediaType:Q}}let Fe=P.toolCallId??J?.toolCallId,je=Te?[Te]:[],lt=[];for(let ot of je){if(!ot||typeof ot!="object")continue;let Je=ot,mt=typeof Je.type=="string"?Je.type:void 0,Tt=typeof Je.mediaType=="string"?Je.mediaType.toLowerCase():"",ee=null,Oe="";if(mt==="media"){let $e=typeof Je.data=="string"?Je.data:void 0;if(!$e)continue;Oe=Tt.length>0?Tt:"application/octet-stream",ee=`data:${Oe};base64,${$e}`}else if(mt==="image-url"){let $e=typeof Je.url=="string"?Je.url:void 0;if(!$e)continue;Oe=Tt,ee=$e}else if(mt==="file-url"){let $e=typeof Je.url=="string"?Je.url:void 0;if(!$e)continue;Oe=Tt,ee=$e}else continue;if(ee)if(mt==="image-url"||Oe.startsWith("image/"))lt.push({type:"image",image:ee,...Oe.includes("/")?{mimeType:Oe}:{}});else if(Oe.startsWith("audio/"))lt.push({type:"audio",audio:ee,mimeType:Oe});else if(Oe.startsWith("video/"))lt.push({type:"video",video:ee,mimeType:Oe});else{let $e=Oe||"application/octet-stream";lt.push({type:"file",data:ee,mimeType:$e,filename:$L($e)})}}if(lt.length>0){let ot=u(),Je=Fe,Tt={id:`agent-media-${typeof Je=="string"&&Je.length>0?`${Je}-${ot}`:String(ot)}`,role:"assistant",content:"",contentParts:lt,createdAt:new Date().toISOString(),streaming:!1,sequence:ot,agentMetadata:{executionId:P.executionId,iteration:Pe}};g(Tt);let ee=b;ee&&(ee.streaming=!1,g(ee)),b=null,S.current=null}}else if(P.type==="execution_complete"){let j=b;j&&(P.kind==="flow"&&j.streaming!==!1?ye(j):(j.streaming=!1,g(j)),b=null),A=null,I="",ge=null,n({type:"status",status:"idle",terminal:!0})}else if(P.type==="execution_error"){let j=typeof P.error=="string"?P.error:P.error?.message??"Execution error";n({type:"error",error:new Error(j)})}else if(P.type!=="ping"){if(P.type==="approval_start"){let j=P.approvalId??`approval-${u()}`,J={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:Ge?.agentId??"virtual",executionId:P.executionId??Ge?.executionId??"",toolName:P.toolName??"",toolType:P.toolType,description:P.description??`Execute ${P.toolName??"tool"}`,...typeof P.reason=="string"&&P.reason?{reason:P.reason}:{},parameters:P.parameters}};g(J)}else if(P.type==="approval_complete"){let j=P.approvalId;if(j){let Q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:P.decision??"approved",agentId:Ge?.agentId??"virtual",executionId:P.executionId??Ge?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};g(Q)}}else if(P.type==="artifact_start"||P.type==="artifact_delta"||P.type==="artifact_update"||P.type==="artifact_complete"){if(P.type==="artifact_start"){let j=P.artifactType,J=String(P.id),Q=typeof P.title=="string"?P.title:void 0,de=P.file,Me;if(de&&typeof de=="object"&&!Array.isArray(de)&&typeof de.path=="string"&&typeof de.mimeType=="string"&&(Me={path:de.path,mimeType:de.mimeType,...typeof de.language=="string"?{language:de.language}:{}}),n({type:"artifact_start",id:J,artifactType:j,title:Q,component:typeof P.component=="string"?P.component:void 0,...Me?{file:Me}:{}}),z.set(J,{markdown:"",title:Q,file:Me}),!G.has(J)){G.add(J);let Te=is(this.config.features?.artifacts,{artifactType:j,...Me?{file:Me}:{}}),Fe=typeof P.component=="string"?P.component:void 0,je={id:`artifact-ref-${J}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:El(Te,{artifactId:J,title:Q,artifactType:j,status:"streaming",...Me?{file:Me}:{},...Fe?{component:Fe}:{}})};D.set(J,je),g(je)}}else if(P.type==="artifact_delta"){let j=String(P.id),J=typeof P.delta=="string"?P.delta:String(P.delta??"");n({type:"artifact_delta",id:j,artDelta:J});let Q=z.get(j);Q&&(Q.markdown+=J)}else if(P.type==="artifact_update"){let j=P.props&&typeof P.props=="object"&&!Array.isArray(P.props)?P.props:{};n({type:"artifact_update",id:String(P.id),props:j,component:typeof P.component=="string"?P.component:void 0});let J=z.get(String(P.id));J&&(J.props={...J.props??{},...j})}else if(P.type==="artifact_complete"){let j=String(P.id);n({type:"artifact_complete",id:j});let J=D.get(j);if(J){J.streaming=!1;try{let Q=JSON.parse(J.rawContent??"{}");if(Q.props){Q.props.status="complete";let de=z.get(j);de?.markdown&&(Q.props.markdown=de.markdown),de?.file&&(Q.props.file=de.file),Q.component==="PersonaArtifactInline"&&de?.props&&Object.keys(de.props).length>0&&(Q.props.componentProps=de.props)}J.rawContent=JSON.stringify(Q)}catch{}z.delete(j),g(J),D.delete(j)}}}else if(P.type==="error"&&P.recoverable===!1&&P.error!=null&&P.error!==""){let j=typeof P.error=="string"?P.error:P.error?.message!=null?String(P.error.message):"Execution error";n({type:"error",error:new Error(j)});let J=b;J&&J.streaming&&(J.streaming=!1,g(J)),n({type:"status",status:"idle"})}}}nt.length=0};;){let{done:X,value:P}=await s.read();if(X)break;l+=a.decode(P,{stream:!0});let j=l.split(`
1140
+ `});function nb(t){if(!t)return wm;let e={...wm};for(let n of w1){let o=t[n];typeof o=="string"&&o.length>0&&(e[n]=o)}return e}var w1,wm,ob=be(()=>{"use strict";w1=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],wm={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."}});function Gc(t){if(!t)return Kc;let e={...Kc};for(let[n,o]of Object.entries(t))typeof o=="string"&&o.length>0&&(e[n]=o);return e}function wr(t,e){return t.replace(/\{(\w+)\}/g,(n,o)=>o in e?String(e[o]):n)}var Kc,Yc=be(()=>{"use strict";ob();Kc={...wm,emptyTitle:"No conversations yet",emptyDescription:"Start a conversation and it will show up here.",errorTitle:"Could not load conversations",errorDescription:"Something went wrong. Please try again.",retryLabel:"Retry",rateLimitedTitle:"Too many requests",rateLimitedDescription:"Please wait a moment before trying again.",groupStarred:"Starred",groupToday:"Today",groupYesterday:"Yesterday",groupPrevious7Days:"Previous 7 days",groupPrevious30Days:"Previous 30 days",groupMonthYear:"{month} {year}",browserOnlyTitle:"On this device",browserOnlyDescription:"Another browser or device keeps its own separate history.",verifyingTitle:"Checking your account",verifyingDescription:"Looking for messages linked to your account.",verifiedTitle:"Available across signed-in devices",verifiedDescription:"This list refreshes when the chat opens rather than syncing live.",authenticationRequiredTitle:"Sign in to see your messages",authenticationRequiredDescription:"Your session expired. Sign in again to load account history.",identityProviderFailedTitle:"Account history is unavailable",identityProviderFailedDescription:"We could not verify your account, so account history is not shown here.",proofNotAdmittedTitle:"Account history is unavailable",proofNotAdmittedDescription:"This assistant is not set up to accept your account identity.",retryIdentityLabel:"Try again",backLabel:"Back to conversation",closeLabel:"Close conversation list",loadingLabel:"Loading conversations",loadMoreLabel:"Load more",loadingMoreLabel:"Loading more conversations",conversationsTitle:"Conversations",rowActionsLabel:"Conversation options",listOptionsLabel:"Conversation options",deleteConversationLabel:"Delete",clearHistoryLabel:"Delete all conversations",resetIdentityLabel:"Forget this device",messageCountLabel:"{count} messages",messageCountLabelOne:"1 message",conversationRemovedNotice:"Conversation deleted.",historyClearedNotice:"All conversations were deleted.",unavailableTitle:"Conversation history is unavailable",unavailableDescription:"Try again later.",newConversationRequiredTitle:"Start a new conversation",newConversationRequiredDescription:"The previous conversation is gone. Start a new one to keep chatting.",rateLimitedWaitDescription:"You can try again in {seconds} seconds.",openFailedLabel:"Could not open that conversation.",deleteFailedLabel:"Could not delete that conversation.",relativeNow:"now",relativeMinutes:"{value}m",relativeHours:"{value}h",relativeDays:"{value}d",relativeWeeks:"{value}w",relativeYears:"{value}y"}});function x1(t){let e=new Date(t);return e.setHours(0,0,0,0),e.getTime()}function sb(t,e){let n=Date.parse(t);return Number.isFinite(n)?n:e}function S1(t,e){let n=sb(t,e),o=x1(e);if(n>=o)return"today";if(n>=o-rb)return"yesterday";if(n>=o-7*rb)return"previous-7-days";if(n>=o-30*rb)return"previous-30-days";let r=new Date(n);return`month:${r.getFullYear()}-${r.getMonth()}`}function A1(t,e,n,o){if(t==="today")return o.groupToday;if(t==="yesterday")return o.groupYesterday;if(t==="previous-7-days")return o.groupPrevious7Days;if(t==="previous-30-days")return o.groupPrevious30Days;let r=new Date(sb(e,n));return wr(o.groupMonthYear,{month:r.toLocaleString(void 0,{month:"long"}),year:r.getFullYear()})}function RE(t,e,n,o="time"){let r=t.filter(a=>a.starred),s=r.length>0?[{key:"starred",label:n.groupStarred,items:r}]:[];if(o==="none"){let a=t.filter(l=>!l.starred);return a.length>0&&s.push({key:"recent",label:n.conversationsTitle,items:a}),s}for(let a of t){if(a.starred)continue;let l=S1(a.updatedAt,e),c=s[s.length-1];if(c&&c.key===l){c.items.push(a);continue}s.push({key:l,label:A1(l,a.updatedAt,e,n),items:[a]})}return s}function HE(t,e,n){let o=Math.max(0,e-sb(t,e)),r=Math.floor(o/6e4);if(r<1)return n.relativeNow;if(r<60)return wr(n.relativeMinutes,{value:r});let s=Math.floor(r/60);if(s<24)return wr(n.relativeHours,{value:s});let a=Math.floor(s/24);if(a<7)return wr(n.relativeDays,{value:a});let l=Math.floor(a/7);return a<365?wr(n.relativeWeeks,{value:l}):wr(n.relativeYears,{value:Math.floor(a/365)})}function WE(t,e){return t===1?e.messageCountLabelOne:wr(e.messageCountLabel,{count:t})}var rb,ib=be(()=>{"use strict";Yc();rb=864e5});function Os(t,e=20){let n=document.createElementNS(xm,"svg");if(n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","2"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),t==="ellipsis"){for(let r of[12,19,5]){let s=document.createElementNS(xm,"circle");s.setAttribute("cx",String(r)),s.setAttribute("cy","12"),s.setAttribute("r","1"),n.appendChild(s)}return n}let o=T1[t];if(o){let r=document.createElementNS(xm,"rect");r.setAttribute("x",String(o[0])),r.setAttribute("y",String(o[1])),r.setAttribute("width",String(o[2])),r.setAttribute("height",String(o[3])),r.setAttribute("rx","2"),n.appendChild(r)}for(let r of M1[t]){let s=document.createElementNS(xm,"path");s.setAttribute("d",r),n.appendChild(s)}return n}var xm,M1,T1,ab=be(()=>{"use strict";xm="http://www.w3.org/2000/svg",M1={"arrow-left":["m12 19-7-7 7-7","M19 12H5"],plus:["M5 12h14","M12 5v14"],star:["m12 2 2.9 6.2 6.8.7-5.1 4.5 1.4 6.6-6-3.4-6 3.4 1.4-6.6-5.1-4.5 6.8-.7z"],x:["M18 6 6 18","m6 6 12 12"],"panel-left":["M9 3v18"],monitor:["M8 21h8","M12 17v4"],ellipsis:[]},T1={"panel-left":[3,3,18,18],monitor:[2,3,20,14]}});function k1(t){let e=F("span",{className:"persona-history-row-avatar",attrs:{"aria-hidden":"true"}});return E1.test(t)?e.appendChild(F("img",{attrs:{src:t,alt:"",loading:"lazy"}})):e.textContent=t,e}function BE(t){let{conversation:e,copy:n,busy:o,pending:r}=t,s=o||r!==null,a=e.title.trim().length>0,l=e.starred?(()=>{let h=Os("star",11);return h.setAttribute("fill","currentColor"),h.setAttribute("stroke-width","1"),F("span",{className:"persona-history-row-star"},h,F("span",{className:"persona-history-sr-only",text:n.groupStarred}))})():null,c=F("div",{className:"persona-history-row-head"},F("span",{className:"persona-history-row-title persona-history-truncate",text:a?e.title:e.preview??""}),l,F("time",{className:"persona-history-row-time",attrs:{datetime:e.updatedAt},text:HE(e.updatedAt,t.nowMs,n)})),p=a&&e.preview?F("span",{className:"persona-history-row-preview persona-history-truncate",text:e.preview}):null,u=F("button",{className:Gt("persona-history-row",t.active&&"persona-history-row--active",r&&`persona-history-row--${r}`),attrs:{type:"button","data-persona-history-focus":P1(e.id),"data-persona-history-conversation":e.id,...t.active?{"aria-current":"page"}:{},...s?{"aria-disabled":"true"}:{},...r?{"aria-busy":"true"}:{}}},t.avatar?k1(t.avatar):null,F("div",{className:"persona-history-row-body"},c,p,F("span",{className:"persona-history-row-count persona-history-sr-only",text:WE(e.messageCount,n)})));u.addEventListener("click",()=>{s||t.onOpen()});let m=t.showDelete?lb({className:"persona-history-row-menu-button",label:`${n.rowActionsLabel}: ${e.title}`,focusKey:L1(e.id),open:t.menuOpen,inert:s,onToggle:t.onToggleMenu}):null;return F("li",{className:Gt("persona-history-item",!t.showDelete&&"persona-history-item--no-menu"),attrs:{"data-persona-history-item":e.id}},u,m,t.menuOpen&&t.showDelete?I1(t):null,t.error?R1(t.error,n,e.id):null)}function I1(t){let{conversation:e,copy:n}=t;return cb({label:`${n.rowActionsLabel}: ${e.title}`,items:[{label:n.deleteConversationLabel,focusKey:Qc(e.id),danger:!0,onSelect:t.onDelete}],onCloseMenu:t.onCloseMenu})}function lb(t){let e=F("button",{className:Gt("persona-history-icon-button",t.className),attrs:{type:"button","aria-label":t.label,"aria-haspopup":"menu","aria-expanded":t.open?"true":"false","data-persona-history-focus":t.focusKey,...t.inert?{"aria-disabled":"true"}:{}}});e.appendChild(Os("ellipsis",t.iconSize));let n=()=>e.getAttribute("aria-disabled")==="true";return e.addEventListener("click",o=>{o.stopPropagation(),!n()&&t.onToggle()}),e.addEventListener("keydown",o=>{o.key!=="ArrowDown"&&o.key!=="ArrowUp"||(o.preventDefault(),!(n()||e.getAttribute("aria-expanded")==="true")&&t.onToggle())}),e}function cb(t){let e=F("div",{className:"persona-history-menu",attrs:{role:"menu","aria-label":t.label}});for(let n of t.items){let o=F("button",{className:Gt("persona-history-menu-item",n.danger&&"persona-history-menu-item--danger"),text:n.label,attrs:{type:"button",role:"menuitem",tabindex:"0","data-persona-history-focus":n.focusKey}});o.addEventListener("click",()=>{t.onCloseMenu(),n.onSelect()}),e.appendChild(o)}return e.addEventListener("keydown",n=>{let o=Array.from(e.querySelectorAll('[role="menuitem"]'));if(o.length===0)return;let r=o.indexOf(document.activeElement);if(n.key==="Tab"){t.onCloseMenu({restoreFocus:!0});return}if(n.key==="ArrowDown"){n.preventDefault(),o[(r+1+o.length)%o.length]?.focus();return}if(n.key==="ArrowUp"){n.preventDefault(),o[(r-1+o.length)%o.length]?.focus();return}if(n.key==="Home"){n.preventDefault(),o[0]?.focus();return}n.key==="End"&&(n.preventDefault(),o[o.length-1]?.focus())}),e}function R1(t,e,n){let o=F("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":`row-retry:${n}`}});return o.addEventListener("click",t.retry),F("div",{className:"persona-history-row-error",attrs:{role:"alert"}},F("span",{text:t.message}),o)}var E1,P1,L1,Qc,DE=be(()=>{"use strict";je();ab();ib();E1=/^(https?:|\/|data:)/i;P1=t=>`row:${t}`,L1=t=>`menu:${t}`,Qc=t=>`menu-item:${t}`});function H1(t){switch(t){case"authentication_failed":case"authentication_required":case"identity_provider_failed":case"proof_not_admitted":case"unsupported_scope":case"unavailable":return t;default:return"unknown"}}function OE(t){if(Gp(t)){if(t.code==="rate_limited")return{kind:"rate_limited",retryAfterSeconds:t.retryAfterSeconds??0};let e=H1(t.code);return{kind:"error",reason:e,retryable:e!=="unsupported_scope"}}return{kind:"error",reason:"unknown",retryable:!0}}function W1(t,e){switch(t.state){case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};default:return null}}function B1(t,e){switch(t){case"authentication_required":case"authentication_failed":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"proof_not_admitted":case"unsupported_scope":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription};default:return{title:e.errorTitle,description:e.errorDescription}}}function Sm(t,e,n,o){let r=F("button",{className:"persona-history-secondary persona-history-state-action",text:t,attrs:{type:"button","data-persona-history-focus":e,...n?{"aria-disabled":"true"}:{}}});return r.addEventListener("click",()=>{n||o()}),r}function Xc(t,e,n,o,r){return F("div",{className:"persona-history-state",attrs:{"data-persona-history-state":t,...r?{role:"alert"}:{role:"status"}}},F("p",{className:"persona-history-state-title",text:e}),F("p",{className:"persona-history-state-description",text:n}),o)}function D1(t){let e=["42%","58%","34%"],n=["94%","78%","88%"],o=[0,1,2].map(r=>F("div",{className:"persona-history-skeleton-row",attrs:{"aria-hidden":"true"}},F("div",{className:"persona-history-skeleton-head"},F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--title",style:{width:e[r]}}),F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--time"})),F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--preview",style:{width:n[r]}})));return F("div",{className:"persona-history-view-loading",attrs:{"data-persona-history-state":"loading",role:"status","aria-label":t.loadingLabel}},...o)}function _E(t){let{state:e,copy:n,busy:o}=t;if(e.kind==="loading")return D1(n);if(e.kind==="empty"){let l=W1(t.identityStatus,n);return l?Xc("identity",l.title,l.description,t.onRetry?Sm(n.retryIdentityLabel,"state-retry",o,t.onRetry):null,!0):Xc("empty",n.emptyTitle,n.emptyDescription,null,!1)}if(e.kind==="rate_limited"){let l=e.retryAfterSeconds>0?wr(n.rateLimitedWaitDescription,{seconds:e.retryAfterSeconds}):n.rateLimitedDescription;return Xc("rate_limited",n.rateLimitedTitle,l,t.onRetry?Sm(n.retryLabel,"state-retry",o,t.onRetry):null,!1)}if(e.kind==="new_conversation_required")return Xc("new_conversation_required",n.newConversationRequiredTitle,n.newConversationRequiredDescription,t.onStartNew?Sm(n.newConversationLabel,"state-retry",o,t.onStartNew):null,!0);let{title:r,description:s}=B1(e.reason,n),a=e.reason==="authentication_required"||e.reason==="authentication_failed"||e.reason==="identity_provider_failed"?n.retryIdentityLabel:n.retryLabel;return Xc("error",r,s,e.retryable&&t.onRetry?Sm(a,"state-retry",o,t.onRetry):null,!0)}var NE=be(()=>{"use strict";je();Yc();Zl()});function Am(t){return`${t.state}:${"reason"in t?t.reason:""}`}function VE(t,e){switch(t.state){case"verified":return{title:e.verifiedTitle,description:e.verifiedDescription,pending:!1};case"verifying":case"resetting":return{title:e.verifyingTitle,description:e.verifyingDescription,pending:!0};case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription,pending:!1};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription,pending:!1};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription,pending:!1};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription,pending:!1};default:return{title:e.browserOnlyTitle,description:e.browserOnlyDescription,pending:!1}}}function U1(t){return t.state==="verified"||t.state==="browser_only"}function q1(t){return t.state==="authentication_required"||t.state==="identity_provider_failed"||t.state==="configuration_error"}function db(t){let e=Gc(t.copy),n=t.now??(()=>Date.now()),o=t.pageSize??O1,r=`persona-history-title-${Math.random().toString(36).slice(2,8)}`,s=[],a=null,l={kind:"loading",phase:"initial"},c=null,p=t.activeConversationId,u=t.provider.getIdentityStatus(),m=Am(u),g=null,h=!1,b=!1,C=0,M=t.presentation,E=t.collapsible!==!1,T=t.collapsed===!0,H=t.railSide==="right",A=t.renderDom!==!1,D=new Map,W=null,U=kE(),B=z=>{!A&&t.onAnnounce?t.onAnnounce(z):U.announce(z)},O=()=>c!==null,R=`${r}-body`,S=F("button",{className:"persona-history-icon-button persona-history-back",attrs:{type:"button"}}),x=()=>M==="rail"&&E,P,L=()=>{if(t.railBrand){if(!x()){S.classList.remove("persona-history-back--branded");return}if(P===void 0){let z=t.railBrand(!0);P=z?F("span",{className:"persona-history-brand-mark persona-history-toggle-brand",attrs:{"aria-hidden":"true"}},z):null}P&&(S.classList.add("persona-history-back--branded"),S.appendChild(P))}},G=()=>{let z=x(),ge=M==="rail";S.setAttribute("data-persona-history-focus",z?"collapse":"close"),S.setAttribute("aria-label",z?T?e.expandLabel:e.collapseLabel:ge?e.closeLabel:e.backLabel),z?(S.setAttribute("aria-expanded",T?"false":"true"),S.setAttribute("aria-controls",R),t.collapseShortcut?.aria&&S.setAttribute("aria-keyshortcuts",t.collapseShortcut.aria)):(S.removeAttribute("aria-expanded"),S.removeAttribute("aria-controls"),S.removeAttribute("aria-keyshortcuts")),S.replaceChildren(Os(z?"panel-left":ge?"x":"arrow-left")),L()};G(),S.addEventListener("click",()=>{x()?t.onToggleCollapse?.():t.onClose()});let V=F("h2",{className:"persona-history-title",text:e.viewTitle,attrs:{id:r}}),K=F("span",{className:"persona-history-scope-title"}),ee=F("p",{className:"persona-history-scope"},F("span",{className:"persona-history-scope-icon",attrs:{"aria-hidden":"true"}},Os("monitor",14)),K),oe=F("div",{className:"persona-history-heading-group"},V),ne=!1,le,de=()=>{let z=M==="rail",ge=z?t.renderRailHeader:void 0,Ue=null,at=ge!==void 0;if(ge)try{Ue=ge({collapsed:T,defaultTitle:e.viewTitle})}catch(Ce){at=!1,ne||(ne=!0,console.warn("[persona] history rail renderHeader threw",Ce))}if(!at&&z&&t.railBrand){if(le===void 0){let Ce=t.railBrand(!1);le=Ce?F("span",{className:"persona-history-heading-brand",attrs:{"aria-hidden":"true"}},F("span",{className:"persona-history-brand-mark"},Ce),F("span",{className:"persona-history-wordmark",text:e.viewTitle})):null}le&&(at=!0,Ue=le)}V.classList.toggle("persona-history-sr-only",at),oe.replaceChildren(V),Ue&&oe.appendChild(Ue)};de();let ve=F("button",{className:"persona-history-icon-button persona-history-new-icon",attrs:{type:"button","data-persona-history-focus":"new-icon","aria-label":e.newConversationLabel}});ve.appendChild(Os("plus")),ve.addEventListener("click",()=>{we()});let Le=[S,ve].map(z=>t.attachTooltip?.({anchor:z,text:()=>z.getAttribute("aria-label")??"",...z===S&&t.collapseShortcut?{hint:()=>x()?t.collapseShortcut.hint:""}:{}})),se=F("div",{className:"persona-history-topbar"}),_=null,Te=()=>{let z=M==="rail",ge=z?H?"rail-right":"rail":"panel";ge!==_&&(_=ge,ge==="rail"?se.append(oe,S):se.append(S,oe),z?ve.remove():se.appendChild(ve),Y.classList.toggle("persona-history-view--rail-right",ge==="rail-right"))},He=F("div",{className:"persona-history-scope-alert"}),ut=`${r}-scope`,At=Os("plus",18),Wt=F("button",{className:"persona-history-new",attrs:{type:"button","data-persona-history-focus":"new"}},At,F("span",{text:e.newConversationLabel}));Wt.addEventListener("click",()=>{we()});let bt=F("div",{className:"persona-history-list-region"}),xe=t.showDeleteAll!==!1,Ne=!!t.provider.resetDevice,Ae=t.listActions??[],vt=xe||Ne||Ae.length>0?lb({className:"persona-history-list-options",label:e.listOptionsLabel,focusKey:`menu:${Vi}`,open:!1,inert:!0,iconSize:16,onToggle:()=>ot(Vi)}):null,X=F("h3",{className:"persona-history-conversations-title",text:e.conversationsTitle}),I=F("div",{className:"persona-history-caption",attrs:{"data-persona-history-item":Vi}},X,t.showScopeStatus?ee:null,vt),j=F("div",{className:"persona-history-body",attrs:{id:R}},t.showScopeStatus?He:null,Wt,I,bt),J=t.headerPlacement??"inline";J==="external"&&se.classList.add("persona-history-topbar--shell","persona-history-topbar--shell-enter");let Y=F("div",{className:Gt("persona-history-view",`persona-history-view--${t.presentation}`,"persona-history-view--enter"),attrs:{role:"region","aria-labelledby":r,"data-persona-history-presentation":t.presentation}},U.element,J==="inline"?se:null,j),ie=()=>{Y.classList.toggle("persona-history-view--rail-collapsed",T&&x())};ie(),Te();let Me=(z,ge)=>{let Ue=`${r}-s${ge}`,at=F("div",{className:Gt("persona-history-nav",z.placement==="footer"&&"persona-history-nav--footer"),attrs:{role:"group","data-persona-rail-section":z.id,...z.title?{"aria-labelledby":Ue}:{"aria-label":z.id}}});z.title&&at.appendChild(F("h3",{className:"persona-history-group-heading",text:z.title,attrs:{id:Ue}}));for(let Ce of z.items){let St=Ce.iconNode?.()??null,Bn=F("button",{className:Gt("persona-history-nav-item",St&&"persona-history-nav-item--icon"),attrs:{type:"button","aria-label":Ce.label,"data-persona-rail-item":Ce.id}},St?F("span",{className:"persona-history-nav-icon"},St):null,F("span",{className:"persona-history-nav-label persona-history-truncate",text:Ce.label}),Ce.badge?F("span",{className:"persona-history-nav-badge",text:Ce.badge}):null);Bn.addEventListener("click",()=>Ce.onSelect()),at.appendChild(Bn)}return at},Ee=null,Oe=null,Ct=()=>{!Ee||!A||M!=="rail"||T===Oe||(Oe=T,t.railSections.forEach((z,ge)=>{if(!z.render)return;let Ue=Ee[ge],at=z.title?Ue.firstElementChild:null,Ce=null;try{Ce=z.render(T)}catch(St){z.render=void 0,console.warn("[persona] history rail section threw",z.id,St)}Ue.replaceChildren(...at?[at]:[],...Ce?[Ce]:[]),Ue.hidden=!Ce}))},Ot=()=>{let z=t.railSections;if(Y.classList.toggle("persona-history-view--has-nav",M==="rail"&&!!z?.some(ge=>ge.placement==="above-conversations")),!!z?.length){if(M!=="rail"){Ee?.forEach(ge=>ge.remove());return}Ee??(Ee=z.map(Me));for(let ge of["above-conversations","below-conversations","footer"]){let Ue=ge==="above-conversations"?I.parentNode===j?I:bt:null;z.forEach((at,Ce)=>{at.placement===ge&&j.insertBefore(Ee[Ce],Ue)})}Ct()}};Ot(),mu(Y,"persona-history-view",LE);let rt=(z,ge)=>{let Ue=Y.ownerDocument.defaultView?.getComputedStyle(Y).getPropertyValue(z),at=Number.parseFloat(Ue??"");return Number.isFinite(at)&&at>=0?at:ge},Ze=(z,ge)=>Y.ownerDocument.defaultView?.getComputedStyle(Y).getPropertyValue(z).trim()||ge,ct=null,Rt=()=>{ct!==null&&(clearTimeout(ct),ct=null),Y.removeEventListener("animationend",Rt),Y.classList.remove("persona-history-view--enter")};Y.addEventListener("animationend",Rt),ct=setTimeout(()=>{ct=setTimeout(Rt,rt("--persona-history-enter-ms",_1)+60)},0);let Z=null,Fe=()=>{Z!==null&&(clearTimeout(Z),Z=null),se.classList.remove("persona-history-topbar--shell-enter")},Re=()=>{Fe(),se.classList.add("persona-history-topbar--shell-enter"),Z=setTimeout(Fe,FE+60)};J==="external"&&(Z=setTimeout(Fe,FE+60));let nt=[],Bt=null,Ie=()=>{if(Bt)return Bt;if(b||$1()||typeof Y.animate!="function")return Rt(),null;let z=Y.ownerDocument.defaultView?.getComputedStyle(j).opacity||"1";Rt(),Y.style.pointerEvents="none",qe.style.pointerEvents="none";let ge={duration:rt("--persona-history-exit-ms",N1),easing:Ze("--persona-history-exit-easing",F1),fill:"forwards"},Ue=V1[M];return nt=[j.animate([{opacity:z,transform:"none"},{opacity:0,transform:`translateX(${Ue}px)`}],ge)],Bt=Promise.all(nt.map(z1)).then(()=>{}),Bt},Be=(z,ge)=>{z&&(ge?z.setAttribute("aria-disabled","true"):z.removeAttribute("aria-disabled"))},qe=se,Tt=null,mt=()=>{let z=t.slots?.header;if(!z)return;let ge=`${M}|${Am(u)}|${c?`${c.kind}:${"conversationId"in c?c.conversationId:""}`:""}`;if(ge===Tt)return;Tt=ge;let Ue=z({identityStatus:u,pendingAction:c,copy:e,defaultRenderer:()=>se})??se;Ue!==qe&&(qe.replaceWith(Ue),qe=Ue)},xt=null,Mn=()=>{if(!t.showScopeStatus)return;let z=Am(u);if(z===xt)return;xt=z;let ge=VE(u,e);K.textContent=ge.title;let Ue=U1(u);if(ee.hidden=!Ue,He.replaceChildren(...Ue?[]:[F("span",{className:"persona-history-scope-alert-title",text:ge.title})],F("span",{className:"persona-history-scope-description",text:ge.description,attrs:{id:ut}})),He.setAttribute("data-persona-history-scope-tone",Ue?"ambient":"attention"),Ue?ee.setAttribute("aria-describedby",ut):ee.removeAttribute("aria-describedby"),ge.pending?He.setAttribute("role","status"):He.removeAttribute("role"),He.setAttribute("data-persona-history-identity",u.state),ee.setAttribute("data-persona-history-identity",u.state),q1(u)){let at=F("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryIdentityLabel,attrs:{type:"button","data-persona-history-focus":"identity-retry"}});at.addEventListener("click",()=>{O()||We("refresh")}),He.appendChild(at)}},ft=z=>c?c.kind==="open"&&c.conversationId===z?"opening":c.kind==="delete"&&c.conversationId===z?"deleting":null:null,_t=()=>{let z=document.activeElement;return!(z instanceof HTMLElement)||!Y.contains(z)?null:z.getAttribute("data-persona-history-focus")},Vt=z=>{if(h&&g){h=!1;let ge=Y.querySelector(`[data-persona-history-focus="${Qc(g)}"]`);if(ge){ge.focus();return}}z&&Y.querySelector(`[data-persona-history-focus="${z}"]`)?.focus()},pn=()=>{if(!W)return null;let z=F("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":"action-retry"}}),ge=W;return z.addEventListener("click",()=>{O()||ge.retry()}),F("div",{className:"persona-history-row-error",attrs:{role:"alert"}},F("span",{text:ge.message}),z)},ao=()=>RE(s,n(),e,t.grouping).map((z,ge)=>{let Ue=`${r}-g${ge}`,at=F("ul",{className:"persona-history-list",attrs:{"aria-labelledby":Ue}});for(let Ce of z.items){let St=()=>BE({conversation:Ce,active:Ce.id===p,pending:ft(Ce.id),busy:O(),menuOpen:g===Ce.id,error:D.get(Ce.id)??null,avatar:t.rowAvatar,showDelete:t.showDelete!==!1,nowMs:n(),copy:e,onOpen:()=>{Xo(Ce.id)},onToggleMenu:()=>ot(Ce.id),onCloseMenu:$e=>Nt($e),onDelete:()=>{lo(Ce.id)}}),Yn=t.slots?.conversation?.({conversation:Ce,active:Ce.id===p,pending:ft(Ce.id),open:()=>Xo(Ce.id),requestDelete:()=>lo(Ce.id),defaultRenderer:St})??St();at.appendChild(Yn instanceof HTMLLIElement?Yn:F("li",{className:"persona-history-item"},Yn))}return F("div",{className:"persona-history-group",attrs:{"data-persona-history-group":z.key}},F("h3",{className:Gt("persona-history-group-heading",z.key==="recent"&&"persona-history-sr-only"),text:z.label,attrs:{id:Ue}}),at)}),Gn=()=>{if(!a)return null;let z=c?.kind==="load-more"||l.kind==="loading"&&l.phase==="load-more",ge=F("button",{className:"persona-history-secondary persona-history-load-more",text:z?e.loadingMoreLabel:e.loadMoreLabel,attrs:{type:"button","data-persona-history-focus":"load-more",...z?{"aria-busy":"true","aria-disabled":"true"}:{},...O()&&!z?{"aria-disabled":"true"}:{}}});return ge.addEventListener("click",()=>{O()||We("load-more")}),ge},Zc=()=>{let z=_t(),ge=[pn()],Ue=s.length>0;if(Ue&&(ge.push(...ao()),ge.push(Gn())),l.kind!=="ready"&&!(l.kind==="loading"&&l.phase!=="initial"&&Ue)){let Ce=l,St=Ce.kind==="loading"?void 0:()=>We("refresh"),Bn=Ce.kind==="new_conversation_required"?()=>we():void 0,Yn=()=>_E({state:Ce,copy:e,identityStatus:u,busy:O(),...St?{onRetry:()=>{St()}}:{},...Bn?{onStartNew:()=>{Bn()}}:{}}),$e=t.slots?.state?.({state:Ce,identityStatus:u,copy:e,...St?{retry:St}:{},...Bn?{startNewConversation:Bn}:{},defaultRenderer:Yn});ge.push($e??Yn())}bt.replaceChildren(...ge.filter(Ce=>!!Ce)),Vt(z)},_s=()=>{let z=l.kind==="loading"&&s.length===0,ge=[],Ue=()=>ge.length===0?Qc(Vi):`${Qc(Vi)}-${ge.length}`;if(!z)for(let at of Ae)ge.push({label:at.label,focusKey:Ue(),danger:at.danger===!0,onSelect:()=>{at.onSelect({conversations:[...s]})}});return xe&&!(s.length===0&&(l.kind==="empty"||z))&&ge.push({label:e.clearHistoryLabel,focusKey:Ue(),danger:!0,onSelect:()=>{Ve()}}),Ne&&!z&&ge.push({label:e.resetIdentityLabel,focusKey:Ue(),danger:!0,onSelect:()=>{pt()}}),ge},Qo=()=>{if(Be(Wt,O()),Be(ve,O()),vt){let z=_s(),ge=l.kind==="loading"&&s.length===0;vt.hidden=z.length===0&&!ge,Be(vt,O()||z.length===0),vt.setAttribute("aria-expanded",g===Vi?"true":"false");let Ue=I.querySelector(".persona-history-menu");if(g!==Vi||z.length===0)Ue?.remove();else{let at=cb({label:e.listOptionsLabel,items:z,onCloseMenu:Ce=>Nt(Ce)});Ue?Ue.replaceWith(at):I.appendChild(at)}}I.hidden=M!=="rail"&&(!vt||vt.hidden)&&(!t.showScopeStatus||ee.hidden)},Cn,dt=()=>{let z=t.onActiveConversationChange;if(!z)return;let ge=s.find(at=>at.id===p)??null,Ue=ge?`${ge.id}\0${ge.title}\0${ge.starred?1:0}`:"";Ue!==Cn&&(Cn=Ue,z(ge))},Se=()=>{if(!b){if(dt(),!A){t.onModelChange?.();return}mt(),Mn(),Qo(),Zc(),Ct()}},Nt=z=>{if(!g)return;let ge=g;g=null,h=!1,Se(),z?.restoreFocus&&Y.querySelector(`[data-persona-history-focus="menu:${ge}"]`)?.focus()},ot=z=>{if(g===z){Nt({restoreFocus:!0});return}g=z,h=!0,Se()},Pe=z=>{if(!g)return;let ge=z.target;ge instanceof Node&&Y.contains(ge)&&ge.closest?.(`[data-persona-history-item="${g}"]`)||Nt()};document.addEventListener("pointerdown",Pe,!0);let pe=z=>{z.key!=="Escape"||!g||(z.stopPropagation(),Nt({restoreFocus:!0}))};Y.addEventListener("keydown",pe);async function We(z){if(b)return;let ge=++C,Ue=z==="load-more"?a:null;if(!(z==="load-more"&&!Ue)){c={kind:z==="load-more"?"load-more":"refresh"},l={kind:"loading",phase:z},z!=="load-more"&&(D.clear(),W=null),Nt(),Se();try{let at=await t.provider.list({limit:o,context:t.context,...Ue?{cursor:Ue}:{},...t.targetId?{targetId:t.targetId}:{}});if(b||ge!==C)return;s=Ue?[...s,...at.items]:at.items,a=at.nextCursor,l=s.length===0?{kind:"empty"}:{kind:"ready"}}catch(at){if(b||ge!==C)return;l=OE(at)}finally{!b&&ge===C&&(c=null,Se())}}}let Ns=z=>{s=s.filter(ge=>ge.id!==z),D.delete(z),p===z&&(p=null),s.length===0&&!a&&(l={kind:"empty"})};async function Xo(z){if(!(O()||b)){D.delete(z),Nt(),c={kind:"open",conversationId:z},Se();try{if(await t.onSelect(z),b)return;p=z}catch{if(b)return;D.set(z,{message:e.openFailedLabel,retry:()=>{Xo(z)}})}finally{b||(c=null,Se())}}}async function lo(z){if(O()||b)return"cancelled";D.delete(z),c={kind:"delete",conversationId:z},Se();try{let ge=await t.onRequestDeleteConversation(z);return b||ge==="deleted"&&(Ns(z),B(e.conversationRemovedNotice)),ge}catch(ge){return b||(Gp(ge)&&ge.code==="not_found"?Ns(z):D.set(z,{message:e.deleteFailedLabel,retry:()=>{lo(z)}})),"cancelled"}finally{b||(c=null,Se())}}async function we(){if(!(O()||b)){W=null,Nt(),c={kind:"start-new"},Se();try{if(await t.onStartNew(),b)return;l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"})}catch{if(b)return;W={message:e.errorDescription,retry:()=>{we()}}}finally{b||(c=null,Se())}}}async function Ve(){if(O()||b)return"cancelled";W=null,Nt(),c={kind:"clear"},Se();try{let z=await t.onRequestClearHistory();return b||z==="cleared"&&(s=[],a=null,p=null,l={kind:"empty"},B(e.historyClearedNotice)),z}catch{return b||(W={message:e.errorDescription,retry:()=>{Ve()}}),"cancelled"}finally{b||(c=null,Se())}}let Tn={outcome:"cancelled"};async function pt(){if(O()||b||!t.onRequestResetIdentity)return Tn;W=null,Nt(),c={kind:"reset"},Se();try{let z=await t.onRequestResetIdentity();return b||z.outcome==="reset"&&(B(z.remoteRevocationConfirmed?e.identityResetNotice:e.identityResetUnconfirmedNotice),c=null,await We("refresh")),z}catch{return b||(W={message:e.errorDescription,retry:()=>{pt()}}),Tn}finally{!b&&c?.kind==="reset"&&(c=null,Se())}}let gn=t.provider.subscribeIdentityStatus(z=>{if(b)return;let ge=Am(z),Ue=ge!==m;u=z,m=ge,Se(),Ue&&z.state!=="verifying"&&B(VE(z,e).title)}),km=t.provider.subscribeAvailability?.(z=>{if(!b){if(z){We("refresh");return}s=[],a=null,l={kind:"error",reason:"unavailable",retryable:!1},Se()}});return Se(),We("initial"),{element:Y,copy:e,getModel:()=>({conversations:s,activeConversationId:p,state:l,pendingAction:c,identityStatus:u,nextCursor:a}),operations:{refresh:async()=>{O()||await We("refresh")},loadMore:async()=>{O()||await We("load-more")},openConversation:z=>Xo(z),startNewConversation:()=>we(),requestDeleteConversation:z=>lo(z),requestClearConversationHistory:()=>Ve(),requestResetHistoryIdentity:()=>pt()},setDomRenderEnabled:z=>{z!==A&&(A=z,z&&Se())},refresh:()=>{We("refresh")},setPresentation:z=>{if(z===M)return;Rt(),M=z,Tt=null;let ge=z==="rail";Y.classList.toggle("persona-history-view--panel",!ge),Y.classList.toggle("persona-history-view--rail",ge),Y.setAttribute("data-persona-history-presentation",z),G(),ie(),Te(),de(),Ot(),Se()},setCollapsed:z=>{z!==T&&(T=z,ie(),G(),de(),Ct())},setRailSide:z=>{H=z==="right",Te()},getHeaderElement:()=>qe,setHeaderPlacement:z=>{if(z===J)return;J=z;let ge=z==="external";if(se.classList.toggle("persona-history-topbar--shell",ge),ge){Re(),qe.remove();return}Fe(),Y.insertBefore(qe,j)},setActiveConversationId:z=>{p!==z&&(p=z,Se())},applyConversationSummary:z=>{let ge=s.findIndex(Ue=>Ue.id===z.id);ge!==-1&&(s[ge]=z,Se())},removeConversationSummary:z=>{s.some(ge=>ge.id===z)&&(Ns(z),Se())},setNewConversationRequired:z=>{z?l={kind:"new_conversation_required"}:l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"}),Se()},playExit:Ie,destroy:()=>{b=!0,C+=1,Rt(),Fe(),Le.forEach(z=>z?.destroy()),qe.remove(),nt.forEach(z=>z.cancel()),nt=[],gn(),km?.(),document.removeEventListener("pointerdown",Pe,!0),Y.removeEventListener("keydown",pe),U.destroy(),Y.remove(),Y.replaceChildren()}}}var O1,Vi,_1,FE,N1,F1,V1,$1,z1,$E=be(()=>{"use strict";Oa();je();PE();IE();Yc();ib();ab();DE();NE();Zl();O1=25,Vi="persona:list-options",_1=180,FE=120,N1=160,F1="cubic-bezier(0.4, 0, 1, 1)",V1={panel:20,rail:12},$1=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,z1=t=>t.finished?t.finished.then(()=>{},()=>{}):Promise.resolve()});var pb=be(()=>{"use strict";$E();Yc()});var zE={};$n(zE,{HISTORY_VIEW_COPY_DEFAULTS:()=>Kc,createHistoryView:()=>db,resolveHistoryViewCopy:()=>Gc});var UE=be(()=>{"use strict";pb();pb()});var kD={};$n(kD,{createThemePreview:()=>h0});module.exports=WP(kD);var Tp=require("lucide");zn();var uw=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function jo(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];uw(s)&&uw(r)?n[o]=jo(s,r):n[o]=r}return n}var fg=Symbol("persona.defaultsProvenance"),gg=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function up(t,e=""){return Object.entries(t).flatMap(([n,o])=>{let r=e?`${e}.${n}`:n;return gg(o)?up(o,r):[r]})}function mw(t,e){for(let n of e.split(".")){if(!gg(t)||!Object.prototype.hasOwnProperty.call(t,n))return"absent";if(t=t[n],t===void 0)return"clear"}return"explicit"}function fw(t,e){return t?.[fg]??e.filter(n=>mw(t,n)==="explicit")}function hg(t,e){return Object.defineProperty(t,fg,{value:e,enumerable:!0,configurable:!0}),t}function yg(t,e,n){return hg(t,fw(e,up(n)))}function gw(t,e,n){let o=e[fg];if(o)return o;let r=new Set(fw(t,n));for(let s of n){let a=mw(e,s);a==="clear"&&r.delete(s),a==="explicit"&&r.add(s)}return[...r]}function hw(t,e,n){let o={...t};for(let r of e){if(n.includes(r))continue;let s=r.split("."),a=o;for(let l of s.slice(0,-1)){let c=a[l];if(!gg(c)){a=void 0;break}a[l]={...c},a=a[l]}a&&delete a[s[s.length-1]]}return o}var yw="var(--persona-components-panel-width)",bg=Symbol("persona.panelAliasProvenance"),vi=(t,e)=>t!=null&&Object.prototype.hasOwnProperty.call(t,e),mp=(t,e)=>vi(t,e)&&t[e]!==void 0,BP=t=>({launcherWidth:mp(t?.launcher,"width"),legacyLauncherWidth:mp(t,"launcherWidth"),sidebarWidth:mp(t?.launcher,"sidebarWidth"),dockWidth:mp(t?.launcher?.dock,"width")}),Nr=t=>{let e=t?.[bg];return e?{...e}:BP(t)},vg=(t,e)=>(Object.defineProperty(t,bg,{value:e,enumerable:!0,configurable:!0}),t),Cg=(t,e)=>vg(t,Nr(e)),bw=(t,e)=>{let n=e[bg];if(n)return{...n};let o=Nr(t);return vi(e,"launcherWidth")&&(o.legacyLauncherWidth=e.launcherWidth!==void 0),vi(e,"launcher")&&e.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(vi(e.launcher,"width")&&(o.launcherWidth=e.launcher?.width!==void 0),vi(e.launcher,"sidebarWidth")&&(o.sidebarWidth=e.launcher?.sidebarWidth!==void 0),vi(e.launcher,"dock")&&e.launcher?.dock===void 0?o.dockWidth=!1:vi(e.launcher?.dock,"width")&&(o.dockWidth=e.launcher?.dock?.width!==void 0),o)};var wg="min(440px, calc(100vw - 24px))";var Fl="40px",xg="How can I help...",Fr={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},wi={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},DP={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:wg,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:Fl,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)"},OP={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:DP,copy:{inputPlaceholder:xg,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:Fr,reasoningDisplay:wi,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},_P={},NP={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},Ci={launcher:NP,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 bs(t){return t?.future?.v5Defaults===!0?"v5":"v4"}function fp(t){let e=bs(t)==="v5"?Ci:_P;return jo(OP,e)}var UD=fp();function vw(t,e){if(!(!t&&!e))return t?e?jo(t,e):t:e}function gp(t){let e=fp(t);return t?yg(Cg({...e,...t,theme:vw(e.theme,t.theme),darkTheme:vw(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,s=t.features?.scrollToBottom,a=e.features?.scrollBehavior,l=t.features?.scrollBehavior,c=e.features?.streamAnimation,p=t.features?.streamAnimation,u=e.features?.askUserQuestion,m=t.features?.askUserQuestion,g=e.features?.history,h=t.features?.history,b=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},C=r===void 0&&s===void 0?void 0:{...r,...s},M=a===void 0&&l===void 0?void 0:{...a,...l},E=c===void 0&&p===void 0?void 0:{...c,...p},T=u===void 0&&m===void 0?void 0:{...u,...m,styles:{...u?.styles,...m?.styles}},H=g===void 0&&h===void 0?void 0:{...g,...h,copy:{...g?.copy,...h?.copy}};return{...e.features,...t.features,toolCallDisplay:{...e.features?.toolCallDisplay,...t.features?.toolCallDisplay},reasoningDisplay:{...e.features?.reasoningDisplay,...t.features?.reasoningDisplay},...C!==void 0?{scrollToBottom:C}:{},...M!==void 0?{scrollBehavior:M}:{},...b!==void 0?{artifacts:b}:{},...E!==void 0?{streamAnimation:E}:{},...T!==void 0?{askUserQuestion:T}:{},...H!==void 0?{history:H}:{}}})(),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,Ci):yg(Cg(e),void 0,Ci)}je();Zt();je();var Cp=require("lucide");zn();var YP=["persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"],QP="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none",XP="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none",JP=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),wp=(t,e)=>{let n=v("div",["persona-message-bubble",t,...YP].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},xp=t=>{let e=v("button",t.expandable?QP:XP);return e.type="button",t.expandable&&(e.setAttribute("aria-expanded",t.expanded?"true":"false"),e.setAttribute("data-expand-header","true")),e.setAttribute("data-bubble-type",t.bubbleType),e},Tg=(t,e,n)=>{t.innerHTML="";let o=Ge(e?Cp.ChevronUp:Cp.ChevronDown,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},wa=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=v("div","persona-flex persona-items-center");Tg(o,n.expanded,n.iconColor);let r=v("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),t.append(e,r),o},Sp=t=>{let e=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(e.setAttribute("data-persona-collapsed-preview",t.previewKind),e.style.display="none",e.style.whiteSpace="pre-wrap",!t.expanded&&t.isActive&&t.activePreview&&t.previewText){let n=t.renderPreview?.();JP(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},Ap=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&Tg(t.toggleIcon,t.expanded,t.iconColor),t.content.style.display=t.expanded?"":"none",t.collapsedPreview.style.display=t.expanded?"none":t.collapsedPreview.textContent||t.collapsedPreview.childNodes.length?"":"none"},Mp=(t,e,n)=>{let o=n.stateSet.has(t),r=e.querySelector('button[data-expand-header="true"]'),s=e.querySelector(".persona-border-t"),a=e.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&Tg(c,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};function Ep(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return{...t,features:{...t?.features,[n]:{...e==="tool"?Fr:wi,...t?.future?.v5Defaults===!0?Ci.features?.[n]:{},...t?.features?.[n]}}}}function vs(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return t?.features?.[n]?.variant??(t?.future?.v5Defaults?"row":"card")}function Vl(t){let e=Math.max(0,Math.floor((t??0)/1e3));return e<1?"a moment":e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Vr(t,e,n,o){if(vs(n,o)!=="row")return t;t.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,t.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(t.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let r=t.querySelector(":scope > button");if(!r)return t;r.className="persona-activity-header";let s=o==="tool"?e.toolCall:e.reasoning,a=s?.status!=="complete",l=e.approval?.status??e.toolCall?.approvalStatus,c=l==="denied"?"denied":l==="pending"?"awaiting-approval":e.toolCall?.success===!1?"error":a?s?.status==="pending"?"pending":"running":"done";t.dataset.activityState=c;let p=v("span","persona-activity-icon");p.dataset.activityIcon=c;let u={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},m=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,g=m?ke(m,16,"currentColor",2):c==="pending"?Ge(Tp.Circle,16,"currentColor",2):c==="awaiting-approval"?Ge(Tp.Clock,16,"currentColor",2):ke(u[c],16,"currentColor",2);g&&p.appendChild(g),r.querySelector(".persona-reasoning-header-icon")?.remove();let h=o==="tool"?"toolCallDisplay":"reasoningDisplay",b=n.features?.[h]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((b==="always"||b==="active"&&c!=="done")&&r.prepend(p),o==="tool"&&s){let T=v("span","persona-activity-duration");a&&s.startedAt&&T.setAttribute("data-tool-elapsed",String(s.startedAt));let H=(o==="tool"?e.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);T.textContent=H===void 0?"":Vl(H),r.appendChild(T)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let E=t.querySelector(":scope > .persona-border-t");return E?.classList.add("persona-activity-body"),E&&(E.id=`activity-details-${e.id}`,r.setAttribute("aria-controls",E.id)),t}function Aw(t){let e=new Set,n=new Set,o=new Set,r=new Map,s=a=>{clearTimeout(r.get(a)),r.delete(a)};return{observe(a,l,c,p={}){let u=l==="tool"?a.toolCall:a.reasoning;if(!(!u||n.has(a.id))&&(!e.has(a.id)&&u.status!=="complete"&&u.chunks?.some(Boolean)&&(e.add(a.id),p.autoExpand!==!1&&c.add(a.id)),e.has(a.id)&&u.status==="complete"&&!o.has(a.id))){if(o.add(a.id),p.autoCollapseDelay===!1)return;r.set(a.id,setTimeout(()=>{r.delete(a.id),c.delete(a.id),t(a.id,l)},p.autoCollapseDelay??1e3))}},manual(a){n.add(a),s(a)},prune(a){for(let l of new Set([...e,...n,...o]))a.has(l)||(s(l),e.delete(l),n.delete(l),o.delete(l))},clear(){for(let a of r.keys())s(a);e.clear(),n.clear(),o.clear()}}}function Mw(t,e,n,o){let r=v("div","");r.id=`bubble-${t.id}`,r.dataset.messageId=t.id;let s=v("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let a=v("div","");typeof o=="string"?a.textContent=o:a.appendChild(o),wa(s,a,{expandable:!0,expanded:n,iconColor:e.toolCall?.toggleTextColor||e.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=v("div","persona-border-t");return l.id=`activity-details-${t.id}`,l.style.display=n?"":"none",s.setAttribute("aria-controls",l.id),r.append(s,l),Vr(r,t,{...e,features:{...e.features,toolCallDisplay:{...e.features?.toolCallDisplay,variant:"row"}}},"tool"),r.dataset.personaToolGroup="true",e.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(r.dataset.activityGroupShimmer="true"),{bubble:r,body:l}}var ZP=(t,e)=>t.visible!==!1&&(t.mode!=="transient"||e==="connecting"||e==="paused"||e==="resuming"||e==="error"),xi=(t,e,n)=>{let o=e.mode==="transient",r=t.hasAttribute("data-persona-composer-reason")||t.hasAttribute("data-persona-composer-notice");t.style.display=ZP(e,n)||o&&r&&e.visible!==!1?"":"none",t.classList.toggle("persona-mt-2",!o),t.classList.toggle("persona-mb-2",o)},Eg=(t,e,n)=>{!e.parentElement||t.parentElement!==e.parentElement||(n.mode==="transient"?t.nextElementSibling!==e&&e.before(t):e.nextElementSibling!==t&&e.after(t))};function Tw(t,e){let n=t.voiceRecognition,o=e.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||t.agentId!==e.agentId||t.clientToken!==e.clientToken||t.apiUrl!==e.apiUrl}function so(t){return t?.type==="runtype"||t?.type==="custom"}var eL=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Ew(t){try{if(t?.type==="custom"&&t.custom){let e=t.custom,n=typeof e=="function"?e():e;return!!n&&typeof n.startListening=="function"}return t?.type==="runtype"&&t.runtype?!0:eL()}catch{return!1}}Lp();Ig();var Ww=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Bw=t=>t.includes("|"),Dw=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},aL=t=>`| ${t.join(" | ")} |`,lL=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,cL=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Ow=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
1141
+ `),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!Bw(r)||Ww.test(r)||!Ww.test(s))continue;let a=Dw(r).length;if(a<1)continue;let l=lL(a);e[o+1]!==l&&(e[o+1]=l,n=!0);let c=o+2;for(;c<e.length;c++){let p=e[c];if(p.trim()===""||!Bw(p))break;let u=aL(cL(Dw(p),a));e[c]!==u&&(e[c]=u,n=!0)}o=c-1}return n?e.join(`
1142
+ `):t};var _w="var(--persona-md-table-scroll-fade, 24px)",Nw=new WeakSet;function Vw(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function Fw(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,r=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":_w),t.style.setProperty("--persona-fade-r",r<=1?"0px":_w)}function Rg(t){Nw.has(t)||(Nw.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&Fw(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(Fw)}Si();Aa();ro();var{setLoader:MO,load:wL}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(Qw(),Yw))});var Xw=wL;function Ho(t){return t==="card"?"collapsed":t}function Ma(t){return t.split(";",1)[0].trim().toLowerCase()}function xL(t,e){if(!t)return;let n=Object.entries(t);for(let[r,s]of n)if(Ma(r)===e)return{mode:Ho(s),selector:Ma(r)};let o=`${e.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ma(r)===o)return{mode:Ho(s),selector:o}}function SL(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:Ho(o.files),matchedBy:{type:"files"}};let l=e.file.mimeType?Ma(e.file.mimeType):void 0,c=l?xL(o.files.byMediaType,l):void 0;if(l&&c)return{mode:c.mode,matchedBy:{type:"mediaType",mediaType:l,selector:c.selector}};if(o.files.default)return{mode:Ho(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[e.artifactType];if(r)return{mode:Ho(r),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let s=o.byType?.[e.artifactType];if(s)return{mode:Ho(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let a=e.presentation?.preferredMode;return a?{mode:Ho(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:Ho(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Cs(t,e){return SL(t,e).mode}function $l(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var AL="agent_",ML="flow_";function Jw(t){return t.startsWith(AL)?{kind:"agentId",agentId:t}:t.startsWith(ML)?{kind:"flowId",flowId:t}:null}function Zw(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let p=Jw(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let c=e?.[a];if(!c)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(l).payload}}let r=Jw(n);if(r)return r;let s=e?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Dp(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function Ta(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function ex(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var ws=require("partial-json");je();var Wg="ask_user_question",zl=8,Ea="data-persona-ask-sheet-for",TL="Other",EL="Other\u2026",nx="Type your own answer here",ox="Send",kL="Next",PL="Back",LL="Submit all",IL="Skip",RL=3,Bg="data-ask-current-index",Dg="data-ask-question-count",rx="data-ask-answers",Og="data-ask-grouped",sx="data-ask-layout",HL=t=>t.layout==="pills"?"pills":"rows",WL=t=>t.getAttribute(sx)==="pills"?"pills":"rows",tx=!1,ix=t=>t.replace(/["\\]/g,"\\$&"),Ai=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Wg,_g=t=>t?.features?.askUserQuestion??{},ka=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,ws.parse)(r,ws.STR|ws.OBJ|ws.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Ul=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>zl&&!tx&&(tx=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${zl}.`)),e.slice(0,zl)},BL=t=>Ul(t)[0]??null,DL=(t,e)=>Ul(t)[e]??null,OL=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},ax=(t,e,n)=>{if(t!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},_L=(t,e,n,o)=>{let s=v("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=t.label,a.appendChild(l),t.description){let p=v("span","persona-ask-row-description");p.textContent=t.description,a.appendChild(p)}s.appendChild(a);let c=ax(n,o,e);c&&s.appendChild(c)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},NL=t=>{let n=v("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},FL=(t,e,n,o)=>{let s=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!t?.multiSelect,c=(Array.isArray(t?.options)?t.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(c.length===0&&!n){for(let u=0;u<RL;u++)s.appendChild(NL(o));return s}if(c.forEach((u,m)=>{s.appendChild(_L(u,m,o,a))}),t?.allowFreeText!==!1){let u=o==="rows"?TL:EL;if(o==="rows"){let m=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(c.length)),m.setAttribute("data-ask-other-row","true");let g=v("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=e.freeTextPlaceholder??nx,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",e.freeTextLabel??u),g.appendChild(h),m.appendChild(g);let b=ax(o,a,c.length);b&&m.appendChild(b),s.appendChild(m)}else{let m=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=e.freeTextLabel??u,s.appendChild(m)}}return s},lx=(t,e)=>{let o=v("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=t.freeTextPlaceholder??nx,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=v("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??ox,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},VL=t=>{let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??ox,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},$L=(t,e,n)=>{let o=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??PL,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??IL,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let c=t===e-1;return l.textContent=c?n.submitAllLabel??LL:n.nextLabel??kL,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Mi=t=>{let e=t.getAttribute(rx);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},cx=(t,e)=>{t.setAttribute(rx,JSON.stringify(e))},Wo=t=>{let e=Number(t.getAttribute(Bg)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},zL=(t,e)=>{t.setAttribute(Bg,String(Math.max(0,Math.floor(e))))},Pa=t=>{let e=Number(t.getAttribute(Dg)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},xs=t=>t.getAttribute(Og)==="true",UL=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},qL=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},Op=(t,e)=>{let{payload:n}=ka(e),o=Ul(n),r=Mi(t),s={},a=new Set;return o.forEach((l,c)=>{let p=typeof l?.question=="string"?l.question:"";p&&(a.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),a.add(p),Object.prototype.hasOwnProperty.call(r,c)&&(s[p]=r[c]))}),s},dx=t=>{let e=Mi(t),n=Wo(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(c=>r.add(c));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(c=>{let p=c.getAttribute("data-option-label")??"",u=r.has(p);c.setAttribute("aria-pressed",u?"true":"false"),c.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(c=>c.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},px=t=>{if(!xs(t))return;let e=Mi(t),n=Wo(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Ng=(t,e,n)=>{let o=_g(n),r=WL(t),{payload:s,complete:a}=ka(e),l=xs(t),c=Wo(t),p=Pa(t),u=l?DL(s,c):BL(s),m=!!u?.multiSelect,g=t.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=l?`${c+1}/${p}`:"");let h=t.querySelector('[data-ask-stepper="true"]');h&&h.remove();let b=t.querySelector('[data-ask-question="true"]');if(b){let T=typeof u?.question=="string"?u.question:"";b.textContent=T,b.classList.toggle("persona-ask-question-skeleton",!T&&!a)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let T=FL(u,o,a,r);C.replaceWith(T)}if(r!=="rows"){let T=t.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(lx(o,r))}let M=t.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!M?t.appendChild(VL(o)):(!m||l)&&M&&M.remove(),t.setAttribute("data-multi-select",m?"true":"false");let E=t.querySelector('[data-ask-nav-row="true"]');if(l){let T=$L(c,p,o);E?E.replaceWith(T):t.appendChild(T)}else E&&E.remove();dx(t),px(t)},jL=(t,e,n)=>{let o=_g(e),r=HL(o),s=t.toolCall.id,a=Ul(n),l=Math.max(1,a.length),c=l>1,p=UL(t,a),u=c?qL(t,l):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Ea,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(Dg,String(l)),m.setAttribute(Bg,String(u)),m.setAttribute(Og,c?"true":"false"),m.setAttribute(sx,r),cx(m,p),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),OL(m,o);let g=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=v("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",g.appendChild(h);let b=v("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",g.appendChild(b),m.appendChild(g);let M=v("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),m.appendChild(M),r!=="rows"&&m.appendChild(lx(o,r)),Ng(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},KL=(t,e,n)=>{let{payload:o}=ka(e),r=Math.max(1,Ul(o).length);r>Pa(t)&&(t.setAttribute(Dg,String(r)),r>1&&!xs(t)&&t.setAttribute(Og,"true")),Ng(t,e,n)};var _p=(t,e,n)=>{if(!n||!Ai(t)||_g(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${Ea}]`).forEach(p=>{p.getAttribute(Ea)!==r&&p.remove()});let a=n.querySelector(`[${Ea}="${ix(r)}"]`);if(a){KL(a,t,e);return}let{payload:l}=ka(t),c=jL(t,e,l);n.appendChild(c)},La=(t,e)=>{if(!t)return;let n=e?`[${Ea}="${ix(e)}"]`:`[${Ea}]`;t.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Fg=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),Ss=(t,e)=>{let n=Mi(t),o=Wo(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,cx(t,n),dx(t),px(t)},Np=(t,e,n,o)=>{let r=Pa(t),s=Math.max(0,Math.min(r-1,o));zL(t,s),Ng(t,e,n)};var As="suggest_replies";var GL={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},mx={name:As,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:GL,origin:"sdk",annotations:{readOnlyHint:!0}},fx=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ql=t=>t.variant==="tool"&&t.toolCall?.name===As,YL=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},gx=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!ql(n))continue;let o=YL(n.toolCall?.args);return o.length>0?o:null}return null},ux=new Set,QL=(t,e,n)=>{let o=`${t}:${e}:${n}`;ux.has(o)||(ux.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},Ms=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=a=>{let l=e?.[a],c=n?.[a];l===void 0||c===void 0||l!==c&&QL(a,c,l)};t&&(o("enabled"),o("expose"));let r=e?.enabled??n?.enabled??!0,s=r?e?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var XL={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:zl,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},JL={name:Wg,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:XL,origin:"sdk",annotations:{readOnlyHint:!0}},Fp=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(JL),Ms(t).expose&&e.push(mx),e};var ZL=t=>t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),eI=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),tI=t=>{if(t.variant!=="tool")return null;let e=t.agentMetadata?.clientToolAnswer;if(!e||!e.toolCallId||e.result===void 0)return null;let n=ZL(e.toolName);return n?{call:{toolCallId:e.toolCallId,toolName:n,args:eI(e.args)?e.args:{}},result:{toolCallId:e.toolCallId,toolName:n,result:e.result}}:null},Vg=(t,e)=>{let n=[],o=[],r=[],s="",a,l=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:r}),o=[],r=[])};for(let c of t){let p=tI(c);if(p){let m=c.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(m===void 0||m!==a)&&l(),o.length===0&&(s=c.createdAt,a=m),o.some(g=>g.toolCallId===p.call.toolCallId)||(o.push(p.call),r.push(p.result));continue}let u=e(c);u&&(l(),n.push(u))}return l(),n};Ts();var Ax="4.24.0";var Ti=Ax;var Ra="[Image]";function Mx(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function Up(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function fr(t){return{type:"text",text:t}}function Tx(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var Ex=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],lI=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Ur=[...Ex,...lI];function cI(t){return Ex.includes(t)||t.startsWith("image/")}function qp(t){return cI(t.type)}function kx(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function Px(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;qp(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function Lx(t,e=Ur,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function dI(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Ix(t,e){let n=dI(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||n||"FILE"}var pI=["user","assistant","system"],uI=0;function Rx(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function jp(t){return typeof t=="string"?t:void 0}function mI(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?fr(e.text):null;case"image":return typeof e.image=="string"?Tx(e.image,{mimeType:jp(e.mimeType),alt:jp(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?kx(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...jp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...jp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function fI(t,e){let n=Rx(e),o=t.map(a=>Rx(a.timestamp)),r=new Array(t.length),s=0;for(;s<o.length;){let a=o[s];if(a!==null){r[s]=a,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let c=l-s+1,p=s>0?r[s-1]:null,u=l+1<o.length?o[l+1]:null,m=u!==null&&n!==null?Math.min(u,n):u??n;for(let g=0;g<c;g+=1)r[s+g]=m!==null?m-(c-g):p!==null?p+g+1:uI+g;s=l+1}return r.map(a=>new Date(a).toISOString())}function Hx(t,e){let n=fI(t,e?.beforeCreatedAt),o=[];return t.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!pI.includes(r.role))return;let a=r.role,l=n[s];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};o.push({id:r.id,role:a,content:"",createdAt:l,agentMetadata:c});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:a,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:a,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let c=r.content.map(mI).filter(u=>u!==null),p=Mx(c);o.push({id:r.id,role:a,content:p||(Up(c)?Ra:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Yl(t){let e=t.content;if(typeof e!="string"||e==="")return;let n=t.contentParts??t.llmContent??t.rawContent??e;if(!(typeof n=="string"&&n===e))return e}function Ql(t,e){let n=new Map;for(let o of t)n.set(o.id,o);for(let o of e)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),a=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(a)&&s!==a)return s-a;let l=o.sequence??0,c=r.sequence??0;return l!==c?l-c:o.id.localeCompare(r.id)})}var gI="https://api.runtype.com/v1/dispatch",Wx="https://api.runtype.com",it=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Bx=32768,zg=49152,Dx=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:n,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:""}},Ox=t=>"reason"in t?t.reason:void 0,_x="The identity proof was not admitted; account history is unavailable",Ug="The identity proof was rejected",Nx="The request carried no visitor credential",Fx="The stored visitor belongs to a different signed-in user",qg=(t,e)=>t instanceof it&&t.code===e;function hI(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var jg=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0),Vx=t=>t.slice().sort((e,n)=>new Date(e.createdAt).getTime()-new Date(n.createdAt).getTime()),$x=t=>({role:t.role,content:t.contentParts??t.llmContent??t.rawContent??t.content,createdAt:t.createdAt});function yI(t){switch(t){case"json":return xx;case"regex-json":return wx;case"xml":return Sx;default:return Cx}}var zx=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function bI(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=zx(n);if(!zx(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Gl(t);return Gl(e)!==null&&a===null?e:t}var Xl=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.sessionWarmLatch=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??gI,this.headers={"Content-Type":"application/json","X-Persona-Version":Ti,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??yI(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,e.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(e.webmcp))}createWebMcpBridge(e){return Xw().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:Uw,getToolDisplayTitle:Rp,loadPolyfill:jw});return this.pendingWebMcpConfirmHandler!==void 0&&o.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=o,o}).catch(n=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}getWebMcpBridge(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.webMcpBridgePromise||(this.webMcpBridgePromise=this.createWebMcpBridge(this.config.webmcp)),this.webMcpBridgePromise)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.pendingWebMcpConfirmHandler=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=Zw(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Wx}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new it("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:e.after}),c=await fetch(`${a}?${l}`,{method:"GET",headers:{"X-Persona-Version":Ti,"X-Visitor-Token":s},signal:e.signal});if(c.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(c),null,!0);continue}if(!c.ok)throw await this.historyErrorFor(c,!0);return c}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.sessionInitPromise||e&&new Date<e.expiresAt||this.sessionWarmLatch===e?null:(this.sessionWarmLatch=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;let e=this.sessionInitPromise=this._doInitSession().then(n=>this.sessionInitPromise!==e?this.initSession():(this.clientSession=n,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.sessionInitPromise===e&&(this.sessionInitPromise=null)});return e}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.historyAvailabilitySubscribers])e(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(e){return this.historyIdentitySubscribers.add(e),()=>{this.historyIdentitySubscribers.delete(e)}}subscribeHistoryAvailability(e){return this.historyAvailabilitySubscribers.add(e),this.historyUnavailable&&e(!1),()=>{this.historyAvailabilitySubscribers.delete(e)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let e=this.historyIdentityStatus;return e?.state==="browser_only"?e:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&Ox(n)===Ox(e);if(this.historyIdentityStatus=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let r of[...this.historyIdentitySubscribers])r(e)}}async createClientSession(e){let n=this.isHistoryCapable()&&!e.omitVisitorFields,o=!e.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.routing(),a=s.agentId??s.flowId,l=n||e.durableResume?e.conversationId:void 0,c={token:this.config.clientToken,...a&&{flowId:a},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...l?{conversationId:l}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ti},body:JSON.stringify(c),signal:e.signal});if(!p.ok){let m=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new it("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw p.status===403&&m.error==="durable_recovery_disabled"?new it("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&m.error==="visitor_required"?new it("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new it("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):p.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let u=await p.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let r=await this.createClientSession({conversationId:e,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,e,!1)}catch(r){if(!qg(r,"not_found")&&!qg(r,"visitor_required")&&!qg(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(e,n)):this.doOrdinaryInit(e,n)}async doOrdinaryInit(e,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,e,n)}async reinitWithProof(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:e}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),s}async claimFirstConversation(e){if(!e.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.claimInFlight=!1}}finishInit(e,n,o){let r=e.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}prepared(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new it("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new it("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:e,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.createClientSession({});return this.prepared(e)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ti},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.sessionWarmLatch=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}historyUrl(e,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${e}${r?`?${r}`:""}`}resolveHistoryScope(e){if(e)return e;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveChatIdentityProof(e){e?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let r,s;try{let a=Promise.resolve().then(()=>o());r=e?await Promise.race([a,new Promise((l,c)=>{s=()=>c(e.reason),e.addEventListener("abort",s,{once:!0}),e.aborted&&s()})]):await a}catch{throw e?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{s&&e?.removeEventListener("abort",s)}if(typeof r!="string"||!r.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:r}}async resolveIdentityProof(e,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new it("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(e.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new it("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(e,n,o){if(e.visitor?.endUserId!=null)return e;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new it("proof_not_admitted",_x);return r}async readErrorCode(e){let n=await e.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(e,n,o){let r=e.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new it("invalid_identity_proof",Ug);if(r.includes("visitor token required"))throw new it("visitor_token_missing",Nx);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new it("visitor_identity_mismatch",Fx);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new it("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new it("not_found","Conversation not found");if(e.status===429){let r=Number.parseInt(e.headers.get("Retry-After")??"",10);return new it("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(e.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new it("proof_not_admitted",_x);if(e.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new it("invalid_identity_proof",Ug)):r.includes("visitor token required")?new it("visitor_token_missing",Nx):r.includes("visitor_identity_mismatch")?new it("visitor_identity_mismatch",Fx):new it("unauthorized",o||"History request was not authorized")}return new it("request_failed",o||`History request failed (${e.status})`)}commitIdentityAcknowledgement(e,n,o){let r=e?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new it("identity_contract_violation","Server reported an ignored identity proof on a success response"):new it("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new it("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(e,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let a=this.historyInternals.visitorStore,l=!1;for(;;){let c=a?.revision()??0,p=await this.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new it("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(e,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Ti,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(u),s,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),g=await u.json().catch(()=>{});if(a&&a.revision()!==c)throw new it("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,s!==null,o),g}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new it("history_disabled","Visitor history is disabled for this surface")}async listConversations(e){let n=await this.historyFetch("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(n?.data)?n.data:[]).map(Dx),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Dx(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(e,n){this.assertHistoryUsable();let o=0;for(let c of n){let p=c.displayContent.length;if(p>Bx)throw new it("payload_too_large",`displayContent exceeds the ${Bx} character limit`);o+=p}if(o>zg)throw new it("payload_too_large",`Display projection batch exceeds the ${zg} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,s=r?.revision()??0,a=await this.historyFetch(`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=zg,trackIdentity:!1}),l=typeof a?.conversationRevision=="string"?a.conversationRevision:null;return l&&this.clientSession?.conversationId===e&&(r?.revision()??0)===s&&this.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async deleteConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(e){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){let o=ex();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=()=>{if(e.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();a();let c=async()=>{a();let E=l,T=E.durableRecovery?.enabled===!0;if(T&&(!E.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");a();let H=await this.createClientSession({...T||this.isHistoryCapable()?{conversationId:E.conversationId,durableResume:T}:{storedSessionId:E.sessionId},signal:e.signal});if(a(),E.conversationId&&H.conversationId!==E.conversationId||T&&H.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.finishInit(H,E.conversationId??null,!1),this.clientSession=l,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await c();let p=await this.buildPayload(e.messages),u=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,m=this.isHistoryCapable(),g={sessionId:l.sessionId,messages:e.messages.filter(jg).map(E=>{let T=m?Yl(E):void 0;return{id:E.id,role:E.role,content:E.contentParts??E.llmContent??E.rawContent??E.content,...T!==void 0&&{displayContent:T}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},h=async()=>{a();let E=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return a(),this.sendWithClientToolsDiff(l.sessionId,p.clientTools,async T=>{a();let H=await this.resolveChatIdentityProof(e.signal);a();let A={...g,sessionId:l.sessionId,...T,...H&&{identityProof:H}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...A,...H&&{identityProof:{provider:H.provider,token:"[REDACTED]"}}}),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ti,...E?{"X-Visitor-Token":E}:{}},body:JSON.stringify(A),signal:e.signal})})},b=await h();if(a(),b.response.status===401){let E=await b.response.clone().json().catch(()=>null);a(),E?.error==="Session not found or expired"&&(await c(),b=await h(),a())}let{response:C,commit:M}=b;if(!C.ok){let E=await C.json().catch(()=>({error:"Chat request failed"}));if(C.status===401&&E.error==="invalid_identity_proof"){let H=new it("invalid_identity_proof",Ug);throw s({type:"error",error:H}),H}if(C.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let H=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:H}),H}if(C.status===429){let H=new Error(E.hint||"Message limit reached for this session.");throw s({type:"error",error:H}),H}if(C.status===410&&E.error==="conversation_deleted"){let H=new it("conversation_deleted","This conversation was deleted");throw s({type:"error",error:H}),H}let T=new Error(E.error||"Failed to send message");throw s({type:"error",error:T}),T}if(!C.body){let E=new Error("No response body received");throw s({type:"error",error:E}),E}M(),s({type:"status",status:"connected"});try{await this.streamResponse(C.body,s,e.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof it)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let o=`${this.clientApiBase()}/v1/agents/${e.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),a=s?qw(n):void 0,l=this.clientToolsFingerprintSessionId===e,c=s&&l&&this.lastSentClientToolsFingerprint===a,p=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,u=!1,m;for(let g=0;;g++){if(m=await o({...s&&(u||!c)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),m.status===409&&g===0&&s&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:p&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Wx}/resume`,a,l=null;if(r){let u=await this.initSession();a=u.sessionId,u.durableRecovery?.enabled===!0&&(l=await this.readVisitorToken())}let c={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...this.headers};this.getHeaders&&Object.assign(c,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(a&&(p.sessionId=a),r&&a){let u=[...Fp(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:g}=await this.sendWithClientToolsDiff(a,u,h=>{let b={...p,...h};return this.debug&&console.debug("[AgentWidgetClient] client token resume",b),fetch(s,{method:"POST",headers:c,body:JSON.stringify(b),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&g(),m}return fetch(s,{method:"POST",headers:c,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:e,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(s=>s.id===o)?{...e,model:o}:e}async buildAgentPayload(e,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=Vg(Vx(e),p=>jg(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?$x(p):null),s=this.normalizeComposerOptions(n),a={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(a.composerOptions=s);let l=[...Fp(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(a.clientTools=l);let c=await this.buildContextAggregate(e);return c&&(a.context=c),a}async buildPayload(e,n){let o=Vg(Vx(e),p=>jg(p)?$x(p):null),r=this.routing(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,u]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=u);let a=[...Fp(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(s.clientTools=a);let l=await this.buildContextAggregate(e);l&&(s.context=l);let c=this.normalizeComposerOptions(n);if(c&&(s.composerOptions=c),this.requestMiddleware)try{let p=await this.requestMiddleware({payload:{...s},config:this.config});if(p&&typeof p=="object"){let u=p;return s.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=s.clientTools),u}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async handleCustomSSEEvent(e,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let c=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=m,r(m),m},p=u=>o.current?o.current:c(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),c(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=p(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,r(u)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),a=new TextDecoder,l="",c=Date.now(),p=0,u=()=>c+p++,m=X=>{let I=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,j=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,J=X.tools?X.tools.map(Y=>({...Y,chunks:Y.chunks?[...Y.chunks]:void 0})):void 0;return{...X,reasoning:I,toolCall:j,tools:J}},g=X=>{if(X.role!=="assistant"||X.variant)return!0;let I=Array.isArray(X.contentParts)&&X.contentParts.length>0,j=typeof X.rawContent=="string"&&X.rawContent.trim()!=="";return typeof X.content=="string"&&X.content.trim()!==""||I||j||!!X.stopReason},h=X=>{g(X)&&n({type:"message",message:m(X)})},b=null,C=null,M={current:null},E={current:null},T=null,H="",A=new Map,D=new Map,W=new Map,U=new Map,B=new Map,O=o,R=!1,S=()=>{if(b)return b;let X,I="",j=T;return!R&&O?(X=O,R=!0,I=r??""):O&&j?X=`${O}_${j}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:X,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},h(b),b},x=X=>{let I=U.get(X);if(I)return I;let j={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:X,status:"streaming",chunks:[]}};return U.set(X,j),h(j),j},P=new Set,L=new Map,G=new Set,V=new Map,K=X=>{if(!X)return!1;let I=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return I==="emit_artifact_markdown"||I==="emit_artifact_component"},ee=X=>{let I=B.get(X);if(I)return I;let j={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:X,status:"pending"}};return B.set(X,j),h(j),j},oe=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let I=Number(X);if(!Number.isNaN(I)&&Number.isFinite(I))return I;let j=Date.parse(X);if(!Number.isNaN(j))return j}return Date.now()},ne=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},le=new Map,de=new Map,ve=(X,I)=>{let j=ne(I),J=de.get(X.id),Y=bI(J,j);X.rawContent=Y;let ie=le.get(X.id),Me=rt=>{let Ze=X.content??"";rt.trim()!==""&&(Ze.trim().length===0||rt.startsWith(Ze)||rt.trimStart().startsWith(Ze.trim()))&&(X.content=rt)},Ee=()=>{if(ie){let rt=ie.close?.();rt instanceof Promise&&rt.catch(()=>{})}le.delete(X.id),de.delete(X.id),X.streaming=!1,h(X)};if(!ie){Me(j),Ee();return}let Oe=Gl(Y);if(Oe!==null&&Oe.trim()!==""){Me(Oe),Ee();return}let Ct=rt=>{let Ze=typeof rt=="string"?rt:rt?.text??null;if(Ze!==null&&Ze.trim()!=="")return Ze;let ct=ie.getExtractedText();return ct!==null&&ct.trim()!==""?ct:j},Ot;try{Ot=ie.processChunk(Y)}catch{Me(j),Ee();return}if(Ot instanceof Promise){Ot.then(rt=>{Me(Ct(rt)),Ee()}).catch(()=>{Me(j),Ee()});return}Me(Ct(Ot)),Ee()},Le=null,se=(X,I,j,J)=>{X.rawContent=I,le.has(X.id)||le.set(X.id,this.createStreamParser());let Y=le.get(X.id),ie=I.trim().startsWith("{")||I.trim().startsWith("[");if(ie&&de.set(X.id,I),Y.__isPlainTextParser===!0){X.content=J!==void 0?I:X.content+j,de.delete(X.id),le.delete(X.id),X.rawContent=void 0,h(X);return}let Ee=Y.processChunk(I);if(Ee instanceof Promise)Ee.then(Oe=>{let Ct=typeof Oe=="string"?Oe:Oe?.text??null;Ct!==null&&Ct.trim()!==""?(X.content=Ct,h(X)):!ie&&!I.trim().startsWith("<")&&(X.content=J!==void 0?I:X.content+j,de.delete(X.id),le.delete(X.id),X.rawContent=void 0,h(X))}).catch(()=>{X.content=J!==void 0?I:X.content+j,de.delete(X.id),le.delete(X.id),X.rawContent=void 0,h(X)});else{let Oe=typeof Ee=="string"?Ee:Ee?.text??null;Oe!==null&&Oe.trim()!==""?(X.content=Oe,h(X)):!ie&&!I.trim().startsWith("<")&&(X.content=J!==void 0?I:X.content+j,de.delete(X.id),le.delete(X.id),X.rawContent=void 0,h(X))}},_=(X,I)=>{let j=I??X.content;if(j==null||j===""){X.streaming=!1,h(X);return}let Y=de.get(X.id)??ne(j);X.rawContent=Y;let ie=le.get(X.id),Me=null,Ee=!1;if(ie&&(Me=ie.getExtractedText(),Me===null&&(Me=Gl(Y)),Me===null)){let Oe=ie.processChunk(Y);Oe instanceof Promise?(Ee=!0,Oe.then(Ct=>{let Ot=typeof Ct=="string"?Ct:Ct?.text??null;Ot!==null&&(X.content=Ot,X.streaming=!1,le.delete(X.id),de.delete(X.id),h(X))}).catch(()=>{})):Me=typeof Oe=="string"?Oe:Oe?.text??null}if(!Ee){Me!==null&&Me.trim()!==""?X.content=Me:de.has(X.id)||(X.content=ne(j));let Oe=le.get(X.id);if(Oe){let Ct=Oe.close?.();Ct instanceof Promise&&Ct.catch(()=>{}),le.delete(X.id)}de.delete(X.id),X.streaming=!1,h(X)}},Te=(X,I,j)=>{let J=D.get(X);if(J)return J;let Y={id:`nested-${I}-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...j?{variant:j}:{},...j==="reasoning"?{reasoning:{id:X,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:I}};return D.set(X,Y),h(Y),Y},He=[],ut,At=new Map,Wt=0,bt="agent",xe=!1,Ne=null,Ae=null,vt=this.config.iterationDisplay??"separate";for(ut=()=>{for(let X=0;X<He.length;X++){let I=He[X];if(!xe&&bt!=="flow"&&typeof I.stepType=="string"&&(bt="flow"),I.type==="reasoning_start"){let j=typeof I.id=="string"?I.id:null,J=typeof I.parentToolCallId=="string"&&I.parentToolCallId?I.parentToolCallId:null;if(j&&J){A.set(j,J),Te(j,J,"reasoning");continue}let Y=I.id,ie=x(Y);ie.reasoning=ie.reasoning??{id:Y,status:"streaming",chunks:[]},ie.reasoning.startedAt=ie.reasoning.startedAt??Date.now(),ie.reasoning.completedAt=void 0,ie.reasoning.durationMs=void 0,(I.scope==="loop"||I.scope==="turn")&&(ie.reasoning.scope=I.scope),ie.streaming=!0,ie.reasoning.status="streaming",h(ie)}else if(I.type==="reasoning_delta"){let j=typeof I.id=="string"?I.id:null;if(j&&A.has(j)&&D.has(j)){let ie=D.get(j),Me=I.delta;Me&&ie.reasoning&&(ie.reasoning.chunks.push(String(Me)),h(ie));continue}let J=I.id,Y=x(J);Y.reasoning=Y.reasoning??{id:J,status:"streaming",chunks:[]},Y.reasoning.startedAt=Y.reasoning.startedAt??Date.now(),I.delta&&Y.reasoning.chunks.push(I.delta),Y.reasoning.status="streaming",Y.streaming=!0,h(Y)}else if(I.type==="reasoning_complete"){let j=typeof I.id=="string"?I.id:null;if(j&&A.has(j)&&D.has(j)){let Me=D.get(j);if(Me.reasoning){let Ee=typeof I.text=="string"?I.text:"";Ee&&Me.reasoning.chunks.length===0&&Me.reasoning.chunks.push(Ee),Me.reasoning.status="complete",Me.streaming=!1,h(Me)}A.delete(j),D.delete(j);continue}let J=I.id,Y=typeof I.text=="string"?I.text:"";!U.get(J)&&(Y||I.scope==="loop")&&x(J);let ie=U.get(J);if(ie?.reasoning){(I.scope==="loop"||I.scope==="turn")&&(ie.reasoning.scope=I.scope),Y&&ie.reasoning.chunks.length===0&&ie.reasoning.chunks.push(Y),ie.reasoning.status="complete",ie.reasoning.completedAt=Date.now();let Me=ie.reasoning.startedAt??Date.now();ie.reasoning.durationMs=Math.max(0,(ie.reasoning.completedAt??Date.now())-Me),ie.streaming=!1,h(ie)}}else if(I.type==="tool_start"){b&&(b.streaming=!1,h(b),b=null),typeof I.iteration=="number"&&(Wt=I.iteration);let j=I.toolCallId,J=I.toolName;if(K(J)){P.add(j);continue}let Y=ee(j),ie=Y.toolCall??{id:j,status:"pending"};ie.name=J??ie.name,ie.status="running",ie.success=void 0,ie.error=void 0,ie.duration=void 0,I.parameters!==void 0&&(ie.args=I.parameters),ie.startedAt=ie.startedAt??oe(I.startedAt),ie.completedAt=void 0,ie.durationMs=void 0,Y.toolCall=ie,Y.streaming=!0,I.executionId&&(Y.agentMetadata={executionId:I.executionId,iteration:I.iteration}),h(Y)}else if(I.type==="tool_output_delta"){let j=I.toolCallId;if(P.has(j))continue;let J=ee(j),Y=J.toolCall??{id:j,status:"running"};Y.startedAt=Y.startedAt??Date.now();let ie=I.delta;ie&&(Y.chunks=Y.chunks??[],Y.chunks.push(String(ie))),Y.status="running",J.toolCall=Y,J.streaming=!0,I.executionId&&(J.agentMetadata=J.agentMetadata??{executionId:I.executionId,iteration:Wt}),h(J)}else if(I.type==="tool_complete"){let j=I.toolCallId;if(P.has(j)){P.delete(j);continue}let J=ee(j),Y=J.toolCall??{id:j,status:"running"};Y.status="complete",I.result!==void 0&&(Y.result=I.result),Y.name=I.toolName??Y.name,Y.success=I.success,Y.error=I.error,Y.completedAt=Date.now();let ie=I.executionTime;if(typeof ie=="number")Y.durationMs=ie,Y.duration=ie;else{let Me=Y.startedAt??Date.now();Y.durationMs=Math.max(0,(Y.completedAt??Date.now())-Me)}J.toolCall=Y,J.streaming=!1,I.executionId&&(J.agentMetadata=J.agentMetadata??{executionId:I.executionId,iteration:I.iteration??Wt}),h(J)}else if(I.type==="await"&&I.toolName){let j=typeof I.toolCallId=="string"&&I.toolCallId.length>0?I.toolCallId:void 0,J=j??I.toolId??`local-${u()}`,Y=ee(J),ie=I.toolName,Me=I.origin==="webmcp"&&!Sa(ie)?`webmcp:${ie}`:ie,Ee=Sa(Me),Oe=Y.toolCall??{id:J,status:"pending"};Oe.name=Me,Oe.args=I.parameters,Oe.status=Ee?"running":"complete",Oe.chunks=Oe.chunks??[],Oe.startedAt=Oe.startedAt??oe(I.awaitedAt),Ee?(Oe.completedAt=void 0,Oe.duration=void 0,Oe.durationMs=void 0):Oe.completedAt=Oe.completedAt??Oe.startedAt,Y.toolCall=Oe,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:I.executionId??Y.agentMetadata?.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},h(Y)}else if(I.type==="text_start"){let j=typeof I.id=="string"?I.id:null,J=typeof I.parentToolCallId=="string"&&I.parentToolCallId?I.parentToolCallId:null;if(j&&J){A.set(j,J);continue}let Y=b;Y&&(bt==="flow"?(_(Y),Le=Y):(Y.streaming=!1,h(Y)),b=null),T=typeof I.id=="string"?I.id:T,H=""}else if(I.type==="text_delta"){let j=typeof I.id=="string"?I.id:null,J=j?A.get(j):void 0;if(j&&J){let Me=typeof I.delta=="string"?I.delta:"",Ee=(W.get(j)??"")+Me;if(W.set(j,Ee),Ee.trim()==="")continue;let Oe=Te(j,J);Oe.agentMetadata={...Oe.agentMetadata,executionId:I.executionId,parentToolId:J},se(Oe,Ee,Me,void 0);continue}if(T=typeof I.id=="string"?I.id:T,bt==="flow"){let Me=typeof I.delta=="string"?I.delta:"";if(H+=Me,H.trim()==="")continue;let Ee=S();Ee.agentMetadata={executionId:I.executionId,iteration:Wt},se(Ee,H,Me,void 0),C=Ee;continue}let Y=typeof I.delta=="string"?I.delta:"";H+=Y;let ie=S();ie.agentMetadata={executionId:I.executionId,iteration:Wt,turnId:Ne??void 0,agentName:Ae?.agentName},se(ie,H,Y,void 0),C=ie}else if(I.type==="text_complete"){let j=typeof I.id=="string"?I.id:null;if(j&&A.has(j)){let Y=D.get(j);Y&&_(Y),A.delete(j),W.delete(j),D.delete(j);continue}let J=b;J&&(bt==="flow"?(_(J),Le=J):((J.content??"")===""&&typeof I.text=="string"&&(J.content=I.text),J.streaming=!1,h(J)),b=null),T=null,H=""}else if(I.type==="step_complete"){if(I.stepType==="tool")continue;if(I.success===!1){let j=I.error||"Step failed";n({type:"error",error:new Error(j)});let J=b;J&&J.streaming&&(J.streaming=!1,h(J)),n({type:"status",status:"idle"});continue}{let j=Le;Le=null;let J=I.stopReason,ie=(I.result&&typeof I.result=="object"?I.result:null)?.response;if(j)J&&(j.stopReason=J),ie!=null?ve(j,ie):j.streaming!==!1&&(le.delete(j.id),de.delete(j.id),j.streaming=!1,h(j));else{let Me=ie!=null&&ie!=="";if(Me||J){let Ee=S();J&&(Ee.stopReason=J),Me?_(Ee,ie):(Ee.streaming=!1,h(Ee))}}continue}}else if(I.type==="execution_start")bt=I.kind==="flow"?"flow":"agent",xe=!0,bt==="agent"&&(Ae={executionId:I.executionId,agentId:I.agentId??"virtual",agentName:I.agentName??""});else if(I.type==="turn_start"){let j=typeof I.iteration=="number"?I.iteration:Wt;if(j!==Wt){if(vt==="separate"&&j>1){let J=b;J&&(J.streaming=!1,h(J),b=null)}Wt=j}Ne=typeof I.id=="string"?I.id:null,C=null}else if(I.type==="tool_input_delta"){let j=I.toolCallId;if(j){let J=B.get(j);J?.toolCall&&(J.toolCall.chunks=J.toolCall.chunks??[],J.toolCall.chunks.push(I.delta??""),h(J))}}else if(I.type==="tool_input_complete"){if(P.has(I.toolCallId))continue;let j=ee(I.toolCallId),J=j.toolCall;J.args=I.parameters,J.name=I.toolName??J.name,h(j)}else if(I.type==="turn_complete"){let j=I.stopReason,J=b??C;if(j&&J!==null){let Y=I.id;(!Y||J.agentMetadata?.turnId===Y)&&(J.stopReason=j,h(J))}Ne===I.id&&(Ne=null)}else if(I.type==="media_start"){let j=String(I.id);At.set(j,{mediaType:typeof I.mediaType=="string"?I.mediaType:void 0,toolCallId:I.toolCallId,parts:[]})}else if(I.type==="media_delta"){let j=At.get(String(I.id));j&&typeof I.delta=="string"&&j.parts.push(I.delta)}else if(I.type==="media_complete"){let j=String(I.id),J=At.get(j);At.delete(j);let Y=(typeof I.mediaType=="string"?I.mediaType:void 0)??J?.mediaType??"application/octet-stream",ie=typeof I.data=="string"?I.data:void 0,Me=typeof I.url=="string"?I.url:J&&J.parts.length>0?J.parts.join(""):void 0,Ee=null;if(ie)Ee={type:"media",data:ie,mediaType:Y};else if(Me){let rt=Y.toLowerCase();Ee={type:rt==="image"||rt.startsWith("image/")?"image-url":"file-url",url:Me,mediaType:Y}}let Oe=I.toolCallId??J?.toolCallId,Ct=Ee?[Ee]:[],Ot=[];for(let rt of Ct){if(!rt||typeof rt!="object")continue;let Ze=rt,ct=typeof Ze.type=="string"?Ze.type:void 0,Rt=typeof Ze.mediaType=="string"?Ze.mediaType.toLowerCase():"",Z=null,Fe="";if(ct==="media"){let Re=typeof Ze.data=="string"?Ze.data:void 0;if(!Re)continue;Fe=Rt.length>0?Rt:"application/octet-stream",Z=`data:${Fe};base64,${Re}`}else if(ct==="image-url"){let Re=typeof Ze.url=="string"?Ze.url:void 0;if(!Re)continue;Fe=Rt,Z=Re}else if(ct==="file-url"){let Re=typeof Ze.url=="string"?Ze.url:void 0;if(!Re)continue;Fe=Rt,Z=Re}else continue;if(Z)if(ct==="image-url"||Fe.startsWith("image/"))Ot.push({type:"image",image:Z,...Fe.includes("/")?{mimeType:Fe}:{}});else if(Fe.startsWith("audio/"))Ot.push({type:"audio",audio:Z,mimeType:Fe});else if(Fe.startsWith("video/"))Ot.push({type:"video",video:Z,mimeType:Fe});else{let Re=Fe||"application/octet-stream";Ot.push({type:"file",data:Z,mimeType:Re,filename:hI(Re)})}}if(Ot.length>0){let rt=u(),Ze=Oe,Rt={id:`agent-media-${typeof Ze=="string"&&Ze.length>0?`${Ze}-${rt}`:String(rt)}`,role:"assistant",content:"",contentParts:Ot,createdAt:new Date().toISOString(),streaming:!1,sequence:rt,agentMetadata:{executionId:I.executionId,iteration:Wt}};h(Rt);let Z=b;Z&&(Z.streaming=!1,h(Z)),b=null,M.current=null}}else if(I.type==="execution_complete"){let j=b;j&&(I.kind==="flow"&&j.streaming!==!1?_(j):(j.streaming=!1,h(j)),b=null),T=null,H="",Le=null,n({type:"status",status:"idle",terminal:!0})}else if(I.type==="execution_error"){let j=typeof I.error=="string"?I.error:I.error?.message??"Execution error";n({type:"error",error:new Error(j)})}else if(I.type!=="ping"){if(I.type==="approval_start"){let j=I.approvalId??`approval-${u()}`,J={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:Ae?.agentId??"virtual",executionId:I.executionId??Ae?.executionId??"",toolName:I.toolName??"",toolType:I.toolType,description:I.description??`Execute ${I.toolName??"tool"}`,...typeof I.reason=="string"&&I.reason?{reason:I.reason}:{},parameters:I.parameters}};h(J)}else if(I.type==="approval_complete"){let j=I.approvalId;if(j){let Y={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:I.decision??"approved",agentId:Ae?.agentId??"virtual",executionId:I.executionId??Ae?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};h(Y)}}else if(I.type==="artifact_start"||I.type==="artifact_delta"||I.type==="artifact_update"||I.type==="artifact_complete"){if(I.type==="artifact_start"){let j=I.artifactType,J=String(I.id),Y=typeof I.title=="string"?I.title:void 0,ie=I.file,Me;if(ie&&typeof ie=="object"&&!Array.isArray(ie)&&typeof ie.path=="string"&&typeof ie.mimeType=="string"&&(Me={path:ie.path,mimeType:ie.mimeType,...typeof ie.language=="string"?{language:ie.language}:{}}),n({type:"artifact_start",id:J,artifactType:j,title:Y,component:typeof I.component=="string"?I.component:void 0,...Me?{file:Me}:{}}),V.set(J,{markdown:"",title:Y,file:Me}),!G.has(J)){G.add(J);let Ee=Cs(this.config.features?.artifacts,{artifactType:j,...Me?{file:Me}:{}}),Oe=typeof I.component=="string"?I.component:void 0,Ct={id:`artifact-ref-${J}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:$l(Ee,{artifactId:J,title:Y,artifactType:j,status:"streaming",...Me?{file:Me}:{},...Oe?{component:Oe}:{}})};L.set(J,Ct),h(Ct)}}else if(I.type==="artifact_delta"){let j=String(I.id),J=typeof I.delta=="string"?I.delta:String(I.delta??"");n({type:"artifact_delta",id:j,artDelta:J});let Y=V.get(j);Y&&(Y.markdown+=J)}else if(I.type==="artifact_update"){let j=I.props&&typeof I.props=="object"&&!Array.isArray(I.props)?I.props:{};n({type:"artifact_update",id:String(I.id),props:j,component:typeof I.component=="string"?I.component:void 0});let J=V.get(String(I.id));J&&(J.props={...J.props??{},...j})}else if(I.type==="artifact_complete"){let j=String(I.id);n({type:"artifact_complete",id:j});let J=L.get(j);if(J){J.streaming=!1;try{let Y=JSON.parse(J.rawContent??"{}");if(Y.props){Y.props.status="complete";let ie=V.get(j);ie?.markdown&&(Y.props.markdown=ie.markdown),ie?.file&&(Y.props.file=ie.file),Y.component==="PersonaArtifactInline"&&ie?.props&&Object.keys(ie.props).length>0&&(Y.props.componentProps=ie.props)}J.rawContent=JSON.stringify(Y)}catch{}V.delete(j),h(J),L.delete(j)}}}else if(I.type==="error"&&I.recoverable===!1&&I.error!=null&&I.error!==""){let j=typeof I.error=="string"?I.error:I.error?.message!=null?String(I.error.message):"Execution error";n({type:"error",error:new Error(j)});let J=b;J&&J.streaming&&(J.streaming=!1,h(J)),n({type:"status",status:"idle"})}}}He.length=0};;){let{done:X,value:I}=await s.read();if(X)break;l+=a.decode(I,{stream:!0});let j=l.split(`
1143
1143
 
1144
- `);l=j.pop()??"";for(let J of j){let Q=J.split(`
1145
- `),de="message",Me="",Te=null;for(let Je of Q)Je.startsWith("event:")?de=Je.replace("event:","").trim():Je.startsWith("data:")?Me+=Je.replace("data:","").trim():Je.startsWith("id:")&&(Te=Je.slice(3).trim());let Fe=()=>{Te!==null&&Te!==""&&n({type:"cursor",id:Te})};if(!Me){Fe();continue}let je;try{je=JSON.parse(Me)}catch(Je){n({type:"error",error:Je instanceof Error?Je:new Error("Failed to parse chat stream payload")});continue}let lt=je!==null&&typeof je=="object"&&!Array.isArray(je)?je:null,ot=de!=="message"?de:typeof lt?.type=="string"?lt.type:"message";if(this.onSSEEvent?.(ot,je),this.parseSSEEvent){S.current=b;let Je=await this.handleCustomSSEEvent(je,n,S,g,u,T);if(S.current&&S.current!==b&&(b=S.current),Je){Fe();continue}}lt&&(nt.push({...lt,type:ot}),Ee()),Fe()}}Ee()}};na();eg();var KL=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function GL(t){let e=t?.text?.trim()??"";return e?Dl(KL(t),e):""}function Hw(t){let e=GL(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[sr(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
1144
+ `);l=j.pop()??"";for(let J of j){let Y=J.split(`
1145
+ `),ie="message",Me="",Ee=null;for(let Ze of Y)Ze.startsWith("event:")?ie=Ze.replace("event:","").trim():Ze.startsWith("data:")?Me+=Ze.replace("data:","").trim():Ze.startsWith("id:")&&(Ee=Ze.slice(3).trim());let Oe=()=>{Ee!==null&&Ee!==""&&n({type:"cursor",id:Ee})};if(!Me){Oe();continue}let Ct;try{Ct=JSON.parse(Me)}catch(Ze){n({type:"error",error:Ze instanceof Error?Ze:new Error("Failed to parse chat stream payload")});continue}let Ot=Ct!==null&&typeof Ct=="object"&&!Array.isArray(Ct)?Ct:null,rt=ie!=="message"?ie:typeof Ot?.type=="string"?Ot.type:"message";if(this.onSSEEvent?.(rt,Ct),this.parseSSEEvent){M.current=b;let Ze=await this.handleCustomSSEEvent(Ct,n,M,h,u,E);if(M.current&&M.current!==b&&(b=M.current),Ze){Oe();continue}}Ot&&(He.push({...Ot,type:rt}),ut()),Oe()}}ut()}};Aa();Kg();var wI=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function xI(t){let e=t?.text?.trim()??"";return e?Jl(wI(t),e):""}function qx(t){let e=xI(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[fr(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
1146
1146
 
1147
- `)}:{}}function fp(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function Rw(t,e){let n=t.findIndex(r=>r.id===e);if(n===-1||t[n].role!=="user")return null;let o=n+1;for(;o<t.length&&t[o].role!=="user";)o+=1;return{start:n,end:o}}function tg(t,e){let n=t.findIndex(o=>o.id===e);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(t[o].role==="user")return t[o].id;return null}function Ww(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return tg(t,n.id)?n.id:null}return null}function ng(t){return t.role!=="user"||t.variant||t.streaming||t.contentParts?.length||t.contextMentions?.length||t.contentSegments?.length||t.mentionContext&&Object.keys(t.mentionContext).length>0||t.rawContent!==void 0||t.llmContent!==void 0&&t.llmContent!==t.content||t.quote?!1:typeof t.content=="string"&&t.content.length>0}_l();function og(t){let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var Nl=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),s=o.getVoices();if(e.voice){let a=s.find(l=>l.name===e.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):og(s));e.rate!==void 0&&(r.rate=e.rate),e.pitch!==void 0&&(r.pitch=e.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var hp=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(e,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};var Fl=class{constructor(){this.cancelled=!1}start(e){this.turnId=e,this.cancelled=!1}cancel(){this.cancelled=!0}accepts(e){return!this.cancelled&&(!e||!this.turnId||e===this.turnId)}};oo();var{setLoader:xO,load:tP}=$t({fallbackImport:()=>Promise.resolve().then(()=>(Nw(),_w))});var lg=tP;function cg(t){if(!t)return"";let e=nP(t);return Fw(e!==null?e:t)}function nP(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Fw(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
1147
+ `)}:{}}function Kp(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function jx(t,e){let n=t.findIndex(r=>r.id===e);if(n===-1||t[n].role!=="user")return null;let o=n+1;for(;o<t.length&&t[o].role!=="user";)o+=1;return{start:n,end:o}}function Gg(t,e){let n=t.findIndex(o=>o.id===e);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(t[o].role==="user")return t[o].id;return null}function Kx(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return Gg(t,n.id)?n.id:null}return null}function Yg(t){return t.role!=="user"||t.variant||t.streaming||t.contentParts?.length||t.contextMentions?.length||t.contentSegments?.length||t.mentionContext&&Object.keys(t.mentionContext).length>0||t.rawContent!==void 0||t.llmContent!==void 0&&t.llmContent!==t.content||t.quote?!1:typeof t.content=="string"&&t.content.length>0}Zl();function Qg(t){let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var ec=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),s=o.getVoices();if(e.voice){let a=s.find(l=>l.name===e.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Qg(s));e.rate!==void 0&&(r.rate=e.rate),e.pitch!==void 0&&(r.pitch=e.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var Yp=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(e,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};var tc=class{constructor(){this.cancelled=!1}start(e){this.turnId=e,this.cancelled=!1}cancel(){this.cancelled=!0}accepts(e){return!this.cancelled&&(!e||!this.turnId||e===this.turnId)}};ro();var{setLoader:w_,load:PI}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(Jx(),Xx))});var th=PI;function nh(t){if(!t)return"";let e=LI(t);return Zx(e!==null?e:t)}function LI(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Zx(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
1148
1148
  `),e=e.replace(/\n{2,}/g,`
1149
- `),e.trim()}var qw=null;var dg=()=>qw?qw():Promise.resolve().then(()=>(Uw(),zw));oo();var{setLoader:HO,load:aP}=$t({fallbackImport:()=>Promise.resolve().then(()=>(Kw(),jw))});var Gw=aP;var lP=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function cP(t,e){return lP.some(n=>t[n]!==e[n])}var ar=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function pg(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
1149
+ `),e.trim()}var rS=null;var oh=()=>rS?rS():Promise.resolve().then(()=>(oS(),nS));ro();var{setLoader:I_,load:BI}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(iS(),sS))});var aS=BI;var DI=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","identityProvider","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function OI(t,e){return DI.some(n=>t[n]!==e[n])}var hr=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function rh(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
1150
1150
 
1151
- _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]}),dP=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Yw=t=>ta(t)||t===ds,vp=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.voiceTurns=new Fl;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new hp(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(ta(n.name)||n.name===ds&&ps(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...e.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Ol(e,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of e.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&lg().catch(()=>{})}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||dg().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return fC(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&(this.voiceTurns.cancel(),this.voiceProvider.stopPlayback())}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=Nl.isSupported()?new Nl({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=e.browserFallback!==!1;if(o&&r&&s)return dg().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&n?new d(p,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):p});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.voiceDisconnectPromise,r=++this.voiceSetupGeneration;this.voiceSetupPromise=lg().then(async s=>{await o,r===this.voiceSetupGeneration&&this.wireVoiceProvider(s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(e){try{this.voiceProvider=e;let n=this.voiceSetupGeneration,o=()=>this.voiceProvider===e&&n===this.voiceSetupGeneration,s=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{o()&&a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,l,d,p)=>{if(o())if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let u=this.injectMessage({role:"user",content:l,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=u.id}if(d){this.voiceTurns.start(p?.turnId),this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(p?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let u=this.injectMessage({role:"assistant",content:l,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=u.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(a=>{o()&&(this.voiceLevel=Number.isFinite(a)?Math.max(0,Math.min(1,a)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{o()&&this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{o()&&(console.error("Voice error:",a),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(a=>{o()&&(this.voiceStatus=a,this.voiceActive=a==="listening",(a==="listening"||a==="idle"||a==="disconnected")&&this.settlePendingVoiceTurn(a!=="listening"),this.callbacks.onVoiceStatusChanged?.(a))}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){let e=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let n=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(n)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new Fl,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}settlePendingVoiceTurn(e){let n=e?this.pendingVoiceUserMessageId:null,o=this.pendingVoiceAssistantMessageId;!n&&!o||(o&&this.voiceTurns.cancel(),e&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(r=>r.id!==n&&r.id!==o?[r]:r.id===o&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){this.clientSession=e,this.injectWelcomeMessage(e)}injectWelcomeMessage(e){if(this.suppressWelcomeInjection||!e.config.welcomeMessage||this.messages.length!==0)return;let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.composeHistoryInternals(e),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let e=this.historyProvider;if(!e)throw new ar("history_unavailable","No conversation history provider is installed");return e}historyContext(e){let n=this.requireHistoryProvider(),o=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new ir("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.historyGate;e&&await e.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new ar("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.requireHistoryProvider().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.historyContext(e?.scope)})}async openConversation(e,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(n?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,a=await o.getPage(e,{context:r});if(s!==this.historyOpenEpoch)throw new ar("superseded","A later selection won");let l=await o.prepareOpen(e,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new ar("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(l)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=l.conversationId||e,this.activeConversationRevision=l.conversationRevision||a.conversationRevision||null,this.historyNextMessageCursor=a.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.persistConversationMetadata(),this.hydrateMessages(a.messages),this.emitHistoryState(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,n,o){let r=this.requireHistoryProvider(),s=this.historyContext(o?.scope),a=n??this.historyNextMessageCursor;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${e} ${a}`,d=this.olderPageRequests.get(l);if(d)return d;let p=this.fetchOlderPage(r,e,a,s).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,p),p}async fetchOlderPage(e,n,o,r){let s=this.messages[0]?.createdAt,a=await e.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:a.nextCursor};let l=Bl(this.messages,a.messages);this.messages=this.sortMessages(l.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=a.nextCursor;for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,s=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw s.discard(),new ar("superseded","A later action won");await this.installFreshConversation(s)}async installFreshConversation(e){this.discardConversationState(),await this.commitActivation(e),this.activeConversationId=e.conversationId||null,this.activeConversationRevision=e.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(e,n){let o=this.requireHistoryProvider(),r=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:r}),e===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(e,n,o){let r=this.requireHistoryProvider();if(!r.update)throw new ar("history_unavailable","This history provider cannot update conversations");let s=this.historyContext(o?.scope);return await this.awaitHistorySettled(),r.update(e,n,{context:s})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),r}async resetHistoryDevice(){let e=this.requireHistoryProvider();if(!e.resetDevice)throw new ar("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await e.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(e)}async prepareReplacementConversation(e){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:e});await this.installFreshConversation(o)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new ar("new_conversation_required","A new conversation is required before sending")}async commitActivation(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.activeConversationId=e.conversationId,this.activeConversationRevision=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(e)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=e.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let e=this.historyInternals.visitorStore??null;e!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=e,e&&(this.visitorStoreUnsubscribe=e.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(e){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(e?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(e,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let a=await e.getPage(n,{context:o}),l=new Set(a.messages.map(m=>m.id)),d=this.messages.some(m=>l.has(m.id)),p=a.messages[0]?.createdAt,u;if(!d)u=a.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,y=this.messages.filter(g=>l.has(g.id)||g.id===m?!0:p!==void 0&&g.createdAt<p);u=Bl(y,a.messages).map(g=>this.ensureSequence(g))}this.historyNextMessageCursor=a.nextCursor,this.activeConversationRevision=a.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of a.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(u),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(e){this.pendingProjections=e,this.historyInternals.setPendingDisplayProjections?.(e)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(e){if(this.projectionFinalizationEnabled())for(let n of e){let o=Wl(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let e=this.activeConversationId;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Wl(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:e,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(e,n))}enqueueProjectionFinalization(e,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(e,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(e,n,o){if(this.activeConversationId!==e)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(e,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(e,r);for(let a of r)this.acknowledgedProjections.set(a.id,a.displayContent);this.activeConversationId===e&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(e,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(e,r,!0);return}if(s instanceof at&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(e,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(e){return e instanceof at?e.code==="request_failed":e instanceof Error}clearFinalizedMarker(e,n){let o=this.readPendingProjections();if(!o||o.conversationId!==e)return;let r=new Set(n.map(a=>a.id)),s=o.messageIds.filter(a=>!r.has(a));this.setPendingProjections(s.length?{conversationId:e,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let e=this.readPendingProjections();if(!e)return;if(this.activeConversationId&&e.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of e.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(e.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(e){return e instanceof at&&e.code==="conversation_deleted"}async dispatchWithDeletedRecovery(e,n,o,r,s){this.recordDispatchedProjections(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(a){if(!t.isConversationDeleted(a))throw a;let l=await this.recoverFromDeletedConversation(r);if(!l)throw a;this.recordDispatchedProjections([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(e){let n=this.messages.find(r=>r.id===e);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},r=mC(this.config,o),s=cP(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&no(o.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),a&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new Ol(this.config,this.historyInternals),a&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:d,streaming:p=!1,voiceProcessing:u,rawContent:m}=e,g={id:a??(n==="user"?op():n==="assistant"?ra():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(g),g}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:a,contentParts:l,id:d,createdAt:p,sequence:u,streaming:m=!1,voiceProcessing:y,rawContent:g}=o,C={id:d??(r==="user"?op():r==="assistant"?ra():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...y!==void 0&&{voiceProcessing:y},...g!==void 0&&{rawContent:g}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:d}=e,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
1151
+ _Details: ${n.message}_`:o}var sh=t=>({isError:!0,content:[{type:"text",text:t}]}),_I=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,lS=t=>Sa(t)||t===As,Jp=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.voiceTurns=new tc;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new Yp(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(Sa(n.name)||n.name===As&&Ms(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...e.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Xl(e,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of e.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&th().catch(()=>{})}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||oh().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Ew(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&(this.voiceTurns.cancel(),this.voiceProvider.stopPlayback())}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=ec.isSupported()?new ec({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=e.browserFallback!==!1;if(o&&r&&s)return oh().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:c})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&n?new c(p,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):p});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.voiceDisconnectPromise,r=++this.voiceSetupGeneration;this.voiceSetupPromise=th().then(async s=>{await o,r===this.voiceSetupGeneration&&this.wireVoiceProvider(s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(e){try{this.voiceProvider=e;let n=this.voiceSetupGeneration,o=()=>this.voiceProvider===e&&n===this.voiceSetupGeneration,s=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{o()&&a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,l,c,p)=>{if(o())if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let u=this.injectMessage({role:"user",content:l,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=u.id}if(c){this.voiceTurns.start(p?.turnId),this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(p?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let u=this.injectMessage({role:"assistant",content:l,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=u.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(a=>{o()&&(this.voiceLevel=Number.isFinite(a)?Math.max(0,Math.min(1,a)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{o()&&this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{o()&&(console.error("Voice error:",a),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(a=>{o()&&(this.voiceStatus=a,this.voiceActive=a==="listening",(a==="listening"||a==="idle"||a==="disconnected")&&this.settlePendingVoiceTurn(a!=="listening"),this.callbacks.onVoiceStatusChanged?.(a))}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){let e=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let n=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(n)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new tc,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}settlePendingVoiceTurn(e){let n=e?this.pendingVoiceUserMessageId:null,o=this.pendingVoiceAssistantMessageId;!n&&!o||(o&&this.voiceTurns.cancel(),e&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(r=>r.id!==n&&r.id!==o?[r]:r.id===o&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,e)})}setClientSession(e,n){this.clientSession=e,this.injectWelcomeMessage(e,n)}injectWelcomeMessage(e,n=!this.messages.length){if(this.suppressWelcomeInjection||!e.config.welcomeMessage||!n)return;let o=this.messages[0],r={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.nextSequence()};this.appendMessage(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.composeHistoryInternals(e),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let e=this.historyProvider;if(!e)throw new hr("history_unavailable","No conversation history provider is installed");return e}historyContext(e){let n=this.requireHistoryProvider(),o=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new gr("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.historyGate;e&&await e.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new hr("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.requireHistoryProvider().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.historyContext(e?.scope)})}async openConversation(e,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(n?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,a=await o.getPage(e,{context:r});if(s!==this.historyOpenEpoch)throw new hr("superseded","A later selection won");let l=await o.prepareOpen(e,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new hr("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(l)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=l.conversationId||e,this.activeConversationRevision=l.conversationRevision||a.conversationRevision||null,this.historyNextMessageCursor=a.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let c of a.messages)this.acknowledgedProjections.set(c.id,c.content);return this.persistConversationMetadata(),this.hydrateMessages(a.messages),this.emitHistoryState(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,n,o){let r=this.requireHistoryProvider(),s=this.historyContext(o?.scope),a=n??this.historyNextMessageCursor;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${e} ${a}`,c=this.olderPageRequests.get(l);if(c)return c;let p=this.fetchOlderPage(r,e,a,s).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,p),p}async fetchOlderPage(e,n,o,r){let s=this.messages[0]?.createdAt,a=await e.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:a.nextCursor};let l=Ql(this.messages,a.messages);this.messages=this.sortMessages(l.map(c=>this.ensureSequence(c))),this.historyNextMessageCursor=a.nextCursor;for(let c of a.messages)this.acknowledgedProjections.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,s=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw s.discard(),new hr("superseded","A later action won");await this.installFreshConversation(s)}async installFreshConversation(e){this.discardConversationState(),await this.commitActivation(e),this.activeConversationId=e.conversationId||null,this.activeConversationRevision=e.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(e,n){let o=this.requireHistoryProvider(),r=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:r}),e===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(e,n,o){let r=this.requireHistoryProvider();if(!r.update)throw new hr("history_unavailable","This history provider cannot update conversations");let s=this.historyContext(o?.scope);return await this.awaitHistorySettled(),r.update(e,n,{context:s})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),r}async resetHistoryDevice(){let e=this.requireHistoryProvider();if(!e.resetDevice)throw new hr("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await e.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(e)}async prepareReplacementConversation(e){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:e});await this.installFreshConversation(o)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new hr("new_conversation_required","A new conversation is required before sending")}async commitActivation(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.activeConversationId=e.conversationId,this.activeConversationRevision=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(e)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=e.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let e=this.historyInternals.visitorStore??null;e!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=e,e&&(this.visitorStoreUnsubscribe=e.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(e){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(e?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(e,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let a=await e.getPage(n,{context:o}),l=new Set(a.messages.map(m=>m.id)),c=this.messages.some(m=>l.has(m.id)),p=a.messages[0]?.createdAt,u;if(!c)u=a.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,g=this.messages.filter(h=>l.has(h.id)||h.id===m?!0:p!==void 0&&h.createdAt<p);u=Ql(g,a.messages).map(h=>this.ensureSequence(h))}this.historyNextMessageCursor=a.nextCursor,this.activeConversationRevision=a.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of a.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(u),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(e){this.pendingProjections=e,this.historyInternals.setPendingDisplayProjections?.(e)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(e){if(this.projectionFinalizationEnabled())for(let n of e){let o=Yl(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let e=this.activeConversationId;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Yl(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:e,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(e,n))}enqueueProjectionFinalization(e,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(e,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(e,n,o){if(this.activeConversationId!==e)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(e,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(e,r);for(let a of r)this.acknowledgedProjections.set(a.id,a.displayContent);this.activeConversationId===e&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(e,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(e,r,!0);return}if(s instanceof it&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(e,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(e){return e instanceof it?e.code==="request_failed":e instanceof Error}clearFinalizedMarker(e,n){let o=this.readPendingProjections();if(!o||o.conversationId!==e)return;let r=new Set(n.map(a=>a.id)),s=o.messageIds.filter(a=>!r.has(a));this.setPendingProjections(s.length?{conversationId:e,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let e=this.readPendingProjections();if(!e)return;if(this.activeConversationId&&e.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of e.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(e.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(e){return e instanceof it&&e.code==="conversation_deleted"}async dispatchWithDeletedRecovery(e,n,o,r,s){this.recordDispatchedProjections(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(a){if(!t.isConversationDeleted(a))throw a;let l=await this.recoverFromDeletedConversation(r);if(!l)throw a;this.recordDispatchedProjections([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(e){let n=this.messages.find(r=>r.id===e);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},r=Tw(this.config,o),s=OI(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&so(o.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),a&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new Xl(this.config,this.historyInternals),a&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:c,streaming:p=!1,voiceProcessing:u,rawContent:m}=e,h={id:a??(n==="user"?Dp():n==="assistant"?Ta():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:a,contentParts:l,id:c,createdAt:p,sequence:u,streaming:m=!1,voiceProcessing:g,rawContent:h}=o,C={id:c??(r==="user"?Dp():r==="assistant"?Ta():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...g!==void 0&&{voiceProcessing:g},...h!==void 0&&{rawContent:h}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:c}=e,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...c!==void 0&&{sequence:c}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
1152
1152
 
1153
1153
  `),a=[s,n].filter(Boolean).join(`
1154
1154
 
1155
- `),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,d=r.contentParts.length>0;if(l){let p=[];s&&p.push(sr(s)),p.push(...r.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(d){let p=[];a&&p.push(sr(a)),p.push(...r.contentParts),e.contentParts=p}else s&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim(),r=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!r)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let s=op(),a=ra();this.activeAssistantMessageId=null;let l=n?.contentParts&&pp(n.contentParts)?da:"",d={id:s,role:"user",content:o||l,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};this.appendMessage(d),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let m=this.messages.find(y=>y.id===s)??d;if(await this.applyMentionBundle(m,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(g=>g.id===s)??d,y=Hw({quote:n.quote,text:m.llmContent??m.content,contentParts:m.contentParts});y.contentParts&&(m.contentParts=y.contentParts),y.llmContent!==void 0&&(m.llmContent=y.llmContent),(y.contentParts||y.llmContent!==void 0)&&(m.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,p,a,s,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let y=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!y){let g=pg(m,this.config.errorMessage);if(g){let b={id:a,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(b)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,y||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(e,n){let o=Rw(this.messages,e);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,a=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!a?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},u=s?this.toComposerOptionsPayload(s.options):r.composerOptions,m=s?s.contentSegments:r.contentSegments,y=s?s.options?.quote:void 0,g=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(a??"",{...l?.length?{contentParts:[...l]}:{},...m?.length?{contentSegments:[...m]}:{},...u?{composerOptions:u}:{},...y?{quote:y}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:g===!0}),!0}toComposerOptionsPayload(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let e=ra();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=pg(r,this.config.errorMessage);if(a){let l={id:e,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(s=>s.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(u=>u.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,p=d&&typeof d=="object"?d.onDecision:void 0;try{let u;if(p?u=await p({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),u){let m=null;if(u instanceof Response){if(!u.ok){let y=await u.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${u.status}`)}m=u.body}else u instanceof ReadableStream&&(m=u);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(u=>u.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,s=e.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let u=e.toolCall?.args,m=Array.isArray(u?.questions)?u.questions:[];if(m.length===1){let y=typeof m[0]?.question=="string"?m[0].question:"";y&&(a={[y]:n})}}this.markAskUserQuestionResolved(e,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,d=e.toolCall?.args,p=Array.isArray(d?.questions)?d.questions:[];if(p.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=a??{};p.forEach((m,y)=>{let g=typeof m?.question=="string"?m.question:"";if(!g)return;let b=u[g],C=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${y}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${y}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(r,{[s]:n},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==ds?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let s=async d=>{let p=d.toolCall?.name,u=d.toolCall?.id;if(!p||!u)return null;let m=`${e}:${u}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(m),o.push(m);let y=this.markWebMcpToolRunning(d),g=d.agentMetadata?.webMcpToolCallId??p;if(p===ds)return{dedupeKey:m,resumeKey:g,output:nw(),toolMessage:d,startedAt:y,completedAt:Date.now()};let b=this.client.executeWebMcpToolCall(p,d.toolCall?.args,r.signal),C;if(!b)C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{C=await b}catch(S){let T=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));return T||this.callbacks.onError?.(S instanceof Error?S:new Error(String(S))),this.markWebMcpToolComplete(d,ug(T?"Aborted by cancel()":dP(S)),y),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,ug("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:g,output:C,toolMessage:d,startedAt:y,completedAt:Date.now()}},a;if(this.config.webmcp?.execution==="sequential"){a=[];for(let d of n)a.push(await s(d))}else a=await Promise.all(n.map(s));let l=[];try{if(l=a.filter(u=>u!==null),l.length===0)return;let d={};for(let u of l)d[u.resumeKey]=u.output;let p=await this.client.resumeFlow(e,d,{signal:r.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!p.ok){let u=await p.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${p.status}`)}for(let u of l)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt,u.toolMessage.toolCall?.name===ds?{suggestRepliesResolved:!0}:void 0);p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,ug("Aborted by cancel()"),u.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let a=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a))return;this.webMcpInflightKeys.add(a);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(a)}catch(l){this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{this.webMcpInflightKeys.delete(a)}return}let s=`${n}:${r}`;if(!(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e)))return this.resolveWebMcpToolCallBatch(n,[e])}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=is(this.config.features?.artifacts,e),r=El(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=is(this.config.features?.artifacts,n),s=El(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Gw().then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>pg(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=ra(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=cg(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return og(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=cg(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let u=r.approval,m=n.approval;a.approval={...u,...m,executionId:m.executionId||u.executionId,toolName:m.toolName||u.toolName,description:m.description||u.description,toolType:m.toolType??u.toolType,reason:m.reason??u.reason,parameters:m.parameters??u.parameters}}let l=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(l&&Yw(l)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let u=`${d}:${p}`,m=this.webMcpInflightKeys.has(u),y=this.webMcpResolvedKeys.has(u),g=r.toolCall?.name,b=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&g!==void 0&&Yw(g)&&r.toolCall?.status==="complete";(m||y||b)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};Ye();var ko=require("lucide");ro();Yt();var CP={add:t=>yw(t)},wP=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,Ap={allowedTypes:Hr,maxFileSize:10*1024*1024,maxFiles:4};function xP(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function SP(t){return t==="application/pdf"?ko.FileText:t.startsWith("text/")?ko.FileText:t.includes("word")?ko.FileText:t.includes("excel")||t.includes("spreadsheet")?ko.FileSpreadsheet:t==="application/json"?ko.FileCode:ko.File}var $l=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??Ap.allowedTypes,maxFileSize:e.maxFileSize??Ap.maxFileSize,maxFiles:e.maxFiles??Ap.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:CP}setPreviewsContainer(e){this.previewsContainer=e}remountPreviews(e){if(this.previewsContainer=e,e){e.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ap.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.destroyed)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=bw(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let a=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,a);continue}let s={id:xP(),file:o,previewUrl:up(o)?URL.createObjectURL(o):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(s),this.renderPreview(s),n.push(s)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(n.map(o=>this.runAdd(o)))}async runAdd(e){let n=new AbortController;this.pendingAdds.set(e.id,n);let o=()=>this.destroyed||n.signal.aborted||this.pendingAdds.get(e.id)!==n||!this.attachments.includes(e);try{let r=await this.adapter().add(e.file,{signal:n.signal,onProgress:s=>{o()||e.status!=="uploading"||(e.progress=wP(s),this.updatePreview(e),this.notify())}});if(o())return;e.contentPart=r,e.status="ready",e.progress=void 0,e.error=void 0}catch(r){if(o())return;e.status="error",e.progress=void 0,e.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(e.id)===n&&this.pendingAdds.delete(e.id)}this.updatePreview(e),this.notify()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.destroyed||(n.status=this.hasCustomAdapter()?"uploading":"processing",n.progress=this.hasCustomAdapter()?0:void 0,n.error=void 0,this.updatePreview(n),this.notify(),this.runAdd(n))}abortAdd(e){let n=this.pendingAdds.get(e);n&&(this.pendingAdds.delete(e),n.abort())}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];this.abortAdd(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.releasePart(o.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(e){let n=this.config.adapter?.remove;if(n)try{let o=n(e,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let e of this.attachments)this.abortAdd(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.pendingAdds.values())e.abort();this.pendingAdds.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=up(e.file),o=v("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let u=v("img");u.src=e.previewUrl,u.alt=e.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=v("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let m=SP(e.file.type),y=Qe(m,20,"var(--persona-muted, #6b7280)",1.5);y&&u.appendChild(y);let g=v("span");g.textContent=vw(e.file.type,e.file.name),g.style.fontSize="8px",g.style.fontWeight="600",g.style.color="var(--persona-muted, #6b7280)",g.style.textTransform="uppercase",g.style.lineHeight="1",u.appendChild(g),o.appendChild(u)}let r=$("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=v("div","persona-attachment-progress");s.appendChild(v("div","persona-attachment-progress__bar"));let a=$("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=Ie("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?a.appendChild(l):a.textContent="\u21BB",a.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.retryAttachment(e.id)}),r.append(s,a),o.appendChild(r);let d=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let p=Qe(ko.X,10,"var(--persona-text-inverse, #ffffff)",2);p?d.appendChild(p):(d.textContent="\xD7",d.style.color="var(--persona-text-inverse, #ffffff)",d.style.fontSize="14px",d.style.lineHeight="1"),d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(d),this.previewsContainer.appendChild(o),this.applyPreviewState(o,e)}updatePreview(e){let n=this.previewsContainer?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.applyPreviewState(n,e)}applyPreviewState(e,n){e.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";e.setAttribute("aria-busy",o?"true":"false"),e.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=e.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n,adapter:e?.adapter})}};var Zw=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),AP=(t,e)=>t.length===e.length&&t.every((n,o)=>{let r=e[o];return n.id===r.id&&n.name===r.name&&n.mimeType===r.mimeType&&n.size===r.size&&n.status===r.status&&n.progress===r.progress&&n.error===r.error});function ex(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,r=!1,s=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",a=()=>{let u=s();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:u,inputDisabled:t.inputDisabled,sendDisabled:u!=="idle"||t.sendDisabled||t.inputDisabled})},l=()=>(n||(n=a()),n),d=()=>{if(o=!1,r||e.size===0)return;let u=l();for(let m of[...e])try{m(u)}catch(y){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",y)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(d))};return{getState:l,subscribe:u=>(e.add(u),()=>e.delete(u)),setText:u=>{t.text!==u&&(t.text=u,p())},setAttachments:u=>{AP(t.attachments,u)||(t.attachments=[...u],p())},setMentionRefs:u=>{Zw(t.mentionRefs,u)||(t.mentionRefs=[...u],p())},setSelectedModelId:u=>{t.selectedModelId!==u&&(t.selectedModelId=u,p())},setActiveModeIds:u=>{Zw(t.activeModeIds,u)||(t.activeModeIds=[...u],p())},setQuote:u=>{let m=t.quote;m?.text===u?.text&&m?.messageId===u?.messageId&&m?.sourceLabel===u?.sourceLabel||(t.quote=u?{...u}:void 0,p())},setPendingSubmission:u=>{t.pendingSubmission!==u&&(t.pendingSubmission=u,p())},setPreparing:u=>{t.preparing!==u&&(t.preparing=u,p())},setStreaming:u=>{t.streaming!==u&&(t.streaming=u,p())},setInputDisabled:u=>{t.inputDisabled!==u&&(t.inputDisabled=u,p())},setSendDisabled:u=>{t.sendDisabled!==u&&(t.sendDisabled=u,p())},flush:()=>{o&&d()},destroy:()=>{r=!0,o=!1,e.clear()}}}Ye();var so=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},tx=(t,e)=>{let n=v("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function nx(t,e={}){let n=so(t,"[data-persona-composer-form]"),o=so(t,"[data-persona-composer-input]");if(!n||!o){let T=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(e.debug&&(n||o))throw new Error(T);return typeof console<"u"&&console.warn(T),null}let r={header:so(t,"[data-persona-composer-header]"),body:so(t,"[data-persona-composer-body]"),actionsStart:so(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:so(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:so(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:so(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:so(t,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=tx("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(a,n):t.appendChild(a));let l=r.body??o.parentElement??n,d=(S,T,A,I,M)=>{if(T)return T;s.add(S);let O=tx(A,I);return M.appendChild(O),O},p=d("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=d("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=d("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),y=d("status",r.status,"persona-widget-composer__status","data-persona-composer-status",t),g=[],b=(S,T)=>S.target===T.target&&S.type===T.type&&S.handler===T.handler,C=so(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:a,body:l,actionsStart:p,actionsEnd:u,suggestions:m,status:y,attachmentInput:C,attachmentPreviews:so(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:so(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:so(t,"[data-persona-composer-submit]")??void 0,micButton:so(t,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(S,T,A,I)=>{S.addEventListener(T,A,I),g.push({target:S,type:T,handler:A,options:I})},removeListener:(S,T,A,I)=>{S.removeEventListener(T,A,I),g=g.filter(M=>!b(M,{target:S,type:T,handler:A}))},destroy:()=>{for(let S of g)S.target.removeEventListener(S.type,S.handler,S.options);g=[]}}}Ye();Yt();fs();var MP=8,TP=8,hg=10,ox=200,rx=300,sx=0,Tp=t=>Math.max(0,t);function ix(t){t.delayMs!==void 0&&(ox=Tp(t.delayMs)),t.skipDelayMs!==void 0&&(rx=Tp(t.skipDelayMs))}var EP=()=>Date.now()<sx,kP=t=>{sx=t>0?Date.now()+t:0},Mp=new WeakMap,bg="data-persona-tooltip-suppressed",LP=t=>typeof t.closest=="function"&&t.closest(`[${bg}]`)!==null;function ax(t){Mp.get(t)?.hide()}var lx=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,PP=t=>{let e=t.getRootNode?.();return lx(e)?e:t.ownerDocument.body},yg=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),IP=[...["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 Mn(t){Mp.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:r,enabled:s=!0,gap:a=MP,viewportPadding:l=TP}=t,d=()=>e.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,y=null,g=null,b,C=!1,S=!1,T=!1,A=()=>(typeof o=="function"?o():o).trim(),I=()=>(typeof r=="function"?r():r??"").trim(),M=()=>Tp(t.delayMs??ox),O=()=>Tp(t.skipDelayMs??rx),k=()=>{b!==void 0&&(p().clearTimeout(b),b=void 0)},B=()=>{k();let re=u!==null;g?.(),g=null,u?.remove(),u=null,m=null,y=null,re&&kP(O())},W=()=>{if(!u)return;let re=d(),oe=p(),se=e.getBoundingClientRect(),ce=u.getBoundingClientRect(),we=re.documentElement.clientWidth||oe.innerWidth,ge=re.documentElement.clientHeight||oe.innerHeight,N=we-l-ce.width,ye=se.left+se.width/2-ce.width/2,ke=yg(ye,l,N),nt=se.top-l,Ee=ge-l-se.bottom,Ne=ce.height+a,Pe=nt>=Ne||nt>=Ee?"top":"bottom",dt=Pe==="top"?se.top-a-ce.height:se.bottom+a,Xe=ge-l-ce.height,xt=yg(dt,l,Xe),Ge=se.left+se.width/2,yt=Math.max(hg,ce.width-hg),X=yg(Ge-ke,hg,yt);u.dataset.placement=Pe,u.style.left=`${ke}px`,u.style.top=`${xt}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${X}px`)},V=()=>{if(T||!s||u||!e.isConnected||LP(e))return;let re=A(),oe=PP(e);if(!re||!oe)return;let se=d(),ce=p();u=se.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(fa);let we=ce.getComputedStyle?.(e);if(we){for(let Ne of IP){let Pe=we.getPropertyValue(Ne).trim();Pe&&u.style.setProperty(Ne,Pe)}we.fontFamily&&(u.style.fontFamily=we.fontFamily)}m=se.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=re,u.appendChild(m);let ge=I();ge&&(y=se.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=ge,u.appendChild(y));let N=se.createElement("span");N.className="persona-control-tooltip__arrow",u.appendChild(N),oe.appendChild(u),W(),u.dataset.state="open";let ye=()=>{if(!e.isConnected){B();return}m&&(m.textContent=A()),y&&(y.textContent=I()),W()};ce.addEventListener("scroll",ye,!0),ce.addEventListener("resize",ye);let ke=e.getRootNode(),nt=lx(ke)?ke:se.documentElement,Ee=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||B()});Ee?.observe(nt,{childList:!0,subtree:!0}),g=()=>{ce.removeEventListener("scroll",ye,!0),ce.removeEventListener("resize",ye),Ee?.disconnect()}},R=re=>{if(!(T||u)){if(k(),re||M()<=0||EP()){V();return}b=p().setTimeout(()=>{b=void 0,V()},M())}},w=()=>{C||S?R(S):B()},E=()=>{let re=p();(!re.matchMedia||!re.matchMedia("(hover: none)").matches)&&(C=!0,w())},H=()=>{C=!1,w()},D=()=>{try{S=e.matches(":focus-visible")}catch{S=!0}w()},G=()=>{S=!1,w()},z=()=>{C=!1,S=!1,B()},K=re=>{re.key==="Escape"&&z()};n.addEventListener("mouseenter",E),n.addEventListener("mouseleave",H),e.addEventListener("focus",D),e.addEventListener("blur",G),e.addEventListener("keydown",K),e.addEventListener("click",z);let Y={get isOpen(){return u!==null},show:V,hide:B,reposition:W,destroy:()=>{T||(T=!0,B(),n.removeEventListener("mouseenter",E),n.removeEventListener("mouseleave",H),e.removeEventListener("focus",D),e.removeEventListener("blur",G),e.removeEventListener("keydown",K),e.removeEventListener("click",z),Mp.delete(e))}};return Mp.set(e,Y),Y}Ye();Yt();var cx=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function ga(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];cx(s)&&cx(r)?n[o]=ga(s,r):n[o]=r}return n}var Rr="min(440px, calc(100vw - 24px))",px="440px",vg="How can I help...",HP={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:Rr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},It={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:HP,copy:{inputPlaceholder:vg,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:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},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};function dx(t,e){if(!(!t&&!e))return t?e?ga(t,e):t:e}function Ep(t){return t?{...It,...t,theme:dx(It.theme,t.theme),darkTheme:dx(It.darkTheme,t.darkTheme),launcher:{...It.launcher,...t.launcher,dock:{...It.launcher?.dock,...t.launcher?.dock},clearChat:{...It.launcher?.clearChat,...t.launcher?.clearChat}},tooltip:{...It.tooltip,...t.tooltip},copy:{...It.copy,...t.copy},sendButton:{...It.sendButton,...t.sendButton},statusIndicator:{...It.statusIndicator,...t.statusIndicator},voiceRecognition:{...It.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=It.features?.artifacts,n=t.features?.artifacts,o=It.features?.scrollToBottom,r=t.features?.scrollToBottom,s=It.features?.scrollBehavior,a=t.features?.scrollBehavior,l=It.features?.streamAnimation,d=t.features?.streamAnimation,p=It.features?.askUserQuestion,u=t.features?.askUserQuestion,m=It.features?.history,y=t.features?.history,g=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},C=s===void 0&&a===void 0?void 0:{...s,...a},S=l===void 0&&d===void 0?void 0:{...l,...d},T=p===void 0&&u===void 0?void 0:{...p,...u,styles:{...p?.styles,...u?.styles}},A=m===void 0&&y===void 0?void 0:{...m,...y,copy:{...m?.copy,...y?.copy}};return{...It.features,...t.features,...b!==void 0?{scrollToBottom:b}:{},...C!==void 0?{scrollBehavior:C}:{},...g!==void 0?{artifacts:g}:{},...S!==void 0?{streamAnimation:S}:{},...T!==void 0?{askUserQuestion:T}:{},...A!==void 0?{history:A}:{}}})(),suggestionChips:t.suggestionChips??It.suggestionChips,suggestionChipsConfig:{...It.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...It.layout,...t.layout,header:{...It.layout?.header,...t.layout?.header},messages:{...It.layout?.messages,...t.layout?.messages,avatar:{...It.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...It.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...It.layout?.slots,...t.layout?.slots}},markdown:{...It.markdown,...t.markdown,options:{...It.markdown?.options,...t.markdown?.options}},messageActions:{...It.messageActions,...t.messageActions}}:It}function Cg(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 kp(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function ux(t,e){t.style.maxHeight=`${e*Cg(t)}px`,t.style.overflowY="auto"}function ql(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 mx(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function fx(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||!mx(e)}function RP(t){return(t.submitKey??"enter")!=="enter"||mx(t)?"enter":"send"}function Lp(t,e){t.setAttribute("enterkeyhint",RP(e))}function Pp(t,e){let n=e?.autocomplete;t.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?t.removeAttribute(r):t.setAttribute(r,s)};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 wg(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 fo="persona-composer-control",$o="persona-composer-control--glyph",Sg=40,$n=24,Ip=(t,e,n)=>{let o=t.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(t);for(let s of n){let a=r.getPropertyValue(s).trim();a?e.style.setProperty(s,a):e.style.removeProperty(s)}},Hp=(t,e)=>{let n=v("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??vg,n.dir="auto",Lp(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:ql(n)}),Pp(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=kp(t?.composer?.maxLines,e?.defaultMaxLines??3),r=`${o*20}px`;n.style.maxHeight=r,n.style.overflowY="auto";let s=()=>{let l=n.style.maxHeight;if(l!==r){let p=parseFloat(l);if(Number.isFinite(p)&&p>0)return p}let d=o*Cg(n);return r=`${d}px`,n.style.maxHeight=r,d},a=()=>{n.addEventListener("input",()=>{n.style.height="auto";let l=Math.min(n.scrollHeight,s());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:a}},BP="[data-persona-glyph-stack]",Ag=(t,e,n="send")=>{let o=$("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},Rp=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,s=e.stopIconName??"square",a=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",d=t?.copy?.sendButtonLabel??"Send",p=t?.copy?.stopButtonLabel??"Stop",u=e.showTooltip??!1,m=e.size,y=parseFloat(m??"")||Sg,g=e.backgroundColor,b=e.textColor,C=v("div","persona-send-button-wrapper"),S=$("button",{className:Vt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${fo}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!b&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?b||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":b||void 0,backgroundColor:n&&g||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}}),T=null,A=null,I=null;if(n){let k=parseFloat(e.iconSize??"")||Math.round(y*.5),B=e.iconStrokeWidth??2,W=b?.trim()||"currentColor";r&&(T=Ie(r,k,W,B)),A=Ie(s,k,W,B),T&&A?(I=Ag(T,A),S.appendChild(I)):T?S.appendChild(T):(S.textContent=o,A=null)}else S.textContent=d;S.setAttribute("aria-label",a),C.appendChild(S),Mn({anchor:S,trigger:C,text:()=>S.getAttribute("aria-label")??"",enabled:u});let M="send";return{button:S,wrapper:C,setMode:k=>{if(k===M)return;M=k;let B=k==="stop"?l:a;S.setAttribute("aria-label",B),S.setAttribute("data-persona-send-mode",k),n?(S.querySelector(BP)??I)?.setAttribute("data-mode",k):S.textContent=k==="stop"?p:d},glyphStack:I}},ha=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",s=e.provider?.type==="custom";if(!(o||r||s))return null;let l=e.iconName??"mic",d=e.iconSize,p=parseFloat(d??"")||$n,u=e.backgroundColor??t?.sendButton?.backgroundColor,m=e.iconColor??t?.sendButton?.textColor,y=v("div","persona-send-button-wrapper"),g=$("button",{className:Vt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",fo,!d&&$o),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:m||"var(--persona-text, #111827)",backgroundColor:u||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}}),C=Ie(l,p,m||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",y.appendChild(g);let S=e.tooltipText??"Start voice recognition",T=e.showTooltip??!1;return Mn({anchor:g,trigger:y,text:()=>g.getAttribute("aria-label")??S,enabled:T}),{button:g,wrapper:y}},Wp=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=v("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=v("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(e.allowedTypes??Hr).join(","),o.multiple=(e.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=e.buttonIconName??"paperclip",s=v("div","persona-send-button-wrapper"),a=$("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${fo} ${$o}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=Ie(r,$n,"currentColor",1.5);l?a.appendChild(l):a.textContent="\u{1F4CE}",a.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(a);let d=e.buttonTooltipText??"Attach file";return Mn({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??d}),{button:a,wrapper:s,input:o,previewsContainer:n}},Bp=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=e.visible??!0;o.style.display=r?"":"none";let s=e.idleText??"Online";if(e.idleLink){let a=v("a");a.href=e.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},Op=()=>$("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});ya();Ye();Yt();var DP='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',_P=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],Mg="data-persona-menu-focus",NP=new Set(["ArrowDown","ArrowUp","Home","End"]);function bx(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(DP)??t}var FP=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function vx(t){let e=t.label,n=!1,o=v("div","persona-send-button-wrapper"),r=$("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${fo} ${$o}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=$("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let D=t.getButtonSize?.()??"";r.style.width=D,r.style.height=D,r.style.minWidth=D,r.style.minHeight=D,r.style.lineHeight="1",r.replaceChildren();let G=Ie("plus",$n,"currentColor",1.5);G?r.appendChild(G):r.textContent="+"},l=()=>{r.setAttribute("aria-label",e),r.setAttribute("title",e),s.setAttribute("aria-label",e)};l(),a();let d=[],p=-1,u=!1,m=()=>{let G=s.getRootNode().activeElement;return G instanceof HTMLElement?G:null},y=()=>{let D=m();for(let G of d){let z=!!D&&bx(G)===D;G.toggleAttribute(Mg,z&&u)}},g=()=>d.filter(D=>D.isConnected||s.contains(D)).map(bx).filter(D=>!FP(D)),b=(D,G)=>{D.forEach((z,K)=>{z.setAttribute("tabindex",K===G?"0":"-1")})},C=D=>{let G=g();if(G.length===0)return;let z=(D%G.length+G.length)%G.length;p=z,b(G,z),G[z].focus(),y()},S=()=>o.ownerDocument??document,T=null,A=null,I=null,M=()=>{T&&(S().removeEventListener("focusin",T,!0),T=null)},O=()=>{A&&(s.removeEventListener("focusin",A),A=null),I&&(s.removeEventListener("pointerdown",I,!0),I=null)},k=null,B=()=>(k||(k=gs({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),M()}})),k),W=()=>k?.isOpen===!0,V=(D=!1)=>{if(W()){k?.close(),r.setAttribute("aria-expanded","false"),M(),O(),p=-1,u=!1;for(let G of d)G.removeAttribute(Mg);D&&r.focus()}},R=(D=0,G=!1)=>{if(n||W())return;u=G,Ip(r,s,_P),B().open(),r.setAttribute("aria-expanded","true");let z=g();b(z,-1),C(D<0?z.length-1:D),T=K=>{let Y=typeof K.composedPath=="function"?K.composedPath():[];Y.includes(s)||Y.includes(o)||V()},S().addEventListener("focusin",T,!0),A=()=>y(),s.addEventListener("focusin",A),I=()=>{u=!1},s.addEventListener("pointerdown",I,!0)},w=D=>{D.preventDefault(),D.stopPropagation(),W()?V(!0):R(0)},E=D=>{if(D.key==="ArrowDown"||D.key==="Enter"||D.key===" "){D.preventDefault(),u=!0,W()?C(0):R(0,!0);return}D.key==="ArrowUp"&&(D.preventDefault(),u=!0,W()?C(-1):R(-1,!0))},H=D=>{switch(NP.has(D.key)&&(u=!0),D.key){case"ArrowDown":D.preventDefault(),C(p+1);return;case"ArrowUp":D.preventDefault(),C(p-1);return;case"Home":D.preventDefault(),C(0);return;case"End":D.preventDefault(),C(g().length-1);return;case"Escape":D.preventDefault(),D.stopPropagation(),V(!0);return;case"Tab":V(!0);return;default:}};return r.addEventListener("click",w),r.addEventListener("keydown",E),s.addEventListener("keydown",H),{trigger:o,triggerButton:r,panel:s,setItems:D=>{for(let z of d)D.includes(z)||z.removeAttribute(Mg);if(d=[...D],!W())return;let G=g();b(G,Math.min(p,G.length-1)),y()},isOpen:W,open:()=>R(0),close:V,setLabel:D=>{D!==e&&(e=D,l())},applyButtonSize:a,destroy:()=>{n=!0,M(),O(),r.removeEventListener("click",w),r.removeEventListener("keydown",E),s.removeEventListener("keydown",H),k?.destroy(),k=null,o.remove(),s.remove(),d=[]}}}var lr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Cx="data-persona-composer-action",Tg="data-persona-composer-disable-when-streaming",VP="core:overflow",$P=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function zP(t,e){if(t===void 0)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;let n=Number.parseFloat(t);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(t)&&Number.isFinite(n))return n;let o=v("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=t,e.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function Eg(t){let e=t.clientWidth;if(!e)return 0;let n=t.ownerDocument?.defaultView;if(!n?.getComputedStyle)return e;let o=n.getComputedStyle(t),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,e-r)}var wx=(t,e)=>{!t||typeof console>"u"||console.warn(e)},UP=(t,e)=>e.includes(":")?e:`${t}:${e}`;function qP(t){let{debug:e}=t,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){wx(e,`[Persona] composer action "${l.id}" is already contributed by ${xx(d)}; the ${xx(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of t.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let a=(l,d,p)=>{let u=p?UP(p,l.id):l.id,m=l.order??lr.custom;l.placement==="end"&&m>=lr.send&&(wx(e,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${lr.send-1}.`),m=lr.send-1),s({id:u,placement:l.placement,presentation:l.presentation??"bar",order:m,sequence:r++,source:d,pluginId:p,action:l})};for(let l of t.configActions??[])a(l,"config");for(let l of t.plugins){if(!l.contributeComposerActions)continue;let d;try{d=l.contributeComposerActions(t.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of d??[])a(p,"plugin",l.id)}return n.sort((l,d)=>l.order===d.order?l.sequence-d.sequence:l.order-d.order)}var xx=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",Sx=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,jP=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function KP(t,e){if(!t||t==="always")return!0;let n=jP(e);return t==="when-text"?n:!n}var hs=t=>t.kind==="custom",kg=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,GP=t=>{let e=kg(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},YP='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function QP(t){let e="",n=o=>{if(o.nodeType===Node.TEXT_NODE){e+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(YP)||o.childNodes.forEach(n)};return n(t),e.trim()}var XP=t=>QP(t).length===0;function Ax(t){let e=new Map,n=[],o=!1,r=()=>t.getButtonSize?.(),s=(w,E)=>{let H=w.button;if(!H)return;H.setAttribute("role","menuitem"),H.setAttribute("tabindex","-1"),H.className="persona-composer-overflow-menu__item";for(let z of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])H.style[z]="";H.style.lineHeight="1",E.tooltipText?H.setAttribute("title",E.tooltipText):H.removeAttribute("title"),H.replaceChildren();let D=v("span","persona-composer-overflow-menu__icon");if(E.iconName){let z=Ie(E.iconName,16,"currentColor",1.5);z&&D.appendChild(z)}let G=v("span","persona-composer-overflow-menu__label");G.textContent=E.shortLabel??E.label,H.append(D,G)},a=(w,E)=>{let H=w.button;if(!H)return;if(H.setAttribute("aria-label",E.label),E.pressed===void 0?H.removeAttribute("aria-pressed"):H.setAttribute("aria-pressed",E.pressed?"true":"false"),H.toggleAttribute(Tg,E.disableWhenStreaming===!0),w.mode==="menu"){w.tooltip?.destroy(),w.tooltip=void 0,s(w,E);return}H.removeAttribute("role"),H.removeAttribute("tabindex"),H.removeAttribute("title");let D=r(),G=!!E.shortLabel;if(H.className=Vt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",fo,$o,G&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),H.style.width=D&&!G?D:"",H.style.height=D??"",H.style.minWidth=D&&!G?D:"",H.style.minHeight=D??"",H.style.fontSize=G?"":"18px",H.style.lineHeight="1",H.style.color=E.iconColor??"",H.style.backgroundColor=E.backgroundColor??"",H.replaceChildren(),E.iconName){let z=Ie(E.iconName,$n,"currentColor",1.5);z&&H.appendChild(z)}if(G){let z=v("span","persona-composer-action-button__label");z.textContent=E.shortLabel,H.appendChild(z)}else H.firstChild||(H.textContent=E.label);w.tooltip?.destroy(),w.tooltip=Mn({anchor:H,trigger:w.element,text:()=>E.tooltipText??E.label,enabled:!!E.tooltipText})},l=(w,E)=>{let H=w.action,D=$("button",{attrs:{type:"button"}}),G=D;if(E==="bar"){let Y=v("div","persona-send-button-wrapper");Y.appendChild(D),G=Y}G.setAttribute(Cx,w.id);let z={resolved:w,element:G,button:D,owned:!0,managed:!0,busy:!1,visible:!0,mode:E},K=Y=>{if(Y.preventDefault(),Y.stopPropagation(),z.busy||D.disabled)return;let re=z.resolved.action;z.mode==="menu"&&g?.close(!0);let oe;try{oe=re.onSelect(t.actionContext,Y)}catch(se){t.reportError(se,{actionId:z.resolved.id});return}!oe||typeof oe.then!="function"||(z.busy=!0,D.setAttribute("aria-busy","true"),oe.catch(se=>{t.reportError(se,{actionId:z.resolved.id})}).finally(()=>{z.busy=!1,D.removeAttribute("aria-busy")}))};return D.addEventListener("click",K),z.detach=()=>D.removeEventListener("click",K),a(z,H),z},d=w=>{let E=w.action,H;try{H=E.render({...t.actionContext,id:w.id,action:E})}catch(D){return t.reportError(D,{actionId:w.id}),null}return H?.element?(H.element.setAttribute(Cx,w.id),H.element.toggleAttribute(Tg,E.disableWhenStreaming===!0),{resolved:w,element:H.element,owned:!0,managed:!0,destroy:H.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(w,E)=>{if(w.builtIn){let D=w.builtIn.element;return D?{resolved:w,element:D,owned:!1,managed:w.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let H=w.action;return H?hs(H)?d(w):l(w,E):null},u=w=>{if(w.detach?.(),w.tooltip?.destroy(),w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0,w.owned){try{w.destroy?.()}catch(E){t.reportError(E,{actionId:w.resolved.id})}w.element.remove()}},m=(w,E)=>{for(let H=0;H<E.length;H++){let D=E[H];if(!D.managed)continue;let G=null;for(let z=H+1;z<E.length;z++){let K=E[z];if(!K.managed&&K.element.parentElement===w){G=K.element;break}}G?(D.element.parentElement!==w||D.element.nextSibling!==G)&&w.insertBefore(D.element,G):w.lastChild!==D.element&&w.appendChild(D.element)}},y=(w,E)=>{if(w.button){w.button.disabled=E;return}if(!w.owned)return;let H=w.element;H.toggleAttribute("data-disabled",E),H.setAttribute("aria-disabled",E?"true":"false");let D=H instanceof HTMLButtonElement||H instanceof HTMLSelectElement||H instanceof HTMLInputElement||H instanceof HTMLTextAreaElement?H:H.querySelector("button, select, input, textarea");D&&(D.disabled=E)},g=null,b=null,C=null,S=0,T=()=>{let w=t.getOverflow?.();return w?.enabled===!0?w:void 0},A=()=>(g?g.setLabel(t.getOverflowLabel?.()??"More actions"):g=vx({label:t.getOverflowLabel?.()??"More actions",getButtonSize:r}),g),I=w=>{b!==w&&(C?.disconnect(),b=w,S=Eg(w),!(typeof ResizeObserver>"u")&&(C=new ResizeObserver(E=>{let D=E[E.length-1]?.contentRect?.width??Eg(w);D!==S&&(S=D,V())}),C.observe(w)))},M=(w,E)=>{let H=zP(w.collapseAutoActionsBelow,E);if(H===null)return!1;let D=S||Eg(E);return D>0&&D<H},O=(w,E,H)=>{if(!E)return"bar";if(w.resolved.builtIn){let G=$P(w.resolved.id);return G&&E.includeBuiltIns?.includes(G)?"menu":"bar"}let D=w.resolved.presentation;return D==="overflow"||D==="auto"&&H?"menu":"bar"},k=w=>{let E=w.menuSlot;if(!E)return;if(!XP(w.element)){w.menuLabel?.remove(),w.menuLabel=void 0;return}let H=GP(w.element);if(!H){w.menuLabel?.remove(),w.menuLabel=void 0;return}w.menuLabel||(w.menuLabel=v("span","persona-composer-overflow-menu__label")),w.menuLabel.textContent!==H&&(w.menuLabel.textContent=H),w.menuLabel.parentElement!==E&&E.appendChild(w.menuLabel)},B=(w,E)=>{if(w.mode===E)return w;let H=w.resolved.action;if(H&&!hs(H)){u(w),e.delete(w.resolved.id);let D=l(w.resolved,E);return e.set(w.resolved.id,D),D}if(E==="menu"){let D=$("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[bg]:""}});D.appendChild(w.element),ax(kg(w.element)),w.menuSlot=D;let G=z=>{let K=kg(w.element);if(K.disabled)return;let Y=z.target===K||K.contains(z.target);g?.close(!0),Y||K.click()};D.addEventListener("click",G,!0),w.detachMenuSlot=()=>D.removeEventListener("click",G,!0),w.managed=!0,k(w)}else w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0;return w.mode=E,w},W=(w,E)=>{let H=E.map(D=>D.menuSlot??D.element);for(H.forEach((D,G)=>{let z=w.children[G];z!==D&&(z?w.insertBefore(D,z):w.appendChild(D))});w.children.length>H.length;)w.lastElementChild?.remove()},V=()=>{if(o)return;let w=t.getBindings();if(!w)return;let E=t.getState(),H=E.phase==="streaming",D=T();D&&I(w.footer);let G=D?M(D,w.footer):!1,z={start:[],end:[]},K=[];for(let Y of n){let re=e.get(Y.id);if(!re)continue;let oe=Y.action,se=oe?Sx(oe.visible,E,!0)&&KP(oe.visibility,E):!0;if(re.visible!==se&&(re.visible=se,!se&&re.managed&&(re.menuSlot??re.element).remove()),!!se){if(re=B(re,O(re,D,G)),oe){let ce=Sx(oe.disabled,E,!1)||oe.disableWhenStreaming===!0&&H;y(re,ce),!hs(oe)&&oe.pressed!==void 0&&re.button?.setAttribute("aria-pressed",oe.pressed?"true":"false")}re.mode==="menu"?(k(re),K.push(re)):z[Y.placement].push(re)}}if(K.length>0){let Y=A();W(Y.panel,K),Y.setItems(K.map(ce=>ce.menuSlot??ce.element)),Y.applyButtonSize();let re=Number.isFinite(D?.order)?D?.order:lr.overflow,oe=z.start.findIndex(ce=>ce.resolved.order>re),se={resolved:{id:VP,placement:"start",presentation:"bar",order:re,sequence:-1,source:"core"},element:Y.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};z.start.splice(oe<0?z.start.length:oe,0,se)}else g&&(g.close(),g.trigger.remove(),g.setItems([]));m(w.actionsStart,z.start),m(w.actionsEnd,z.end)};return{resolve:()=>{if(o)return;let w=qP(t.collect()),E=new Set(w.map(H=>H.id));for(let[H,D]of e)E.has(H)||(u(D),e.delete(H));for(let H of w){let D=e.get(H.id);if(!D){let Y=p(H,"bar");Y&&e.set(H.id,Y);continue}let G=D.resolved.action,z=H.action;if(!!G!=!!z||G&&z&&hs(G)!==hs(z)||G&&z&&hs(G)&&hs(z)&&G.render!==z.render){u(D),e.delete(H.id);let Y=p(H,D.mode);Y&&e.set(H.id,Y);continue}D.resolved=H,H.builtIn?(D.managed=H.builtIn.managed===!0||D.mode==="menu",H.builtIn.element&&D.mode==="bar"&&(D.element=H.builtIn.element)):z&&!hs(z)?a(D,z):z&&D.element.toggleAttribute(Tg,z.disableWhenStreaming===!0)}n=w,V()},sync:V,getResolved:()=>n,getOverflowMenu:()=>g,destroy:()=>{if(!o){o=!0,C?.disconnect(),C=null,b=null;for(let w of e.values())u(w);e.clear(),g?.destroy(),g=null,n=[]}}}}ya();Ye();Yt();var JP="core:model",ZP=700,Mx=16,eI=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],Tx=()=>{let t=$("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=$("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function Ex(t){let e=t.label??"Model",n=t.presentation??"native",o=null,r=d=>{let p=t.getSelectedModelId();return d.find(u=>u.id===p)??d[0]},s=()=>{let d=$("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),p="",u=()=>{let C=t.getModels(),S=C.map(T=>`${T.id}:${T.label}`).join("|");S!==p&&(p=S,d.replaceChildren(...C.map(T=>{let A=$("option",{attrs:{value:T.id}});return A.textContent=T.label,A}))),d.value=r(C)?.id??""};u(),o=u;let m=()=>{d.value&&t.onSelect(d.value)};d.addEventListener("change",m);let y=C=>C.stopPropagation();d.addEventListener("click",y);let{wrapper:g,chevron:b}=Tx();return g.append(d,b),{element:g,destroy:()=>{o===u&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",y)}}},a=()=>{let d=$("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=v("span","persona-composer-model-picker-label"),u=v("span","persona-composer-model-picker-suffix");d.append(p,u);let m=$("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),y=new Map,g="",b=null,C=()=>b?.isOpen===!0,S=(E=!1)=>{C()&&(b?.close(),d.setAttribute("aria-expanded","false"),E&&d.focus())},T=E=>{let H=[...y.values()];if(H.length===0)return;let D=(E%H.length+H.length)%H.length;H[D].focus()},A=E=>{if(C())return;b||(b=gs({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),Ip(d,m,eI),b.open(),d.setAttribute("aria-expanded","true");let D=[...y.keys()].indexOf(r(t.getModels())?.id??"");T(E??(D>=0?D:0))},I=E=>{S(!0),t.onSelect(E)},M=E=>{E.preventDefault(),E.stopPropagation();let H=E.currentTarget.getAttribute("data-persona-model-option");H&&I(H)},O=E=>{let H=$("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":E.id}});if(E.icon){let Y=Ie(E.icon,Mx,"currentColor",1.5);if(Y){let re=v("span","persona-composer-model-option-icon");re.appendChild(Y),H.appendChild(re)}}let D=v("span","persona-composer-model-option-body"),G=v("span","persona-composer-model-option-label");if(G.textContent=E.label,D.appendChild(G),E.description){let Y=v("span","persona-composer-model-option-description");Y.textContent=E.description,D.appendChild(Y)}H.appendChild(D);let z=v("span","persona-composer-model-option-check");z.setAttribute("aria-hidden","true");let K=Ie("check",Mx,"currentColor",2);return K&&z.appendChild(K),H.appendChild(z),H.addEventListener("click",M),H},k=()=>{let E=t.getModels(),H=E.map(z=>`${z.id}:${z.label}:${z.icon??""}:${z.description??""}`).join("|");if(H!==g){g=H;for(let z of y.values())z.removeEventListener("click",M);y.clear(),m.replaceChildren(...E.map(z=>{let K=O(z);return y.set(z.id,K),K}))}let D=r(E);for(let[z,K]of y)K.setAttribute("aria-selected",String(z===D?.id));p.textContent=D?.label??"";let G=t.getSuffix?.()??"";u.textContent=G,d.setAttribute("aria-label",[e,[D?.label,G].filter(Boolean).join(" ")].filter(Boolean).join(": "))};k(),o=k;let B=E=>{E.preventDefault(),E.stopPropagation(),C()?S(!0):A()},W=E=>{if(E.key==="ArrowDown"){E.preventDefault(),C()?T(0):A(0);return}E.key==="ArrowUp"&&(E.preventDefault(),C()?T(-1):A(-1))},V=E=>{let H=[...y.values()],D=H.indexOf(E.target?.closest?.(".persona-composer-model-option"));switch(E.key){case"ArrowDown":E.preventDefault(),T(D+1);return;case"ArrowUp":E.preventDefault(),T(D-1);return;case"Home":E.preventDefault(),T(0);return;case"End":E.preventDefault(),T(H.length-1);return;case"Escape":E.preventDefault(),E.stopPropagation(),S(!0);return;case"Tab":S(!0);return;default:}};d.addEventListener("click",B),d.addEventListener("keydown",W),m.addEventListener("keydown",V);let{wrapper:R,chevron:w}=Tx();return R.append(d,w),{element:R,destroy:()=>{o===k&&(o=null),d.removeEventListener("click",B),d.removeEventListener("keydown",W),m.removeEventListener("keydown",V);for(let E of y.values())E.removeEventListener("click",M);y.clear(),b?.destroy(),b=null,m.remove()}}};return{action:{id:JP,kind:"custom",placement:"end",order:ZP,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}Ye();Yt();Fp();var tI=":scope > [data-persona-composer-mode]";function kx(t){let e=t.row,n="",o=!1,r=new Set(t.initialIds??[]),s=p=>{let u=$("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let b=v("span","persona-mention-chip-icon"),C=Ie(p.iconName,12,"currentColor",1.5);C&&b.appendChild(C),u.appendChild(b)}let m=v("span","persona-mention-chip-label");m.textContent=p.shortLabel??p.label,u.appendChild(m);let y=$("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),g=Ie("x",12,"currentColor",2);return g?y.appendChild(g):y.textContent="\xD7",y.addEventListener("click",b=>{b.preventDefault(),b.stopPropagation(),t.onRemove(p.id)}),u.appendChild(y),u},a=()=>Array.from(e.querySelectorAll(tI)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),ba(e)},m=e.ownerDocument.defaultView,y=typeof m?.getComputedStyle=="function"?m.getComputedStyle(p).animationName:"";if(!y||y==="none"){u();return}p.addEventListener("animationend",u,{once:!0}),p.addEventListener("animationcancel",u,{once:!0})},d=()=>{for(let p of a())p.remove()};return{element:e,render:(p,u)=>{if(o)return;let m=u.filter(C=>p.includes(C.id)),y=m.map(C=>`${C.id}:${C.shortLabel??C.label}`).join("|");if(y===n)return;n=y;let g=new Map;for(let C of a()){let S=C.getAttribute("data-persona-composer-mode");S&&m.some(A=>A.id===S)&&!C.hasAttribute("data-persona-chip-exit")?g.set(S,C):C.hasAttribute("data-persona-chip-exit")||l(C)}let b=e.firstChild;for(let C of m){let S=g.get(C.id);S||(S=s(C),r.has(C.id)||(S.setAttribute("data-persona-chip-enter",""),S.addEventListener("animationend",()=>S?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(C.id),S!==b&&e.insertBefore(S,b),b=S.nextSibling}ba(e)},destroy:()=>{o=!0,d(),ba(e)}}}Ye();Yt();var Lx=t=>`core:mode:${t}`;var Ig=t=>Math.min(300+t,499),Px=t=>`core:mode-group:${t}`;function Vp(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function nI(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Ix(t,e){return t?.length?t.filter(n=>!Vp(n.groupId,e)&&!nI(n.groupId,e)):[]}var oI=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Hx(t,e,n,o){let r=n.find(l=>l.id===e);if(!r)return[...t];let s=t.includes(e),a=new Set(t);if(s)a.delete(e);else{if(oI(r,o)==="single"){let l=n.filter(d=>d.groupId===r.groupId).map(d=>d.id);a=new Set([...a].filter(d=>!l.includes(d)))}a.add(e)}return n.filter(l=>a.has(l.id)).map(l=>l.id)}function $p(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Rx(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Wx(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var rI=16;function Bx(t){let e=null;return{action:{id:Px(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=$("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),r=new Map,s="",a=p=>{p.preventDefault(),p.stopPropagation();let m=p.currentTarget.getAttribute("data-persona-composer-mode");!m||t.getActiveIds().includes(m)&&t.getGroup()?.selection==="single"||t.onSelect(m)},l=p=>{let u=$("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let y=Ie(p.iconName,rI,"currentColor",1.5);y&&u.appendChild(y)}let m=v("span","persona-composer-segmented-label");return m.textContent=p.shortLabel??p.label,u.appendChild(m),u.addEventListener("click",a),u},d=()=>{let p=t.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=t.getModes(),m=u.map(g=>`${g.id}:${g.shortLabel??g.label}:${g.iconName??""}`).join("|");if(m!==s){s=m;for(let b of r.values())b.removeEventListener("click",a);r.clear();let g=u.map(b=>{let C=l(b);return r.set(b.id,C),C});o.replaceChildren(...g)}let y=t.getActiveIds();for(let[g,b]of r)b.setAttribute("aria-pressed",String(y.includes(g)))};return d(),e=d,{element:o,destroy:()=>{e===d&&(e=null);for(let p of r.values())p.removeEventListener("click",a);r.clear()}}}},repaint:()=>e?.()}}Fp();Ye();Yt();function Ox(t){let e=$("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,r=s=>{let a=v("span","persona-composer-quote-bar"),l=v("div","persona-composer-quote-content");if(s.sourceLabel){let m=v("div","persona-composer-quote-source");m.textContent=s.sourceLabel,l.appendChild(m)}let d=$("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=fp(s.text),l.appendChild(d);let p=$("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=Ie("x",12,"currentColor",2);u?p.appendChild(u):p.textContent="\xD7",p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),t.onDismiss()}),e.replaceChildren(a,l,p)};return{element:e,render:s=>{if(o)return;let a=s?`${s.sourceLabel??""}\0${s.text}`:"";if(a!==n){if(n=a,!s){e.replaceChildren(),e.style.display="none";return}r(s),e.style.display="flex"}},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}Ye();Yt();function Dx(t){let e=$("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,r=(a,l,d,p)=>{let u=$("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[d]:""}}),m=Ie(a,12,"currentColor",2);return m?u.appendChild(m):u.textContent=l,u.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),p()}),u},s=a=>{let l=fp(a.text??"",90);if(l)return l;let d=a.contentParts?.length??0;return d>0?d===1?"1 attachment":`${d} attachments`:(a.mentionRefs?.length??0)>0?a.mentionRefs.map(u=>u.label).join(", "):"Queued message"};return{element:e,render:a=>{if(o||a===n)return;if(n=a,!a){e.replaceChildren(),e.style.display="none";return}let l=v("span","persona-composer-pending-badge");l.textContent=t.label??"Sends next";let d=$("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});d.textContent=s(a),e.replaceChildren(l,d,r("pencil",t.editLabel??"Edit queued message","data-persona-composer-pending-edit",t.onEdit),r("x",t.removeLabel??"Remove queued message","data-persona-composer-pending-remove",t.onRemove)),e.style.display="flex"},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}Ye();function _x(t){let e=$("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=$("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=t.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=v("div","persona-message-edit-actions"),s=(l,d,p,u)=>{let m=$("button",{className:`persona-message-edit-button ${d}`,attrs:{type:"button",[p]:""},text:l});return m.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),u()}),m},a=()=>{let l=n.value.trim();l&&t.onSave(l)};return r.append(s(t.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",t.onCancel),s(t.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",a)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),t.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),a())}),e.append(n,r),{element:e,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{e.replaceChildren(),e.remove()}}}function Nx(t){let e=t.text??"";if(e.trim().length>0||(t.mentionRefs?.length??0)>0||(t.activeModeIds?.length??0)>0||t.quote||t.selectedModelId)return{text:e,...t.mentionRefs?.length?{mentionRefs:[...t.mentionRefs]}:{},...t.contentSegments?.length?{contentSegments:[...t.contentSegments]}:{},...t.selectedModelId?{selectedModelId:t.selectedModelId}:{},...t.activeModeIds?.length?{activeModeIds:[...t.activeModeIds]}:{},...t.quote?{quote:{...t.quote}}:{}}}function Fx(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(d=>n.has(d.sourceId)),r=o.length===(t.mentionRefs?.length??0)&&o.length>0,s=new Set(e.modes.map(d=>d.id)),a=(t.activeModeIds??[]).filter(d=>s.has(d)),l=t.selectedModelId&&e.modelIds.includes(t.selectedModelId)?t.selectedModelId:void 0;return{text:t.text,...r?{mentionRefs:o}:{},...r&&t.contentSegments?.length?{contentSegments:t.contentSegments}:{},...l?{selectedModelId:l}:{},...a.length?{activeModeIds:a}:{},...t.quote?.text?{quote:t.quote}:{}}}function Vx(t){let e=t.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,t.write()},e))},flush:()=>{o||n===null||(r(),t.write())},cancel:r,destroy:()=>{o=!0,r()}}}function $x(t){return t.wrapped||t.text.includes(`
1156
- `)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission||t.dictationActive)}function zx(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function Ux(t){if(!t)return!1;let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return!1;let n=e.getComputedStyle(t),o=Number.parseFloat(n.lineHeight),r=Number.parseFloat(n.fontSize),s=Number.isFinite(o)&&o>0?o:Number.isFinite(r)&&r>0?r*1.4:0;if(!s)return!1;let a=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return t.scrollHeight-a>s*1.5}zp();function Hg(t){return Object.freeze({text:t.text,contentParts:t.contentParts?Object.freeze([...t.contentParts]):void 0,mentionRefs:Object.freeze([...t.mentionRefs]),contentSegments:t.contentSegments?Object.freeze([...t.contentSegments]):void 0,options:Object.freeze({...t.options}),viaVoice:t.viaVoice})}function Kx(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var sI=t=>typeof t?.then=="function";function jx(t,e){return e===!1?{status:"canceled"}:!e||typeof e!="object"?{status:"proceed"}:(typeof e.text=="string"&&(t.text=e.text),e.options&&(t.options={...t.options,...e.options}),{status:"proceed"})}function Gx(t,e,n){let o;try{o=t(Hg(e),{signal:n})}catch(r){return{status:"error",error:r}}return sI(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:jx(e,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):jx(e,o)}Ye();Up();Rg();Ye();Yt();function Jx(t){let{config:e,onOpen:n}=t,o=e.buttonIconName??"plus",r=e.buttonTooltipText??"Add context",s=v("div","persona-send-button-wrapper"),a=$("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${fo} ${$o}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=Ie(o,$n,"currentColor",1.5);return l?a.appendChild(l):a.textContent="+",a.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),s.appendChild(a),Mn({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??r}),{button:a,wrapper:s}}oo();var{setLoader:oN,load:uI}=$t({fallbackImport:()=>Promise.resolve().then(()=>(hS(),gS))});var Dg=uI;Yt();oo();var{setLoader:gN,load:xI}=$t({fallbackImport:()=>Promise.resolve().then(()=>(kS(),ES)),resetOnSetLoader:!0});var LS=xI;Ye();Yt();function Jl(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=$("span",{className:Vt("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=Ie(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=v("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild($("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function PS(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=qp(e).filter(M=>M.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(M=>M.sources.some(O=>typeof O.matchCommand=="function")),r=M=>o.some(O=>O.trigger?O.position==="line-start"?M.split(`
1157
- `).some(B=>B.startsWith(O.trigger)):(O.position==="anywhere"?M:M.split(`
1158
- `)[0]).startsWith(O.trigger):!1),s=(M,O)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${M}`,{detail:O}))}catch{}},a=!t.chipRow,l=t.chipRow??$("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,p=null,u=t.textarea,m=null,y=null,g=null,b=null,C=()=>{if(d)return Promise.resolve(d);if(p)return p;let M=Dg().then(O=>(O.setMentionIconRenderer(Ie),d=O.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:m??void 0,anchor:t.anchor,contextRow:l,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:I,emit:s}),d)).catch(O=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",O),p===M&&(p=null),null));return p=M,M},S=()=>{LS().then(M=>{let O=M.mountInlineComposer({textarea:t.textarea,renderToken:B=>Jl(B,{render:e.renderMentionToken}),onMentionRemoved:B=>d?.untrackMention(B)});m=O.input,y=O.destroy;let k=u;k.replaceWith(O.element),u=O.element,b={next:O.element,prev:k},g?.(O.element,k),d?d.rebindComposer(O.input):p&&p.then(B=>B?.rebindComposer(O.input))}).catch(M=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",M)})};e.display==="inline"&&S();let T=[],A=new Map;for(let M of n){if(!M.showButton)continue;let O=Jx({config:{...e,buttonIconName:M.buttonIconName,buttonTooltipText:M.buttonTooltipText},onOpen:()=>{C().then(k=>k?.openMenu(M.trigger))}});T.push(O),A.set(M.trigger,O.button)}let I=(M,O,k)=>{let B=A.get(O);B&&(B.setAttribute("aria-expanded",M?"true":"false"),M?B.setAttribute("aria-controls",k):B.removeAttribute("aria-controls"))};return{affordanceButtons:T.map(M=>M.wrapper),contextRow:l,handleInput:M=>{if(d){d.handleInput();return}if(!Qx(M))return;let O=u,k=O.selectionStart??0;Kl(O.value,k,n)&&C().then(B=>B?.handleInput())},handleKeydown:M=>{if(d?.isMenuOpen())return d.handleKeydown(M);if(M.key==="Backspace"&&d?.hasMentions()&&!b){let O=u,k=O.selectionStart===0&&O.selectionEnd===0;if((O.value.length===0||k)&&d.removeLastChip())return M.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async M=>r(M)?(d??await C())?.dispatchInlineCommand(M)??null:null,clear:()=>d?.clear(),prefetch:()=>{Dg().catch(()=>{})},onComposerSwap:M=>{g=M,b&&M(b.next,b.prev)},destroy:()=>{d?.destroy(),y?.();for(let M of T)M.wrapper.remove();a&&l.remove()}}}var ou="16px",ru="transparent",SI=(()=>{let t={};for(let e of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])t[e]=e===0?"0px":`${e/4}rem`;return t})(),AI={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:SI,typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},MI={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},TI={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Rr,maxWidth:px,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ou,canvasBackground:ru},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function zn(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?zn(t,o):o}function HS(t){let e={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let d=zn(t,a);d!==void 0&&(e[l]={path:l,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function EI(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function RS(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=RS(s,r):n[o]=r}return n}function kI(t,e){return e?RS(t,e):t}function va(t,e={}){let n={palette:AI,semantic:MI,components:TI},o={palette:{...n.palette,...t?.palette,colors:{...n.palette.colors,...t?.palette?.colors},spacing:{...n.palette.spacing,...t?.palette?.spacing},typography:{...n.palette.typography,...t?.palette?.typography},shadows:{...n.palette.shadows,...t?.palette?.shadows},borders:{...n.palette.borders,...t?.palette?.borders},radius:{...n.palette.radius,...t?.palette?.radius}},semantic:{...n.semantic,...t?.semantic,colors:{...n.semantic.colors,...t?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...t?.semantic?.spacing},typography:{...n.semantic.typography,...t?.semantic?.typography}},components:kI(n.components,t?.components)};if(e.validate!==!1){let r=EI(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(e.plugins)for(let r of e.plugins)o=r.transform(o);return o}var jg=t=>t.trim()==="0"?"0px":t,IS="--persona-",LI=t=>{if(!t)return;let e=t.trim().toLowerCase(),n;if(e.charCodeAt(0)===35){let a=e.slice(1);if(!/^[0-9a-f]+$/.test(a))return;a.length===3||a.length===4?n=[0,1,2].map(l=>parseInt(a[l]+a[l],16)):(a.length===6||a.length===8)&&(n=[0,2,4].map(l=>parseInt(a.slice(l,l+2),16)))}else{let a=e.match(/^rgba?\(([^)]+)\)$/);if(a){let l=a[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(d=>{let p=d.endsWith("%"),u=parseFloat(p?d.slice(0,-1):d);return p?u/100*255:u}))}}if(!n||n.some(a=>!Number.isFinite(a)))return;let[o,r,s]=n.map(a=>{let l=Math.max(0,Math.min(255,a))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},PI=.179,Tn=(t,e)=>{for(let[n,...o]of e){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):t[IS+s],r!==void 0)break;r!==void 0&&(t[IS+n]=r)}};function WS(t){let e=HS(t),n={};for(let[N,ye]of Object.entries(e)){let ke=N.replace(/\./g,"-");n[`--persona-${ke}`]=ye.value}Tn(n,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],Tn(n,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),Tn(n,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,Tn(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??ou,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ru,Tn(n,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),Tn(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],a=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],Tn(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??a??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??a??n["--persona-muted"],Tn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=t.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[N,ye]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let ke=n[`--persona-components-history-overlay-${N}`];ke&&(n[`--persona-history-overlay-${ye}`]=ke)}for(let[N,ye]of[["background","bg"],["borderRadius","radius"]]){let ke=n[`--persona-components-history-menu-${N}`];ke&&(n[`--persona-history-menu-${ye}`]=ke)}let m=t.components?.history?.motion;if(m){let N=nt=>{if(nt===void 0)return;let Ee=String(nt).trim();return/^\d+(\.\d+)?$/.test(Ee)?`${Ee}ms`:Ee},ye=N(m.enterDurationMs);ye!==void 0&&(n["--persona-history-enter-ms"]=ye);let ke=N(m.exitDurationMs);ke!==void 0&&(n["--persona-history-exit-ms"]=ke),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let y=n["--persona-components-history-dangerForeground"];y&&(n["--persona-history-danger-fg"]=y),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let N of["scrim","shadow"]){let ye=n[`--persona-components-history-confirm-${N}`];ye&&(n[`--persona-history-confirm-${N}`]=ye)}for(let[N,ye]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let ke=n[`--persona-components-tooltip-${N}`];ke&&(n[`--persona-tooltip-${ye}`]=ke)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[N,ye]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let ke=n[`--persona-components-messageActions-${N}`];ke&&(n[`--persona-message-action-${ye}`]=ke)}Tn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let g=n["--persona-components-introCard-background"],b=n["--persona-components-introCard-shadow"],C=(!g||g==="transparent"||g==="none")&&(!b||b==="none"),S=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=C&&S==="1.5rem"?"1.5rem 0":S,Tn(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),Tn(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let T=n["--persona-components-markdown-heading-h1-fontSize"];T&&(n["--persona-md-h1-size"]=T);let A=n["--persona-components-markdown-heading-h1-fontWeight"];A&&(n["--persona-md-h1-weight"]=A);let I=n["--persona-components-markdown-heading-h2-fontSize"];I&&(n["--persona-md-h2-size"]=I);let M=n["--persona-components-markdown-heading-h2-fontWeight"];M&&(n["--persona-md-h2-weight"]=M);let O=n["--persona-components-markdown-prose-fontFamily"];O&&O!=="inherit"&&(n["--persona-md-prose-font-family"]=O),Tn(n,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),Tn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Tn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Tn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Tn(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]),n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],Tn(n,[["message-border","components-message-border","border"]]),Tn(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let k=t.components,B=k?.iconButton;B&&(B.background&&(n["--persona-icon-btn-bg"]=B.background),B.border&&(n["--persona-icon-btn-border"]=B.border),B.color&&(n["--persona-icon-btn-color"]=B.color),B.padding&&(n["--persona-icon-btn-padding"]=B.padding),B.borderRadius&&(n["--persona-icon-btn-radius"]=B.borderRadius),B.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=B.hoverBackground),B.hoverColor&&(n["--persona-icon-btn-hover-color"]=B.hoverColor),B.activeBackground&&(n["--persona-icon-btn-active-bg"]=B.activeBackground),B.activeBorder&&(n["--persona-icon-btn-active-border"]=B.activeBorder));let W=k?.labelButton;W&&(W.background&&(n["--persona-label-btn-bg"]=W.background),W.border&&(n["--persona-label-btn-border"]=W.border),W.color&&(n["--persona-label-btn-color"]=W.color),W.padding&&(n["--persona-label-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-label-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-label-btn-hover-bg"]=W.hoverBackground),W.fontSize&&(n["--persona-label-btn-font-size"]=W.fontSize),W.gap&&(n["--persona-label-btn-gap"]=W.gap));let V=k?.toggleGroup;V&&(V.gap&&(n["--persona-toggle-group-gap"]=V.gap),V.borderRadius&&(n["--persona-toggle-group-radius"]=V.borderRadius));let R=k?.artifact;if(R?.toolbar){let N=R.toolbar;N.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=N.iconHoverColor),N.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=N.iconHoverBackground),N.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=N.iconPadding),N.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=N.iconBorderRadius),N.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=N.iconBorder),N.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=jg(N.toggleGroupGap)),N.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=N.toggleBorderRadius),N.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=jg(N.toggleGroupPadding)),N.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=N.toggleGroupBorder),N.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=N.toggleGroupBorderRadius),N.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=zn(t,N.toggleGroupBackground)??N.toggleGroupBackground),N.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=N.copyBackground),N.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=N.copyBorder),N.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=N.copyColor),N.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=jg(N.copyBorderRadius)),N.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=N.copyPadding),N.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=N.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??N.copyMenuBackground),N.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=N.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??N.copyMenuBorder),N.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=N.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??N.copyMenuShadow),N.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=N.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??N.copyMenuBorderRadius),N.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=N.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??N.copyMenuItemHoverBackground),N.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=N.iconBackground),N.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=N.toolbarBorder)}if(R?.tab){let N=R.tab;N.background&&(n["--persona-artifact-tab-bg"]=N.background),N.activeBackground&&(n["--persona-artifact-tab-active-bg"]=N.activeBackground),N.activeBorder&&(n["--persona-artifact-tab-active-border"]=N.activeBorder),N.borderRadius&&(n["--persona-artifact-tab-radius"]=N.borderRadius),N.textColor&&(n["--persona-artifact-tab-color"]=N.textColor),N.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=N.hoverBackground),N.listBackground&&(n["--persona-artifact-tab-list-bg"]=N.listBackground),N.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=N.listBorderColor),N.listPadding&&(n["--persona-artifact-tab-list-padding"]=N.listPadding)}if(R?.pane){let N=R.pane;if(N.toolbarBackground){let ye=zn(t,N.toolbarBackground)??N.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ye}}if(R?.card){let N=R.card;N.background&&(n["--persona-artifact-card-bg"]=N.background),N.border&&(n["--persona-artifact-card-border"]=N.border),N.borderRadius&&(n["--persona-artifact-card-radius"]=N.borderRadius),N.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=N.hoverBackground),N.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=N.hoverBorderColor)}if(R?.inline){let N=R.inline;N.background&&(n["--persona-artifact-inline-bg"]=zn(t,N.background)??N.background),N.border&&(n["--persona-artifact-inline-border"]=N.border),N.borderRadius&&(n["--persona-artifact-inline-radius"]=N.borderRadius),N.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=zn(t,N.chromeBackground)??N.chromeBackground),N.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=zn(t,N.chromeBorder)??N.chromeBorder),N.titleColor&&(n["--persona-artifact-inline-title-color"]=zn(t,N.titleColor)??N.titleColor),N.mutedColor&&(n["--persona-artifact-inline-muted-color"]=zn(t,N.mutedColor)??N.mutedColor),N.frameHeight&&(n["--persona-artifact-inline-frame-height"]=N.frameHeight)}let w=k?.code;w&&(w.keywordColor&&(n["--persona-code-keyword-color"]=w.keywordColor),w.stringColor&&(n["--persona-code-string-color"]=w.stringColor),w.commentColor&&(n["--persona-code-comment-color"]=w.commentColor),w.numberColor&&(n["--persona-code-number-color"]=w.numberColor),w.tagColor&&(n["--persona-code-tag-color"]=w.tagColor),w.attrColor&&(n["--persona-code-attr-color"]=w.attrColor),w.propertyColor&&(n["--persona-code-property-color"]=w.propertyColor),w.lineNumberColor&&(n["--persona-code-line-number-color"]=w.lineNumberColor),w.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=w.gutterBorderColor),w.background&&(n["--persona-code-bg"]=zn(t,w.background)??w.background));let E=n["--persona-surface"],H=n["--persona-container"],D=n["--persona-palette-colors-gray-100"]??"#f3f4f6",G=n["--persona-palette-colors-gray-200"]??"#e5e7eb",z=n["--persona-palette-colors-gray-300"]??"#d1d5db",K=!H||H===E,Y=LI(E??n["--persona-background"]),re=K&&Y!==void 0&&Y<PI,oe=re?"rgba(255, 255, 255, 0.08)":D,se=re?"rgba(255, 255, 255, 0.12)":G,ce=re?"rgba(255, 255, 255, 0.16)":z,we=K?oe:H,ge=K?se:H;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??we,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??ge,K&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ce),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??we,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??we,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??we,n}var II={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},HI={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},BS=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Kg=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",RI=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Kg()},OS=t=>RI(t),WI=t=>va(t),BI=t=>{let e=ga(HI,t??{})??{};return va({...e,palette:{...e.palette,colors:{...II.colors,...e.palette?.colors}}},{validate:!1})},Ca=t=>{let e=OS(t),n=BS(t?.theme),o=BS(t?.darkTheme);return e==="dark"?BI(ga(n??{},o??{})):WI(n)},OI=t=>WS(t),Zl=(t,e)=>{let n=Ca(e),o=OI(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",OS(e))},su=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Kg())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(Kg());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};var Fr=require("lucide");Yt();ro();Ye();var ys=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var iu="24px",Gg=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",ec=t=>{if(typeof t!="string")return null;let e=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(t);if(!e)return null;let n=Number(e[1])/100;return n>0&&n<1?n:null},DS=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var _S=null;var Yg=()=>{if(_S!==null)return _S;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},DI="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",au=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},lu=t=>{let e=t.toLowerCase().split("+").map(r=>r.trim()),n=e.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of e)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return au("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(au("unsupported",t),null):(n==="space"&&(o.key=" "),o)},_I=t=>DI.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),NS=(t,e)=>{let n=lu(t);if(!n)return"";let o=Yg(),r=_I(n.key);if(!e&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[e?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},cu=t=>NS(t,!1),tc=t=>NS(t,!0),NI=(t,e)=>e.key?.toLowerCase()===t.key&&(Yg()?e.metaKey:e.ctrlKey)===t.mod&&!(Yg()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,FI=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},FS=t=>{let e=new Map,n=t?.ownerDocument??(typeof document<"u"?document:null),o=(s,a)=>{if((s.scope??"widget")==="page")return!0;if(!t)return!1;let l=a.composedPath?.();return l?.length?l.includes(t):t.contains(a.target)},r=s=>{if(s.isComposing||!e.size)return;let a=s.composedPath?.()[0]??s.target;for(let l of e.values())if(NI(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&FI(a))){s.preventDefault();try{l.run(s)}catch(d){au(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=lu(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=e.get(l);return d?(au(`${d.id} already owns`,s.combo),()=>{}):(e.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",tc(s.combo)),()=>{e.get(l)?.id===s.id&&e.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){e.clear(),n?.removeEventListener("keydown",r)}}};var VS=require("idiomorph"),du=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;VS.Idiomorph.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var $S=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Qg={index:-1,draft:""};function zS(t){let{direction:e,history:n,currentValue:o,atStart:r,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function US(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function qS(){return new Map}function jS(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function KS(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function GS(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}Jg();fs();ac();oo();var{setLoader:QN,load:pH}=$t({fallbackImport:()=>Promise.resolve().then(()=>(yA(),hA))});var bA=pH;fs();function rh(t,e=Hn){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var cc=0,bs=null;function sh(t=document){if(cc++,cc===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;bs={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,cc=Math.max(0,cc-1),cc===0&&bs)){let n=t.body,o=t.defaultView??window;n.style.overflow=bs.originalOverflow,n.style.position=bs.originalPosition,n.style.top=bs.originalTop,n.style.width=bs.originalWidth,o.scrollTo(0,bs.scrollY),bs=null}}}var dc={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},rn=t=>(t?.launcher?.mountMode??"floating")==="docked",pc=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Lo=t=>{let e=t?.launcher?.dock;return{side:e?.side??dc.side,width:e?.width??dc.width,animate:e?.animate??dc.animate,reveal:e?.reveal??dc.reveal,maxHeight:e?.maxHeight??dc.maxHeight}};Ye();Ye();var CA=require("lucide");Yt();ro();var ih=t=>t==="followUp"?"follow-up":t,ah=(t,e=0)=>{if(typeof t=="string"){let r=t.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},uH=t=>{switch(t){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},vA=new WeakSet,mH=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,fH=t=>{mH()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},lh=t=>{var I,M,O;let{item:e,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:d,chipsConfig:p,session:u,getTextarea:m,eventTarget:y,submitPrompt:g}=t,b=o==="followUp",C=e.behavior,S=()=>{if(u.isStreaming())return;let k={suggestion:{...e},surface:o,source:r,behavior:C},B=y.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:k,bubbles:!0,composed:!0,cancelable:!0}));if(b&&y.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!B)return;for(let V of d)if(V.onSuggestionSelect?.({suggestion:{...e},surface:o,source:r,variant:s,config:l})===!1)return;let W=m();if(C==="fill"){W.value=e.prompt,W.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),W.focus();return}if(g){g(e.prompt);return}W.value="",u.sendMessage(e.prompt)},T=()=>{let k=v("button",`persona-suggestion persona-suggestion--${s}`);if(k.type="button",k.disabled=a,k.dataset.suggestionId=e.id,k.dataset.emphasis=e.emphasis,k.dataset.behavior=C,s==="chip"&&(p?.fontFamily&&(k.style.fontFamily=uH(p.fontFamily)),p?.fontWeight&&(k.style.fontWeight=p.fontWeight),p?.paddingX&&(k.style.paddingLeft=p.paddingX,k.style.paddingRight=p.paddingX),p?.paddingY&&(k.style.paddingTop=p.paddingY,k.style.paddingBottom=p.paddingY)),e.icon){let W=Ie(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);W&&(W.classList.add("persona-suggestion__icon"),e.iconColor&&(W.style.color=e.iconColor),k.appendChild(W))}let B=v("span","persona-suggestion__copy");if(B.appendChild($("span",{className:"persona-suggestion__label",text:e.label})),e.description&&s!=="chip"&&B.appendChild($("span",{className:"persona-suggestion__description",text:e.description})),k.appendChild(B),s!=="chip"){let W=Qe(CA.ArrowRight,16,"currentColor",1.8);W&&(W.classList.add("persona-suggestion__arrow"),k.appendChild(W))}return k.addEventListener("click",S),k},A=null;for(let k of d)if(k.renderSuggestion&&(A=k.renderSuggestion({suggestion:{...e},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:T,select:S}),A))break;return A??(A=T()),(I=A.dataset).suggestionId||(I.suggestionId=e.id),(M=A.dataset).behavior||(M.behavior=C),(O=A.dataset).emphasis||(O.emphasis=e.emphasis),A instanceof HTMLButtonElement||A.setAttribute("aria-disabled",a?"true":"false"),A},uc=t=>{let e=[],n=[],o=null,r=null,s=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},a=()=>{if(r=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,t.scrollWidth-t.clientWidth);if(u<=1){s();return}let m=getComputedStyle(t).direction==="rtl",y=Math.min(u,Math.max(0,Math.abs(t.scrollLeft))),g=4,b=y<=g,C=y>=u-g,S=m?!C:!b,T=m?!b:!C;t.toggleAttribute("data-scroll-left",S),t.toggleAttribute("data-scroll-right",T)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};t.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(u,m,y,g,b,C)=>{t.replaceChildren(),e.length=0,n.length=0;let S=C?.source??"config",T=C?.surface??(S==="config"?"starter":"followUp"),A=T==="followUp",I=C?.variant??"chip",M=C?.behavior??"send",O=C?.overflow??"wrap",k=C?.config??{},B=C?.plugins??[],W=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,V=A?"followUps":"starters";!vA.has(k)&&k.debug===!0&&I!=="chip"&&k.suggestions?.[V]?.overflow!==void 0&&(vA.add(k),console.info(`[persona] suggestions.${V}.overflow applies to the "chip" variant only; the "${I}" variant manages its own stacking.`));let R=z=>z.map(ah).filter(K=>K!==null).map(K=>({...K,behavior:K.behavior??M})),w=R(u??[]);B.forEach(z=>{z.transformSuggestions&&(w=R(z.transformSuggestions({suggestions:w.map(K=>({...K})),surface:T,source:S,config:k})))});let E=W===void 0?w:w.slice(0,W);if(!E.length){t.hidden=!0,o=null,s();return}if(!A&&(g??m.getMessages()).some(K=>K.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=ih(T),t.dataset.variant=I,t.dataset.overflow=O;let H=document.createDocumentFragment(),D=m.isStreaming();E.forEach((z,K)=>{let Y=lh({item:z,index:K,surface:T,source:S,variant:I,streaming:D,config:k,plugins:B,chipsConfig:b,session:m,getTextarea:()=>y,eventTarget:t,submitPrompt:C?.submitPrompt});H.appendChild(Y),n.push(Y),[...Y instanceof HTMLButtonElement?[Y]:[],...Array.from(Y.querySelectorAll("button"))].forEach(oe=>{e.includes(oe)||(oe.disabled=D,e.push(oe))})}),t.appendChild(H),a(),l();let G=JSON.stringify({normalized:E,surface:T,variant:I,source:S});G!==o&&(o=G,fH(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:E.map(z=>({...z})),surface:T,source:S,variant:I},bubbles:!0,composed:!0})),A&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:E.map(z=>z.prompt)},bubbles:!0,composed:!0})))}}};var go={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};fs();Ye();Yt();Ye();Yt();var gH="persona-header-control",hH="persona-header-control--glyph",yH="persona-header-control--sparse",bH=20,vH={x:[1.4,1.05]},wA="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",CH="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yu=(t,e,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=vH[e]??[1,1.5],l=!o;t.classList.toggle(hH,l),t.classList.toggle(yH,l&&s!==1);let d=parseFloat(o??"")||bH,p=Ie(e,`${Math.round(d*s)}px`,"currentColor",a);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((a/1.5).toFixed(4))})`),t.replaceChildren(p)):r&&(t.textContent=r)},ai=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=wA,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:y,borderRadius:g,paddingX:b,paddingY:C,hidden:S,extraClassName:T,attrs:A}=t,I=v("div",a),M=!!(m||y),O=$("button",{className:Vt(gH,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!M&&"persona-border-none",!g&&"persona-rounded-full",T),attrs:{type:"button","aria-label":e,...A},style:{width:l,height:l,minWidth:l,minHeight:l,display:S?"none":void 0,color:p||Un.actionIconColor,backgroundColor:u,border:M?`${m||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:g,paddingLeft:b,paddingRight:b,paddingTop:C,paddingBottom:C}});return r?yu(O,r,{iconSize:d,iconText:s}):s&&(O.textContent=s),I.appendChild(O),Mn({anchor:O,trigger:I,text:()=>O.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:O,wrapper:I}},xa=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=wA,buttonSize:r,iconSize:s}=e,a=t?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=ai({ariaLabel:l,tooltip:d,iconName:a.closeButtonIconName??"x",iconText:a.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??a.closeButtonSize,iconSize:s,color:a.closeButtonColor,backgroundColor:a.closeButtonBackgroundColor,borderWidth:a.closeButtonBorderWidth,borderColor:a.closeButtonBorderColor,borderRadius:a.closeButtonBorderRadius,paddingX:a.closeButtonPaddingX,paddingY:a.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:u}},Sa=(t,e={})=>{let{wrapperClassName:n=CH,buttonSize:o,iconSize:r}=e,a=(t?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=ai({ariaLabel:l,tooltip:d,iconName:a.iconName??"refresh-cw",wrapperClassName:n,size:o??a.size,iconSize:r,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:p,wrapper:u}};var Un={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))",minHeight:"var(--persona-header-min-height, auto)"},ch={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},wH={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},li=t=>{let{config:e,showClose:n=!0}=t,o=$("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{minHeight:Un.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=e?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,p=$("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(d){let O=parseFloat(s)||24,k=Ie(d,O*.6,"currentColor",1);k?p.replaceChildren(k):p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let O=v("img");O.src=e.launcher.iconUrl,O.alt="",O.className="persona-rounded-xl persona-object-cover",O.style.height=s,O.style.width=s,p.replaceChildren(O)}else p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let u=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=$("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Un.titleColor,...ch}}),y=$("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Un.subtitleColor,...wH}});u.append(m,y),l?o.append(u):o.append(p,u);let g=r.clearChat??{},b=g.enabled??!0,C=g.placement??"inline",S=null,T=null;if(b){let k=Sa(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=k.button,T=k.wrapper,C==="top-right"&&(T.style.right="48px"),C==="inline"&&o.appendChild(T)}let A=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:I,wrapper:M}=xa(e,{showClose:n,wrapperClassName:A});return a!=="top-right"&&o.appendChild(M),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:y,closeButton:I,closeButtonWrapper:M,clearChatButton:S,clearChatButtonWrapper:T}},mc=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};Ye();dh();di();var xH=t=>{let e=li({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return e};function SH(t,e,n){if(e?.length)for(let o of e){let{button:r,wrapper:s}=ai({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?cu(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let a=tc(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=fc({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()})}else r.addEventListener("click",()=>n?.(o.id));t.appendChild(s)}}var AH=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,a=e?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=Un.minHeight,l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r?.titleMenu,p,u;if(d){let M=SA({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:O=>{let k=W=>{W===!1&&M.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:O}}))},B=d.onSelect(O);B instanceof Promise?B.then(k,()=>{}):k(B)},hover:d.hover,className:""});p=M.element,p.style.color=Un.titleColor,u=p.querySelector(".persona-combo-btn-label")??p}else{if(p=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=v("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Un.titleColor,Object.assign(u.style,ch),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let O=r.onTitleClick;p.addEventListener("click",k=>{k.target.closest("button")||O()}),p.addEventListener("keydown",k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),O())})}let M=r?.titleRowHover;M&&(p.style.borderRadius=M.borderRadius??"10px",p.style.padding=M.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=M.background??"",p.style.borderColor=M.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:y,wrapper:g}=xa(e,{showClose:n,wrapperClassName:m});o&&y.addEventListener("click",o);let b=v("div","persona-flex persona-items-center persona-gap-1");d||SH(b,r?.trailingActions,r?.onAction??s);let C=a.clearChat??{},S=null,T=null;if(C.enabled??!0){let M=C.placement??"inline",O=Sa(e,{wrapperClassName:M==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});S=O.button,T=O.wrapper,M==="top-right"?T.style.right="48px":b.appendChild(T)}b.appendChild(g),l.appendChild(b);let A=v("div");A.style.display="none";let I=v("span");return I.style.display="none",{header:l,iconHolder:A,headerTitle:u,headerSubtitle:I,closeButton:y,closeButtonWrapper:g,clearChatButton:S,clearChatButtonWrapper:T}},AA={default:xH,minimal:AH},MH=t=>AA[t]??AA.default,vu=(t,e,n)=>{if(e?.render){let a=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=v("div");l.style.display="none";let d=v("span"),p=v("span"),u=v("button");u.style.display="none";let m=v("div");return m.style.display="none",{header:a,iconHolder:l,headerTitle:d,headerSubtitle:p,closeButton:u,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=MH(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};Ye();var gc=t=>{let{config:e}=t,n=$("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Op(),r=$("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Hp(e);a();let l=Rp(e),d=ha(e),p=Wp(e),u=Bp(e),m=$("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),p&&(p.previewsContainer.style.gap="8px",m.append(p.previewsContainer),r.append(p.input)),r.append(s);let y=$("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=$("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),b=$("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&g.append(p.wrapper),d&&b.append(d.wrapper),b.append(l.wrapper),y.append(g,b),r.append(y),r.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==d?.button&&C.target!==d?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,header:m,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:u,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:y,leftActions:g,rightActions:b,setSendButtonMode:l.setMode}};Ye();var Cu=require("lucide");ro();var MA=()=>{let t=$("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=v("span","persona-pill-peek__icon"),n=Qe(Cu.MessageSquare,16,"currentColor",1.5);n&&e.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),s=Qe(Cu.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},wu=t=>{let{config:e}=t,n=$("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Op(),r=Bp(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=Hp(e,{defaultMaxLines:5});a();let l=Rp(e),d=ha(e),p=Wp(e);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=$("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=$("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let y=$("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&y.append(d.wrapper),y.append(l.wrapper),u.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==d?.button&&C.target!==d?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(m,s,y);let g=$("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(g),p&&g.append(p.previewsContainer),n.append(o,u,r);let b=u;return{footer:n,suggestions:o,composerForm:u,header:g,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:b,leftActions:m,rightActions:y,setSendButtonMode:l.setMode}};Ye();Yt();Ye();di();Yt();ac();var TH=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},EH=(t,e)=>{if(!t)return null;let n=TH(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},kH=(t,e)=>{let n=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},LH=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},uh=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},mh=320,PA=320,PH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),IH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),HH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),RH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),WH=t=>{if(!t||t.length===0)return null;let e=$("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=$("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=Ie(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild($("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},BH=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Jl(o.ref,{readonly:!0,render:e}))}return n},TA="\uE000",EA="\uE001",OH=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${TA}${r}:${y}${EA}`,a=e.map((y,g)=>y.kind==="text"?y.text:s(g)).join(""),l=n(a);if(!e.every((y,g)=>y.kind==="text"||l.includes(s(g)))){t.replaceChildren(BH(e,o));return}t.innerHTML=l;let p=new RegExp(`${TA}${r}:(\\d+)${EA}`),u=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),m=[];for(let y=u.nextNode();y;y=u.nextNode())m.push(y);for(let y of m){let g=y;for(let b=p.exec(g.data);b;b=p.exec(g.data)){let C=e[Number(b[1])],S=g.splitText(b.index);S.data=S.data.slice(b[0].length),C?.kind==="mention"&&S.parentNode?.insertBefore(Jl(C.ref,{readonly:!0,render:o}),S),g=S}}},DH=(t,e,n)=>{if(t.length===0)return null;try{let o=v("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return t.forEach((l,d)=>{let p=v("img");p.alt=l.alt?.trim()||`Attached image ${d+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${mh}px`,p.style.maxHeight=`${PA}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,p.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),p.remove(),r===0&&a())}),p.addEventListener("load",()=>{u=!0}),LH(l.image)?(p.src=l.image,o.appendChild(p)):(u=!0,r=Math.max(0,r-1),p.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},_H=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!uh(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mh}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},NH=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!uh(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mh}px`,r.style.maxHeight=`${PA}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},FH=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!uh(o.data))return;let r=v("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},hc=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},VH=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:hc};if(e){let r=e(o);if(r!==null)return r}return hc()},$H=(t,e)=>{let n=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=v("img");r.src=o,r.alt=e==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},kA=(t,e,n="div")=>{let o=v(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},yc=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},LA={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},zH=(t,e,n="bubble",o)=>{if(!o)return;let r=e==="user"?"user":"assistant",s=LA[n??"bubble"]??LA.bubble;o.padding&&(t.style.padding=`var(--persona-message-${r}-padding, ${s.padding})`),o.fontSize&&(t.style.fontSize=`var(--persona-message-${r}-font-size, ${s.fontSize})`),o.lineHeight&&(t.style.lineHeight=`var(--persona-message-${r}-line-height, ${s.lineHeight})`),o.fontFamily&&(t.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},xu="custom:",UH=t=>`${xu}${t}`,IA=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),qH=(t,e,n,o)=>{let r=e.showCopy??!0,s=e.showUpvote??!0,a=e.showDownvote??!0,l=e.showReadAloud??!1,d=(e.showRegenerate??!1)&&o?.canRegenerate===!0,p=(e.showEdit??!1)&&o?.canEdit===!0,u=(e.showQuote??!1)&&o?.canQuote!==!1,m=IA(e,t.role);if(!r&&!s&&!a&&!l&&!d&&!p&&!u&&m.length===0){let I=v("div");return I.style.display="none",I.id=`actions-${t.id}`,I.setAttribute("data-actions-for",t.id),I}let y=e.visibility??"hover",g=e.align??"right",b=e.layout??"pill-inside",C={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[g],S={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[b],T=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${C} ${S} ${y==="hover"?"persona-message-actions-hover":""}`);T.id=`actions-${t.id}`,T.setAttribute("data-actions-for",t.id);let A=(I,M,O)=>{let k=gn({icon:I,label:M,size:14,className:"persona-message-action-btn",chromeless:!0});return k.setAttribute("data-action",O),k};r&&T.appendChild(A("copy","Copy message","copy")),l&&T.appendChild(A("volume-2","Read aloud","read-aloud")),s&&T.appendChild(A("thumbs-up","Upvote","upvote")),a&&T.appendChild(A("thumbs-down","Downvote","downvote")),d&&T.appendChild(A("refresh-cw","Regenerate response","regenerate")),p&&T.appendChild(A("pencil","Edit message","edit")),u&&T.appendChild(A("quote","Quote message","quote"));for(let I of m)T.appendChild(A(I.iconName??"ellipsis",I.label,UH(I.id)));return T},fh=(t,e,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",d=a.avatar,p=a.timestamp,u=d?.show??!1,m=p?.show??!1,y=d?.position??"left",g=p?.position??"below",b=yc(t.role,l),C=v("div",b.join(" "));C.id=`bubble-${t.id}`,C.setAttribute("data-message-id",t.id),C.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let S=s?.widgetConfig?.theme?.components?.message;zH(C,t.role,l,t.role==="user"?S?.user:S?.assistant),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=PH(t),A=t.content?.trim()??"",M=T.length>0&&A===da,O=fu(s?.widgetConfig?.features?.streamAnimation),k=s?.widgetConfig?.features?.streamAnimation?.plugins,B=t.role==="assistant"&&O.type!=="none"?oc(O.type,k):null,W=t.role==="assistant"&&B?.isAnimating?.(t)===!0,V=t.role==="assistant"&&B!==null&&(!!t.streaming||W);V&&B?.bubbleClass&&C.classList.add(B.bubbleClass);let R=document.createElement("div");R.classList.add("persona-message-content"),t.streaming&&R.classList.add("persona-content-streaming"),V&&B&&(B.containerClass&&R.classList.add(B.containerClass),R.style.setProperty("--persona-stream-step",`${O.speed}ms`),R.style.setProperty("--persona-stream-duration",`${O.duration}ms`));let w=V?gu(t.content??"",O.buffer,B,t,!!t.streaming):t.content??"",E=()=>{let ge=e({text:w,message:t,streaming:!!t.streaming,raw:t.rawContent});return V&&B?.wrap==="char"?rc(ge,"char",t.id,{skipTags:B.skipTags}):V&&B?.wrap==="word"?rc(ge,"word",t.id,{skipTags:B.skipTags}):ge},H=null;if(M?(H=document.createElement("div"),H.innerHTML=E(),H.style.display="none",R.appendChild(H)):t.contentSegments?.length?OH(R,t.contentSegments,ge=>e({text:ge,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):R.innerHTML=E(),V&&B?.useCaret&&!M&&A){let ge=hu(),N=R.querySelectorAll(".persona-stream-char, .persona-stream-word"),ye=N[N.length-1];if(ye?.parentNode)ye.parentNode.insertBefore(ge,ye.nextSibling);else{let ke=R.lastElementChild;ke?ke.appendChild(ge):R.appendChild(ge)}}if(m&&g==="inline"&&t.createdAt){let ge=kA(t,p,"span");ge.classList.add("persona-timestamp-inline");let N=R.lastElementChild;N?N.appendChild(ge):R.appendChild(ge)}if(T.length>0){let ge=DH(T,!M&&!!A,()=>{M&&H&&(H.style.display="")});ge?C.appendChild(ge):M&&H&&(H.style.display="")}let D=IH(t);if(D.length>0){let ge=_H(D);ge&&C.appendChild(ge)}let G=HH(t);if(G.length>0){let ge=NH(G);ge&&C.appendChild(ge)}let z=RH(t);if(z.length>0){let ge=FH(z);ge&&C.appendChild(ge)}let K=t.contentSegments?.length?null:WH(t.contextMentions);if(K&&C.appendChild(K),C.appendChild(R),m&&g==="below"&&t.createdAt){let ge=kA(t,p);ge.classList.add("persona-mt-1"),C.appendChild(ge)}let Y=t.role==="assistant"?EH(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let ge=!!(w&&w.trim()),N=O.placeholder==="skeleton",ye=N&&O.buffer==="line"&&ge;if(ge)ye&&C.appendChild(sc());else if(N)C.appendChild(sc());else{let ke=VH("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ke&&C.appendChild(ke)}}Y&&t.stopReason&&!t.streaming&&(A||(R.style.display="none"),C.appendChild(kH(t.stopReason,Y)));let re=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,oe=s?.actionEligibility,se=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&oe?.canEdit===!0||o?.showQuote===!0&&oe?.canQuote===!0||IA(o,"user").length>0);if((re||se)&&o){let ge=qH(t,se?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,oe);C.appendChild(ge)}if(!u||t.role==="system")return C;let ce=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),we=$H(d,t.role);return y==="right"||y==="left"&&t.role==="user"?ce.append(C,we):ce.append(we,C),ce};var jH=40,KH=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=Ie(e.name,jH);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild($("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild($("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},HA=(t,e,n={})=>{let o=$("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("p","persona-welcome-kicker");r.hidden=!0;let s=v("h2","persona-welcome-title"),a=v("p","persona-welcome-subtitle"),l=$("div",{className:"persona-welcome-head-text"},r,s),d=$("div",{className:"persona-welcome-title-row"},o,l);return{host:$("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},d,a,e),iconHolder:o,kicker:r,title:s,subtitle:a,starterSuggestions:e}},Aa=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},Au=(t,e)=>{t.title.textContent=e.title,t.kicker.textContent=e.kicker??"",t.kicker.hidden=!e.kicker,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",KH(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss),t.host.setAttribute("data-persona-welcome-anchor",e.anchor??"bottom"),e.iconPlacement==="inline"?t.host.setAttribute("data-persona-welcome-icon-placement","inline"):t.host.removeAttribute("data-persona-welcome-icon-placement"),e.align?t.host.setAttribute("data-persona-welcome-align",e.align):t.host.removeAttribute("data-persona-welcome-align")},GH="data-persona-welcome-plugin",RA="data-persona-welcome-overlay",Su="persona-welcome-overlay-active",gh=new WeakMap,hh=(t,e,n)=>{n.setAttribute(GH,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(RA,""),t.classList.contains(Su)||(gh.set(t,t.scrollTop),t.classList.add(Su),t.scrollTop=0)},yh=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(RA),t.classList.contains(Su)&&(t.classList.remove(Su),t.scrollTop=gh.get(t)??t.scrollTop,gh.delete(t))},WA=()=>{let t=$("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},Mu=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=$("div",{className:yc("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});t.appendChild($("div",{className:"persona-flex"},r)),t.hidden=!1},BA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,OA=(t,e)=>{if(BA()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,r=0,s=0,a=0;if(o){let b=getComputedStyle(o);r=parseFloat(b.rowGap)||0;let C=t.previousElementSibling,S=t.nextElementSibling,A=o.getBoundingClientRect().top+(parseFloat(b.borderTopWidth)||0)+(parseFloat(b.paddingTop)||0)-o.scrollTop;s=Math.max(0,C?n.top-C.getBoundingClientRect().bottom-r:n.top-A),a=Math.max(0,S?S.getBoundingClientRect().top-n.bottom-r:0)}let l=t.style.overflow;t.style.overflow="hidden";let d=getComputedStyle(t),p=parseFloat(d.paddingTop)||0,u=parseFloat(d.paddingBottom)||0,m=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${u}px`,marginTop:`${s}px`,marginBottom:`${a}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),y=!1,g=()=>{y||(y=!0,t.style.overflow=l,e(m))};return m.finished.then(g).catch(g),m},DA=(t,e,n)=>{if(e<=1||BA()||typeof t.animate!="function"||!t.isConnected)return null;let o=n==="drop"?-e:e;return t.animate([{transform:`translateY(${o}px)`},{transform:"none"}],{duration:260,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var YH="Hello \u{1F44B}",QH="I can answer questions and help you get things done here.",_A=new WeakSet,qn=(t,e)=>!!t&&t[e]!==void 0,XH=(t,e)=>{!t||t.debug!==!0||!e.length||_A.has(t)||(_A.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},Br=t=>{let e=t?.welcome,n=t?.copy,o=qn(e,"variant")?e.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":qn(e,"dismiss")?e.dismiss:"never",s=[];qn(e,"title")&&qn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),qn(e,"subtitle")&&qn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),qn(e,"variant")&&qn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&qn(e,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&qn(e,"dismiss")&&e.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let a=e?.anchor==="center"?"center":"bottom",l=ec(e?.anchorComposerTop)!==null;return qn(e,"anchorComposerTop")&&!l&&s.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),a!=="center"&&(qn(e,"anchorComposerTop")||qn(e,"composerGap"))&&s.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),XH(t,s),{title:qn(e,"title")?e.title:n?.welcomeTitle??YH,kicker:e?.kicker??"",subtitle:qn(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??QH,icon:e?.icon,align:e?.align==="start"||e?.align==="center"?e.align:void 0,iconPlacement:e?.icon&&typeof e.icon!="function"&&e.icon.placement==="inline"?"inline":"above",variant:o,dismiss:r,message:o==="hero"?void 0:e?.message,anchor:a,anchorComposerTop:l?e.anchorComposerTop:"44%",composerGap:e?.composerGap?.trim()||iu}},NA=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Ma=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var FA="16px",vh="10px",Ch="14px",VA=t=>{let e=t?.launcher?.enabled??!0,n=rn(t);if(pc(t)){let u=t?.launcher?.composerBar??{},m=v("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=u.expandedSize??"anchored",m.style.zIndex=String(t?.launcher?.zIndex??Hn);let y=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",m.appendChild(y);let g=v("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=u.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??Hn),{wrapper:m,panel:y,pillRoot:g}}if(n){let u=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return u.appendChild(m),{wrapper:u,panel:m}}if(!e){let u=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=t?.launcher?.width??"100%";return u.style.width=y,m.style.width="100%",u.appendChild(m),{wrapper:u,panel:m}}let r=t?.launcher??{},s=r.position&&go[r.position]?go[r.position]:go["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??Hn);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=t?.launcher?.width??t?.launcherWidth??Rr;return l.style.width=p,l.style.maxWidth=p,a.appendChild(l),{wrapper:a,panel:l}},wh=t=>{let e=$("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":ih(t)}});return e.hidden=!0,e},$A=(t,e)=>{let n=wh("starter"),o=HA(t,n,{flatShadow:rn(t)}),r=Br(t);Au(o,r),Aa(e,o.host,Ma(r,t?.initialMessages));let s=WA();return Mu(s,r.message,t),{welcome:o,greetingHost:s}},JH=(t,e)=>{let n=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=xa(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:FA,iconSize:vh});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=t?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let B=Sa(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:FA,iconSize:Ch});a=B.button,l=B.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=$("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=$("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=$A(t,p),{host:y,title:g,subtitle:b}=u,C=u.starterSuggestions,S=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),T=wh("followUp"),A=ys(t,!0);A&&(S.style.maxWidth=A,S.style.marginLeft="auto",S.style.marginRight="auto",S.style.width="100%"),p.append(y,m,S,T);let I=$("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),M=wu({config:t}),{root:O,textNode:k}=MA();return n.append(d,r,p,I),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:S,starterSuggestions:C,transcriptSuggestions:T,composerOverlay:I,suggestions:M.suggestions,textarea:M.textarea,sendButton:M.sendButton,sendButtonWrapper:M.sendButtonWrapper,micButton:M.micButton,micButtonWrapper:M.micButtonWrapper,composerForm:M.composerForm,statusText:M.statusText,welcomeHost:y,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:g,introSubtitle:b,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode,peekBanner:O,peekTextNode:k}},zA=(t,e=!0)=>{if(pc(t))return JH(t,e);let n=$("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?vu(t,o,{showClose:e}):li({config:t,showClose:e}),a=$("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:d}=$A(t,a),{host:p,title:u,subtitle:m}=l,y=l.starterSuggestions,g=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),b=wh("followUp"),C=ys(t,!1);C&&(g.style.maxWidth=C,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),a.append(p,d,g,b);let S=gc({config:t}),T=t?.layout?.showFooter!==!1;r?mc(n,s,t):(s.header.style.display="none",mc(n,s,t)),n.append(a);let A=$("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return T||(S.footer.style.display="none"),n.append(S.footer),n.append(A),{container:n,body:a,messagesWrapper:g,starterSuggestions:y,transcriptSuggestions:b,composerOverlay:A,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:d,introKicker:l.kicker,introTitle:u,introSubtitle:m,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode}};Ye();Yt();fs();var xh=(t,e)=>{let n=v("button");n.type="button",n.innerHTML=`
1155
+ `),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,c=r.contentParts.length>0;if(l){let p=[];s&&p.push(fr(s)),p.push(...r.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(c){let p=[];a&&p.push(fr(a)),p.push(...r.contentParts),e.contentParts=p}else s&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim(),r=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!r)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let s=Dp(),a=Ta();this.activeAssistantMessageId=null;let l=n?.contentParts&&Up(n.contentParts)?Ra:"",c={id:s,role:"user",content:o||l,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};this.appendMessage(c),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let m=this.messages.find(g=>g.id===s)??c;if(await this.applyMentionBundle(m,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(h=>h.id===s)??c,g=qx({quote:n.quote,text:m.llmContent??m.content,contentParts:m.contentParts});g.contentParts&&(m.contentParts=g.contentParts),g.llmContent!==void 0&&(m.llmContent=g.llmContent),(g.contentParts||g.llmContent!==void 0)&&(m.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,p,a,s,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let g=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!g){let h=rh(m,this.config.errorMessage);if(h){let b={id:a,role:"assistant",createdAt:new Date().toISOString(),content:h,sequence:this.nextSequence()};this.appendMessage(b)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(e,n){let o=jx(this.messages,e);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,a=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!a?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},u=s?this.toComposerOptionsPayload(s.options):r.composerOptions,m=s?s.contentSegments:r.contentSegments,g=s?s.options?.quote:void 0,h=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(a??"",{...l?.length?{contentParts:[...l]}:{},...m?.length?{contentSegments:[...m]}:{},...u?{composerOptions:u}:{},...g?{quote:g}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:h===!0}),!0}toComposerOptionsPayload(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let e=Ta();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=rh(r,this.config.errorMessage);if(a){let l={id:e,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(s=>s.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(u=>u.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,p=c&&typeof c=="object"?c.onDecision:void 0;try{let u;if(p?u=await p({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),u){let m=null;if(u instanceof Response){if(!u.ok){let g=await u.json().catch(()=>null);throw new Error(g?.error??`Approval request failed: ${u.status}`)}m=u.body}else u instanceof ReadableStream&&(m=u);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(u=>u.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,s=e.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let u=e.toolCall?.args,m=Array.isArray(u?.questions)?u.questions:[];if(m.length===1){let g=typeof m[0]?.question=="string"?m[0].question:"";g&&(a={[g]:n})}}this.markAskUserQuestionResolved(e,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,c=e.toolCall?.args,p=Array.isArray(c?.questions)?c.questions:[];if(p.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([m,g])=>`${m}: ${Array.isArray(g)?g.join(", "):g}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=a??{};p.forEach((m,g)=>{let h=typeof m?.question=="string"?m.question:"";if(!h)return;let b=u[h],C=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${g}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${g}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(r,{[s]:n},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==As?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let s=async c=>{let p=c.toolCall?.name,u=c.toolCall?.id;if(!p||!u)return null;let m=`${e}:${u}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(c))return null;this.webMcpInflightKeys.add(m),o.push(m);let g=this.markWebMcpToolRunning(c),h=c.agentMetadata?.webMcpToolCallId??p;if(p===As)return{dedupeKey:m,resumeKey:h,output:fx(),toolMessage:c,startedAt:g,completedAt:Date.now()};let b=this.client.executeWebMcpToolCall(p,c.toolCall?.args,r.signal),C;if(!b)C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{C=await b}catch(M){let E=M instanceof Error&&(M.name==="AbortError"||M.message.includes("aborted")||M.message.includes("abort"));return E||this.callbacks.onError?.(M instanceof Error?M:new Error(String(M))),this.markWebMcpToolComplete(c,sh(E?"Aborted by cancel()":_I(M)),g),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(c,sh("Aborted by cancel()"),g),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:h,output:C,toolMessage:c,startedAt:g,completedAt:Date.now()}},a;if(this.config.webmcp?.execution==="sequential"){a=[];for(let c of n)a.push(await s(c))}else a=await Promise.all(n.map(s));let l=[];try{if(l=a.filter(m=>m!==null),l.length===0)return;let c={};for(let m of l)c[m.resumeKey]=m.output;let p=await this.client.resumeFlow(e,c,{signal:r.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!p.ok){let m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}let u=l[0].dedupeKey;for(let m of l){this.webMcpResolvedKeys.add(m.dedupeKey);let g=m.toolMessage.toolCall?.name,h=m.toolMessage.agentMetadata?.webMcpToolCallId;this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt,{...g===As?{suggestRepliesResolved:!0}:{},...g&&h?{clientToolAnswer:{toolCallId:h,toolName:g,args:m.toolMessage.toolCall?.args,result:m.output,batch:u}}:{}})}p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,sh("Aborted by cancel()"),u.startedAt)}finally{for(let c of o)this.webMcpInflightKeys.delete(c);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let a=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a))return;this.webMcpInflightKeys.add(a);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(a)}catch(l){this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{this.webMcpInflightKeys.delete(a)}return}let s=`${n}:${r}`;if(!(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e)))return this.resolveWebMcpToolCallBatch(n,[e])}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=Cs(this.config.features?.artifacts,e),r=$l(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=Cs(this.config.features?.artifacts,n),s=$l(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=aS().then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>rh(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Ta(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=nh(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Qg(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=nh(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let l=r.agentMetadata?.clientToolAnswer;if(l&&a.agentMetadata&&!a.agentMetadata.clientToolAnswer&&(a.agentMetadata={...a.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let m=r.approval,g=n.approval;a.approval={...m,...g,executionId:g.executionId||m.executionId,toolName:g.toolName||m.toolName,description:g.description||m.description,toolType:g.toolType??m.toolType,reason:g.reason??m.reason,parameters:g.parameters??m.parameters}}let c=n.toolCall?.name,p=n.agentMetadata?.executionId,u=n.toolCall?.id;if(c&&lS(c)&&p&&u&&n.agentMetadata?.awaitingLocalTool===!0){let m=`${p}:${u}`,g=this.webMcpInflightKeys.has(m),h=this.webMcpResolvedKeys.has(m),b=r.toolCall?.name,C=r.agentMetadata?.executionId===p&&r.toolCall?.id===u&&b!==void 0&&lS(b)&&r.toolCall?.status==="complete";(g||h||C)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};je();var Bo=require("lucide");zn();Zt();var NI={add:t=>Px(t)},FI=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,Zp={allowedTypes:Ur,maxFileSize:10*1024*1024,maxFiles:4};function VI(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $I(t){return t==="application/pdf"?Bo.FileText:t.startsWith("text/")?Bo.FileText:t.includes("word")?Bo.FileText:t.includes("excel")||t.includes("spreadsheet")?Bo.FileSpreadsheet:t==="application/json"?Bo.FileCode:Bo.File}var oc=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??Zp.allowedTypes,maxFileSize:e.maxFileSize??Zp.maxFileSize,maxFiles:e.maxFiles??Zp.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:NI}setPreviewsContainer(e){this.previewsContainer=e}remountPreviews(e){if(this.previewsContainer=e,e){e.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Zp.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.destroyed)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=Lx(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let a=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,a);continue}let s={id:VI(),file:o,previewUrl:qp(o)?URL.createObjectURL(o):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(s),this.renderPreview(s),n.push(s)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(n.map(o=>this.runAdd(o)))}async runAdd(e){let n=new AbortController;this.pendingAdds.set(e.id,n);let o=()=>this.destroyed||n.signal.aborted||this.pendingAdds.get(e.id)!==n||!this.attachments.includes(e);try{let r=await this.adapter().add(e.file,{signal:n.signal,onProgress:s=>{o()||e.status!=="uploading"||(e.progress=FI(s),this.updatePreview(e),this.notify())}});if(o())return;e.contentPart=r,e.status="ready",e.progress=void 0,e.error=void 0}catch(r){if(o())return;e.status="error",e.progress=void 0,e.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(e.id)===n&&this.pendingAdds.delete(e.id)}this.updatePreview(e),this.notify()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.destroyed||(n.status=this.hasCustomAdapter()?"uploading":"processing",n.progress=this.hasCustomAdapter()?0:void 0,n.error=void 0,this.updatePreview(n),this.notify(),this.runAdd(n))}abortAdd(e){let n=this.pendingAdds.get(e);n&&(this.pendingAdds.delete(e),n.abort())}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];this.abortAdd(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.releasePart(o.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(e){let n=this.config.adapter?.remove;if(n)try{let o=n(e,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let e of this.attachments)this.abortAdd(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.pendingAdds.values())e.abort();this.pendingAdds.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=qp(e.file),o=v("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let u=v("img");u.src=e.previewUrl,u.alt=e.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=v("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let m=$I(e.file.type),g=Ge(m,20,"var(--persona-muted, #6b7280)",1.5);g&&u.appendChild(g);let h=v("span");h.textContent=Ix(e.file.type,e.file.name),h.style.fontSize="8px",h.style.fontWeight="600",h.style.color="var(--persona-muted, #6b7280)",h.style.textTransform="uppercase",h.style.lineHeight="1",u.appendChild(h),o.appendChild(u)}let r=F("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=v("div","persona-attachment-progress");s.appendChild(v("div","persona-attachment-progress__bar"));let a=F("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ke("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?a.appendChild(l):a.textContent="\u21BB",a.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.retryAttachment(e.id)}),r.append(s,a),o.appendChild(r);let c=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let p=Ge(Bo.X,10,"var(--persona-text-inverse, #ffffff)",2);p?c.appendChild(p):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(c),this.previewsContainer.appendChild(o),this.applyPreviewState(o,e)}updatePreview(e){let n=this.previewsContainer?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.applyPreviewState(n,e)}applyPreviewState(e,n){e.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";e.setAttribute("aria-busy",o?"true":"false"),e.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=e.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n,adapter:e?.adapter})}};var cS=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),zI=(t,e)=>t.length===e.length&&t.every((n,o)=>{let r=e[o];return n.id===r.id&&n.name===r.name&&n.mimeType===r.mimeType&&n.size===r.size&&n.status===r.status&&n.progress===r.progress&&n.error===r.error});function dS(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,r=!1,s=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",a=()=>{let u=s();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:u,inputDisabled:t.inputDisabled,sendDisabled:u!=="idle"||t.sendDisabled||t.inputDisabled})},l=()=>(n||(n=a()),n),c=()=>{if(o=!1,r||e.size===0)return;let u=l();for(let m of[...e])try{m(u)}catch(g){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",g)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(c))};return{getState:l,subscribe:u=>(e.add(u),()=>e.delete(u)),setText:u=>{t.text!==u&&(t.text=u,p())},setAttachments:u=>{zI(t.attachments,u)||(t.attachments=[...u],p())},setMentionRefs:u=>{cS(t.mentionRefs,u)||(t.mentionRefs=[...u],p())},setSelectedModelId:u=>{t.selectedModelId!==u&&(t.selectedModelId=u,p())},setActiveModeIds:u=>{cS(t.activeModeIds,u)||(t.activeModeIds=[...u],p())},setQuote:u=>{let m=t.quote;m?.text===u?.text&&m?.messageId===u?.messageId&&m?.sourceLabel===u?.sourceLabel||(t.quote=u?{...u}:void 0,p())},setPendingSubmission:u=>{t.pendingSubmission!==u&&(t.pendingSubmission=u,p())},setPreparing:u=>{t.preparing!==u&&(t.preparing=u,p())},setStreaming:u=>{t.streaming!==u&&(t.streaming=u,p())},setInputDisabled:u=>{t.inputDisabled!==u&&(t.inputDisabled=u,p())},setSendDisabled:u=>{t.sendDisabled!==u&&(t.sendDisabled=u,p())},flush:()=>{o&&c()},destroy:()=>{r=!0,o=!1,e.clear()}}}je();var io=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},pS=(t,e)=>{let n=v("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function uS(t,e={}){let n=io(t,"[data-persona-composer-form]"),o=io(t,"[data-persona-composer-input]");if(!n||!o){let E=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(e.debug&&(n||o))throw new Error(E);return typeof console<"u"&&console.warn(E),null}let r={header:io(t,"[data-persona-composer-header]"),body:io(t,"[data-persona-composer-body]"),actionsStart:io(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:io(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:io(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:io(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:io(t,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=pS("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(a,n):t.appendChild(a));let l=r.body??o.parentElement??n,c=(M,E,T,H,A)=>{if(E)return E;s.add(M);let D=pS(T,H);return A.appendChild(D),D},p=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),g=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",t),h=[],b=(M,E)=>M.target===E.target&&M.type===E.type&&M.handler===E.handler,C=io(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:a,body:l,actionsStart:p,actionsEnd:u,suggestions:m,status:g,attachmentInput:C,attachmentPreviews:io(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:io(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:io(t,"[data-persona-composer-submit]")??void 0,micButton:io(t,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(M,E,T,H)=>{M.addEventListener(E,T,H),h.push({target:M,type:E,handler:T,options:H})},removeListener:(M,E,T,H)=>{M.removeEventListener(E,T,H),h=h.filter(A=>!b(A,{target:M,type:E,handler:T}))},destroy:()=>{for(let M of h)M.target.removeEventListener(M.type,M.handler,M.options);h=[]}}}je();Zt();ks();var UI=8,qI=8,ih=10,mS=200,fS=300,gS=0,tu=t=>Math.max(0,t);function hS(t){t.delayMs!==void 0&&(mS=tu(t.delayMs)),t.skipDelayMs!==void 0&&(fS=tu(t.skipDelayMs))}var jI=()=>Date.now()<gS,KI=t=>{gS=t>0?Date.now()+t:0},eu=new WeakMap,lh="data-persona-tooltip-suppressed",GI=t=>typeof t.closest=="function"&&t.closest(`[${lh}]`)!==null;function yS(t){eu.get(t)?.hide()}var bS=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,YI=t=>{let e=t.getRootNode?.();return bS(e)?e:t.ownerDocument.body},ah=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),QI=[...["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 In(t){eu.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:r,enabled:s=!0,gap:a=UI,viewportPadding:l=qI}=t,c=()=>e.ownerDocument,p=()=>c().defaultView??window,u=null,m=null,g=null,h=null,b,C=!1,M=!1,E=!1,T=()=>(typeof o=="function"?o():o).trim(),H=()=>(typeof r=="function"?r():r??"").trim(),A=()=>tu(t.delayMs??mS),D=()=>tu(t.skipDelayMs??fS),W=()=>{b!==void 0&&(p().clearTimeout(b),b=void 0)},U=()=>{W();let oe=u!==null;h?.(),h=null,u?.remove(),u=null,m=null,g=null,oe&&KI(D())},B=()=>{if(!u)return;let oe=c(),ne=p(),le=e.getBoundingClientRect(),de=u.getBoundingClientRect(),ve=oe.documentElement.clientWidth||ne.innerWidth,Le=oe.documentElement.clientHeight||ne.innerHeight,se=ve-l-de.width,_=le.left+le.width/2-de.width/2,Te=ah(_,l,se),He=le.top-l,ut=Le-l-le.bottom,At=de.height+a,Wt=He>=At||He>=ut?"top":"bottom",bt=Wt==="top"?le.top-a-de.height:le.bottom+a,xe=Le-l-de.height,Ne=ah(bt,l,xe),Ae=le.left+le.width/2,vt=Math.max(ih,de.width-ih),X=ah(Ae-Te,ih,vt);u.dataset.placement=Wt,u.style.left=`${Te}px`,u.style.top=`${Ne}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${X}px`)},O=()=>{if(E||!s||u||!e.isConnected||GI(e))return;let oe=T(),ne=YI(e);if(!oe||!ne)return;let le=c(),de=p();u=le.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(Ba);let ve=de.getComputedStyle?.(e);if(ve){for(let At of QI){let Wt=ve.getPropertyValue(At).trim();Wt&&u.style.setProperty(At,Wt)}ve.fontFamily&&(u.style.fontFamily=ve.fontFamily)}m=le.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=oe,u.appendChild(m);let Le=H();Le&&(g=le.createElement("span"),g.className="persona-control-tooltip__hint",g.textContent=Le,u.appendChild(g));let se=le.createElement("span");se.className="persona-control-tooltip__arrow",u.appendChild(se),ne.appendChild(u),B(),u.dataset.state="open";let _=()=>{if(!e.isConnected){U();return}m&&(m.textContent=T()),g&&(g.textContent=H()),B()};de.addEventListener("scroll",_,!0),de.addEventListener("resize",_);let Te=e.getRootNode(),He=bS(Te)?Te:le.documentElement,ut=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||U()});ut?.observe(He,{childList:!0,subtree:!0}),h=()=>{de.removeEventListener("scroll",_,!0),de.removeEventListener("resize",_),ut?.disconnect()}},R=oe=>{if(!(E||u)){if(W(),oe||A()<=0||jI()){O();return}b=p().setTimeout(()=>{b=void 0,O()},A())}},S=()=>{C||M?R(M):U()},x=()=>{let oe=p();(!oe.matchMedia||!oe.matchMedia("(hover: none)").matches)&&(C=!0,S())},P=()=>{C=!1,S()},L=()=>{try{M=e.matches(":focus-visible")}catch{M=!0}S()},G=()=>{M=!1,S()},V=()=>{C=!1,M=!1,U()},K=oe=>{oe.key==="Escape"&&V()};n.addEventListener("mouseenter",x),n.addEventListener("mouseleave",P),e.addEventListener("focus",L),e.addEventListener("blur",G),e.addEventListener("keydown",K),e.addEventListener("click",V);let ee={get isOpen(){return u!==null},show:O,hide:U,reposition:B,destroy:()=>{E||(E=!0,U(),n.removeEventListener("mouseenter",x),n.removeEventListener("mouseleave",P),e.removeEventListener("focus",L),e.removeEventListener("blur",G),e.removeEventListener("keydown",K),e.removeEventListener("click",V),eu.delete(e))}};return eu.set(e,ee),ee}je();Zt();function ch(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 nu(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function vS(t,e){t.style.maxHeight=`${e*ch(t)}px`,t.style.overflowY="auto"}function rc(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 CS(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function wS(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||!CS(e)}function XI(t){return(t.submitKey??"enter")!=="enter"||CS(t)?"enter":"send"}function ou(t,e){t.setAttribute("enterkeyhint",XI(e))}function ru(t,e){let n=e?.autocomplete;t.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?t.removeAttribute(r):t.setAttribute(r,s)};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 dh(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 yo="persona-composer-control",Go="persona-composer-control--glyph",uh=40,Un=24,su=(t,e,n)=>{let o=t.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(t);for(let s of n){let a=r.getPropertyValue(s).trim();a?e.style.setProperty(s,a):e.style.removeProperty(s)}},iu=(t,e)=>{let n=v("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??xg,n.dir="auto",ou(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:rc(n)}),ru(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=nu(t?.composer?.maxLines,e?.defaultMaxLines??3),r=`${o*20}px`;n.style.maxHeight=r,n.style.overflowY="auto";let s=()=>{let l=n.style.maxHeight;if(l!==r){let p=parseFloat(l);if(Number.isFinite(p)&&p>0)return p}let c=o*ch(n);return r=`${c}px`,n.style.maxHeight=r,c},a=()=>{n.addEventListener("input",()=>{n.style.height="auto";let l=Math.min(n.scrollHeight,s());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:a}},ZI="[data-persona-glyph-stack]",mh=(t,e,n="send")=>{let o=F("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},au=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,s=e.stopIconName??"square",a=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",c=t?.copy?.sendButtonLabel??"Send",p=t?.copy?.stopButtonLabel??"Stop",u=e.showTooltip??!1,m=e.size,g=parseFloat(m??"")||uh,h=e.backgroundColor,b=e.textColor,C=v("div","persona-send-button-wrapper"),M=F("button",{className:Gt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${yo}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!b&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?b||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":b||void 0,backgroundColor:n&&h||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}}),E=null,T=null,H=null;if(n){let W=parseFloat(e.iconSize??"")||Math.round(g*.5),U=e.iconStrokeWidth??2,B=b?.trim()||"currentColor";if(r&&(E=ke(r,W,B,U)),T=ke(s,W,B,U),!e.iconSize)for(let O of[E,T])O&&(O.style.width=`var(--persona-components-composer-sendIconSize, ${W}px)`,O.style.height=`var(--persona-components-composer-sendIconSize, ${W}px)`);E&&T?(H=mh(E,T),M.appendChild(H)):E?M.appendChild(E):(M.textContent=o,T=null)}else M.textContent=c;M.setAttribute("aria-label",a),C.appendChild(M),In({anchor:M,trigger:C,text:()=>M.getAttribute("aria-label")??"",enabled:u});let A="send";return{button:M,wrapper:C,setMode:W=>{if(W===A)return;A=W;let U=W==="stop"?l:a;M.setAttribute("aria-label",U),M.setAttribute("data-persona-send-mode",W),n?(M.querySelector(ZI)??H)?.setAttribute("data-mode",W):M.textContent=W==="stop"?p:c},glyphStack:H}},Da=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",s=e.provider?.type==="custom";if(!(o||r||s))return null;let l=e.iconName??"mic",c=e.iconSize,p=parseFloat(c??"")||Un,u=e.backgroundColor??t?.sendButton?.backgroundColor,m=e.iconColor??t?.sendButton?.textColor,g=v("div","persona-send-button-wrapper"),h=F("button",{className:Gt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",yo,!c&&Go),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":e.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:u||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}}),C=ke(l,p,m||"currentColor",1.5);C?h.appendChild(C):h.textContent="\u{1F3A4}",g.appendChild(h);let M=e.tooltipText??"Start voice recognition",E=e.showTooltip??!1;return In({anchor:h,trigger:g,text:()=>h.getAttribute("aria-label")??M,enabled:E}),{button:h,wrapper:g}},lu=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=v("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=v("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(e.allowedTypes??Ur).join(","),o.multiple=(e.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=e.buttonIconName??"paperclip",s=v("div","persona-send-button-wrapper"),a=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${yo} ${Go}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=ke(r,Un,"currentColor",1.5);l?a.appendChild(l):a.textContent="\u{1F4CE}",a.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(a);let c=e.buttonTooltipText??"Attach file";return In({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??c}),{button:a,wrapper:s,input:o,previewsContainer:n}},cu=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),xi(o,e,"idle");let r=e.idleText??"Online";if(e.idleLink){let s=v("a");s.href=e.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=r;return o},du=()=>F("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});Oa();je();Zt();var tR='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',nR=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],fh="data-persona-menu-focus",oR=new Set(["ArrowDown","ArrowUp","Home","End"]);function MS(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(tR)??t}var rR=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function TS(t){let e=t.label,n=!1,o=v("div","persona-send-button-wrapper"),r=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${yo} ${Go}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=F("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let L=t.getButtonSize?.()??"";r.style.width=L,r.style.height=L,r.style.minWidth=L,r.style.minHeight=L,r.style.lineHeight="1",r.replaceChildren();let G=ke("plus",Un,"currentColor",1.5);G?r.appendChild(G):r.textContent="+"},l=()=>{r.setAttribute("aria-label",e),r.setAttribute("title",e),s.setAttribute("aria-label",e)};l(),a();let c=[],p=-1,u=!1,m=()=>{let G=s.getRootNode().activeElement;return G instanceof HTMLElement?G:null},g=()=>{let L=m();for(let G of c){let V=!!L&&MS(G)===L;G.toggleAttribute(fh,V&&u)}},h=()=>c.filter(L=>L.isConnected||s.contains(L)).map(MS).filter(L=>!rR(L)),b=(L,G)=>{L.forEach((V,K)=>{V.setAttribute("tabindex",K===G?"0":"-1")})},C=L=>{let G=h();if(G.length===0)return;let V=(L%G.length+G.length)%G.length;p=V,b(G,V),G[V].focus(),g()},M=()=>o.ownerDocument??document,E=null,T=null,H=null,A=()=>{E&&(M().removeEventListener("focusin",E,!0),E=null)},D=()=>{T&&(s.removeEventListener("focusin",T),T=null),H&&(s.removeEventListener("pointerdown",H,!0),H=null)},W=null,U=()=>(W||(W=Ps({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),A()}})),W),B=()=>W?.isOpen===!0,O=(L=!1)=>{if(B()){W?.close(),r.setAttribute("aria-expanded","false"),A(),D(),p=-1,u=!1;for(let G of c)G.removeAttribute(fh);L&&r.focus()}},R=(L=0,G=!1)=>{if(n||B())return;u=G,su(r,s,nR),U().open(),r.setAttribute("aria-expanded","true");let V=h();b(V,-1),C(L<0?V.length-1:L),E=K=>{let ee=typeof K.composedPath=="function"?K.composedPath():[];ee.includes(s)||ee.includes(o)||O()},M().addEventListener("focusin",E,!0),T=()=>g(),s.addEventListener("focusin",T),H=()=>{u=!1},s.addEventListener("pointerdown",H,!0)},S=L=>{L.preventDefault(),L.stopPropagation(),B()?O(!0):R(0)},x=L=>{if(L.key==="ArrowDown"||L.key==="Enter"||L.key===" "){L.preventDefault(),u=!0,B()?C(0):R(0,!0);return}L.key==="ArrowUp"&&(L.preventDefault(),u=!0,B()?C(-1):R(-1,!0))},P=L=>{switch(oR.has(L.key)&&(u=!0),L.key){case"ArrowDown":L.preventDefault(),C(p+1);return;case"ArrowUp":L.preventDefault(),C(p-1);return;case"Home":L.preventDefault(),C(0);return;case"End":L.preventDefault(),C(h().length-1);return;case"Escape":L.preventDefault(),L.stopPropagation(),O(!0);return;case"Tab":O(!0);return;default:}};return r.addEventListener("click",S),r.addEventListener("keydown",x),s.addEventListener("keydown",P),{trigger:o,triggerButton:r,panel:s,setItems:L=>{for(let V of c)L.includes(V)||V.removeAttribute(fh);if(c=[...L],!B())return;let G=h();b(G,Math.min(p,G.length-1)),g()},isOpen:B,open:()=>R(0),close:O,setLabel:L=>{L!==e&&(e=L,l())},applyButtonSize:a,destroy:()=>{n=!0,A(),D(),r.removeEventListener("click",S),r.removeEventListener("keydown",x),s.removeEventListener("keydown",P),W?.destroy(),W=null,o.remove(),s.remove(),c=[]}}}var yr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},ES="data-persona-composer-action",gh="data-persona-composer-disable-when-streaming",sR="core:overflow",iR=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function aR(t,e){if(t===void 0)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;let n=Number.parseFloat(t);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(t)&&Number.isFinite(n))return n;let o=v("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=t,e.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function hh(t){let e=t.clientWidth;if(!e)return 0;let n=t.ownerDocument?.defaultView;if(!n?.getComputedStyle)return e;let o=n.getComputedStyle(t),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,e-r)}var kS=(t,e)=>{!t||typeof console>"u"||console.warn(e)},lR=(t,e)=>e.includes(":")?e:`${t}:${e}`;function cR(t){let{debug:e}=t,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){kS(e,`[Persona] composer action "${l.id}" is already contributed by ${PS(c)}; the ${PS(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of t.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let a=(l,c,p)=>{let u=p?lR(p,l.id):l.id,m=l.order??yr.custom;l.placement==="end"&&m>=yr.send&&(kS(e,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${yr.send-1}.`),m=yr.send-1),s({id:u,placement:l.placement,presentation:l.presentation??"bar",order:m,sequence:r++,source:c,pluginId:p,action:l})};for(let l of t.configActions??[])a(l,"config");for(let l of t.plugins){if(!l.contributeComposerActions)continue;let c;try{c=l.contributeComposerActions(t.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of c??[])a(p,"plugin",l.id)}return n.sort((l,c)=>l.order===c.order?l.sequence-c.sequence:l.order-c.order)}var PS=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",LS=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,dR=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function pR(t,e){if(!t||t==="always")return!0;let n=dR(e);return t==="when-text"?n:!n}var Ls=t=>t.kind==="custom",yh=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,uR=t=>{let e=yh(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},mR='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function fR(t){let e="",n=o=>{if(o.nodeType===Node.TEXT_NODE){e+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(mR)||o.childNodes.forEach(n)};return n(t),e.trim()}var gR=t=>fR(t).length===0;function IS(t){let e=new Map,n=[],o=!1,r=()=>t.getButtonSize?.(),s=(S,x)=>{let P=S.button;if(!P)return;P.setAttribute("role","menuitem"),P.setAttribute("tabindex","-1"),P.className="persona-composer-overflow-menu__item";for(let V of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])P.style[V]="";P.style.lineHeight="1",x.tooltipText?P.setAttribute("title",x.tooltipText):P.removeAttribute("title"),P.replaceChildren();let L=v("span","persona-composer-overflow-menu__icon");if(x.iconName){let V=ke(x.iconName,16,"currentColor",1.5);V&&L.appendChild(V)}let G=v("span","persona-composer-overflow-menu__label");G.textContent=x.shortLabel??x.label,P.append(L,G)},a=(S,x)=>{let P=S.button;if(!P)return;if(P.setAttribute("aria-label",x.label),x.pressed===void 0?P.removeAttribute("aria-pressed"):P.setAttribute("aria-pressed",x.pressed?"true":"false"),P.toggleAttribute(gh,x.disableWhenStreaming===!0),S.mode==="menu"){S.tooltip?.destroy(),S.tooltip=void 0,s(S,x);return}P.removeAttribute("role"),P.removeAttribute("tabindex"),P.removeAttribute("title");let L=r(),G=!!x.shortLabel;if(P.className=Gt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",yo,Go,G&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),P.style.width=L&&!G?L:"",P.style.height=L??"",P.style.minWidth=L&&!G?L:"",P.style.minHeight=L??"",P.style.fontSize=G?"":"18px",P.style.lineHeight="1",P.style.color=x.iconColor??"",P.style.backgroundColor=x.backgroundColor??"",P.replaceChildren(),x.iconName){let V=ke(x.iconName,Un,"currentColor",1.5);V&&P.appendChild(V)}if(G){let V=v("span","persona-composer-action-button__label");V.textContent=x.shortLabel,P.appendChild(V)}else P.firstChild||(P.textContent=x.label);S.tooltip?.destroy(),S.tooltip=In({anchor:P,trigger:S.element,text:()=>x.tooltipText??x.label,enabled:!!x.tooltipText})},l=(S,x)=>{let P=S.action,L=F("button",{attrs:{type:"button"}}),G=L;if(x==="bar"){let ee=v("div","persona-send-button-wrapper");ee.appendChild(L),G=ee}G.setAttribute(ES,S.id);let V={resolved:S,element:G,button:L,owned:!0,managed:!0,busy:!1,visible:!0,mode:x},K=ee=>{if(ee.preventDefault(),ee.stopPropagation(),V.busy||L.disabled)return;let oe=V.resolved.action;V.mode==="menu"&&h?.close(!0);let ne;try{ne=oe.onSelect(t.actionContext,ee)}catch(le){t.reportError(le,{actionId:V.resolved.id});return}!ne||typeof ne.then!="function"||(V.busy=!0,L.setAttribute("aria-busy","true"),ne.catch(le=>{t.reportError(le,{actionId:V.resolved.id})}).finally(()=>{V.busy=!1,L.removeAttribute("aria-busy")}))};return L.addEventListener("click",K),V.detach=()=>L.removeEventListener("click",K),a(V,P),V},c=S=>{let x=S.action,P;try{P=x.render({...t.actionContext,id:S.id,action:x})}catch(L){return t.reportError(L,{actionId:S.id}),null}return P?.element?(P.element.setAttribute(ES,S.id),P.element.toggleAttribute(gh,x.disableWhenStreaming===!0),{resolved:S,element:P.element,owned:!0,managed:!0,destroy:P.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(S,x)=>{if(S.builtIn){let L=S.builtIn.element;return L?{resolved:S,element:L,owned:!1,managed:S.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let P=S.action;return P?Ls(P)?c(S):l(S,x):null},u=S=>{if(S.detach?.(),S.tooltip?.destroy(),S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0,S.owned){try{S.destroy?.()}catch(x){t.reportError(x,{actionId:S.resolved.id})}S.element.remove()}},m=(S,x)=>{for(let P=0;P<x.length;P++){let L=x[P];if(!L.managed)continue;let G=null;for(let V=P+1;V<x.length;V++){let K=x[V];if(!K.managed&&K.element.parentElement===S){G=K.element;break}}G?(L.element.parentElement!==S||L.element.nextSibling!==G)&&S.insertBefore(L.element,G):S.lastChild!==L.element&&S.appendChild(L.element)}},g=(S,x)=>{if(S.button){S.button.disabled=x;return}if(!S.owned)return;let P=S.element;P.toggleAttribute("data-disabled",x),P.setAttribute("aria-disabled",x?"true":"false");let L=P instanceof HTMLButtonElement||P instanceof HTMLSelectElement||P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement?P:P.querySelector("button, select, input, textarea");L&&(L.disabled=x)},h=null,b=null,C=null,M=0,E=()=>{let S=t.getOverflow?.();return S?.enabled===!0?S:void 0},T=()=>(h?h.setLabel(t.getOverflowLabel?.()??"More actions"):h=TS({label:t.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),H=S=>{b!==S&&(C?.disconnect(),b=S,M=hh(S),!(typeof ResizeObserver>"u")&&(C=new ResizeObserver(x=>{let L=x[x.length-1]?.contentRect?.width??hh(S);L!==M&&(M=L,O())}),C.observe(S)))},A=(S,x)=>{let P=aR(S.collapseAutoActionsBelow,x);if(P===null)return!1;let L=M||hh(x);return L>0&&L<P},D=(S,x,P)=>{if(!x)return"bar";if(S.resolved.builtIn){let G=iR(S.resolved.id);return G&&x.includeBuiltIns?.includes(G)?"menu":"bar"}let L=S.resolved.presentation;return L==="overflow"||L==="auto"&&P?"menu":"bar"},W=S=>{let x=S.menuSlot;if(!x)return;if(!gR(S.element)){S.menuLabel?.remove(),S.menuLabel=void 0;return}let P=uR(S.element);if(!P){S.menuLabel?.remove(),S.menuLabel=void 0;return}S.menuLabel||(S.menuLabel=v("span","persona-composer-overflow-menu__label")),S.menuLabel.textContent!==P&&(S.menuLabel.textContent=P),S.menuLabel.parentElement!==x&&x.appendChild(S.menuLabel)},U=(S,x)=>{if(S.mode===x)return S;let P=S.resolved.action;if(P&&!Ls(P)){u(S),e.delete(S.resolved.id);let L=l(S.resolved,x);return e.set(S.resolved.id,L),L}if(x==="menu"){let L=F("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[lh]:""}});L.appendChild(S.element),yS(yh(S.element)),S.menuSlot=L;let G=V=>{let K=yh(S.element);if(K.disabled)return;let ee=V.target===K||K.contains(V.target);h?.close(!0),ee||K.click()};L.addEventListener("click",G,!0),S.detachMenuSlot=()=>L.removeEventListener("click",G,!0),S.managed=!0,W(S)}else S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0;return S.mode=x,S},B=(S,x)=>{let P=x.map(L=>L.menuSlot??L.element);for(P.forEach((L,G)=>{let V=S.children[G];V!==L&&(V?S.insertBefore(L,V):S.appendChild(L))});S.children.length>P.length;)S.lastElementChild?.remove()},O=()=>{if(o)return;let S=t.getBindings();if(!S)return;let x=t.getState(),P=x.phase==="streaming",L=E();L&&H(S.footer);let G=L?A(L,S.footer):!1,V={start:[],end:[]},K=[];for(let ee of n){let oe=e.get(ee.id);if(!oe)continue;let ne=ee.action,le=ne?LS(ne.visible,x,!0)&&pR(ne.visibility,x):!0;if(oe.visible!==le&&(oe.visible=le,!le&&oe.managed&&(oe.menuSlot??oe.element).remove()),!!le){if(oe=U(oe,D(oe,L,G)),ne){let de=LS(ne.disabled,x,!1)||ne.disableWhenStreaming===!0&&P;g(oe,de),!Ls(ne)&&ne.pressed!==void 0&&oe.button?.setAttribute("aria-pressed",ne.pressed?"true":"false")}oe.mode==="menu"?(W(oe),K.push(oe)):V[ee.placement].push(oe)}}if(K.length>0){let ee=T();B(ee.panel,K),ee.setItems(K.map(de=>de.menuSlot??de.element)),ee.applyButtonSize();let oe=Number.isFinite(L?.order)?L?.order:yr.overflow,ne=V.start.findIndex(de=>de.resolved.order>oe),le={resolved:{id:sR,placement:"start",presentation:"bar",order:oe,sequence:-1,source:"core"},element:ee.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};V.start.splice(ne<0?V.start.length:ne,0,le)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));m(S.actionsStart,V.start),m(S.actionsEnd,V.end)};return{resolve:()=>{if(o)return;let S=cR(t.collect()),x=new Set(S.map(P=>P.id));for(let[P,L]of e)x.has(P)||(u(L),e.delete(P));for(let P of S){let L=e.get(P.id);if(!L){let ee=p(P,"bar");ee&&e.set(P.id,ee);continue}let G=L.resolved.action,V=P.action;if(!!G!=!!V||G&&V&&Ls(G)!==Ls(V)||G&&V&&Ls(G)&&Ls(V)&&G.render!==V.render){u(L),e.delete(P.id);let ee=p(P,L.mode);ee&&e.set(P.id,ee);continue}L.resolved=P,P.builtIn?(L.managed=P.builtIn.managed===!0||L.mode==="menu",P.builtIn.element&&L.mode==="bar"&&(L.element=P.builtIn.element)):V&&!Ls(V)?a(L,V):V&&L.element.toggleAttribute(gh,V.disableWhenStreaming===!0)}n=S,O()},sync:O,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,C?.disconnect(),C=null,b=null;for(let S of e.values())u(S);e.clear(),h?.destroy(),h=null,n=[]}}}}Oa();je();Zt();var hR="core:model",yR=700,RS=16,bR=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],HS=()=>{let t=F("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=F("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function WS(t){let e=t.label??"Model",n=t.presentation??"native",o=null,r=c=>{let p=t.getSelectedModelId();return c.find(u=>u.id===p)??c[0]},s=()=>{let c=F("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),p="",u=()=>{let C=t.getModels(),M=C.map(E=>`${E.id}:${E.label}`).join("|");M!==p&&(p=M,c.replaceChildren(...C.map(E=>{let T=F("option",{attrs:{value:E.id}});return T.textContent=E.label,T}))),c.value=r(C)?.id??""};u(),o=u;let m=()=>{c.value&&t.onSelect(c.value)};c.addEventListener("change",m);let g=C=>C.stopPropagation();c.addEventListener("click",g);let{wrapper:h,chevron:b}=HS();return h.append(c,b),{element:h,destroy:()=>{o===u&&(o=null),c.removeEventListener("change",m),c.removeEventListener("click",g)}}},a=()=>{let c=F("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=v("span","persona-composer-model-picker-label"),u=v("span","persona-composer-model-picker-suffix");c.append(p,u);let m=F("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),g=new Map,h="",b=null,C=()=>b?.isOpen===!0,M=(x=!1)=>{C()&&(b?.close(),c.setAttribute("aria-expanded","false"),x&&c.focus())},E=x=>{let P=[...g.values()];if(P.length===0)return;let L=(x%P.length+P.length)%P.length;P[L].focus()},T=x=>{if(C())return;b||(b=Ps({anchor:c,content:m,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),su(c,m,bR),b.open(),c.setAttribute("aria-expanded","true");let L=[...g.keys()].indexOf(r(t.getModels())?.id??"");E(x??(L>=0?L:0))},H=x=>{M(!0),t.onSelect(x)},A=x=>{x.preventDefault(),x.stopPropagation();let P=x.currentTarget.getAttribute("data-persona-model-option");P&&H(P)},D=x=>{let P=F("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":x.id}});if(x.icon){let ee=ke(x.icon,RS,"currentColor",1.5);if(ee){let oe=v("span","persona-composer-model-option-icon");oe.appendChild(ee),P.appendChild(oe)}}let L=v("span","persona-composer-model-option-body"),G=v("span","persona-composer-model-option-label");if(G.textContent=x.label,L.appendChild(G),x.description){let ee=v("span","persona-composer-model-option-description");ee.textContent=x.description,L.appendChild(ee)}P.appendChild(L);let V=v("span","persona-composer-model-option-check");V.setAttribute("aria-hidden","true");let K=ke("check",RS,"currentColor",2);return K&&V.appendChild(K),P.appendChild(V),P.addEventListener("click",A),P},W=()=>{let x=t.getModels(),P=x.map(V=>`${V.id}:${V.label}:${V.icon??""}:${V.description??""}`).join("|");if(P!==h){h=P;for(let V of g.values())V.removeEventListener("click",A);g.clear(),m.replaceChildren(...x.map(V=>{let K=D(V);return g.set(V.id,K),K}))}let L=r(x);for(let[V,K]of g)K.setAttribute("aria-selected",String(V===L?.id));p.textContent=L?.label??"";let G=t.getSuffix?.()??"";u.textContent=G,c.setAttribute("aria-label",[e,[L?.label,G].filter(Boolean).join(" ")].filter(Boolean).join(": "))};W(),o=W;let U=x=>{x.preventDefault(),x.stopPropagation(),C()?M(!0):T()},B=x=>{if(x.key==="ArrowDown"){x.preventDefault(),C()?E(0):T(0);return}x.key==="ArrowUp"&&(x.preventDefault(),C()?E(-1):T(-1))},O=x=>{let P=[...g.values()],L=P.indexOf(x.target?.closest?.(".persona-composer-model-option"));switch(x.key){case"ArrowDown":x.preventDefault(),E(L+1);return;case"ArrowUp":x.preventDefault(),E(L-1);return;case"Home":x.preventDefault(),E(0);return;case"End":x.preventDefault(),E(P.length-1);return;case"Escape":x.preventDefault(),x.stopPropagation(),M(!0);return;case"Tab":M(!0);return;default:}};c.addEventListener("click",U),c.addEventListener("keydown",B),m.addEventListener("keydown",O);let{wrapper:R,chevron:S}=HS();return R.append(c,S),{element:R,destroy:()=>{o===W&&(o=null),c.removeEventListener("click",U),c.removeEventListener("keydown",B),m.removeEventListener("keydown",O);for(let x of g.values())x.removeEventListener("click",A);g.clear(),b?.destroy(),b=null,m.remove()}}};return{action:{id:hR,kind:"custom",placement:"end",order:yR,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}je();Zt();fu();var vR=":scope > [data-persona-composer-mode]";function BS(t){let e=t.row,n="",o=!1,r=new Set(t.initialIds??[]),s=p=>{let u=F("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let b=v("span","persona-mention-chip-icon"),C=ke(p.iconName,12,"currentColor",1.5);C&&b.appendChild(C),u.appendChild(b)}let m=v("span","persona-mention-chip-label");m.textContent=p.shortLabel??p.label,u.appendChild(m);let g=F("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ke("x",12,"currentColor",2);return h?g.appendChild(h):g.textContent="\xD7",g.addEventListener("click",b=>{b.preventDefault(),b.stopPropagation(),t.onRemove(p.id)}),u.appendChild(g),u},a=()=>Array.from(e.querySelectorAll(vR)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),_a(e)},m=e.ownerDocument.defaultView,g=typeof m?.getComputedStyle=="function"?m.getComputedStyle(p).animationName:"";if(!g||g==="none"){u();return}p.addEventListener("animationend",u,{once:!0}),p.addEventListener("animationcancel",u,{once:!0})},c=()=>{for(let p of a())p.remove()};return{element:e,render:(p,u)=>{if(o)return;let m=u.filter(C=>p.includes(C.id)),g=m.map(C=>`${C.id}:${C.shortLabel??C.label}`).join("|");if(g===n)return;n=g;let h=new Map;for(let C of a()){let M=C.getAttribute("data-persona-composer-mode");M&&m.some(T=>T.id===M)&&!C.hasAttribute("data-persona-chip-exit")?h.set(M,C):C.hasAttribute("data-persona-chip-exit")||l(C)}let b=e.firstChild;for(let C of m){let M=h.get(C.id);M||(M=s(C),r.has(C.id)||(M.setAttribute("data-persona-chip-enter",""),M.addEventListener("animationend",()=>M?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(C.id),M!==b&&e.insertBefore(M,b),b=M.nextSibling}_a(e)},destroy:()=>{o=!0,c(),_a(e)}}}je();Zt();var DS=t=>`core:mode:${t}`;var Ch=t=>Math.min(300+t,499),OS=t=>`core:mode-group:${t}`;function gu(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function CR(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function _S(t,e){return t?.length?t.filter(n=>!gu(n.groupId,e)&&!CR(n.groupId,e)):[]}var wR=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function NS(t,e,n,o){let r=n.find(l=>l.id===e);if(!r)return[...t];let s=t.includes(e),a=new Set(t);if(s)a.delete(e);else{if(wR(r,o)==="single"){let l=n.filter(c=>c.groupId===r.groupId).map(c=>c.id);a=new Set([...a].filter(c=>!l.includes(c)))}a.add(e)}return n.filter(l=>a.has(l.id)).map(l=>l.id)}function hu(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function FS(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function VS(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var xR=16;function $S(t){let e=null;return{action:{id:OS(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=F("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),r=new Map,s="",a=p=>{p.preventDefault(),p.stopPropagation();let m=p.currentTarget.getAttribute("data-persona-composer-mode");!m||t.getActiveIds().includes(m)&&t.getGroup()?.selection==="single"||t.onSelect(m)},l=p=>{let u=F("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let g=ke(p.iconName,xR,"currentColor",1.5);g&&u.appendChild(g)}let m=v("span","persona-composer-segmented-label");return m.textContent=p.shortLabel??p.label,u.appendChild(m),u.addEventListener("click",a),u},c=()=>{let p=t.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=t.getModes(),m=u.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(m!==s){s=m;for(let b of r.values())b.removeEventListener("click",a);r.clear();let h=u.map(b=>{let C=l(b);return r.set(b.id,C),C});o.replaceChildren(...h)}let g=t.getActiveIds();for(let[h,b]of r)b.setAttribute("aria-pressed",String(g.includes(h)))};return c(),e=c,{element:o,destroy:()=>{e===c&&(e=null);for(let p of r.values())p.removeEventListener("click",a);r.clear()}}}},repaint:()=>e?.()}}fu();je();Zt();function zS(t){let e=F("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,r=s=>{let a=v("span","persona-composer-quote-bar"),l=v("div","persona-composer-quote-content");if(s.sourceLabel){let m=v("div","persona-composer-quote-source");m.textContent=s.sourceLabel,l.appendChild(m)}let c=F("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Kp(s.text),l.appendChild(c);let p=F("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=ke("x",12,"currentColor",2);u?p.appendChild(u):p.textContent="\xD7",p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),t.onDismiss()}),e.replaceChildren(a,l,p)};return{element:e,render:s=>{if(o)return;let a=s?`${s.sourceLabel??""}\0${s.text}`:"";if(a!==n){if(n=a,!s){e.replaceChildren(),e.style.display="none";return}r(s),e.style.display="flex"}},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}je();Zt();function US(t){let e=F("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,r=(a,l,c,p)=>{let u=F("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),m=ke(a,12,"currentColor",2);return m?u.appendChild(m):u.textContent=l,u.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),p()}),u},s=a=>{let l=Kp(a.text??"",90);if(l)return l;let c=a.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(a.mentionRefs?.length??0)>0?a.mentionRefs.map(u=>u.label).join(", "):"Queued message"};return{element:e,render:a=>{if(o||a===n)return;if(n=a,!a){e.replaceChildren(),e.style.display="none";return}let l=v("span","persona-composer-pending-badge");l.textContent=t.label??"Sends next";let c=F("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=s(a),e.replaceChildren(l,c,r("pencil",t.editLabel??"Edit queued message","data-persona-composer-pending-edit",t.onEdit),r("x",t.removeLabel??"Remove queued message","data-persona-composer-pending-remove",t.onRemove)),e.style.display="flex"},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}je();function qS(t){let e=F("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=F("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=t.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=v("div","persona-message-edit-actions"),s=(l,c,p,u)=>{let m=F("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[p]:""},text:l});return m.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),u()}),m},a=()=>{let l=n.value.trim();l&&t.onSave(l)};return r.append(s(t.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",t.onCancel),s(t.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",a)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),t.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),a())}),e.append(n,r),{element:e,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{e.replaceChildren(),e.remove()}}}function jS(t){let e=t.text??"";if(e.trim().length>0||(t.mentionRefs?.length??0)>0||(t.activeModeIds?.length??0)>0||t.quote||t.selectedModelId)return{text:e,...t.mentionRefs?.length?{mentionRefs:[...t.mentionRefs]}:{},...t.contentSegments?.length?{contentSegments:[...t.contentSegments]}:{},...t.selectedModelId?{selectedModelId:t.selectedModelId}:{},...t.activeModeIds?.length?{activeModeIds:[...t.activeModeIds]}:{},...t.quote?{quote:{...t.quote}}:{}}}function KS(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(c=>n.has(c.sourceId)),r=o.length===(t.mentionRefs?.length??0)&&o.length>0,s=new Set(e.modes.map(c=>c.id)),a=(t.activeModeIds??[]).filter(c=>s.has(c)),l=t.selectedModelId&&e.modelIds.includes(t.selectedModelId)?t.selectedModelId:void 0;return{text:t.text,...r?{mentionRefs:o}:{},...r&&t.contentSegments?.length?{contentSegments:t.contentSegments}:{},...l?{selectedModelId:l}:{},...a.length?{activeModeIds:a}:{},...t.quote?.text?{quote:t.quote}:{}}}function GS(t){let e=t.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,t.write()},e))},flush:()=>{o||n===null||(r(),t.write())},cancel:r,destroy:()=>{o=!0,r()}}}function YS(t){return t.wrapped||t.text.includes(`
1156
+ `)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission)}function QS(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function XS(t){if(!t)return!1;let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return!1;let n=e.getComputedStyle(t),o=Number.parseFloat(n.lineHeight),r=Number.parseFloat(n.fontSize),s=Number.isFinite(o)&&o>0?o:Number.isFinite(r)&&r>0?r*1.4:0;if(!s)return!1;let a=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return t.scrollHeight-a>s*1.5}yu();function wh(t){return Object.freeze({text:t.text,contentParts:t.contentParts?Object.freeze([...t.contentParts]):void 0,mentionRefs:Object.freeze([...t.mentionRefs]),contentSegments:t.contentSegments?Object.freeze([...t.contentSegments]):void 0,options:Object.freeze({...t.options}),viaVoice:t.viaVoice})}function eA(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var SR=t=>typeof t?.then=="function";function ZS(t,e){return e===!1?{status:"canceled"}:!e||typeof e!="object"?{status:"proceed"}:(typeof e.text=="string"&&(t.text=e.text),e.options&&(t.options={...t.options,...e.options}),{status:"proceed"})}function tA(t,e,n){let o;try{o=t(wh(e),{signal:n})}catch(r){return{status:"error",error:r}}return SR(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:ZS(e,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):ZS(e,o)}je();bu();xh();je();Zt();function sA(t){let{config:e,onOpen:n}=t,o=e.buttonIconName??"plus",r=e.buttonTooltipText??"Add context",s=v("div","persona-send-button-wrapper"),a=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${yo} ${Go}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=ke(o,Un,"currentColor",1.5);return l?a.appendChild(l):a.textContent="+",a.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),n()}),s.appendChild(a),In({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??r}),{button:a,wrapper:s}}ro();var{setLoader:jF,load:LR}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(SA(),xA))});var Th=LR;Zt();ro();var{setLoader:r2,load:FR}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(BA(),WA)),resetOnSetLoader:!0});var DA=FR;je();Zt();function pc(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=F("span",{className:Gt("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=ke(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=v("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(F("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function OA(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=vu(e).filter(A=>A.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(A=>A.sources.some(D=>typeof D.matchCommand=="function")),r=A=>o.some(D=>D.trigger?D.position==="line-start"?A.split(`
1157
+ `).some(U=>U.startsWith(D.trigger)):(D.position==="anywhere"?A:A.split(`
1158
+ `)[0]).startsWith(D.trigger):!1),s=(A,D)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:D}))}catch{}},a=!t.chipRow,l=t.chipRow??F("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),c=null,p=null,u=t.textarea,m=null,g=null,h=null,b=null,C=()=>{if(c)return Promise.resolve(c);if(p)return p;let A=Th().then(D=>(D.setMentionIconRenderer(ke),c=D.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:m??void 0,anchor:t.anchor,contextRow:l,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:H,emit:s}),c)).catch(D=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",D),p===A&&(p=null),null));return p=A,A},M=()=>{DA().then(A=>{let D=A.mountInlineComposer({textarea:t.textarea,renderToken:U=>pc(U,{render:e.renderMentionToken}),onMentionRemoved:U=>c?.untrackMention(U)});m=D.input,g=D.destroy;let W=u;W.replaceWith(D.element),u=D.element,b={next:D.element,prev:W},h?.(D.element,W),c?c.rebindComposer(D.input):p&&p.then(U=>U?.rebindComposer(D.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};e.display==="inline"&&M();let E=[],T=new Map;for(let A of n){if(!A.showButton)continue;let D=sA({config:{...e,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},onOpen:()=>{C().then(W=>W?.openMenu(A.trigger))}});E.push(D),T.set(A.trigger,D.button)}let H=(A,D,W)=>{let U=T.get(D);U&&(U.setAttribute("aria-expanded",A?"true":"false"),A?U.setAttribute("aria-controls",W):U.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(A=>A.wrapper),contextRow:l,handleInput:A=>{if(c){c.handleInput();return}if(!oA(A))return;let D=u,W=D.selectionStart??0;ic(D.value,W,n)&&C().then(U=>U?.handleInput())},handleKeydown:A=>{if(c?.isMenuOpen())return c.handleKeydown(A);if(A.key==="Backspace"&&c?.hasMentions()&&!b){let D=u,W=D.selectionStart===0&&D.selectionEnd===0;if((D.value.length===0||W)&&c.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>c?.isMenuOpen()??!1,hasMentions:()=>c?.hasMentions()??!1,getMentionRefs:()=>c?.getMentionRefs()??[],collectForSubmit:()=>c?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(c??await C())?.dispatchInlineCommand(A)??null:null,clear:()=>c?.clear(),prefetch:()=>{Th().catch(()=>{})},onComposerSwap:A=>{h=A,b&&A(b.next,b.prev)},destroy:()=>{c?.destroy(),g?.();for(let A of E)A.wrapper.remove();a&&l.remove()}}}var Iu=t=>t?.launcher?.variant??(t?.future?.v5Defaults===!0?"circle":"pill"),Ru={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"};var Wu="16px",Bu="transparent",VR=(()=>{let t={};for(let e of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])t[e]=e===0?"0px":`${e/4}rem`;return t})(),uc={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:VR,typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Hu={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},bo={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:wg,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Wu,canvasBackground:Bu,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}},$R=uc.colors.gray,zR={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},UR={...uc,colors:{...uc.colors,gray:$R}},qR={...uc,colors:{...uc.colors,gray:zR},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}};var jR=Hu,KR={...Hu,colors:{...Hu.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...Hu.typography,fontSize:"14px",lineHeight:"1.5"}};var Dh=bo,GR={...bo,launcher:Ru,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...bo.input,borderRadius:"palette.radius.full"},introCard:{...bo.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...bo.suggestion.chip,fontWeight:"400"},card:{...bo.suggestion.card,fontWeight:"400"},list:{...bo.suggestion.list,fontWeight:"400"}},panel:{...bo.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...bo.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...bo.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...bo.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...bo.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...bo.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}};var YR=t=>bs({future:t}),Oh=t=>YR(t)==="v5"?{palette:qR,semantic:KR,components:GR}:{palette:UR,semantic:jR,components:Dh};function Hn(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Hn(t,o):o}function NA(t){let e={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let c=Hn(t,a);c!==void 0&&(e[l]={path:l,value:c,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function QR(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function FA(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=FA(s,r):n[o]=r}return n}function XR(t,e){return e?FA(t,e):t}function Na(t,e={}){let n=Oh(e.future),o={palette:n.palette,semantic:n.semantic,components:n.components},r={palette:{...o.palette,...t?.palette,colors:{...o.palette.colors,...t?.palette?.colors},spacing:{...o.palette.spacing,...t?.palette?.spacing},typography:{...o.palette.typography,...t?.palette?.typography},shadows:{...o.palette.shadows,...t?.palette?.shadows},borders:{...o.palette.borders,...t?.palette?.borders},radius:{...o.palette.radius,...t?.palette?.radius}},semantic:{...o.semantic,...t?.semantic,colors:{...o.semantic.colors,...t?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...t?.semantic?.spacing},typography:{...o.semantic.typography,...t?.semantic?.typography}},components:XR(o.components,t?.components)},s=t?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let u of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[u]!==void 0&&(r.components[p][u]=s[u]);let a=t?.components?.collapsibleWidget?.surface;a!==void 0&&s?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:a});let l=t?.components?.header;l?.padding!==void 0&&l.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let c=t?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),e.validate!==!1){let p=QR(r);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(u=>u.message).join(", ")}`)}if(e.plugins)for(let p of e.plugins)r=p.transform(r);return r}var Bh=t=>t.trim()==="0"?"0px":t,_A="--persona-",JR=t=>{if(!t)return;let e=t.trim().toLowerCase(),n;if(e.charCodeAt(0)===35){let a=e.slice(1);if(!/^[0-9a-f]+$/.test(a))return;a.length===3||a.length===4?n=[0,1,2].map(l=>parseInt(a[l]+a[l],16)):(a.length===6||a.length===8)&&(n=[0,2,4].map(l=>parseInt(a.slice(l,l+2),16)))}else{let a=e.match(/^rgba?\(([^)]+)\)$/);if(a){let l=a[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(c=>{let p=c.endsWith("%"),u=parseFloat(p?c.slice(0,-1):c);return p?u/100*255:u}))}}if(!n||n.some(a=>!Number.isFinite(a)))return;let[o,r,s]=n.map(a=>{let l=Math.max(0,Math.min(255,a))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},ZR=.179,Rn=(t,e)=>{for(let[n,...o]of e){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):t[_A+s],r!==void 0)break;r!==void 0&&(t[_A+n]=r)}};function VA(t){let e=NA(t),n={};for(let[_,Te]of Object.entries(e)){let He=_.replace(/\./g,"-");n[`--persona-${He}`]=Te.value}Rn(n,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],Rn(n,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),Rn(n,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,Rn(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Wu,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Bu,Rn(n,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),Rn(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],a=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],Rn(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??a??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??a??n["--persona-muted"],Rn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=t.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let c=n["--persona-components-history-railHeader-background"];c&&(n["--persona-history-rail-header-bg"]=c);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[_,Te]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let He=n[`--persona-components-history-overlay-${_}`];He&&(n[`--persona-history-overlay-${Te}`]=He)}for(let[_,Te]of[["background","bg"],["borderRadius","radius"]]){let He=n[`--persona-components-history-menu-${_}`];He&&(n[`--persona-history-menu-${Te}`]=He)}let m=t.components?.history?.motion;if(m){let _=ut=>{if(ut===void 0)return;let At=String(ut).trim();return/^\d+(\.\d+)?$/.test(At)?`${At}ms`:At},Te=_(m.enterDurationMs);Te!==void 0&&(n["--persona-history-enter-ms"]=Te);let He=_(m.exitDurationMs);He!==void 0&&(n["--persona-history-exit-ms"]=He),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let g=n["--persona-components-history-dangerForeground"];g&&(n["--persona-history-danger-fg"]=g),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let _ of["scrim","shadow"]){let Te=n[`--persona-components-history-confirm-${_}`];Te&&(n[`--persona-history-confirm-${_}`]=Te)}for(let[_,Te]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let He=n[`--persona-components-tooltip-${_}`];He&&(n[`--persona-tooltip-${Te}`]=He)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[_,Te]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let He=n[`--persona-components-messageActions-${_}`];He&&(n[`--persona-message-action-${Te}`]=He)}Rn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],b=n["--persona-components-introCard-shadow"],C=(!h||h==="transparent"||h==="none")&&(!b||b==="none"),M=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=C&&M==="1.5rem"?"1.5rem 0":M,Rn(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),Rn(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let E=n["--persona-components-markdown-heading-h1-fontSize"];E&&(n["--persona-md-h1-size"]=E);let T=n["--persona-components-markdown-heading-h1-fontWeight"];T&&(n["--persona-md-h1-weight"]=T);let H=n["--persona-components-markdown-heading-h2-fontSize"];H&&(n["--persona-md-h2-size"]=H);let A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let D=n["--persona-components-markdown-prose-fontFamily"];D&&D!=="inherit"&&(n["--persona-md-prose-font-family"]=D),Rn(n,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),Rn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Rn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Rn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Rn(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]);let W=[["container","surface"],["surface","surface"],["border","border"]];for(let[_,Te]of W){let He=n[`--persona-components-collapsibleWidget-${_}`]??n[`--persona-${Te}`];He!==void 0&&(n[`--persona-cw-${_}`]=He,n[`--cw-${_}`]=He)}Rn(n,[["message-border","components-message-border","border"]]),Rn(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-border-width","components-message-assistant-borderWidth"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let U=t.components,B=U?.iconButton;B&&(B.background&&(n["--persona-icon-btn-bg"]=B.background),B.border&&(n["--persona-icon-btn-border"]=B.border),B.color&&(n["--persona-icon-btn-color"]=B.color),B.padding&&(n["--persona-icon-btn-padding"]=B.padding),B.borderRadius&&(n["--persona-icon-btn-radius"]=B.borderRadius),B.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=B.hoverBackground),B.hoverColor&&(n["--persona-icon-btn-hover-color"]=B.hoverColor),B.activeBackground&&(n["--persona-icon-btn-active-bg"]=B.activeBackground),B.activeBorder&&(n["--persona-icon-btn-active-border"]=B.activeBorder));let O=U?.labelButton;O&&(O.background&&(n["--persona-label-btn-bg"]=O.background),O.border&&(n["--persona-label-btn-border"]=O.border),O.color&&(n["--persona-label-btn-color"]=O.color),O.padding&&(n["--persona-label-btn-padding"]=O.padding),O.borderRadius&&(n["--persona-label-btn-radius"]=O.borderRadius),O.hoverBackground&&(n["--persona-label-btn-hover-bg"]=O.hoverBackground),O.fontSize&&(n["--persona-label-btn-font-size"]=O.fontSize),O.gap&&(n["--persona-label-btn-gap"]=O.gap));let R=U?.toggleGroup;R&&(R.gap&&(n["--persona-toggle-group-gap"]=R.gap),R.borderRadius&&(n["--persona-toggle-group-radius"]=R.borderRadius));let S=U?.artifact;if(S?.toolbar){let _=S.toolbar;_.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=_.iconHoverColor),_.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=_.iconHoverBackground),_.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=_.iconPadding),_.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=_.iconBorderRadius),_.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=_.iconBorder),_.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Bh(_.toggleGroupGap)),_.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=_.toggleBorderRadius),_.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Bh(_.toggleGroupPadding)),_.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=_.toggleGroupBorder),_.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=_.toggleGroupBorderRadius),_.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Hn(t,_.toggleGroupBackground)??_.toggleGroupBackground),_.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=_.copyBackground),_.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=_.copyBorder),_.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=_.copyColor),_.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Bh(_.copyBorderRadius)),_.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=_.copyPadding),_.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=_.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??_.copyMenuBackground),_.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=_.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??_.copyMenuBorder),_.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=_.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??_.copyMenuShadow),_.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=_.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??_.copyMenuBorderRadius),_.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=_.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??_.copyMenuItemHoverBackground),_.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=_.iconBackground),_.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=_.toolbarBorder)}if(S?.tab){let _=S.tab;_.background&&(n["--persona-artifact-tab-bg"]=_.background),_.activeBackground&&(n["--persona-artifact-tab-active-bg"]=_.activeBackground),_.activeBorder&&(n["--persona-artifact-tab-active-border"]=_.activeBorder),_.borderRadius&&(n["--persona-artifact-tab-radius"]=_.borderRadius),_.textColor&&(n["--persona-artifact-tab-color"]=_.textColor),_.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=_.hoverBackground),_.listBackground&&(n["--persona-artifact-tab-list-bg"]=_.listBackground),_.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=_.listBorderColor),_.listPadding&&(n["--persona-artifact-tab-list-padding"]=_.listPadding)}if(S?.pane){let _=S.pane;if(_.toolbarBackground){let Te=Hn(t,_.toolbarBackground)??_.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Te}}if(S?.card){let _=S.card;_.background&&(n["--persona-artifact-card-bg"]=_.background),_.border&&(n["--persona-artifact-card-border"]=_.border),_.borderRadius&&(n["--persona-artifact-card-radius"]=_.borderRadius),_.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=_.hoverBackground),_.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=_.hoverBorderColor)}if(S?.inline){let _=S.inline;_.background&&(n["--persona-artifact-inline-bg"]=Hn(t,_.background)??_.background),_.border&&(n["--persona-artifact-inline-border"]=_.border),_.borderRadius&&(n["--persona-artifact-inline-radius"]=_.borderRadius),_.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Hn(t,_.chromeBackground)??_.chromeBackground),_.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Hn(t,_.chromeBorder)??_.chromeBorder),_.titleColor&&(n["--persona-artifact-inline-title-color"]=Hn(t,_.titleColor)??_.titleColor),_.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Hn(t,_.mutedColor)??_.mutedColor),_.frameHeight&&(n["--persona-artifact-inline-frame-height"]=_.frameHeight)}let x=U?.code;x&&(x.keywordColor&&(n["--persona-code-keyword-color"]=x.keywordColor),x.stringColor&&(n["--persona-code-string-color"]=x.stringColor),x.commentColor&&(n["--persona-code-comment-color"]=x.commentColor),x.numberColor&&(n["--persona-code-number-color"]=x.numberColor),x.tagColor&&(n["--persona-code-tag-color"]=x.tagColor),x.attrColor&&(n["--persona-code-attr-color"]=x.attrColor),x.propertyColor&&(n["--persona-code-property-color"]=x.propertyColor),x.lineNumberColor&&(n["--persona-code-line-number-color"]=x.lineNumberColor),x.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=x.gutterBorderColor),x.background&&(n["--persona-code-bg"]=Hn(t,x.background)??x.background));let P=n["--persona-surface"],L=n["--persona-container"],G=n["--persona-palette-colors-gray-100"]??"#f3f4f6",V=n["--persona-palette-colors-gray-200"]??"#e5e7eb",K=n["--persona-palette-colors-gray-300"]??"#d1d5db",ee=!L||L===P,oe=JR(P??n["--persona-background"]),ne=ee&&oe!==void 0&&oe<ZR,le=ne?"rgba(255, 255, 255, 0.08)":G,de=ne?"rgba(255, 255, 255, 0.12)":V,ve=ne?"rgba(255, 255, 255, 0.16)":K,Le=ee?le:L,se=ee?de:L;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Le,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??se,ee&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ve),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Le,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Le,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Le,n}var eH=t=>!!t&&"launcher"in t&&(t.launcher?.sidebarMode===!0||t.launcher?.mountMode==="docked"),$A=(t,e)=>{if(!e||!eH(e))return t;let n=e.theme?.components?.panel?.width,o=e.darkTheme?.components?.panel?.width;return(fc(e)==="dark"?o??n:n)!=null?t:{...t,components:{...t.components,panel:{...t.components.panel,width:bs(e)==="v5"?"400px":"420px"}}}},tH={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},mc={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},_h=tH,nH={..._h,colors:{..._h.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},oH=mc,rH={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600"}}},components:{...mc.components,button:{...mc.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...mc.components?.eventStream,badge:{...mc.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},sH=t=>bs({future:t})==="v5"?{palette:nH,components:rH}:{palette:_h,components:oH},zA=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Nh=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",iH=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Nh()},fc=t=>iH(t),aH=(t,e={})=>Na(t,e),lH=(t,e={})=>{let n=sH(e.future),o=jo(n.components,t??{})??{};return Na({...o,palette:{...o.palette,colors:bs(e)==="v5"?jo(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:e.future})},qr=t=>{let e=fc(t),n=zA(t?.theme),o=Iu(t)==="circle"?Ru:{...Dh.launcher,...t?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=jo({components:{launcher:o}},n),s=zA(t?.darkTheme);return $A(e==="dark"?lH(jo(r??{},s??{}),{future:t?.future}):aH(r,{future:t?.future}),t)},cH=t=>VA(t),gc=(t,e)=>{let n=qr(e),o=cH(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",fc(e)),t.setAttribute("data-persona-defaults",bs(e))},Du=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Nh())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(Nh());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};var Xr=require("lucide");Zt();zn();je();var Is=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Ou="24px",Fh=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",hc=t=>{if(typeof t!="string")return null;let e=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(t);if(!e)return null;let n=Number(e[1])/100;return n>0&&n<1?n:null},UA=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var qA=null;var Vh=()=>{if(qA!==null)return qA;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},dH="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",_u=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},Nu=t=>{let e=t.toLowerCase().split("+").map(r=>r.trim()),n=e.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of e)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return _u("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(_u("unsupported",t),null):(n==="space"&&(o.key=" "),o)},pH=t=>dH.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),jA=(t,e)=>{let n=Nu(t);if(!n)return"";let o=Vh(),r=pH(n.key);if(!e&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[e?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},Fu=t=>jA(t,!1),yc=t=>jA(t,!0),uH=(t,e)=>e.key?.toLowerCase()===t.key&&(Vh()?e.metaKey:e.ctrlKey)===t.mod&&!(Vh()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,mH=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},KA=t=>{let e=new Map,n=t?.ownerDocument??(typeof document<"u"?document:null),o=(s,a)=>{if((s.scope??"widget")==="page")return!0;if(!t)return!1;let l=a.composedPath?.();return l?.length?l.includes(t):t.contains(a.target)},r=s=>{if(s.isComposing||!e.size)return;let a=s.composedPath?.()[0]??s.target;for(let l of e.values())if(uH(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&mH(a))){s.preventDefault();try{l.run(s)}catch(c){_u(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let a=Nu(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,c=e.get(l);return c?(_u(`${c.id} already owns`,s.combo),()=>{}):(e.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",yc(s.combo)),()=>{e.get(l)?.id===s.id&&e.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){e.clear(),n?.removeEventListener("keydown",r)}}};var GA=require("idiomorph"),Vu=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;GA.Idiomorph.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var YA=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var $h={index:-1,draft:""};function QA(t){let{direction:e,history:n,currentValue:o,atStart:r,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function XA(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function JA(){return new Map}function ZA(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function eM(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function tM(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}Uh();ks();Sc();ro();var{setLoader:z2,load:_H}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(AM(),SM))});var MM=_H;ks();function Qh(t,e=On){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var Mc=0,Rs=null;function Xh(t=document){if(Mc++,Mc===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;Rs={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,Mc=Math.max(0,Mc-1),Mc===0&&Rs)){let n=t.body,o=t.defaultView??window;n.style.overflow=Rs.originalOverflow,n.style.position=Rs.originalPosition,n.style.top=Rs.originalTop,n.style.width=Rs.originalWidth,o.scrollTo(0,Rs.scrollY),Rs=null}}}var Tc={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},nn=t=>(t?.launcher?.mountMode??"floating")==="docked",Ec=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Do=t=>{let e=t?.launcher?.dock,n=Nr(t).dockWidth?e?.width:Hn(qr(t),"components.panel.width");return{side:e?.side??Tc.side,width:n??Tc.width,animate:e?.animate??Tc.animate,reveal:e?.reveal??Tc.reveal,maxHeight:e?.maxHeight??Tc.maxHeight}};je();je();var EM=require("lucide");Zt();zn();var Jh=t=>t==="followUp"?"follow-up":t,Zh=(t,e=0)=>{if(typeof t=="string"){let r=t.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},TM=new WeakSet,NH=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,FH=t=>{NH()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},ey=t=>{var H,A,D;let{item:e,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:c,chipsConfig:p,session:u,getTextarea:m,eventTarget:g,submitPrompt:h}=t,b=o==="followUp",C=e.behavior,M=()=>{if(u.isStreaming())return;let W={suggestion:{...e},surface:o,source:r,behavior:C},U=g.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:W,bubbles:!0,composed:!0,cancelable:!0}));if(b&&g.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!U)return;for(let O of c)if(O.onSuggestionSelect?.({suggestion:{...e},surface:o,source:r,variant:s,config:l})===!1)return;let B=m();if(C==="fill"){B.value=e.prompt,B.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),B.focus();return}if(h){h(e.prompt);return}B.value="",u.sendMessage(e.prompt)},E=()=>{let W=v("button",`persona-suggestion persona-suggestion--${s}`);if(W.type="button",W.disabled=a,W.dataset.suggestionId=e.id,W.dataset.emphasis=e.emphasis,W.dataset.behavior=C,s==="chip"&&(p?.fontWeight&&(W.style.fontWeight=p.fontWeight),p?.paddingX&&(W.style.paddingLeft=p.paddingX,W.style.paddingRight=p.paddingX),p?.paddingY&&(W.style.paddingTop=p.paddingY,W.style.paddingBottom=p.paddingY)),e.icon){let B=ke(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);B&&(B.classList.add("persona-suggestion__icon"),e.iconColor&&(B.style.color=e.iconColor),W.appendChild(B))}let U=v("span","persona-suggestion__copy");if(U.appendChild(F("span",{className:"persona-suggestion__label",text:e.label})),e.description&&s!=="chip"&&U.appendChild(F("span",{className:"persona-suggestion__description",text:e.description})),W.appendChild(U),s!=="chip"){let B=Ge(EM.ArrowRight,16,"currentColor",1.8);B&&(B.classList.add("persona-suggestion__arrow"),W.appendChild(B))}return W.addEventListener("click",M),W},T=null;for(let W of c)if(W.renderSuggestion&&(T=W.renderSuggestion({suggestion:{...e},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:E,select:M}),T))break;return T??(T=E()),(H=T.dataset).suggestionId||(H.suggestionId=e.id),(A=T.dataset).behavior||(A.behavior=C),(D=T.dataset).emphasis||(D.emphasis=e.emphasis),T instanceof HTMLButtonElement||T.setAttribute("aria-disabled",a?"true":"false"),T},kc=t=>{let e=[],n=[],o=null,r=null,s=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},a=()=>{if(r=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,t.scrollWidth-t.clientWidth);if(u<=1){s();return}let m=getComputedStyle(t).direction==="rtl",g=Math.min(u,Math.max(0,Math.abs(t.scrollLeft))),h=4,b=g<=h,C=g>=u-h,M=m?!C:!b,E=m?!b:!C;t.toggleAttribute("data-scroll-left",M),t.toggleAttribute("data-scroll-right",E)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};t.addEventListener("scroll",l,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return c?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",l),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(u,m,g,h,b,C)=>{t.replaceChildren(),e.length=0,n.length=0;let M=C?.source??"config",E=C?.surface??(M==="config"?"starter":"followUp"),T=E==="followUp",H=C?.variant??"chip",A=C?.behavior??"send",D=C?.overflow??"wrap",W=C?.config??{},U=C?.plugins??[],B=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,O=T?"followUps":"starters";!TM.has(W)&&W.debug===!0&&H!=="chip"&&W.suggestions?.[O]?.overflow!==void 0&&(TM.add(W),console.info(`[persona] suggestions.${O}.overflow applies to the "chip" variant only; the "${H}" variant manages its own stacking.`));let R=V=>V.map(Zh).filter(K=>K!==null).map(K=>({...K,behavior:K.behavior??A})),S=R(u??[]);U.forEach(V=>{V.transformSuggestions&&(S=R(V.transformSuggestions({suggestions:S.map(K=>({...K})),surface:E,source:M,config:W})))});let x=B===void 0?S:S.slice(0,B);if(!x.length){t.hidden=!0,o=null,s();return}if(!T&&(h??m.getMessages()).some(K=>K.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=Jh(E),t.dataset.variant=H,t.dataset.overflow=D;let P=document.createDocumentFragment(),L=m.isStreaming();x.forEach((V,K)=>{let ee=ey({item:V,index:K,surface:E,source:M,variant:H,streaming:L,config:W,plugins:U,chipsConfig:b,session:m,getTextarea:()=>g,eventTarget:t,submitPrompt:C?.submitPrompt});P.appendChild(ee),n.push(ee),[...ee instanceof HTMLButtonElement?[ee]:[],...Array.from(ee.querySelectorAll("button"))].forEach(ne=>{e.includes(ne)||(ne.disabled=L,e.push(ne))})}),t.appendChild(P),a(),l();let G=JSON.stringify({normalized:x,surface:E,variant:H,source:M});G!==o&&(o=G,FH(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:x.map(V=>({...V})),surface:E,source:M,variant:H},bubbles:!0,composed:!0})),T&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:x.map(V=>V.prompt)},bubbles:!0,composed:!0})))}}};var vo={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};ks();je();Zt();je();Zt();var VH="persona-header-control",$H="persona-header-control--glyph",zH="persona-header-control--sparse",UH=20,qH={x:[1.4,1.05]},kM="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",jH="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Gu=(t,e,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=qH[e]??[1,1.5],l=!o;t.classList.toggle($H,l),t.classList.toggle(zH,l&&s!==1);let c=parseFloat(o??"")||UH,p=ke(e,`${Math.round(c*s)}px`,"currentColor",a);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((a/1.5).toFixed(4))})`),t.replaceChildren(p)):r&&(t.textContent=r)},ki=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=kM,size:l,iconSize:c,color:p,backgroundColor:u,borderWidth:m,borderColor:g,borderRadius:h,paddingX:b,paddingY:C,hidden:M,extraClassName:E,attrs:T}=t,H=v("div",a),A=!!(m||g),D=F("button",{className:Gt(VH,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"persona-border-none",!h&&"persona-rounded-full",E),attrs:{type:"button","aria-label":e,...T},style:{width:l,height:l,minWidth:l,minHeight:l,display:M?"none":void 0,color:p||qn.actionIconColor,backgroundColor:u,border:A?`${m||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:h,paddingLeft:b,paddingRight:b,paddingTop:C,paddingBottom:C}});return r?Gu(D,r,{iconSize:c,iconText:s}):s&&(D.textContent=s),H.appendChild(D),In({anchor:D,trigger:H,text:()=>D.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:D,wrapper:H}},Va=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=kM,buttonSize:r,iconSize:s}=e,a=t?.launcher??{},l=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=ki({ariaLabel:l,tooltip:c,iconName:a.closeButtonIconName??"x",iconText:a.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??a.closeButtonSize,iconSize:s,color:a.closeButtonColor,backgroundColor:a.closeButtonBackgroundColor,borderWidth:a.closeButtonBorderWidth,borderColor:a.closeButtonBorderColor,borderRadius:a.closeButtonBorderRadius,paddingX:a.closeButtonPaddingX,paddingY:a.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:u}},$a=(t,e={})=>{let{wrapperClassName:n=jH,buttonSize:o,iconSize:r}=e,a=(t?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",c=a.showTooltip??!0,{button:p,wrapper:u}=ki({ariaLabel:l,tooltip:c,iconName:a.iconName??"refresh-cw",wrapperClassName:n,size:o??a.size,iconSize:r,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:p,wrapper:u}};var qn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},ty={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},KH={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},Pi=t=>{let{config:e,showClose:n=!0}=t,o=F("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:qn.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=e?.launcher??{},s=r.headerIconSize??Fl,a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,p=F("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(c){let D=parseFloat(s)||24,W=ke(c,D*.6,"currentColor",1);W?(W.style.width=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,W.style.height=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(W)):p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let D=v("img");D.src=e.launcher.iconUrl,D.alt="",D.className="persona-rounded-xl persona-object-cover",D.style.height=s,D.style.width=s,p.replaceChildren(D)}else p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let u=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=F("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:qn.titleColor,...ty}}),g=F("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:qn.subtitleColor,...KH}});u.append(m,g),l?o.append(u):o.append(p,u);let h=r.clearChat??{},b=h.enabled??!0,C=h.placement??"inline",M=null,E=null;if(b){let W=$a(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=W.button,E=W.wrapper,C==="top-right"&&(E.style.right="48px"),C==="inline"&&o.appendChild(E)}let T=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:H,wrapper:A}=Va(e,{showClose:n,wrapperClassName:T});return a!=="top-right"&&o.appendChild(A),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:g,closeButton:H,closeButtonWrapper:A,clearChatButton:M,clearChatButtonWrapper:E}},Pc=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};je();ny();Ii();var GH=t=>{let e=Pi({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return e};function YH(t,e,n){if(e?.length)for(let o of e){let{button:r,wrapper:s}=ki({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Fu(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let a=yc(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=Lc({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()})}else r.addEventListener("click",()=>n?.(o.id));t.appendChild(s)}}var QH=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,a=e?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=qn.minHeight,l.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=r?.titleMenu,p,u;if(c){let A=LM({label:a.title??"Chat Assistant",menuItems:c.menuItems,onSelect:D=>{let W=B=>{B===!1&&A.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:D}}))},U=c.onSelect(D);U instanceof Promise?U.then(W,()=>{}):W(U)},hover:c.hover,className:""});p=A.element,p.style.color=qn.titleColor,u=p.querySelector(".persona-combo-btn-label")??p}else{if(p=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=v("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=qn.titleColor,Object.assign(u.style,ty),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let D=r.onTitleClick;p.addEventListener("click",W=>{W.target.closest("button")||D()}),p.addEventListener("keydown",W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),D())})}let A=r?.titleRowHover;A&&(p.style.borderRadius=A.borderRadius??"10px",p.style.padding=A.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=A.background??"",p.style.borderColor=A.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:g,wrapper:h}=Va(e,{showClose:n,wrapperClassName:m});o&&g.addEventListener("click",o);let b=v("div","persona-flex persona-items-center persona-gap-1");c||YH(b,r?.trailingActions,r?.onAction??s);let C=a.clearChat??{},M=null,E=null;if(C.enabled??!0){let A=C.placement??"inline",D=$a(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});M=D.button,E=D.wrapper,A==="top-right"?E.style.right="48px":b.appendChild(E)}b.appendChild(h),l.appendChild(b);let T=v("div");T.style.display="none";let H=v("span");return H.style.display="none",{header:l,iconHolder:T,headerTitle:u,headerSubtitle:H,closeButton:g,closeButtonWrapper:h,clearChatButton:M,clearChatButtonWrapper:E}},IM={default:GH,minimal:QH},XH=t=>IM[t]??IM.default,Qu=(t,e,n)=>{if(e?.render){let a=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=v("div");l.style.display="none";let c=v("span"),p=v("span"),u=v("button");u.style.display="none";let m=v("div");return m.style.display="none",{header:a,iconHolder:l,headerTitle:c,headerSubtitle:p,closeButton:u,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=XH(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};je();var Ic=t=>{let{config:e}=t,n=F("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=du(),r=F("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""}}),{textarea:s,attachAutoResize:a}=iu(e);a();let l=au(e),c=Da(e),p=lu(e),u=cu(e),m=F("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),p&&(p.previewsContainer.style.gap="8px",m.append(p.previewsContainer),r.append(p.input)),r.append(s);let g=F("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=F("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),b=F("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&h.append(p.wrapper),c&&b.append(c.wrapper),b.append(l.wrapper),g.append(h,b),r.append(g),r.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==c?.button&&C.target!==c?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),e?.statusIndicator?.mode==="transient"?n.append(o,u,r):n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,header:m,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:u,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:g,leftActions:h,rightActions:b,setSendButtonMode:l.setMode}};je();var Xu=require("lucide");zn();var RM=()=>{let t=F("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=v("span","persona-pill-peek__icon"),n=Ge(Xu.MessageSquare,16,"currentColor",1.5);n&&e.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),s=Ge(Xu.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},Ju=t=>{let{config:e}=t,n=F("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=du(),r=cu(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=iu(e,{defaultMaxLines:5});a();let l=au(e),c=Da(e),p=lu(e);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=F("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),m=F("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let g=F("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&g.append(c.wrapper),g.append(l.wrapper),u.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==c?.button&&C.target!==c?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(m,s,g);let h=F("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),p&&h.append(p.previewsContainer),n.append(o,u,r);let b=u;return{footer:n,suggestions:o,composerForm:u,header:h,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:b,leftActions:m,rightActions:g,setSendButtonMode:l.setMode}};je();Zt();je();Ii();Zt();Sc();var JH=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},ZH=(t,e)=>{if(!t)return null;let n=JH(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},eW=(t,e)=>{let n=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},tW=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},ry=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},sy=320,OM=320,nW=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),oW=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),rW=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),sW=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),iW=t=>{if(!t||t.length===0)return null;let e=F("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=F("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=ke(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(F("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},aW=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(pc(o.ref,{readonly:!0,render:e}))}return n},HM="\uE000",WM="\uE001",lW=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=g=>`${HM}${r}:${g}${WM}`,a=e.map((g,h)=>g.kind==="text"?g.text:s(h)).join(""),l=n(a);if(!e.every((g,h)=>g.kind==="text"||l.includes(s(h)))){t.replaceChildren(aW(e,o));return}t.innerHTML=l;let p=new RegExp(`${HM}${r}:(\\d+)${WM}`),u=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),m=[];for(let g=u.nextNode();g;g=u.nextNode())m.push(g);for(let g of m){let h=g;for(let b=p.exec(h.data);b;b=p.exec(h.data)){let C=e[Number(b[1])],M=h.splitText(b.index);M.data=M.data.slice(b[0].length),C?.kind==="mention"&&M.parentNode?.insertBefore(pc(C.ref,{readonly:!0,render:o}),M),h=M}}},cW=(t,e,n)=>{if(t.length===0)return null;try{let o=v("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return t.forEach((l,c)=>{let p=v("img");p.alt=l.alt?.trim()||`Attached image ${c+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${sy}px`,p.style.maxHeight=`${OM}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,p.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),p.remove(),r===0&&a())}),p.addEventListener("load",()=>{u=!0}),tW(l.image)?(p.src=l.image,o.appendChild(p)):(u=!0,r=Math.max(0,r-1),p.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},dW=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!ry(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${sy}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},pW=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!ry(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${sy}px`,r.style.maxHeight=`${OM}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},uW=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!ry(o.data))return;let r=v("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Rc=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},mW=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Rc};if(e){let r=e(o);if(r!==null)return r}return Rc()},fW=(t,e)=>{let n=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=v("img");r.src=o,r.alt=e==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},BM=(t,e,n="div")=>{let o=v(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Hc=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},DM={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},gW=(t,e,n="bubble",o)=>{if(!o)return;let r=e==="user"?"user":"assistant",s=DM[n??"bubble"]??DM.bubble;o.padding&&(t.style.padding=`var(--persona-message-${r}-padding, ${s.padding})`),o.fontSize&&(t.style.fontSize=`var(--persona-message-${r}-font-size, ${s.fontSize})`),o.lineHeight&&(t.style.lineHeight=`var(--persona-message-${r}-line-height, ${s.lineHeight})`),o.fontFamily&&(t.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},Zu="custom:",hW=t=>`${Zu}${t}`,_M=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),yW=(t,e,n,o)=>{let r=e.showCopy??!0,s=e.showUpvote??!1,a=e.showDownvote??!1,l=e.showReadAloud??!1,c=(e.showRegenerate??!1)&&o?.canRegenerate===!0,p=(e.showEdit??!1)&&o?.canEdit===!0,u=(e.showQuote??!1)&&o?.canQuote!==!1,m=_M(e,t.role);if(!r&&!s&&!a&&!l&&!c&&!p&&!u&&m.length===0){let H=v("div");return H.style.display="none",H.id=`actions-${t.id}`,H.setAttribute("data-actions-for",t.id),H}let g=e.visibility??"hover",h=e.align??"right",b=e.layout??"pill-inside",C={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],M={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[b],E=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${C} ${M} ${g==="hover"?"persona-message-actions-hover":""}`);E.id=`actions-${t.id}`,E.setAttribute("data-actions-for",t.id);let T=(H,A,D)=>{let W=vn({icon:H,label:A,size:14,className:"persona-message-action-btn",chromeless:!0});return W.setAttribute("data-action",D),W};r&&E.appendChild(T("copy","Copy message","copy")),l&&E.appendChild(T("volume-2","Read aloud","read-aloud")),s&&E.appendChild(T("thumbs-up","Upvote","upvote")),a&&E.appendChild(T("thumbs-down","Downvote","downvote")),c&&E.appendChild(T("refresh-cw","Regenerate response","regenerate")),p&&E.appendChild(T("pencil","Edit message","edit")),u&&E.appendChild(T("quote","Quote message","quote"));for(let H of m)E.appendChild(T(H.iconName??"ellipsis",H.label,hW(H.id)));return E},iy=(t,e,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",c=a.avatar,p=a.timestamp,u=c?.show??!1,m=p?.show??!1,g=c?.position??"left",h=p?.position??"below",b=Hc(t.role,l),C=v("div",b.join(" "));C.id=`bubble-${t.id}`,C.setAttribute("data-message-id",t.id),C.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let M=Oh(s?.widgetConfig?.future).components.message,E=s?.widgetConfig?.theme?.components?.message;gW(C,t.role,l,t.role==="user"?{...M.user,...E?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...M.assistant,...E?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=nW(t),H=t.content?.trim()??"",D=T.length>0&&H===Ra,W=qu(s?.widgetConfig?.features?.streamAnimation),U=s?.widgetConfig?.features?.streamAnimation?.plugins,B=t.role==="assistant"&&W.type!=="none"?vc(W.type,U):null,O=t.role==="assistant"&&B?.isAnimating?.(t)===!0,R=t.role==="assistant"&&B!==null&&(!!t.streaming||O);R&&B?.bubbleClass&&C.classList.add(B.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),t.streaming&&S.classList.add("persona-content-streaming"),R&&B&&(B.containerClass&&S.classList.add(B.containerClass),S.style.setProperty("--persona-stream-step",`${W.speed}ms`),S.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let x=R?ju(t.content??"",W.buffer,B,t,!!t.streaming):t.content??"",P=()=>{let se=e({text:x,message:t,streaming:!!t.streaming,raw:t.rawContent});return R&&B?.wrap==="char"?Cc(se,"char",t.id,{skipTags:B.skipTags}):R&&B?.wrap==="word"?Cc(se,"word",t.id,{skipTags:B.skipTags}):se},L=null;if(D?(L=document.createElement("div"),L.innerHTML=P(),L.style.display="none",S.appendChild(L)):t.contentSegments?.length?lW(S,t.contentSegments,se=>e({text:se,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):S.innerHTML=P(),R&&B?.useCaret&&!D&&H){let se=Ku(),_=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),Te=_[_.length-1];if(Te?.parentNode)Te.parentNode.insertBefore(se,Te.nextSibling);else{let He=S.lastElementChild;He?He.appendChild(se):S.appendChild(se)}}if(m&&h==="inline"&&t.createdAt){let se=BM(t,p,"span");se.classList.add("persona-timestamp-inline");let _=S.lastElementChild;_?_.appendChild(se):S.appendChild(se)}if(T.length>0){let se=cW(T,!D&&!!H,()=>{D&&L&&(L.style.display="")});se?C.appendChild(se):D&&L&&(L.style.display="")}let G=oW(t);if(G.length>0){let se=dW(G);se&&C.appendChild(se)}let V=rW(t);if(V.length>0){let se=pW(V);se&&C.appendChild(se)}let K=sW(t);if(K.length>0){let se=uW(K);se&&C.appendChild(se)}let ee=t.contentSegments?.length?null:iW(t.contextMentions);if(ee&&C.appendChild(ee),C.appendChild(S),m&&h==="below"&&t.createdAt){let se=BM(t,p);se.classList.add("persona-mt-1"),C.appendChild(se)}let oe=t.role==="assistant"?ZH(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let se=!!(x&&x.trim()),_=W.placeholder==="skeleton",Te=_&&W.buffer==="line"&&se;if(se)Te&&C.appendChild(wc());else if(_)C.appendChild(wc());else{let He=mW("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);He&&C.appendChild(He)}}oe&&t.stopReason&&!t.streaming&&(H||(S.style.display="none"),C.appendChild(eW(t.stopReason,oe)));let ne=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,le=s?.actionEligibility,de=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&le?.canEdit===!0||o?.showQuote===!0&&le?.canQuote===!0||_M(o,"user").length>0);if((ne||de)&&o){let se=yW(t,de?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,le);C.appendChild(se)}if(!u||t.role==="system")return C;let ve=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),Le=fW(c,t.role);return g==="right"||g==="left"&&t.role==="user"?ve.append(C,Le):ve.append(Le,C),ve};var bW=40,vW=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=ke(e.name,bW);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(F("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(F("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},NM=(t,e,n={})=>{let o=F("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("p","persona-welcome-kicker");r.hidden=!0;let s=v("h2","persona-welcome-title"),a=v("p","persona-welcome-subtitle"),l=F("div",{className:"persona-welcome-head-text"},r,s),c=F("div",{className:"persona-welcome-title-row"},o,l);return{host:F("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},c,a,e),iconHolder:o,kicker:r,title:s,subtitle:a,starterSuggestions:e}},za=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},tm=(t,e)=>{t.title.textContent=e.title,t.kicker.textContent=e.kicker??"",t.kicker.hidden=!e.kicker,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",vW(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss),t.host.setAttribute("data-persona-welcome-layout",e.layout??"top"),t.host.setAttribute("data-persona-welcome-anchor",e.anchor??"bottom"),e.iconPlacement==="inline"?t.host.setAttribute("data-persona-welcome-icon-placement","inline"):t.host.removeAttribute("data-persona-welcome-icon-placement"),e.align?t.host.setAttribute("data-persona-welcome-align",e.align):t.host.removeAttribute("data-persona-welcome-align")},CW="data-persona-welcome-plugin",FM="data-persona-welcome-overlay",em="persona-welcome-overlay-active",ay=new WeakMap,ly=(t,e,n)=>{n.setAttribute(CW,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(FM,""),t.classList.contains(em)||(ay.set(t,t.scrollTop),t.classList.add(em),t.scrollTop=0)},cy=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(FM),t.classList.contains(em)&&(t.classList.remove(em),t.scrollTop=ay.get(t)??t.scrollTop,ay.delete(t))},VM=()=>{let t=F("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},nm=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=F("div",{className:Hc("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});t.appendChild(F("div",{className:"persona-flex"},r)),t.hidden=!1},$M=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,zM=(t,e)=>{if($M()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,r=0,s=0,a=0;if(o){let b=getComputedStyle(o);r=parseFloat(b.rowGap)||0;let C=t.previousElementSibling,M=t.nextElementSibling,T=o.getBoundingClientRect().top+(parseFloat(b.borderTopWidth)||0)+(parseFloat(b.paddingTop)||0)-o.scrollTop;s=Math.max(0,C?n.top-C.getBoundingClientRect().bottom-r:n.top-T),a=Math.max(0,M?M.getBoundingClientRect().top-n.bottom-r:0)}let l=t.style.overflow;t.style.overflow="hidden";let c=getComputedStyle(t),p=parseFloat(c.paddingTop)||0,u=parseFloat(c.paddingBottom)||0,m=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${u}px`,marginTop:`${s}px`,marginBottom:`${a}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),g=!1,h=()=>{g||(g=!0,t.style.overflow=l,e(m))};return m.finished.then(h).catch(h),m},UM=(t,e,n,o=260)=>{if(e<=1||$M()||typeof t.animate!="function"||!t.isConnected)return null;let r=n==="drop"?-e:e;return t.animate([{transform:`translateY(${r}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var wW="Hello \u{1F44B}",xW="I can answer questions and help you get things done here.",qM=new WeakSet,jn=(t,e)=>!!t&&t[e]!==void 0,SW=(t,e)=>{!t||t.debug!==!0||!e.length||qM.has(t)||(qM.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},om=(t,e=t?.launcher?.fullHeight===!0&&!t.launcher.sidebarMode&&t.launcher.mountMode!=="docked")=>{let n=t?.welcome,o=t?.copy,r=t?.future?.v5Defaults===!0,s=n?.layout??(r?"centered":"top"),a=jn(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=a==="hero"&&!r&&n?.layout===void 0?"on-first-message":jn(n,"dismiss")?n.dismiss:r||a==="hero"?"on-first-message":"never",c=[];jn(n,"title")&&jn(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),jn(n,"subtitle")&&jn(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),jn(n,"variant")&&jn(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),a==="hero"&&jn(n,"message")&&c.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&n?.layout===void 0&&a==="hero"&&jn(n,"dismiss")&&n.dismiss!=="on-first-message"&&c.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let p=n?.anchor??(s==="centered"&&e?"center":"bottom"),u=hc(n?.anchorComposerTop)!==null;return jn(n,"anchorComposerTop")&&!u&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&(jn(n,"anchorComposerTop")||jn(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),SW(t,c),{title:jn(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":wW),kicker:n?.kicker??"",subtitle:jn(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":xW),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:s==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:a,dismiss:l,message:a==="hero"?void 0:n?.message,layout:s,anchor:p,anchorComposerTop:u?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||Ou}},jM=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Ua=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var AW="var(--persona-components-panel-maxWidth)",KM="var(--persona-components-panel-height)",MW="var(--persona-components-panel-maxHeight)",Ri=t=>{let e=Nr(t),n=e.launcherWidth?t?.launcher?.width:e.legacyLauncherWidth?t?.launcherWidth:void 0,o=t?.launcher?.heightOffset??0,r=o===0?`max(200px, ${KM})`:`max(200px, calc(${KM} - ${o}px))`;return{width:n??yw,maxWidth:n??AW,height:r,maxHeight:MW}},GM="16px",py="10px",uy="14px",YM=t=>{let e=t?.launcher?.enabled??!0,n=nn(t);if(Ec(t)){let p=t?.launcher?.composerBar??{},u=v("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=p.expandedSize??"anchored",u.style.zIndex=String(t?.launcher?.zIndex??On);let m=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");m.style.width="100%",u.appendChild(m);let g=v("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=p.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??On),{wrapper:u,panel:m,pillRoot:g}}if(n){let p=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(u),{wrapper:p,panel:u}}if(!e){let p=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),m=Nr(t),h=m.launcherWidth||m.legacyLauncherWidth||t?.theme?.components?.panel?.width!==void 0?Ri(t).width:"100%";return p.style.width=h,u.style.width="100%",p.appendChild(u),{wrapper:p,panel:u}}let r=t?.launcher??{},s=r.position&&vo[r.position]?vo[r.position]:vo["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??On);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=Ri(t);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,a.appendChild(l),{wrapper:a,panel:l}},my=t=>{let e=F("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Jh(t)}});return e.hidden=!0,e},QM=(t,e)=>{let n=my("starter"),o=NM(t,n,{flatShadow:nn(t)}),r=om(t);tm(o,r),za(e,o.host,Ua(r,t?.initialMessages));let s=VM();return nm(s,r.message,t),{welcome:o,greetingHost:s}},TW=(t,e)=>{let n=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Va(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:GM,iconSize:py});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=t?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let U=$a(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:GM,iconSize:uy});a=U.button,l=U.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=F("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=F("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=QM(t,p),{host:g,title:h,subtitle:b}=u,C=u.starterSuggestions,M=v("div","persona-widget-messages persona-flex persona-flex-col");M.style.gap="var(--persona-components-message-gap, 12px)";let E=my("followUp"),T=Is(t,!0);T&&(M.style.maxWidth=T,M.style.marginLeft="auto",M.style.marginRight="auto",M.style.width="100%"),p.append(g,m,M,E);let H=F("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),A=Ju({config:t}),{root:D,textNode:W}=RM();return n.append(c,r,p,H),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:M,starterSuggestions:C,transcriptSuggestions:E,composerOverlay:H,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:g,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:h,introSubtitle:b,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:c,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:D,peekTextNode:W}},XM=(t,e=!0)=>{if(Ec(t))return TW(t,e);let n=F("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?Qu(t,o,{showClose:e}):Pi({config:t,showClose:e}),a=F("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:c}=QM(t,a),{host:p,title:u,subtitle:m}=l,g=l.starterSuggestions,h=v("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let b=my("followUp"),C=Is(t,!1);C&&(h.style.maxWidth=C,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),a.append(p,c,h,b);let M=Ic({config:t}),E=t?.layout?.showFooter!==!1;r?Pc(n,s,t):(s.header.style.display="none",Pc(n,s,t)),n.append(a);let T=F("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return E||(M.footer.style.display="none"),n.append(M.footer),n.append(T),{container:n,body:a,messagesWrapper:h,starterSuggestions:g,transcriptSuggestions:b,composerOverlay:T,suggestions:M.suggestions,textarea:M.textarea,sendButton:M.sendButton,sendButtonWrapper:M.sendButtonWrapper,micButton:M.micButton,micButtonWrapper:M.micButtonWrapper,composerForm:M.composerForm,statusText:M.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:c,introKicker:l.kicker,introTitle:u,introSubtitle:m,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode}};je();Zt();ks();var fy=(t,e)=>{let n=v("button");n.type="button",n.innerHTML=`
1159
1159
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
1160
1160
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
1161
1161
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -1163,14 +1163,15 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1163
1163
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
1164
1164
  </span>
1165
1165
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
1166
- `,n.addEventListener("click",e);let o=s=>{let a=s.launcher??{},l=rn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let I=a.title??"Chat Assistant";d.textContent=I,d.setAttribute("title",I)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let I=a.subtitle??"Here to help you get answers fast";p.textContent=I,p.setAttribute("title",I)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||l?u.style.display="none":u.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let I=a.agentIconSize??"40px";if(m.style.height=I,m.style.width=I,a.agentIconBackgroundColor?(m.style.backgroundColor=a.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",a.agentIconName){let M=parseFloat(I)||24,O=Ie(a.agentIconName,M*.6,"var(--persona-text-inverse, #ffffff)",1.5);O?(m.appendChild(O),m.style.display=""):(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let I=a.agentIconSize??"40px";y.style.height=I,y.style.width=I,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let I=a.callToActionIconSize??"32px";g.style.height=I,g.style.width=I,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let M=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,M=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=l?"none":"",g.innerHTML="",a.callToActionIconName){let O=parseFloat(I)||24,k=Math.max(O-M,8),B=Ie(a.callToActionIconName,k,"currentColor",1.5);B?g.appendChild(B):g.textContent=a.callToActionIconText??"\u2197"}else g.textContent=a.callToActionIconText??"\u2197"}let b=a.position&&go[a.position]?go[a.position]:go["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",S="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?S:`${C} ${b}`,l||(n.style.zIndex=String(a.zIndex??Hn));let T="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",A="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:A,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:r}},ZH="teaser-dismissed",qA=new Set,UA=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${ZH}`},eR=(t,e)=>{if(qA.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},tR=(t,e)=>{if(qA.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},nR=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,oR=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||rn(t??{})?null:e},jA=(t,e)=>{let n=v("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=t??{},r=null,s=null,a=null,l=null,d=null,p=!1,u=!1,m=!1,y=!1,g=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,b=()=>{d!==null&&(clearTimeout(d),d=null)},C=()=>{!s||!p||(p=!1,s.hidden=!0)},S=G=>{b(),m=!0,C(),tR(UA(o),G&&g())},T=G=>{!r||m||S(G==="user"&&p)},A=()=>{d=null,!(!s||m||y)&&(u=!0,p=!0,s.hidden=!1,!(nR()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},I=()=>{!r||!s||m||u||y||eR(UA(o),g())||(b(),d=setTimeout(A,Math.max(0,r.delayMs??0)))},M=()=>{S(g()),e()},O=G=>{G.stopPropagation(),S(g())},B=xh(t,()=>{T("user"),e()}),W=()=>{b(),l?.removeEventListener("click",M),a?.removeEventListener("click",O),s?.remove(),s=null,l=null,a=null,p=!1},V=()=>{l=$("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",M),a=$("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",O),s=$("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,B.element)},R=()=>{let G=o.launcher?.position??"bottom-right",z=go[G]??go["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",B.element.style.position="";return}n.className=Vt("persona-launcher-surface",z),n.setAttribute("data-teaser",G),n.style.zIndex=String(o.launcher?.zIndex??Hn),B.element.style.position="static"},w=G=>{let z=oR(G);if(r=z,!z){W();return}s||V(),l.textContent=z.text,a.hidden=z.dismissible===!1,a.setAttribute("aria-label",z.dismissLabel??"Dismiss message"),I()},E=G=>{o=G,B.update(G),w(G),R()},H=(G,z="user")=>{y=G,G&&T(z)},D=()=>{W(),B.destroy(),n.remove()};return n.appendChild(B.element),t&&(w(t),R()),{element:n,launcher:B,get teaser(){return s?{element:s,show:A,dismiss:S}:null},setPanelOpen:H,update:E,destroy:D}};var KA=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=VA(t),s=zA(t,e),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},p={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:l,header:d,composer:p,replaceHeader:y=>(d.element.replaceWith(y.header),d.element=y.header,d.iconHolder=y.iconHolder,d.headerTitle=y.headerTitle,d.headerSubtitle=y.headerSubtitle,d.closeButton=y.closeButton,d.closeButtonWrapper=y.closeButtonWrapper,d.clearChatButton=y.clearChatButton,d.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{p.footer.replaceWith(y),p.footer=y}}},Sh=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>xh(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=jA(t,n);return{instance:r,element:r.element}};var rR=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},sR=(t,e,n)=>`${rR(t)}plugin:${e}:${n}`,GA=t=>{let e=new Map,n=!1,o=()=>{if(n||t()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=a=>sR(t(),r,a);return{get:a=>{let l=s(a),d=o();if(d)try{return d.getItem(l)}catch{n=!0}return e.get(l)??null},set:(a,l)=>{let d=s(a),p=o();if(p)try{p.setItem(d,l);return}catch{n=!0}e.set(d,l)},remove:a=>{let l=s(a);e.delete(l);let d=o();if(d)try{d.removeItem(l)}catch{n=!0}}}}};Ye();Yt();ri();Tu();Ye();var Eu=require("lucide");ro();var iR=["persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"],aR="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none",lR="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none",cR=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),ku=(t,e)=>{let n=v("div",["persona-message-bubble",t,...iR].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},Lu=t=>{let e=v("button",t.expandable?aR:lR);return e.type="button",t.expandable&&(e.setAttribute("aria-expanded",t.expanded?"true":"false"),e.setAttribute("data-expand-header","true")),e.setAttribute("data-bubble-type",t.bubbleType),e},Ah=(t,e,n)=>{t.innerHTML="";let o=Qe(e?Eu.ChevronUp:Eu.ChevronDown,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},Pu=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=v("div","persona-flex persona-items-center");Ah(o,n.expanded,n.iconColor);let r=v("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),t.append(e,r),o},Iu=t=>{let e=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(e.setAttribute("data-persona-collapsed-preview",t.previewKind),e.style.display="none",e.style.whiteSpace="pre-wrap",!t.expanded&&t.isActive&&t.activePreview&&t.previewText){let n=t.renderPreview?.();cR(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},Hu=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&Ah(t.toggleIcon,t.expanded,t.iconColor),t.content.style.display=t.expanded?"":"none",t.collapsedPreview.style.display=t.expanded?"none":t.collapsedPreview.textContent||t.collapsedPreview.childNodes.length?"":"none"},Ru=(t,e,n)=>{let o=n.stateSet.has(t),r=e.querySelector('button[data-expand-header="true"]'),s=e.querySelector(".persona-border-t"),a=e.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let d=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");d&&Ah(d,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};var Ta=new Set,dR=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
1167
- `):""},YA=(t,e)=>{Ru(t,e,{stateSet:Ta,previewKind:"reasoning",iconColor:"currentColor"})},Mh=(t,e)=>{let n=t.reasoning,o=ku("persona-reasoning-bubble",t.id);if(!n)return o;let r=e?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&Ta.has(t.id),l=n.status!=="complete",d=dR(t,r.previewMaxLines??3),p=Lu({expandable:s,expanded:a,bubbleType:"reasoning"}),u=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary"),y="Thinking...",g=e?.reasoning??{},b=String(n.startedAt??Date.now()),C=()=>{let D=v("span","");return D.setAttribute("data-tool-elapsed",b),D.textContent=cp(n),D},S=g.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:y,previewText:d,isActive:l,config:e??{},elapsed:cp(n),createElapsedElement:C});typeof S=="string"&&S.trim()?(m.textContent=S,u.appendChild(m)):S instanceof HTMLElement?u.appendChild(S):(m.textContent=y,u.appendChild(m));let T=v("span","persona-text-xs persona-text-persona-primary");T.textContent=sw(n),u.appendChild(T);let A=r.loadingAnimation??"none",I=g.activeTextTemplate,M=g.completeTextTemplate,O=l?I:M,k=S instanceof HTMLElement,B=(D,G)=>{m.textContent="";let z=dp(D,""),K=0;for(let Y of z){let re=Y.styles.length>0?(()=>{let oe=v("span",Y.styles.map(se=>`persona-tool-text-${se}`).join(" "));return m.appendChild(oe),oe})():m;if(Y.isDuration&&l)re.appendChild(C());else{let oe=Y.isDuration?cp(n):Y.text;G?K=vs(re,oe,K):re.appendChild(document.createTextNode(oe))}}};if(!k&&O)if(T.style.display="none",m.style.display="",l&&A!=="none"){let D=g.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),A==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${D}ms`),B(O,!1)):(m.classList.add(`persona-tool-loading-${A}`),m.style.setProperty("--persona-tool-anim-duration",`${D}ms`),A==="shimmer-color"&&(g.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),B(O,!0))}else B(O,!1);else if(!k&&l&&A!=="none"){m.style.display="";let D=g.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),A==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${D}ms`);else{m.classList.add(`persona-tool-loading-${A}`),m.style.setProperty("--persona-tool-anim-duration",`${D}ms`),A==="shimmer-color"&&(g.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let G=m.textContent||y;m.textContent="",vs(m,G,0)}n.status==="complete"&&(m.style.display="none")}else k||(n.status==="complete"?m.style.display="none":m.style.display="");if(r.iconName&&!k){let D=v("span","persona-reasoning-header-icon"),G=Ie(r.iconName,16,"currentColor",2);G&&(D.appendChild(G),p.appendChild(D))}let W="currentColor",V=Pu(p,u,{expandable:s,expanded:a,iconColor:W,metaGap:!1}),R=Iu({bubble:o,previewKind:"reasoning",expanded:a,isActive:l,previewText:d,activePreview:r.activePreview,activeMinHeight:r.activeMinHeight,renderPreview:()=>e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:d,isActive:l,config:e??{}})});if(!s)return o.append(p,R),o;let w=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");w.style.display=a?"":"none";let E=n.chunks.join(""),H=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return H.textContent=E||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),w.appendChild(H),Hu({expanded:a,header:p,toggleIcon:V,content:w,collapsedPreview:R,iconColor:W}),o.append(p,R,w),o};Ye();ri();Tu();var Ea=new Set,QA=t=>t.toggleTextColor||t.headerTextColor||"var(--persona-primary, #171717)",pR=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-e).join(`
1168
- `);let r=us(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
1169
- `):""},Th=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},uR=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=n?.success===!1?n.error||"Tool failed":pR(t,o?.previewMaxLines??3),a=n?aw(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",d=e?.toolCall??{},p=a;return r==="tool-name"?p=n.name?.trim()||a:r==="tool-preview"&&s&&(p=s),l&&d.activeTextTemplate?p=Qf(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=Qf(n,d.completeTextTemplate,p)),n.success===!1&&(p+=" \xB7 Failed"),{summary:p,previewText:s,isActive:l}},XA=(t,e,n)=>{Ru(t,e,{stateSet:Ea,previewKind:"tool",iconColor:QA(n?.toolCall??{})})},Eh=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=ku("persona-tool-bubble",t.id);if(o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=e?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&Ea.has(t.id),{summary:d,previewText:p,isActive:u}=uR(t,e),m=Lu({expandable:a,expanded:l,bubbleType:"tool"});o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let y=v("div","persona-flex persona-flex-col persona-text-left"),g=v("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let b=String(n.startedAt??Date.now()),C=()=>{let w=v("span","");return w.setAttribute("data-tool-elapsed",b),w.textContent=Hl(n),w},S=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:u,config:e??{},elapsed:Hl(n),createElapsedElement:C});typeof S=="string"&&S.trim()?(g.textContent=S,y.appendChild(g)):S instanceof HTMLElement?y.appendChild(S):(g.textContent=d,y.appendChild(g));let T=s.loadingAnimation??"none",A=o.activeTextTemplate,I=o.completeTextTemplate,M=u?A:I,O=S instanceof HTMLElement,k=(w,E)=>{g.textContent="";let H=n.name?.trim()||"tool",D=dp(w,H),G=0;for(let z of D){let K=z.styles.length>0?(()=>{let Y=v("span",z.styles.map(re=>`persona-tool-text-${re}`).join(" "));return g.appendChild(Y),Y})():g;if(z.isDuration&&u)K.appendChild(C());else{let Y=z.isDuration?Hl(n):z.text;E?G=vs(K,Y,G):K.appendChild(document.createTextNode(Y))}}};if(!O)if(u&&T!=="none"){let w=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),T==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${w}ms`),M&&k(M,!1);else if(g.classList.add(`persona-tool-loading-${T}`),g.style.setProperty("--persona-tool-anim-duration",`${w}ms`),T==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),M)k(M,!0);else{let E=g.textContent||d;g.textContent="",vs(g,E,0)}}else M&&k(M,!1);let B=QA(o),W=Pu(m,y,{expandable:a,expanded:l,iconColor:B,metaGap:!0}),V=Iu({bubble:r,previewKind:"tool",expanded:l,isActive:u,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:p,isActive:u,config:e??{}})});if(!a)return r.append(m,V),r;let R=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=l?"":"none",o.contentBackgroundColor&&(R.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(R.style.color=o.contentTextColor),o.contentPaddingX&&(R.style.paddingLeft=o.contentPaddingX,R.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(R.style.paddingTop=o.contentPaddingY,R.style.paddingBottom=o.contentPaddingY),n.name){let w=v("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?w.style.color=o.contentTextColor:o.headerTextColor&&(w.style.color=o.headerTextColor),w.textContent=n.name,R.appendChild(w)}if(n.args!==void 0){let w=v("div","persona-space-y-1"),E=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(E.style.color=o.labelTextColor),E.textContent="Arguments";let H=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",Th(H,o),H.textContent=us(n.args),w.append(E,H),R.appendChild(w)}if(n.chunks&&n.chunks.length){let w=v("div","persona-space-y-1"),E=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(E.style.color=o.labelTextColor),E.textContent="Activity";let H=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",Th(H,o),H.textContent=n.chunks.join(""),w.append(E,H),R.appendChild(w)}if(n.success===!1&&R.appendChild($("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),n.status==="complete"&&n.result!==void 0){let w=v("div","persona-space-y-1"),E=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(E.style.color=o.labelTextColor),E.textContent="Result";let H=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",Th(H,o),H.textContent=us(n.result),w.append(E,H),R.appendChild(w)}if(n.status==="complete"&&typeof n.duration=="number"){let w=v("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(w.style.color=o.contentTextColor),w.textContent=`Duration: ${n.duration}ms`,R.appendChild(w)}return Hu({expanded:l,header:m,toggleIcon:W,content:R,collapsedPreview:V,iconColor:B}),r.append(m,V,R),r};ri();oo();var{setLoader:mV,load:vR,provide:fV,getSync:CR}=$t({fallbackImport:()=>Promise.resolve().then(()=>(iM(),sM))});var aM=vR;var lM=CR;na();oo();var{setLoader:PV,load:NR}=$t({fallbackImport:()=>Promise.resolve().then(()=>(CM(),vM))});var Dh=NR;oo();wc();ti();wp();var Qh=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:$$,load:wW,provide:z$,getSync:xW}=$t({fallbackImport:()=>Promise.resolve().then(()=>(GM(),KM))}),Ha=null,qu=new Set,YM=t=>{if(Ha)return Ha;Ha=t,t.initArtifactsUi({componentRegistry:zo});for(let o of Qh)zo.has(o)||zo.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=Mo();e?t.__provideMarkdownParsers(e):ea(()=>{let o=Mo();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>Cp());let n=[...qu];qu.clear();for(let o of n)try{o()}catch{}return t};var ju=()=>wW().then(YM);var Dr=()=>{if(Ha)return Ha;let t=xW();return t?YM(t):null},Xh=t=>Ha?()=>{}:(qu.add(t),()=>{qu.delete(t)});function jn(t){return t?.features?.artifacts?.enabled===!0}function QM(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!jn(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function SW(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var XM=["panel","seamless","detached"];function Jh(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&XM.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Zh(t){return!t||!jn(t)?!1:Jh(t)==="detached"}function kc(t,e){if(!jn(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),SW(t),QM(t,e);return}let n=e.features?.artifacts?.layout,o=Jh(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?t.style.setProperty("--persona-artifact-pane-padding",s):t.style.removeProperty("--persona-artifact-pane-padding");let a=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[l,d]of a){let p=l?.trim();p?t.style.setProperty(d,p):t.style.removeProperty(d)}QM(t,e)}function Lc(t,e){for(let l of XM)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!jn(e))return;let n=e.features?.artifacts?.layout,o=Jh(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&t.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&t.style.setProperty("--persona-artifact-chat-shadow",a)}function JM(t,e){return!e||!jn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var AW=new Set(["__proto__","prototype","constructor"]),MW=new Set(["collapsed","card","panel","inline"]),ZM=new Set(["markdown","component"]),TW=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,bi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Gu=t=>!AW.has(t),ey=t=>typeof t=="string"&&MW.has(t),vi=t=>Object.keys(t).length>0;function pr(t,e,n,o){t.push({path:e,code:n,message:o})}var EW="Ignored because this key is not part of the persisted preference schema.",Ku="Ignored an unsupported value.",kW="Expected collapsed, panel, or inline.",LW='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',eT={kind:"mode",message:Ku},Ra={kind:"string",message:"Expected a CSS length string."},_r={kind:"boolean"},PW={paneWidth:Ra,paneMaxWidth:Ra,paneMinWidth:Ra,expandedPanelWidth:Ra,resizableMinWidth:Ra,resizableMaxWidth:Ra,expandLauncherPanelWhenOpen:_r,resizable:_r},IW={kind:"object",message:"Expected a preference object.",children:{showToolCalls:_r,showReasoning:_r,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Ku},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Ku},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Ku},expandable:_r,grouped:_r}},reasoningDisplay:{kind:"object",children:{expandable:_r,activePreview:_r}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:eT,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:eT,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:ZM,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:ZM}}},filePreview:{kind:"object",children:{enabled:_r}},layout:{kind:"object",children:PW}}}}};function tT(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:pr(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:pr(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:pr(o,n,"invalid_value",e.message);case"mode":return ey(t)?To(t):pr(o,n,"invalid_value",e.message);case"modeMap":{if(!bi(t))return pr(o,n,"invalid_type","Expected an object.");let r=e.keys==="mediaType"?void 0:e.keys,s={};for(let[a,l]of Object.entries(t)){let d=r?a:oa(a);Gu(a)&&(r?r.has(a):TW.test(d))?ey(l)?s[d]=To(l):pr(o,`${n}.${a}`,"invalid_value",kW):pr(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":LW)}return vi(s)?s:void 0}case"object":{if(e.bareMode&&ey(t))return To(t);if(!bi(t))return pr(o,n,"invalid_type",e.message??"Expected an object.");let r=Object.keys(e.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(t))(!Gu(l)||!r.includes(l))&&pr(o,s(l),"unknown_key",EW);let a={};for(let l of r){let d=e.children[l],p=tT(t[l],d,s(l),o);if(d.deprecated&&t[l]!==void 0&&pr(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,m=a[u];a[u]=bi(m)&&bi(p)?{...m,...p}:p}return vi(a)?a:void 0}}}function HW(t){let e=[];return{preferences:(t===null?void 0:tT(t,IW,"",e))??{},issues:e}}function Wa(t){if(Array.isArray(t))return t.map(Wa);if(!bi(t))return t;let e={};for(let[n,o]of Object.entries(t))Gu(n)&&o!==void 0&&(e[n]=Wa(o));return e}function nT(t,e){let n=Wa(t);for(let[o,r]of Object.entries(e)){if(!Gu(o)||r===void 0)continue;let s=n[o];n[o]=bi(s)&&bi(r)?nT(s,r):Wa(r)}return n}function RW(t){let e={},n;for(let r of t){let s=HW(r).preferences;n=oT(n,s.artifacts?.display),e=nT(e,s)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function WW(t,e){if(e===void 0)return t===void 0?void 0:Wa(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byMediaType,...e.byMediaType},s={...o?{default:o}:{},...vi(r)?{byMediaType:r}:{}};return vi(s)?s:void 0}function oT(t,e){if(e===void 0)return t===void 0?void 0:Wa(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byType,...n.byKind,...e.byType,...e.byKind},s=WW(n.files,e.files),a={...o?{default:o}:{},...vi(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return vi(a)?a:void 0}function BW(t={},e){let n=RW(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=t.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=oT(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function ty(t){let e=t.preferences;return!e||!vi(e)?t:{...t,features:BW(t.features??{},[e])}}function OW(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function DW(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function _W(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function NW(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function ny(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function rT(t,e,n,o,r,s,a=200){let l=OW(r,200),d=NW(e,n,o,a);d=Math.max(l,d);let p=DW(s);return p!==null&&(d=Math.min(d,p)),_W(t,l,d)}oo();var{setLoader:Z$,load:FW,provide:ez,getSync:VW}=$t({fallbackImport:()=>Promise.resolve().then(()=>(lT(),aT))});var cT=FW;var dT=VW;var oy=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...e].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},ry=new oy;var pT=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),$W=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),uT=(t,e,n)=>{if(!pT(t)||!pT(e)||$W.has(n))return e;let o={...t};for(let r of Object.keys(e)){if(e[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=uT(t[r],e[r],s)}return o};function mT(t,e){let n=uT(t,e,"");return Ep(n)}var fT=()=>{let t=new Map,e=(r,s)=>(t.has(r)||t.set(r,new Set),t.get(r).add(s),()=>n(r,s)),n=(r,s)=>{t.get(r)?.delete(s)};return{on:e,off:n,emit:(r,s)=>{t.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var zW=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},UW=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let s=e[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},iy=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=zW(t),n=UW(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},sy=t=>typeof t=="string"?t:t==null?"":String(t),Pc={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:sy(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=sy(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:sy(n.text)}}},gT=t=>Array.isArray(t)?t.map(e=>String(e)):[],ay=t=>{let e=new Set(gT(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(gT(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?t.parsers.reduce((p,u)=>p||u?.({text:a,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let d={action:l,message:s.message};t.emit("action:detected",d);for(let p of t.handlers)if(p)try{let u=()=>{t.emit("action:resubmit",d)},m=p(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});if(!m)continue;if(m.handled){let y=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:y,resubmit:m.resubmit}}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var qW=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},jW=t=>t.map(e=>({...e,streaming:!1})),KW=t=>t.map(e=>({...e,status:"complete"})),hT=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?qW(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?jW(n.messages):void 0,artifacts:n.artifacts?KW(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var GW=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},yT=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return GW(t)},YW=async(t,e)=>{let n=await yT(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await yT(`${t}\0${e}`)}`}};var bT=(t,e,n)=>{let o="",r="",s="",a=!1,l=!1,d=0,p=null,u=null,m=new Set,y=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},g=()=>{let k=y();if(!k)return p;try{return k.getItem(o)}catch{return a=!0,p}},b=(k,B)=>{if(l||k===p)return;let W=p;p=k,d+=1;let V={previousToken:W,token:k,source:B,revision:d};for(let R of m)R(V)},C=k=>{l||k.key!==null&&k.key!==o||b(k.key===null?null:k.newValue??null,"external")},S=(async()=>{let k=await YW(t,e);o=k.storageKey,r=k.leaseKey,s=k.lockName,p=g(),!n&&typeof window<"u"&&window.addEventListener("storage",C)})(),T=k=>new Promise(B=>setTimeout(B,k)),A=()=>{let k=y();if(!k)return null;try{let B=k.getItem(r);if(!B)return null;let W=JSON.parse(B);return typeof W?.expiresAt=="number"&&typeof W?.ownerNonce=="string"?W:null}catch{return null}},I=k=>{let B=y();if(B)try{A()?.ownerNonce===k&&B.removeItem(r)}catch{}},M=k=>new Promise(B=>{let W=setTimeout(V,k);function V(){clearTimeout(W),window.removeEventListener("storage",R),B()}function R(w){(w.key===null||w.key===r)&&V()}window.addEventListener("storage",R)}),O=async k=>{let B=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,W=Date.now()+15e3;for(;Date.now()<W;){let V=y();if(!V)break;let R=Date.now(),w=A();if(w&&w.expiresAt>R&&w.ownerNonce!==B){await M(Math.min(w.expiresAt-R,500));continue}try{V.setItem(r,JSON.stringify({ownerNonce:B,expiresAt:R+1e4}))}catch{a=!0;break}if(await T(20+Math.random()*40),A()?.ownerNonce!==B){await M(500);continue}u=B;try{return await k()}finally{u=null,I(B)}}return k()};return{ready:S,async get(){return await S,b(g(),"external"),p},async set(k){await S;let B=y();if(B)try{B.setItem(o,k)}catch{a=!0}b(k,"local")},async clear(){await S;let k=y();if(k)try{k.removeItem(o)}catch{a=!0}b(null,"local")},revision(){return d},subscribe(k){return m.add(k),()=>{m.delete(k)}},async withFirstInitLock(k){await S;let B=globalThis.navigator?.locks;return B?.request?B.request(s,()=>k()):y()?O(k):k()},matches(k,B,W){return k===t&&B===e&&W===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",C),u&&I(u)}}};oo();var{setLoader:$z,load:wB}=$t({fallbackImport:()=>Promise.resolve().then(()=>(BT(),WT))});var by=wB;var vy=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},Nr=t=>Object.freeze({...t}),OT=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),DT=t=>t?Nr(t):null;function _T(t){let{plugins:e,config:n}=t,o=!1,r=!1,s=!1,a=!1,l=null,d=[],p=()=>{for(let M of d.splice(0))try{M()}catch(O){vy("renderHistoryView cleanup",O)}},u=(M,O)=>{for(let k of e){let B=k[M];if(B)try{let W=B(O);if(W)return W}catch(W){vy(M,W)}}return null},m=()=>({presentation:t.getPresentation(),config:n}),y={header:M=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:t.getReturnSurface(),identityStatus:Nr(M.identityStatus),pendingAction:DT(M.pendingAction),copy:Nr(M.copy),actions:Object.freeze({close:C.close,startNewConversation:C.startNewConversation}),defaultRenderer:M.defaultRenderer})):null,conversation:M=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:OT(M.conversation),active:M.active,pending:M.pending,open:M.open,requestDelete:M.requestDelete,defaultRenderer:M.defaultRenderer})):null,state:M=>a?u("renderHistoryState",Object.freeze({...m(),state:Nr(M.state),identityStatus:Nr(M.identityStatus),copy:Nr(M.copy),...M.retry?{retry:M.retry}:{},...M.startNewConversation?{startNewConversation:M.startNewConversation}:{},defaultRenderer:M.defaultRenderer})):null},g=e.flatMap(M=>(M.railSections??[]).map(O=>({...O,placement:O.placement??"above-conversations",items:[],render:k=>O.render(Object.freeze({collapsed:k,presentation:t.getPresentation(),actions:C}))}))),b=t.createView({slots:y,renderDom:!1,onModelChange:()=>I(),railSections:g}),C=Object.freeze({...b.operations,close:t.close}),S=()=>(a=!0,b.setDomRenderEnabled(!0),b.element),T=M=>Object.freeze({conversations:Object.freeze(M.conversations.map(OT)),activeConversationId:M.activeConversationId,state:Nr(M.state),pendingAction:DT(M.pendingAction),identityStatus:Nr(M.identityStatus),nextCursor:M.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:Nr(b.copy),actions:C,defaultRenderer:S,requestRender:()=>I(),onCleanup:O=>{d.push(O)}}),A=()=>{a=!1;let M=null;for(let k of e)if(k.renderHistoryView){try{M=k.renderHistoryView(T(b.getModel()))}catch(B){vy("renderHistoryView",B),M=null}if(M)break}let O=!M||M.contains(b.element);return a=O,b.setDomRenderEnabled(O),M??b.element};function I(){if(!(!s||o||r)){r=!0;try{p();let M=A();if(M===l)return;let O=l;l=M,t.onElementChanged(M,O)}finally{r=!1}}}return s=!0,I(),{view:b,get element(){return l??b.element},requestRender:I,dispose:()=>{o=!0,p()}}}var xB=null;function NT(){return xB}_l();var SB=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),AB=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),Cy=t=>AB.get(t)??"Conversation history is unavailable right now.";function MB(t){if(t instanceof ir)return t;if(t instanceof at){let e=SB.get(t.code)??"unavailable";return new ir(e,Cy(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new ir("unavailable",Cy("unavailable"))}function FT(t){let e=()=>t.getClient?.()??t.client,n=t.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},r=l=>{if(!n.includes(l))throw new ir("unsupported_scope",Cy("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw MB(p)}},a=l=>{let d=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){d||(d=!0,l.commit(),await t.onActivationCommitted(l.session))},discard(){d||(d=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return e().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return e().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return e().subscribeHistoryAvailability(l)},async list(l){return s(l.context.scope,async()=>{let d=await e().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(l,d){return s(d.context.scope,async()=>{let p=await e().getConversation(l,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),u=ww(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:Bl([],u),conversationRevision:p.conversationRevision??"",nextCursor:p.nextMessageCursor}})},async prepareOpen(l,d){return s(d.context.scope,async()=>a(await e().prepareConversationSession(l)))},async prepareStartNew(l){return s(l.context.scope,async()=>a(await e().prepareNewConversationSession()))},async delete(l,d){await s(d.context.scope,()=>e().deleteConversation(l,{scope:d.context.scope}))},async deleteAll(l){return s(l.context.scope,()=>e().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await e().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}cy();Ye();var TB="button:not([disabled])";function em(t){let e=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=$("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),a=$("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=$("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},$("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),$("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),$("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,a));for(let p of[s,a])p.style.minHeight="44px",p.style.minWidth="88px",p.style.padding="0 16px",p.style.borderRadius="var(--persona-radius-md, 0.5rem)",p.style.cursor="pointer",p.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",a.style.border="none",a.style.background="var(--persona-danger, #b42318)",a.style.color="var(--persona-danger-fg, #ffffff)";let d=$("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(p=>{let u=!1,m=g=>{u||(u=!0,d.removeEventListener("keydown",y,!0),d.remove(),e?.focus(),p(g))};function y(g){if(g.key==="Escape"){g.preventDefault(),g.stopPropagation(),m(!1);return}if(g.key!=="Tab")return;let b=Array.from(l.querySelectorAll(TB));if(b.length===0)return;let C=b[0],S=b[b.length-1],T=document.activeElement;g.shiftKey&&(T===C||!l.contains(T))?(g.preventDefault(),S.focus()):!g.shiftKey&&T===S&&(g.preventDefault(),C.focus())}d.addEventListener("keydown",y,!0),d.addEventListener("pointerdown",g=>{g.target===d&&m(!1)}),s.addEventListener("click",()=>m(!1)),a.addEventListener("click",()=>m(!0)),t.host.appendChild(d),s.focus()})}wc();wc();var wy=require("partial-json");Ye();function VT(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=zo.get(t.component);if(!s){if(Qh.includes(t.component)){ju().catch(()=>{});let l=v("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null}let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(t.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function $T(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function xy(t){let e=$T(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function zT(t){let e=$T(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var EB=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function UT(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:p=EB}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,y=document.createElement("div");y.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,g.appendChild(b);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),y.appendChild(g);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let k=1;k<=5;k++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-star-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`${k} star${k>1?"s":""}: ${p[k-1]}`),B.title=p[k-1],B.dataset.rating=String(k),B.innerHTML=`
1166
+ `,n.addEventListener("click",e);let o=s=>{let a=s.launcher??{},l=nn(s),c=Iu(s)==="circle";c?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",a.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let p=n.querySelector("[data-role='launcher-title']");if(p){let A=a.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let u=n.querySelector("[data-role='launcher-subtitle']");if(u){let A=a.subtitle??"Here to help you get answers fast";u.textContent=A,u.setAttribute("title",A)}let m=n.querySelector(".persona-flex-col");m&&(a.textHidden||l||c?m.style.display="none":m.style.display="");let g=n.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let A=a.agentIconSize??"40px";if(g.style.height=A,g.style.width=A,a.agentIconBackgroundColor?(g.style.backgroundColor=a.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",a.agentIconName){let D=parseFloat(A)||24,W=ke(a.agentIconName,D*.6,"var(--persona-text-inverse, #ffffff)",1.5);W?(g.appendChild(W),g.style.display=""):(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}let h=n.querySelector("[data-role='launcher-image']");if(h){let A=a.agentIconSize??"40px";h.style.height=A,h.style.width=A,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(h.src=a.iconUrl,h.style.display="block"):h.style.display="none"}let b=n.querySelector("[data-role='launcher-call-to-action-icon']");if(b){let A=a.callToActionIconSize??"32px";b.style.height=A,b.style.width=A,a.callToActionIconBackgroundColor?(b.style.backgroundColor=a.callToActionIconBackgroundColor,b.classList.remove("persona-bg-persona-primary")):(b.style.backgroundColor="",b.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(b.style.color=a.callToActionIconColor,b.classList.remove("persona-text-persona-call-to-action")):(b.style.color="",b.classList.add("persona-text-persona-call-to-action"));let D=0;if(a.callToActionIconPadding?(b.style.boxSizing="border-box",b.style.padding=a.callToActionIconPadding,D=(parseFloat(a.callToActionIconPadding)||0)*2):(b.style.boxSizing="",b.style.padding=""),a.callToActionIconHidden||c)b.style.display="none";else if(b.style.display=l?"none":"",b.innerHTML="",a.callToActionIconName){let W=parseFloat(A)||24,U=Math.max(W-D,8),B=ke(a.callToActionIconName,U,"currentColor",1.5);B?b.appendChild(B):b.textContent=a.callToActionIconText??"\u2197"}else b.textContent=a.callToActionIconText??"\u2197"}let C=a.position&&vo[a.position]?vo[a.position]:vo["bottom-right"],M="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?E:`${M} ${C}`,l||(n.style.zIndex=String(a.zIndex??On));let T="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",H="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:H,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:r}},EW="teaser-dismissed",ZM=new Set,JM=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${EW}`},kW=(t,e)=>{if(ZM.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},PW=(t,e)=>{if(ZM.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},LW=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,IW=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||nn(t??{})?null:e},eT=(t,e)=>{let n=v("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=t??{},r=null,s=null,a=null,l=null,c=null,p=!1,u=!1,m=!1,g=!1,h=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,b=()=>{c!==null&&(clearTimeout(c),c=null)},C=()=>{!s||!p||(p=!1,s.hidden=!0)},M=G=>{b(),m=!0,C(),PW(JM(o),G&&h())},E=G=>{!r||m||M(G==="user"&&p)},T=()=>{c=null,!(!s||m||g)&&(u=!0,p=!0,s.hidden=!1,!(LW()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},H=()=>{!r||!s||m||u||g||kW(JM(o),h())||(b(),c=setTimeout(T,Math.max(0,r.delayMs??0)))},A=()=>{M(h()),e()},D=G=>{G.stopPropagation(),M(h())},U=fy(t,()=>{E("user"),e()}),B=()=>{b(),l?.removeEventListener("click",A),a?.removeEventListener("click",D),s?.remove(),s=null,l=null,a=null,p=!1},O=()=>{l=F("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",A),a=F("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",D),s=F("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,U.element)},R=()=>{let G=o.launcher?.position??"bottom-right",V=vo[G]??vo["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",U.element.style.position="";return}n.className=Gt("persona-launcher-surface",V),n.setAttribute("data-teaser",G),n.style.zIndex=String(o.launcher?.zIndex??On),U.element.style.position="static"},S=G=>{let V=IW(G);if(r=V,!V){B();return}s||O(),l.textContent=V.text,a.hidden=V.dismissible===!1,a.setAttribute("aria-label",V.dismissLabel??"Dismiss message"),H()},x=G=>{o=G,U.update(G),S(G),R()},P=(G,V="user")=>{g=G,G&&E(V)},L=()=>{B(),U.destroy(),n.remove()};return n.appendChild(U.element),t&&(S(t),R()),{element:n,launcher:U,get teaser(){return s?{element:s,show:T,dismiss:M}:null},setPanelOpen:P,update:x,destroy:L}};var tT=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=YM(t),s=XM(t,e),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},c={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},p={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:l,header:c,composer:p,replaceHeader:g=>(c.element.replaceWith(g.header),c.element=g.header,c.iconHolder=g.iconHolder,c.headerTitle=g.headerTitle,c.headerSubtitle=g.headerSubtitle,c.closeButton=g.closeButton,c.closeButtonWrapper=g.closeButtonWrapper,c.clearChatButton=g.clearChatButton,c.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{p.footer.replaceWith(g),p.footer=g}}},gy=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>fy(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=eT(t,n);return{instance:r,element:r.element}};var RW=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},HW=(t,e,n)=>`${RW(t)}plugin:${e}:${n}`,nT=t=>{let e=new Map,n=!1,o=()=>{if(n||t()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=a=>HW(t(),r,a);return{get:a=>{let l=s(a),c=o();if(c)try{return c.getItem(l)}catch{n=!0}return e.get(l)??null},set:(a,l)=>{let c=s(a),p=o();if(p)try{p.setItem(c,l);return}catch{n=!0}e.set(c,l)},remove:a=>{let l=s(a);e.delete(l);let c=o();if(c)try{c.removeItem(l)}catch{n=!0}}}}};je();Zt();Ts();rm();var WW=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
1167
+ `):""},hy=(t,e,n)=>{Mp(t,e,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},yy=(t,e,n=new Set)=>{e=Ep(e,"reasoning");let o=t.reasoning,r=wp("persona-reasoning-bubble",t.id);if(!o)return Vr(r,t,e,"reasoning");let s=e?.features?.reasoningDisplay??{},a=s.expandable??wi.expandable,l=a&&n.has(t.id),c=o.status!=="complete",p=WW(t,s.previewMaxLines??wi.previewMaxLines),u=xp({expandable:a,expanded:l,bubbleType:"reasoning"}),m=v("div","persona-flex persona-flex-col persona-text-left"),g=v("span","persona-text-xs persona-text-persona-primary"),h=vs(e,"reasoning")==="row",b=h&&!c?`Thought for ${Vl(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",C=e?.reasoning??{},M=String(o.startedAt??Date.now()),E=()=>{let V=v("span","");return V.setAttribute("data-tool-elapsed",M),V.textContent=$p(o),V},T=C.renderCollapsedSummary?.({message:t,reasoning:o,defaultSummary:b,previewText:p,isActive:c,config:e??{},elapsed:$p(o),createElapsedElement:E});typeof T=="string"&&T.trim()?(g.textContent=T,m.appendChild(g)):T instanceof HTMLElement?m.appendChild(T):(g.textContent=b,m.appendChild(g));let H=v("span","persona-text-xs persona-text-persona-primary");H.textContent=yx(o),h||m.appendChild(H);let A=s.loadingAnimation??wi.loadingAnimation,D=C.activeTextTemplate,W=C.completeTextTemplate,U=c?D:W,B=T instanceof HTMLElement,O=(V,K)=>{g.textContent="";let ee=zp(V,""),oe=0;for(let ne of ee){let le=ne.styles.length>0?(()=>{let de=v("span",ne.styles.map(ve=>`persona-tool-text-${ve}`).join(" "));return g.appendChild(de),de})():g;if(ne.isDuration&&c)le.appendChild(E());else{let de=ne.isDuration?$p(o):ne.text;K?oe=Hs(le,de,oe):le.appendChild(document.createTextNode(de))}}};if(!B&&U)if(H.style.display="none",g.style.display="",c&&A!=="none"){let V=C.loadingAnimationDuration??2e3;g.setAttribute("data-preserve-animation","true"),A==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${V}ms`),O(U,!1)):(g.classList.add(`persona-tool-loading-${A}`),g.style.setProperty("--persona-tool-anim-duration",`${V}ms`),A==="shimmer-color"&&(C.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",C.loadingAnimationColor),C.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",C.loadingAnimationSecondaryColor)),O(U,!0))}else O(U,!1);else if(!B&&c&&A!=="none"){g.style.display="";let V=C.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),A==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{g.classList.add(`persona-tool-loading-${A}`),g.style.setProperty("--persona-tool-anim-duration",`${V}ms`),A==="shimmer-color"&&(C.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",C.loadingAnimationColor),C.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",C.loadingAnimationSecondaryColor));let K=g.textContent||b;g.textContent="",Hs(g,K,0)}o.status==="complete"&&!h&&(g.style.display="none")}else B||(o.status==="complete"&&!h?g.style.display="none":g.style.display="");if(s.iconName&&!B){let V=v("span","persona-reasoning-header-icon"),K=ke(s.iconName,16,"currentColor",2);K&&(V.appendChild(K),u.appendChild(V))}let R="currentColor",S=wa(u,m,{expandable:a,expanded:l,iconColor:R,metaGap:!1}),x=Sp({bubble:r,previewKind:"reasoning",expanded:l,isActive:c,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:o,defaultPreview:p,isActive:c,config:e??{}})});if(!a)return r.append(u,x),Vr(r,t,e,"reasoning");let P=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");P.style.display=l?"":"none";let L=o.chunks.join(""),G=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return G.textContent=L||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),P.appendChild(G),Ap({expanded:l,header:u,toggleIcon:S,content:P,collapsedPreview:x,iconColor:R}),r.append(u,x,P),Vr(r,t,e,"reasoning")};je();Ts();Zt();var oT=t=>{if(t==null)return!0;if(typeof t=="string"){if(!t.trim())return!0;try{return oT(JSON.parse(t))}catch{return!1}}return typeof t=="object"&&Object.keys(t).length===0},BW=t=>{if(t!==null&&typeof t=="object")return!0;if(typeof t!="string")return!1;try{let e=JSON.parse(t);return e!==null&&typeof e=="object"}catch{return!1}};function rT(t,e,n){let o=e.toolCall;if(!o)return;let r=n.toolCall??{},s=(l,c)=>{let p=F("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":l.toLowerCase()},style:{backgroundColor:r.codeBlockBackgroundColor,borderColor:r.codeBlockBorderColor,borderWidth:r.codeBlockBorderColor?"1px":void 0}}),u=F("div",{className:"persona-tool-detail-label",text:l,style:{color:r.labelTextColor}}),m=mr(c),g=F("pre",{className:`persona-tool-detail-value${BW(c)?" persona-tool-detail-code":""}`,text:m,attrs:m.length>420||m.split(`
1168
+ `).length>7?{tabindex:"0","aria-label":`${l} content`}:{},style:{color:r.codeBlockTextColor??r.contentTextColor}}),h=F("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),b=ke("copy",14,"currentColor",1.7);b&&h.appendChild(b),p.append(u,g,h),t.appendChild(p)};oT(o.args)||s("Request",o.args);let a=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");a!==void 0&&(typeof a!="string"||a.trim())&&s("Response",a),o.success===!1&&t.appendChild(F("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var by=new WeakMap;async function sT(t){let e=t.closest("[data-persona-tool-detail]"),n=e?.querySelector("pre");if(!n)return;let o=`Copy ${e?.getAttribute("data-persona-tool-detail")}`;clearTimeout(by.get(t));try{await navigator.clipboard.writeText(n.textContent??""),t.dataset.copied="true",t.setAttribute("aria-label","Copied"),t.title="Copied";let r=ke("check",14,"currentColor",2);r&&t.replaceChildren(r)}catch{t.setAttribute("aria-label","Copy failed \u2014 try again"),t.title="Copy failed \u2014 try again"}by.set(t,setTimeout(()=>{delete t.dataset.copied,t.setAttribute("aria-label",o),t.title=o;let r=ke("copy",14,"currentColor",1.7);r&&t.replaceChildren(r),by.delete(t)},1800))}je();Ts();rm();var iT=(t,e=!1)=>t.toggleTextColor||t.headerTextColor||(e?"currentColor":"var(--persona-primary, #171717)"),DW=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-e).join(`
1169
+ `);let r=mr(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
1170
+ `):""},vy=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},OW=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??Fr.collapsedMode,s=n?.success===!1?n.error||"Tool failed":DW(t,o?.previewMaxLines??Fr.previewMaxLines),a=n?vs(e,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:vx(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",c=e?.toolCall??{},p=a;return r==="tool-name"?p=n.name?.trim()||a:r==="tool-preview"&&s&&(p=s),l&&c.activeTextTemplate?p=$g(n,c.activeTextTemplate,p):!l&&c.completeTextTemplate&&(p=$g(n,c.completeTextTemplate,p)),n.success===!1&&(p+=" \xB7 Failed"),{summary:p,previewText:s,isActive:l}},Cy=(t,e,n,o)=>{Mp(t,e,{stateSet:n,previewKind:"tool",iconColor:iT(o?.toolCall??{},e.classList.contains("persona-activity-row"))})},wy=(t,e,n=new Set)=>{e=Ep(e,"tool");let o=t.toolCall,r=e?.toolCall??{},s=wp("persona-tool-bubble",t.id);if(r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow)",!o)return Vr(s,t,e,"tool");let a=e?.features?.toolCallDisplay??{},l=a.expandable??Fr.expandable,c=l&&n.has(t.id),{summary:p,previewText:u,isActive:m}=OW(t,e),g=xp({expandable:l,expanded:c,bubbleType:"tool"});r.headerBackgroundColor&&(g.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(g.style.paddingLeft=r.headerPaddingX,g.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(g.style.paddingTop=r.headerPaddingY,g.style.paddingBottom=r.headerPaddingY);let h=v("div","persona-flex persona-flex-col persona-text-left"),b=v("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(b.style.color=r.headerTextColor);let C=String(o.startedAt??Date.now()),M=()=>{let x=v("span","");return x.setAttribute("data-tool-elapsed",C),x.textContent=Kl(o),x},E=r.renderCollapsedSummary?.({message:t,toolCall:o,defaultSummary:p,previewText:u,collapsedMode:a.collapsedMode??Fr.collapsedMode,isActive:m,config:e??{},elapsed:Kl(o),createElapsedElement:M});typeof E=="string"&&E.trim()?(b.textContent=E,h.appendChild(b)):E instanceof HTMLElement?h.appendChild(E):(b.textContent=p,h.appendChild(b));let T=a.loadingAnimation??Fr.loadingAnimation,H=r.activeTextTemplate,A=r.completeTextTemplate,D=m?H:A,W=E instanceof HTMLElement,U=(x,P)=>{b.textContent="";let L=o.name?.trim()||"tool",G=zp(x,L),V=0;for(let K of G){let ee=K.styles.length>0?(()=>{let oe=v("span",K.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return b.appendChild(oe),oe})():b;if(K.isDuration&&m)ee.appendChild(M());else{let oe=K.isDuration?Kl(o):K.text;P?V=Hs(ee,oe,V):ee.appendChild(document.createTextNode(oe))}}};if(!W)if(m&&T!=="none"){let x=r.loadingAnimationDuration??2e3;if(b.setAttribute("data-preserve-animation","true"),T==="pulse")b.classList.add("persona-tool-loading-pulse"),b.style.setProperty("--persona-tool-anim-duration",`${x}ms`),D&&U(D,!1);else if(b.classList.add(`persona-tool-loading-${T}`),b.style.setProperty("--persona-tool-anim-duration",`${x}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&b.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&b.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),D)U(D,!0);else{let P=b.textContent||p;b.textContent="",Hs(b,P,0)}}else D&&U(D,!1);let B=iT(r,vs(e,"tool")==="row"),O=wa(g,h,{expandable:l,expanded:c,iconColor:B,metaGap:!0}),R=Sp({bubble:s,previewKind:"tool",expanded:c,isActive:m,previewText:u,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>r.renderCollapsedPreview?.({message:t,toolCall:o,defaultPreview:u,isActive:m,config:e??{}})});if(!l)return s.append(g,R),Vr(s,t,e,"tool");let S=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(S.style.display=c?"":"none",r.contentBackgroundColor&&(S.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(S.style.color=r.contentTextColor),r.contentPaddingX&&(S.style.paddingLeft=r.contentPaddingX,S.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(S.style.paddingTop=r.contentPaddingY,S.style.paddingBottom=r.contentPaddingY),e.future?.v5Defaults===!0)rT(S,t,e);else{if(o.name){let x=v("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?x.style.color=r.contentTextColor:r.headerTextColor&&(x.style.color=r.headerTextColor),x.textContent=o.name,S.appendChild(x)}if(o.args!==void 0){let x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Arguments";let L=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",vy(L,r),L.textContent=mr(o.args),x.append(P,L),S.appendChild(x)}if(o.chunks&&o.chunks.length){let x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Activity";let L=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",vy(L,r),L.textContent=o.chunks.join(""),x.append(P,L),S.appendChild(x)}if(o.success===!1&&S.appendChild(F("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Result";let L=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",vy(L,r),L.textContent=mr(o.result),x.append(P,L),S.appendChild(x)}if(o.status==="complete"&&typeof o.duration=="number"){let x=v("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(x.style.color=r.contentTextColor),x.textContent=`Duration: ${o.duration}ms`,S.appendChild(x)}}return Ap({expanded:c,header:g,toggleIcon:O,content:S,collapsedPreview:R,iconColor:B}),s.append(g,R,S),Vr(s,t,e,"tool")};Ts();ro();var{setLoader:bz,load:UW,provide:vz,getSync:qW}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(gT(),fT))});var hT=UW;var yT=qW;Aa();ro();var{setLoader:Bz,load:dB}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(PT(),kT))});var Iy=dB;ro();Oc();Si();yp();var Uy=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:KU,load:jB,provide:GU,getSync:KB}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(oE(),nE))}),Ya=null,hm=new Set,rE=t=>{if(Ya)return Ya;Ya=t,t.initArtifactsUi({componentRegistry:Yo});for(let o of Uy)Yo.has(o)||Yo.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=Ro();e?t.__provideMarkdownParsers(e):xa(()=>{let o=Ro();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>hp());let n=[...hm];hm.clear();for(let o of n)try{o()}catch{}return t};var ym=()=>jB().then(rE);var Gr=()=>{if(Ya)return Ya;let t=KB();return t?rE(t):null},qy=t=>Ya?()=>{}:(hm.add(t),()=>{hm.delete(t)});function Kn(t){return t?.features?.artifacts?.enabled===!0}function sE(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!Kn(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function GB(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var iE=["panel","seamless","detached"];function jy(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&iE.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Ky(t){return!t||!Kn(t)?!1:jy(t)==="detached"}function Uc(t,e){if(!Kn(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),GB(t),sE(t,e);return}let n=e.features?.artifacts?.layout,o=jy(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?t.style.setProperty("--persona-artifact-pane-padding",s):t.style.removeProperty("--persona-artifact-pane-padding");let a=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[l,c]of a){let p=l?.trim();p?t.style.setProperty(c,p):t.style.removeProperty(c)}sE(t,e)}function qc(t,e){for(let l of iE)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!Kn(e))return;let n=e.features?.artifacts?.layout,o=jy(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&t.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&t.style.setProperty("--persona-artifact-chat-shadow",a)}function aE(t,e){return!e||!Kn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var YB=new Set(["__proto__","prototype","constructor"]),QB=new Set(["collapsed","card","panel","inline"]),lE=new Set(["markdown","component"]),XB=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ni=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),vm=t=>!YB.has(t),Gy=t=>typeof t=="string"&&QB.has(t),Fi=t=>Object.keys(t).length>0;function Cr(t,e,n,o){t.push({path:e,code:n,message:o})}var JB="Ignored because this key is not part of the persisted preference schema.",bm="Ignored an unsupported value.",ZB="Expected collapsed, panel, or inline.",e1='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',cE={kind:"mode",message:bm},Qa={kind:"string",message:"Expected a CSS length string."},Yr={kind:"boolean"},t1={paneWidth:Qa,paneMaxWidth:Qa,paneMinWidth:Qa,expandedPanelWidth:Qa,resizableMinWidth:Qa,resizableMaxWidth:Qa,expandLauncherPanelWhenOpen:Yr,resizable:Yr},n1={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Yr,showReasoning:Yr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:bm},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:bm},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:bm},expandable:Yr,grouped:Yr}},reasoningDisplay:{kind:"object",children:{expandable:Yr,activePreview:Yr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:cE,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:cE,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:lE,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:lE}}},filePreview:{kind:"object",children:{enabled:Yr}},layout:{kind:"object",children:t1}}}}};function dE(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Cr(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Cr(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Cr(o,n,"invalid_value",e.message);case"mode":return Gy(t)?Ho(t):Cr(o,n,"invalid_value",e.message);case"modeMap":{if(!Ni(t))return Cr(o,n,"invalid_type","Expected an object.");let r=e.keys==="mediaType"?void 0:e.keys,s={};for(let[a,l]of Object.entries(t)){let c=r?a:Ma(a);vm(a)&&(r?r.has(a):XB.test(c))?Gy(l)?s[c]=Ho(l):Cr(o,`${n}.${a}`,"invalid_value",ZB):Cr(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":e1)}return Fi(s)?s:void 0}case"object":{if(e.bareMode&&Gy(t))return Ho(t);if(!Ni(t))return Cr(o,n,"invalid_type",e.message??"Expected an object.");let r=Object.keys(e.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(t))(!vm(l)||!r.includes(l))&&Cr(o,s(l),"unknown_key",JB);let a={};for(let l of r){let c=e.children[l],p=dE(t[l],c,s(l),o);if(c.deprecated&&t[l]!==void 0&&Cr(o,s(l),"deprecated_key",c.deprecated),p===void 0)continue;let u=c.alias??l,m=a[u];a[u]=Ni(m)&&Ni(p)?{...m,...p}:p}return Fi(a)?a:void 0}}}function o1(t){let e=[];return{preferences:(t===null?void 0:dE(t,n1,"",e))??{},issues:e}}function Xa(t){if(Array.isArray(t))return t.map(Xa);if(!Ni(t))return t;let e={};for(let[n,o]of Object.entries(t))vm(n)&&o!==void 0&&(e[n]=Xa(o));return e}function pE(t,e){let n=Xa(t);for(let[o,r]of Object.entries(e)){if(!vm(o)||r===void 0)continue;let s=n[o];n[o]=Ni(s)&&Ni(r)?pE(s,r):Xa(r)}return n}function r1(t){let e={},n;for(let r of t){let s=o1(r).preferences;n=uE(n,s.artifacts?.display),e=pE(e,s)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function s1(t,e){if(e===void 0)return t===void 0?void 0:Xa(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byMediaType,...e.byMediaType},s={...o?{default:o}:{},...Fi(r)?{byMediaType:r}:{}};return Fi(s)?s:void 0}function uE(t,e){if(e===void 0)return t===void 0?void 0:Xa(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byType,...n.byKind,...e.byType,...e.byKind},s=s1(n.files,e.files),a={...o?{default:o}:{},...Fi(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Fi(a)?a:void 0}function i1(t={},e){let n=r1(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=t.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=uE(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Yy(t){let e=t.preferences;return!e||!Fi(e)?t:{...t,features:i1(t.features??{},[e])}}function a1(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function l1(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function c1(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function d1(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function Qy(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function mE(t,e,n,o,r,s,a=200){let l=a1(r,200),c=d1(e,n,o,a);c=Math.max(l,c);let p=l1(s);return p!==null&&(c=Math.min(c,p)),c1(t,l,c)}ro();var{setLoader:rq,load:p1,provide:sq,getSync:u1}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(yE(),hE))});var bE=p1;var vE=u1;var Xy=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...e].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},Jy=new Xy;var CE=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),m1=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),wE=(t,e,n)=>{if(!CE(t)||!CE(e)||m1.has(n))return e;let o={...t};for(let r of Object.keys(e)){if(e[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=wE(t[r],e[r],s)}return o};function xE(t,e){let n=up(Ci),o=gw(t,e,n),r=hg(hw(wE(t,e,""),n,o),o);return vg(gp(r),bw(t,e))}var SE=()=>{let t=new Map,e=(r,s)=>(t.has(r)||t.set(r,new Set),t.get(r).add(s),()=>n(r,s)),n=(r,s)=>{t.get(r)?.delete(s)};return{on:e,off:n,emit:(r,s)=>{t.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var f1=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},g1=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let s=e[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},eb=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=f1(t),n=g1(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Zy=t=>typeof t=="string"?t:t==null?"":String(t),jc={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Zy(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Zy(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Zy(n.text)}}},AE=t=>Array.isArray(t)?t.map(e=>String(e)):[],tb=t=>{let e=new Set(AE(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(AE(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?t.parsers.reduce((p,u)=>p||u?.({text:a,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let c={action:l,message:s.message};t.emit("action:detected",c);for(let p of t.handlers)if(p)try{let u=()=>{t.emit("action:resubmit",c)},m=p(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var h1=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},y1=t=>t.map(e=>({...e,streaming:!1})),b1=t=>t.map(e=>({...e,status:"complete"})),ME=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?h1(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?y1(n.messages):void 0,artifacts:n.artifacts?b1(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var v1=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},TE=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return v1(t)},C1=async(t,e)=>{let n=await TE(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await TE(`${t}\0${e}`)}`}};var EE=(t,e,n)=>{let o="",r="",s="",a=!1,l=!1,c=0,p=null,u=null,m=new Set,g=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},h=()=>{let W=g();if(!W)return p;try{return W.getItem(o)}catch{return a=!0,p}},b=(W,U)=>{if(l||W===p)return;let B=p;p=W,c+=1;let O={previousToken:B,token:W,source:U,revision:c};for(let R of m)R(O)},C=W=>{l||W.key!==null&&W.key!==o||b(W.key===null?null:W.newValue??null,"external")},M=(async()=>{let W=await C1(t,e);o=W.storageKey,r=W.leaseKey,s=W.lockName,p=h(),!n&&typeof window<"u"&&window.addEventListener("storage",C)})(),E=W=>new Promise(U=>setTimeout(U,W)),T=()=>{let W=g();if(!W)return null;try{let U=W.getItem(r);if(!U)return null;let B=JSON.parse(U);return typeof B?.expiresAt=="number"&&typeof B?.ownerNonce=="string"?B:null}catch{return null}},H=W=>{let U=g();if(U)try{T()?.ownerNonce===W&&U.removeItem(r)}catch{}},A=W=>new Promise(U=>{let B=setTimeout(O,W);function O(){clearTimeout(B),window.removeEventListener("storage",R),U()}function R(S){(S.key===null||S.key===r)&&O()}window.addEventListener("storage",R)}),D=async W=>{let U=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,B=Date.now()+15e3;for(;Date.now()<B;){let O=g();if(!O)break;let R=Date.now(),S=T();if(S&&S.expiresAt>R&&S.ownerNonce!==U){await A(Math.min(S.expiresAt-R,500));continue}try{O.setItem(r,JSON.stringify({ownerNonce:U,expiresAt:R+1e4}))}catch{a=!0;break}if(await E(20+Math.random()*40),T()?.ownerNonce!==U){await A(500);continue}u=U;try{return await W()}finally{u=null,H(U)}}return W()};return{ready:M,async get(){return await M,b(h(),"external"),p},async set(W){await M;let U=g();if(U)try{U.setItem(o,W)}catch{a=!0}b(W,"local")},async clear(){await M;let W=g();if(W)try{W.removeItem(o)}catch{a=!0}b(null,"local")},revision(){return c},subscribe(W){return m.add(W),()=>{m.delete(W)}},async withFirstInitLock(W){await M;let U=globalThis.navigator?.locks;return U?.request?U.request(s,()=>W()):g()?D(W):W()},matches(W,U,B){return W===t&&U===e&&B===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",C),u&&H(u)}}};ro();var{setLoader:Yq,load:j1}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(UE(),zE))});var ub=j1;var mb=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},Qr=t=>Object.freeze({...t}),qE=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),jE=t=>t?Qr(t):null;function KE(t){let{plugins:e,config:n}=t,o=!1,r=!1,s=!1,a=!1,l=null,c=[],p=()=>{for(let A of c.splice(0))try{A()}catch(D){mb("renderHistoryView cleanup",D)}},u=(A,D)=>{for(let W of e){let U=W[A];if(U)try{let B=U(D);if(B)return B}catch(B){mb(A,B)}}return null},m=()=>({presentation:t.getPresentation(),config:n}),g={header:A=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:t.getReturnSurface(),identityStatus:Qr(A.identityStatus),pendingAction:jE(A.pendingAction),copy:Qr(A.copy),actions:Object.freeze({close:C.close,startNewConversation:C.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:qE(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>a?u("renderHistoryState",Object.freeze({...m(),state:Qr(A.state),identityStatus:Qr(A.identityStatus),copy:Qr(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},h=e.flatMap(A=>(A.railSections??[]).map(D=>({...D,placement:D.placement??"above-conversations",items:[],render:W=>D.render(Object.freeze({collapsed:W,presentation:t.getPresentation(),actions:C}))}))),b=t.createView({slots:g,renderDom:!1,onModelChange:()=>H(),railSections:h}),C=Object.freeze({...b.operations,close:t.close}),M=()=>(a=!0,b.setDomRenderEnabled(!0),b.element),E=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(qE)),activeConversationId:A.activeConversationId,state:Qr(A.state),pendingAction:jE(A.pendingAction),identityStatus:Qr(A.identityStatus),nextCursor:A.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:Qr(b.copy),actions:C,defaultRenderer:M,requestRender:()=>H(),onCleanup:D=>{c.push(D)}}),T=()=>{a=!1;let A=null;for(let W of e)if(W.renderHistoryView){try{A=W.renderHistoryView(E(b.getModel()))}catch(U){mb("renderHistoryView",U),A=null}if(A)break}let D=!A||A.contains(b.element);return a=D,b.setDomRenderEnabled(D),A??b.element};function H(){if(!(!s||o||r)){r=!0;try{p();let A=T();if(A===l)return;let D=l;l=A,t.onElementChanged(A,D)}finally{r=!1}}}return s=!0,H(),{view:b,get element(){return l??b.element},requestRender:H,dispose:()=>{o=!0,p()}}}var K1=null;function GE(){return K1}Zl();var G1=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),Y1=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),fb=t=>Y1.get(t)??"Conversation history is unavailable right now.";function Q1(t){if(t instanceof gr)return t;if(t instanceof it){let e=G1.get(t.code)??"unavailable";return new gr(e,fb(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new gr("unavailable",fb("unavailable"))}function YE(t){let e=()=>t.getClient?.()??t.client,n=t.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},r=l=>{if(!n.includes(l))throw new gr("unsupported_scope",fb("unsupported_scope"))},s=async(l,c)=>{r(l);try{return await c()}catch(p){throw Q1(p)}},a=l=>{let c=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){c||(c=!0,l.commit(),await t.onActivationCommitted(l.session))},discard(){c||(c=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return e().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return e().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return e().subscribeHistoryAvailability(l)},async list(l){return s(l.context.scope,async()=>{let c=await e().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:c.data,nextCursor:c.nextCursor}})},async getPage(l,c){return s(c.context.scope,async()=>{let p=await e().getConversation(l,{...c.cursor?{messageCursor:c.cursor}:{},scope:c.context.scope}),u=Hx(p.messages,{...c.beforeCreatedAt?{beforeCreatedAt:c.beforeCreatedAt}:{}});return{summary:p.summary,messages:Ql([],u),conversationRevision:p.conversationRevision??"",nextCursor:p.nextMessageCursor}})},async prepareOpen(l,c){return s(c.context.scope,async()=>a(await e().prepareConversationSession(l)))},async prepareStartNew(l){return s(l.context.scope,async()=>a(await e().prepareNewConversationSession()))},async delete(l,c){await s(c.context.scope,()=>e().deleteConversation(l,{scope:c.context.scope}))},async deleteAll(l){return s(l.context.scope,()=>e().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await e().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}ob();je();var X1="button:not([disabled])";function Mm(t){let e=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=F("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),a=F("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=F("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},F("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),F("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),F("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,a));for(let p of[s,a])p.style.minHeight="44px",p.style.minWidth="88px",p.style.padding="0 16px",p.style.borderRadius="var(--persona-radius-md, 0.5rem)",p.style.cursor="pointer",p.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",a.style.border="none",a.style.background="var(--persona-danger, #b42318)",a.style.color="var(--persona-danger-fg, #ffffff)";let c=F("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(p=>{let u=!1,m=h=>{u||(u=!0,c.removeEventListener("keydown",g,!0),c.remove(),e?.focus(),p(h))};function g(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),m(!1);return}if(h.key!=="Tab")return;let b=Array.from(l.querySelectorAll(X1));if(b.length===0)return;let C=b[0],M=b[b.length-1],E=document.activeElement;h.shiftKey&&(E===C||!l.contains(E))?(h.preventDefault(),M.focus()):!h.shiftKey&&E===M&&(h.preventDefault(),C.focus())}c.addEventListener("keydown",g,!0),c.addEventListener("pointerdown",h=>{h.target===c&&m(!1)}),s.addEventListener("click",()=>m(!1)),a.addEventListener("click",()=>m(!0)),t.host.appendChild(c),s.focus()})}Oc();Oc();var gb=require("partial-json");je();function QE(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=Yo.get(t.component);if(!s){if(Uy.includes(t.component)){ym().catch(()=>{});let l=v("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null}let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(t.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function XE(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function hb(t){let e=XE(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function JE(t){let e=XE(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var J1=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ZE(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:c=!0,ratingLabels:p=J1}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,h.appendChild(b);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,h.appendChild(C),g.appendChild(h);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let W=1;W<=5;W++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-star-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${p[W-1]}`),U.title=p[W-1],U.dataset.rating=String(W),U.innerHTML=`
1170
1171
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1171
1172
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
1172
1173
  </svg>
1173
- `,B.addEventListener("click",()=>{m=k,T.forEach((W,V)=>{let R=V<k;W.classList.toggle("selected",R),W.setAttribute("aria-checked",V===k-1?"true":"false")})}),T.push(B),S.appendChild(B)}y.appendChild(S);let A=null;if(d){let k=document.createElement("div");k.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=s,A.rows=3,A.setAttribute("aria-label","Additional comments"),k.appendChild(A),y.appendChild(k)}let I=document.createElement("div");I.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=l,M.addEventListener("click",()=>{n?.(),u.remove()});let O=document.createElement("button");return O.type="button",O.className="persona-feedback-btn persona-feedback-btn-submit",O.textContent=a,O.addEventListener("click",async()=>{if(m===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let k=A?.value.trim()||void 0;await e(m,k),u.remove()}catch(k){O.disabled=!1,O.textContent=a,console.error("[CSAT Feedback] Failed to submit:",k)}}),I.appendChild(M),I.appendChild(O),y.appendChild(I),u.appendChild(y),u}function qT(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:p="Not likely",highLabel:u="Very likely"}=t,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let y=null,g=document.createElement("div");g.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,b.appendChild(C);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,b.appendChild(S),g.appendChild(b);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let I=document.createElement("span");I.className="persona-feedback-label-low",I.textContent=p;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=u,A.appendChild(I),A.appendChild(M);let O=document.createElement("div");O.className="persona-feedback-numbers";let k=[];for(let w=0;w<=10;w++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-number-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`Rating ${w} out of 10`),E.textContent=String(w),E.dataset.rating=String(w),w<=6?E.classList.add("persona-feedback-detractor"):w<=8?E.classList.add("persona-feedback-passive"):E.classList.add("persona-feedback-promoter"),E.addEventListener("click",()=>{y=w,k.forEach((H,D)=>{H.classList.toggle("selected",D===w),H.setAttribute("aria-checked",D===w?"true":"false")})}),k.push(E),O.appendChild(E)}T.appendChild(A),T.appendChild(O),g.appendChild(T);let B=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=s,B.rows=3,B.setAttribute("aria-label","Additional comments"),w.appendChild(B),g.appendChild(w)}let W=document.createElement("div");W.className="persona-feedback-actions";let V=document.createElement("button");V.type="button",V.className="persona-feedback-btn persona-feedback-btn-skip",V.textContent=l,V.addEventListener("click",()=>{n?.(),m.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(y===null){O.classList.add("persona-feedback-shake"),setTimeout(()=>O.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let w=B?.value.trim()||void 0;await e(y,w),m.remove()}catch(w){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",w)}}),W.appendChild(V),W.appendChild(R),g.appendChild(W),m.appendChild(g),m}var Ba="persona-chat-history",PB=30*1e3,IB=641,Oa="data-persona-composer-reason",HB={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function RB(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){e.push(r);continue}let s=HB[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function tm(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function WB(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function BB(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Sy=t=>!t||typeof t!="object"?{}:{...t},jT=t=>t.map(e=>({...e,streaming:!1})),KT=(t,e,n)=>{let o=t?.markdown?Qd(t.markdown):null,r=Jd(t?.sanitize);t?.postprocessMessage&&r&&t?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let s=!1,a=l=>{let d=l.text??"",p=l.message.rawContent??null;if(e){let y=e.process({text:d,raw:p??d,message:l.message,streaming:l.streaming});y!==null&&(d=y.text,y.persist||(l.message.__skipPersist=!0),y.resubmit&&!l.streaming&&n&&n())}let u=Mo()!==null,m;if(t?.postprocessMessage){let y=t.postprocessMessage({...l,text:d,raw:p??l.text??""});m=r?r(y):y}else if(o){let y=l.streaming?AC(d):d,g=o(y);m=r&&u?r(g):g}else m=Pr(d);return m};return l=>{try{return a(l)}catch(d){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",d)),Pr(l.text??"")}}};function GT(t){let e=v("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",s=t?.iconStrokeWidth??.5,a=Ie(n,o,r,s);if(a&&e.appendChild(a),t?.label){let l=v("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var OB=(t,e)=>{let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];n[o]=s?{...s,...r}:r}return n},DB=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:OB(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),YT=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=Ep(e),r=()=>{ix({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=ty(o);let a=ry.getForInstance(o.plugins),l=FS(t),d=[],p=!1,u=GA(()=>o),m=null,y=null,g=null,b=!1,C=null,S=i=>{m=i,i.initApprovalUi({webMcpToolTitle:Zd});let c=i.createBuiltInApprovalPlugin();y=c.plugin,g=c.teardown},T=()=>{if(m)return m;let i=lM();return i?(S(i),i):(aM().then(c=>{b||m||(S(c),C?.())}).catch(()=>{}),null)},A=!1,I=!1,M=null,O=(i,c,f,h)=>{if(!i.querySelector("[data-tv-form]"))return;let x=dT();if(x){x.enhanceWithForms(i,c,f,h);return}cT().then(()=>{A||I||!M||(I=!0,M())}).catch(()=>{})};o.components&&zo.registerAll(o.components);let k=fT(),W=o.persistState===!1?null:o.storageAdapter??hT(),V=!!o.clientToken&&typeof o.reconnectStream!="function",R={},w=null,E,H=new Promise(i=>{E=i}),D,G=!1,z=i=>{if(o.onStateLoaded)try{let c=o.onStateLoaded(i);if(c&&typeof c=="object"&&"state"in c){let{state:f,open:h}=c;return h&&(G=!0),f}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(W?.load)try{let i=W.load();if(i&&typeof i.then=="function")w=i.then(c=>z(c??{messages:[],metadata:{}}));else{let f=z(i??{messages:[],metadata:{}});f.metadata&&(R=Sy(f.metadata)),f.messages?.length&&(o={...o,initialMessages:f.messages}),f.artifacts?.length&&(o={...o,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),D=f.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=z({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}w||E();let K=()=>R,Y=i=>{R=i({...R})??{},Wi()},re=o.actionParsers&&o.actionParsers.length?o.actionParsers:[iy],oe=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Pc.message,Pc.messageAndClick],se=ay({parsers:re,handlers:oe,getSessionMetadata:K,updateSessionMetadata:Y,emit:k.emit,documentRef:typeof document<"u"?document:null});se.syncFromMetadata();let ce=o.launcher?.enabled??!0,we=o.launcher?.autoExpand??!1,ge=o.autoFocusInput??!1,N=we,ye=ce,ke=o.layout?.header?.layout,nt=!1,Ee=()=>pc(o),Ne=()=>ce||Ee(),Pe=Ee()?!1:ce?we:!0,dt=!1,Xe=null,xt=()=>{dt=!0,Xe&&clearTimeout(Xe),Xe=setTimeout(()=>{dt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),dt=!1)},1e4)},Ge=KT(o,se,xt),yt=o.features?.showReasoning??!0,X=o.features?.showToolCalls??!0,P=o.features?.showEventStreamToggle??!1,j=o.features?.scrollToBottom??{},J=o.features?.scrollBehavior??{},Q=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Me=`${Q()}event-stream`,Te=null,Fe=o.features?.eventStream?.maxEvents??2e3,je=null,lt=null,ot=null,Je=!1,mt=null,Tt=!1,ee=null,Oe=0,$e=(i,c)=>{je?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},pt=(i,c)=>{lt?.processEvent(i,c),je?$e(i,c):ot&&(ot.length>=Fe&&ot.shift(),ot.push({type:i,payload:c}))},_t=()=>{je||!P||(ot??(ot=[]),Dh().then(i=>{if(Je||je||!P)return;Te=new i.EventStreamStore(Me),je=new i.EventStreamBuffer(Fe,Te),lt=lt??new i.ThroughputTracker,Te.open().then(()=>je?.restore()).catch(f=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let c=ot??[];ot=null;for(let f of c)lt?.processEvent(f.type,f.payload),$e(f.type,f.payload)}).catch(()=>{}))};P&&_t();let ve=!1,Se=null,Ke=()=>{},ut=()=>{},vn=()=>{},Cn=()=>{},wn=()=>{},Wt=()=>Tt||ve&&Se==="panel",St={onCopy:i=>{k.emit("message:copy",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{k.emit("message:feedback",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.messageId,i.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(i)}},Et=o.statusIndicator??{},sn=i=>i==="idle"?Et.idleText??fn.idle:i==="connecting"?Et.connectingText??fn.connecting:i==="connected"?Et.connectedText??fn.connected:i==="error"?Et.errorText??fn.error:i==="paused"?Et.pausedText??fn.paused:i==="resuming"?Et.resumingText??fn.resuming:fn[i];function Rn(i,c,f,h){if(!i.hasAttribute(Oa))if(h==="idle"&&f.idleLink){i.textContent="";let x=document.createElement("a");x.href=f.idleLink,x.target="_blank",x.rel="noopener noreferrer",x.textContent=c,x.style.color="inherit",x.style.textDecoration="none",i.appendChild(x)}else i.textContent=c}let tn=KA({config:o,showClose:Ne()}),{wrapper:it,panel:_e,pillRoot:Kt}=tn.shell,Ze=tn.panelElements,{container:Le,body:ie,messagesWrapper:Re,starterSuggestions:wi,transcriptSuggestions:Vr,suggestions:Io,textarea:Ae,sendButton:Ve,composerForm:Wn,statusText:bt,welcomeHost:an,welcomeIconHolder:_a,greetingHost:kn,introKicker:Na,introTitle:om,introSubtitle:rm,closeButton:F,iconHolder:le,headerTitle:Be,headerSubtitle:et,header:he,footer:We,actionsRow:Uo}=Ze,qo=Ze.leftActions,$r=Ze.rightActions,jo=Ze.sendButtonWrapper,Py=Ze.setSendButtonMode,fe=Ze.micButton,io=Ze.micButtonWrapper,Gt=Ze.attachmentButton,Kn=Ze.attachmentButtonWrapper,zt=Ze.attachmentInput,Gn=Ze.attachmentPreviewsContainer;Le.classList.add("persona-relative"),ie.classList.add("persona-relative");let lE=12,Fa=()=>j.label??"",cE=()=>j.iconName??"arrow-down",dE=()=>j.enabled!==!1,ao=()=>J.mode??"anchor-top",zr=()=>ao()==="follow"||ao()==="anchor-top"&&Qa,Va=()=>J.anchorTopOffset??16,pE=()=>J.restorePosition??"bottom",Iy=()=>J.pauseOnInteraction===!0,Hy=()=>J.showActivityWhilePinned!==!1,Ry=()=>J.announce===!0,sm=()=>J.scrollbar??"on-scroll",ln=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");ln.type="button",ln.style.display="none",ln.setAttribute("data-persona-scroll-to-bottom","true");let $a=v("span","persona-flex persona-items-center"),im=v("span",""),As=v("span","");As.setAttribute("data-persona-scroll-to-bottom-count",""),As.style.display="none",ln.append($a,im,As),Le.appendChild(ln);let ho=v("div","persona-stream-anchor-spacer");ho.setAttribute("aria-hidden","true"),ho.setAttribute("data-persona-anchor-spacer",""),ho.style.flexShrink="0",ho.style.pointerEvents="none",ho.style.height="0px",ho.style.display="none",ie.appendChild(ho);let mr=v("div","persona-sr-only");mr.setAttribute("aria-live","polite"),mr.setAttribute("aria-atomic","true"),mr.setAttribute("role","status"),mr.setAttribute("data-persona-live-region",""),Object.assign(mr.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Le.appendChild(mr);let za=null,Dc=null,_c=i=>{!Ry()||!i||(Dc=i,za===null&&(za=setTimeout(()=>{za=null,Dc&&Ry()&&(mr.textContent=Dc),Dc=null},400)))},Nc="empty",Fc=0,am=()=>Fc||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Ms=()=>{let c=We.style.display==="none"?0:We.offsetHeight;ln.style.bottom=`${c+am()+lE}px`};Ms();let lm=()=>{Ti||(We.style.marginBottom=Fc>0?`${Fc}px`:"")},Vc=()=>{let i=Gg(o,Ee()),c=Br(o),h=We.style.display==="none"?0:We.offsetHeight,x=c.anchor==="center"&&Nc==="empty"?ec(c.anchorComposerTop)??ec("44%"):null,L=x===null||Ee()?0:DS({columnHeight:Le.clientHeight,footerHeight:h,fraction:x});t.style.setProperty("--persona-composer-overlay-height",`${h}px`),t.style.setProperty("--persona-composer-lift",`${i==="overlay"?L:0}px`),Fc=i==="block"?L:0,lm(),Ms()},Wy=()=>{let i=!!Fa();ln.setAttribute("aria-label",Fa()||"Jump to latest"),ln.title=Fa(),ln.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),$a.innerHTML="";let c=Ie(cE(),"14px","currentColor",2);c?($a.appendChild(c),$a.style.display=""):$a.style.display="none",im.textContent=Fa(),im.style.display=i?"":"none"};Wy();let At=null,nn=null,ze=ex(),uE=i=>{try{Le.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};ze.subscribe(uE);let Ko=()=>{ze.setText(Ae?.value??"")},Ts=()=>{ze.setMentionRefs(nn?.getMentionRefs()??[])},mE=i=>({id:i.id,name:i.file.name,mimeType:i.file.type,size:i.file.size,status:i.status,progress:i.progress,error:i.error}),By=i=>{let c=Object.freeze(i.map(mE));ze.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}Bm()};ze.setSelectedModelId(o.composer?.selectedModelId);let Ua=()=>o.composer?.modes??[],xi=()=>Ix(Ua(),o.composer?.modeGroups);{let i=$p(o.composer?.defaultActiveModeIds??[],Ua());i.length&&ze.setActiveModeIds(i)}function Oy(i){if(ze.getState().selectedModelId!==i){ze.setSelectedModelId(i),Ur?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function $c(i){ze.setActiveModeIds(i),fr?.render(i,xi()),Si.forEach(c=>c.repaint()),Yo?.resolve(),md(),Ho()}function cm(i){$c(Hx(ze.getState().activeModeIds,i,Ua(),o.composer?.modeGroups))}let Ur=null,dm=null,fr=null,Si=new Map,qr=null;function Go(i){ze.setQuote(i),qr?.render(ze.getState().quote),Ho(),kb()}let Dy=!1;function pm(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!Dy&&o.debug===!0&&(Dy=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let jr=null;function Ai(i){ze.setPendingSubmission(i),jr?.render(ze.getState().pendingSubmission),Ho()}let fE=i=>{let c=Si.get(i);if(c)return c;let f=Bx({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(h=>h.id===i),getModes:()=>Ua().filter(h=>h.groupId===i),getActiveIds:()=>ze.getState().activeModeIds,onSelect:h=>cm(h)});return Si.set(i,f),f},gE=()=>{let i=[],c=ze.getState().activeModeIds,f=new Set;if(Ua().forEach((h,x)=>{if(Vp(h.groupId,o.composer?.modeGroups)){let L=h.groupId;if(f.has(L))return;f.add(L);let q=fE(L);q.action.order=Ig(x),q.action.label=o.composer?.modeGroups?.find(te=>te.id===L)?.label??L,i.push(q.action);return}i.push({id:Lx(h.id),kind:"button",placement:"start",order:Ig(x),presentation:h.presentation??"auto",label:h.label,shortLabel:h.shortLabel,iconName:h.iconName,pressed:c.includes(h.id),onSelect:()=>cm(h.id)})}),o.composer?.models?.length&&!a.some(h=>h.renderComposer)){let h=o.composer?.modelPicker?.presentation??"native";(!Ur||dm!==h)&&(dm=h,Ur=Ex({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>ze.getState().selectedModelId,onSelect:x=>Oy(x),presentation:h,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(Ur.action)}return i},um=null,_y=a.find(i=>i.renderHeader);if(_y?.renderHeader){let i=_y.renderHeader({config:o,defaultRenderer:()=>{let c=li({config:o,showClose:Ne()});return mc(Le,c,o),c.header},onClose:()=>Nt(!1,"user")});if(i){let c=he;c&&(c.replaceWith(i),he=i,tn.header.element=i)}}let Ny=()=>{mt&&(ie.style.display="none",We.parentNode?.insertBefore(mt.element,We),mt.update())},mm=()=>{if(!je){_t();return}if(Tt=!0,mt?Ny():Dh().then(c=>{mt||!Tt||!je||(mt=c.createEventStreamView({buffer:je,getFullHistory:()=>je.getAllFromStore(),onClose:()=>Mi(),config:o,plugins:a,getThroughput:()=>lt?.getMetric()??{status:"idle"},renderIconByName:Ie}),Ny())}).catch(()=>{Mi()}),kt){kt.style.boxShadow=`inset 0 0 0 1.5px ${Un.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(f=>f&&kt.classList.add(f))}let i=()=>{if(!Tt)return;let c=Date.now();c-Oe>=200&&(mt?.update(),Oe=c),ee=requestAnimationFrame(i)};Oe=0,ee=requestAnimationFrame(i),yn(),k.emit("eventStream:opened",{timestamp:Date.now()})},Mi=()=>{if(Tt){if(Tt=!1,mt&&mt.element.remove(),ie.style.display="",kt){kt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&kt.classList.remove(c))}ee!==null&&(cancelAnimationFrame(ee),ee=null),yn(),k.emit("eventStream:closed",{timestamp:Date.now()})}},kt=null;if(P){let i=o.features?.eventStream?.classNames,c="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");kt=v("button",c),kt.style.width="28px",kt.style.height="28px",kt.style.color=Un.actionIconColor,kt.type="button",kt.setAttribute("aria-label","Event Stream"),kt.title="Event Stream";let f=Qe(Fr.Activity,"18px","currentColor",1.5);f&&kt.appendChild(f);let h=Ze.clearChatButtonWrapper,x=Ze.closeButtonWrapper,L=h||x;L&&L.parentNode===he?he.insertBefore(kt,L):he.appendChild(kt),kt.addEventListener("click",()=>{Tt?Mi():mm()})}let Fy=i=>{let c=o.attachments;if(!c?.enabled)return;let f=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!f){f=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let x=i.querySelector("[data-persona-composer-form]");x?.parentNode?x.parentNode.insertBefore(f,x):i.insertBefore(f,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let x=v("input");x.type="file",x.setAttribute("data-persona-composer-attachment-input",""),x.accept=(c.allowedTypes??Hr).join(","),x.multiple=(c.maxFiles??4)>1,x.style.display="none",x.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(x)}},Ti=!1,Vy=i=>{let c=a.find(x=>x.renderComposer);if(!c?.renderComposer)return null;let f=o.composer,h=p?_.isStreaming():!1;return c.renderComposer({config:o,defaultRenderer:i,requestRender:()=>eC(),storage:u(c.id),onSubmit:x=>{!_||_.isStreaming()||Fd(x.trim(),{consumeDraft:!1})},streaming:h,disabled:h,openAttachmentPicker:()=>{Zo()||zt?.click()},models:f?.models,selectedModelId:ze.getState().selectedModelId??f?.selectedModelId,onModelChange:x=>Oy(x),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{um?.()}:void 0})},$y=Vy(()=>gc({config:o}).footer);$y&&(tn.replaceComposer($y),We=tn.composer.footer,Ti=!0);let Lt=null,hE=i=>{Wn=i.form,Ae=i.input,jo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Ve=i.sendButton),i.micButton&&(fe=i.micButton,io=i.micButton.parentElement),i.found.status&&(bt=i.found.status),i.found.suggestions&&(Io=i.found.suggestions),i.attachmentButton&&(Gt=i.attachmentButton,Kn=i.attachmentButton.parentElement),zt=i.attachmentInput??null,Gn=i.attachmentPreviews??null,i.found.actionsRow&&(Uo=i.found.actionsRow),qo=i.found.actionsStart,$r=i.found.actionsEnd};function fm(){let i=Ae;if(!i)return;let c=o.composer?.inputAttributes,f=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;Pp(i,c),f&&i.setAttribute("aria-label",f),Lp(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:ql(i)}),ux(i,kp(o.composer?.maxLines,Ee()?5:3))}let zy=i=>{Lt=nx(i,{debug:o.debug===!0}),Lt&&hE(Lt),fm()};Fy(We),zy(We),Ko();let qa=ys(o,Ee());qa&&(Re.style.maxWidth=qa,Re.style.marginLeft="auto",Re.style.marginRight="auto",Re.style.width="100%",kn.style.maxWidth=qa,kn.style.marginLeft="auto",kn.style.marginRight="auto",kn.style.width="100%",wi.style.maxWidth=qa,Vr.style.maxWidth=qa,Vr.style.marginLeft="auto",Vr.style.marginRight="auto",Vr.style.width="100%");let Uy=()=>{let i=ys(o,Ee());if(!(!i||Ee()))for(let c of[Wn,Io,Gn,bt])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};Uy();let qy=()=>{!o.attachments?.enabled||!zt||!Gn||(At?At.remountPreviews(Gn):(At=$l.fromConfig(o.attachments,By),At.setPreviewsContainer(Gn)),Lt?.addListener(zt,"change",i=>{let c=i.target;At?.handleFileSelect(c.files),c.value=""}),Le.querySelector(".persona-attachment-drop-overlay")||Le.appendChild(GT(o.attachments.dropOverlay)))};qy();let yE=()=>nn?.prefetch(),jy=()=>{if(!o.contextMentions?.enabled||!Ae)return;let i=Lt?.header??null,c=i?Pg(i):void 0;if(nn=PS({config:o,textarea:Ae,anchor:Wn??Ae,getMessages:()=>_.getMessages(),liveRegionHost:Le,chipRow:c}),nn&&!c){let f=Ae;f.parentElement?.insertBefore(nn.contextRow,f)}};jy();let Yo=null,bE={getState:()=>ze.getState(),getValue:()=>Ae?.value??"",setValue:i=>{Ae&&(Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Ko())},submit:()=>{jl(Lt?.form??null)},openAttachmentPicker:()=>{Zo()||zt?.click()},toggleVoice:()=>{um?.()},requestRender:()=>Yo?.resolve()},vE=()=>{let i=[];return(nn?.affordanceButtons??[]).forEach((f,h)=>{i.push({id:`core:mention-${h}`,placement:"start",order:lr.mention+h,element:f,managed:!0})}),Kn&&i.push({id:"core:attachment",placement:"start",order:lr.attachment,element:Kn}),io&&i.push({id:"core:mic",placement:"end",order:lr.mic,element:io}),jo&&i.push({id:"core:send",placement:"end",order:lr.send,element:jo}),i},Ky=()=>{Yo?.destroy(),Yo=Ax({getBindings:()=>Lt,collect:()=>({builtIns:vE(),configActions:[...gE(),...o.composer?.actions??[]],plugins:a,contributionContext:{config:o,getState:()=>ze.getState(),requestRender:()=>Yo?.resolve()},debug:o.debug===!0}),actionContext:bE,getState:()=>ze.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),Yo.resolve()};Ky();let gm=()=>{if(fr?.destroy(),fr=null,!xi().length)return;let i=Lt?.header;i&&(fr=kx({row:Pg(i),onRemove:c=>cm(c),initialIds:ze.getState().activeModeIds}),fr.render(ze.getState().activeModeIds,xi()))};gm();let Gy=()=>{qr?.destroy(),qr=null,jr?.destroy(),jr=null;let i=Lt?.header;i&&(qr=Ox({onDismiss:()=>Go(void 0)}),i.appendChild(qr.element),qr.render(ze.getState().quote),pm()==="defer-one"&&(jr=Dx({onEdit:()=>Kk(),onRemove:()=>Ai(void 0)}),i.appendChild(jr.element),jr.render(ze.getState().pendingSubmission)))};Gy();let hm=zx(),CE=()=>{let i=Lt?.header?.querySelector(Lg);if(i)return i.childElementCount>0;let c=ze.getState();return c.mentionRefs.length>0||$p(c.activeModeIds,xi()).length>0},Yy=()=>!1;function Ho(){let i=ze.getState(),c=hm.observe(Ux(Ae),i.text);We.toggleAttribute("data-persona-composer-compact",$x({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:CE(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0,dictationActive:Yy()}))}function Qy(){o.composer?.layout==="single-row"&&!Ee()?We.setAttribute("data-persona-composer-layout","single-row"):We.removeAttribute("data-persona-composer-layout")}Qy(),ze.subscribe(()=>{Yo?.sync(),Bm(),pd(),Ho(),kb()}),pd();let Xy=!1,wE=i=>{if(Xy||o.debug!==!0)return;let c=["messages","composer"].filter(f=>i[f]);c.length&&(Xy=!0,console.warn(`[persona] layout.slots.${c.join(" and layout.slots.")} ${c.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let i=o.layout?.slots??{};wE(i);let c=h=>{switch(h){case"body-top":return ie.querySelector("[data-persona-intro-card]");case"messages":return Re;case"footer-top":return Io;case"composer":return Wn;case"footer-bottom":return bt;default:return null}},f=(h,x)=>{switch(h){case"header-left":case"header-center":case"header-right":if(h==="header-left")he.insertBefore(x,he.firstChild);else if(h==="header-right")he.appendChild(x);else{let L=he.querySelector(".persona-flex-col");L?L.parentNode?.insertBefore(x,L.nextSibling):he.appendChild(x)}break;case"body-top":{let L=ie.querySelector("[data-persona-intro-card]");L?L.replaceWith(x):ie.insertBefore(x,ie.firstChild);break}case"body-bottom":ie.appendChild(x);break;case"footer-top":Io.replaceWith(x);break;case"footer-bottom":bt.replaceWith(x);break;default:break}};for(let[h,x]of Object.entries(i))if(x)try{let L=x({config:o,defaultContent:()=>c(h)});L&&f(h,L)}catch(L){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${h}":`,L)}})();let Jy=i=>{let f=i.target.closest('button[data-expand-header="true"]');if(!f)return;let h=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!h)return;let x=h.getAttribute("data-message-id");if(!x)return;let L=f.getAttribute("data-bubble-type");if(L==="reasoning")Ta.has(x)?Ta.delete(x):Ta.add(x),YA(x,h);else if(L==="tool")Ea.has(x)?Ea.delete(x):Ea.add(x),XA(x,h,o);else if(L==="approval"&&m){let te=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Z=m.approvalDetailsExpansionState.get(x)??te;m.approvalDetailsExpansionState.set(x,!Z),m.updateApprovalDetailsUI(x,h,o)}cn.delete(x)};Re.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Jy(i))}),Re.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Jy(i))}),Re.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let f=Re.getRootNode(),h=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!h||h.isCollapsed)return;let x=h.toString(),L=$S(x);!L||L===x||(c.setData("text/plain",L),i.preventDefault())});let ym=new Map,Zy=null,eb="idle",xE={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},SE=(i,c)=>{let{icon:f,label:h}=xE[c];i.setAttribute("aria-label",h),i.title=h,i.setAttribute("aria-pressed",c==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",c!=="idle"),i.classList.toggle("persona-message-action-loading",c==="loading");let x=Ie(f,14,"currentColor",2);x&&(i.innerHTML="",i.appendChild(x))},tb=()=>{Re.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let h=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;SE(c,h&&h===Zy?eb:"idle")})};Re.addEventListener("click",i=>{let f=i.target.closest(".persona-message-action-btn[data-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let h=f.closest("[data-actions-for]");if(!h)return;let x=h.getAttribute("data-actions-for");if(!x)return;let L=f.getAttribute("data-action");if(L==="copy"){let te=_.getMessages().find(Z=>Z.id===x);if(te&&St.onCopy){let Z=te.content||"";navigator.clipboard.writeText(Z).then(()=>{f.classList.add("persona-message-action-success");let ne=Qe(Fr.Check,14,"currentColor",2);ne&&(f.innerHTML="",f.appendChild(ne)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let pe=Qe(Fr.Copy,14,"currentColor",2);pe&&(f.innerHTML="",f.appendChild(pe))},2e3)}).catch(ne=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ne)}),St.onCopy(te)}}else if(L==="read-aloud")_.toggleReadAloud(x);else if(L==="upvote"||L==="downvote"){let te=(ym.get(x)??null)===L,Z=L==="upvote"?"thumbs-up":"thumbs-down";if(te){ym.delete(x),f.classList.remove("persona-message-action-active");let ne=Ie(Z,14,"currentColor",2);ne&&(f.innerHTML="",f.appendChild(ne))}else{let ne=L==="upvote"?"downvote":"upvote",pe=h.querySelector(`[data-action="${ne}"]`);if(pe){pe.classList.remove("persona-message-action-active");let Ft=Ie(ne==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ft&&(pe.innerHTML="",pe.appendChild(Ft))}ym.set(x,L),f.classList.add("persona-message-action-active");let Ce=Ie(Z,14,"currentColor",2);Ce&&(Ce.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(Ce)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let wt=_.getMessages().find(Ot=>Ot.id===x);wt&&St.onFeedback&&St.onFeedback({type:L,messageId:wt.id,message:wt})}}else if(L==="regenerate")zc?.regenerate(x);else if(L==="edit")zc?.edit(x);else if(L==="quote")zc?.quote(x);else if(L?.startsWith(xu)){let q=L.slice(xu.length),te=o.messageActions?.custom?.find(ne=>ne.id===q),Z=_.getMessages().find(ne=>ne.id===x);if(!te||!Z)return;try{te.onSelect(Z)}catch(ne){console.error(`[AgentWidget] messageActions.custom "${q}" onSelect failed:`,ne)}}});let zc=null;Re.addEventListener("click",i=>{let f=i.target.closest("button[data-approval-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let h=f.closest(".persona-approval-bubble");if(!h)return;let x=h.getAttribute("data-message-id");if(!x)return;let L=f.getAttribute("data-approval-action");if(!L)return;let q=L==="approve"?"approved":"denied",Z=_.getMessages().find(pe=>pe.id===x);if(!Z?.approval)return;let ne=h.querySelector("[data-approval-buttons]");ne&&ne.querySelectorAll("button").forEach(Ce=>{Ce.disabled=!0,Ce.style.opacity="0.5",Ce.style.cursor="not-allowed"}),Z.approval.toolType==="webmcp"?_.resolveWebMcpApproval(x,q):_.resolveApproval(Z.approval,q)});let ft=null,nb=!1,ja=null,Es=()=>{},Ka="none",Uc=null,yo={artifacts:[],selectedId:null},gr=!1,Ro=!1,Ga=!1,Ei=!1,ob=()=>Ei||yo.artifacts.some(i=>is(o.features?.artifacts,i)==="panel"),qc=()=>yo.artifacts.length>0&&!gr&&ob(),Bt={current:null},bm=(i,c)=>{let f=_.getArtifactById(c),h=f?.markdown,x=f?.title||"artifact",L=f?.file,q=f?.artifactType??"markdown";if(!h){let ne=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ne){let Ce=_.getMessages().find(He=>He.id===ne);if(Ce?.rawContent)try{let He=JSON.parse(Ce.rawContent);h=He?.props?.markdown,x=He?.props?.title||x,He?.props?.file&&typeof He.props.file=="object"&&(L=He.props.file),!f&&typeof He?.props?.artifactType=="string"&&(q=He.props.artifactType)}catch{}}}return{markdown:h,title:x,file:L,artifactType:q}};Re.addEventListener("click",i=>{let f=i.target.closest("[data-download-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let h=f.getAttribute("data-download-artifact");if(!h||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:h})===!0)return;let{markdown:L,title:q,file:te}=bm(f,h);if(!L)return;let Z=Dr();Z&&Z.triggerArtifactDownload(Z.downloadInfoFor({title:q,markdown:L,file:te}))}),Re.addEventListener("click",i=>{let f=i.target.closest("[data-artifact-custom-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let h=f.getAttribute("data-artifact-custom-action");if(!h)return;let x=f.closest("[data-artifact-inline]"),L=x?null:f.closest("[data-open-artifact]"),q=x?x.getAttribute("data-artifact-inline"):L?.getAttribute("data-open-artifact")??null,Z=(x?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(Ot=>Ot.id===h);if(!Z)return;let{markdown:ne,title:pe,file:Ce,artifactType:He}=bm(f,q??""),wt={artifactId:q,title:pe,artifactType:He,markdown:ne,file:Ce};try{Promise.resolve(Z.onClick(wt)).catch(()=>{})}catch{}}),Re.addEventListener("click",i=>{let f=i.target.closest("[data-copy-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let h=f.getAttribute("data-copy-artifact");if(!h)return;let x=_.getArtifactById(h),L=Dr();if(!L)return;let q="";if(x)q=L.artifactCopyText(x);else{let{markdown:te,file:Z,artifactType:ne}=bm(f,h);ne==="markdown"&&(q=L.artifactCopyText({id:h,artifactType:"markdown",status:"complete",markdown:te??"",...Z?{file:Z}:{}}))}q&&navigator.clipboard.writeText(q).then(()=>{let te=Qe(Fr.Check,16,"currentColor",2);te&&(f.replaceChildren(te),setTimeout(()=>{let Z=Qe(Fr.Copy,16,"currentColor",2);Z&&f.replaceChildren(Z)},1500))}).catch(()=>{})}),Re.addEventListener("click",i=>{let f=i.target.closest("[data-expand-artifact-inline]");if(!f)return;i.preventDefault(),i.stopPropagation();let h=f.getAttribute("data-expand-artifact-inline");!h||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:h})===!0||(gr=!1,Ei=!0,Ro=!0,Ga=!0,_.selectArtifact(h),Wo())}),Re.addEventListener("click",i=>{let c=i.target;if(c.closest("[data-download-artifact]")||c.closest("[data-artifact-custom-action]"))return;let f=c.closest("[data-open-artifact]");if(!f)return;let h=f.getAttribute("data-open-artifact");!h||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:h})===!0||(i.preventDefault(),i.stopPropagation(),gr=!1,Ei=!0,_.selectArtifact(h),Wo())}),Re.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let c=i.target;!c.hasAttribute("data-open-artifact")&&!c.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),c.click())});let ki=Ze.composerOverlay,Li=(i,c,f)=>{let h=c.trim();if(!h||!Bt.current)return;let x=i.getAttribute("data-tool-call-id")??"",L=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:x,answer:h,answers:f.structured,values:f.values??(f.source==="multi"?h.split(", "):[h]),isFreeText:L,source:f.source},bubbles:!0,composed:!0})),la(ki,x);let q=Bt.current.getMessages().find(te=>te.toolCall?.id===x);q?.agentMetadata?.awaitingLocalTool?Bt.current.resolveAskUserQuestion(q,f.structured??h):Bt.current.sendMessage(h)},ks=i=>{let c=Bt.current;if(!c)return;let f=i.getAttribute("data-tool-call-id")??"",h=c.getMessages().find(x=>x.toolCall?.id===f);h&&c.persistAskUserQuestionProgress(h,{answers:rp(i,h),currentIndex:Eo(i)})},rb=i=>Object.entries(i).map(([c,f])=>`${c}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),vm=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=Eo(i),f=aa(i);if(c>=f-1)return;let h=Bt.current?.getMessages().find(x=>x.toolCall?.id===i.getAttribute("data-tool-call-id"));h&&(ip(i,h,o,c+1),ks(i))};ki.addEventListener("click",i=>{let f=i.target.closest("[data-ask-user-action]");if(!f)return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;let x=f.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),x==="dismiss"){let L=h.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),la(ki,L);let q=Bt.current?.getMessages().find(te=>te.toolCall?.id===L);q?.agentMetadata?.awaitingLocalTool&&(Bt.current?.markAskUserQuestionResolved(q),Bt.current?.resolveAskUserQuestion(q,"(dismissed)"));return}if(x==="pick"){let L=f.getAttribute("data-option-label");if(!L)return;let q=h.getAttribute("data-multi-select")==="true",te=ls(h);if(te&&q){let Z=oi(h)[Eo(h)],ne=new Set(Array.isArray(Z)?Z:[]);ne.has(L)?ne.delete(L):ne.add(L),cs(h,Array.from(ne)),ks(h);return}if(te){cs(h,L),ks(h),vm(h);return}if(q){let Z=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",Z?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!Z);let ne=h.querySelector('[data-ask-user-action="submit-multi"]');ne&&(ne.disabled=Yf(h).length===0);return}Li(h,L,{source:"pick",values:[L]});return}if(x==="submit-multi"){let L=Yf(h);if(L.length===0)return;Li(h,L.join(", "),{source:"multi",values:L});return}if(x==="open-free-text"){let L=h.querySelector('[data-ask-free-text-row="true"]');L&&(L.classList.remove("persona-hidden"),L.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(x==="focus-free-text"){h.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(x==="submit-free-text"){let q=h.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!q.trim())return;if(ls(h)){cs(h,q.trim()),ks(h),vm(h);return}Li(h,q,{source:"free-text"});return}if(x==="next"||x==="back"){if(!Bt.current)return;let L=h.getAttribute("data-tool-call-id")??"",q=Bt.current.getMessages().find(Ce=>Ce.toolCall?.id===L);if(!q)return;let Z=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(Z){let Ce=oi(h)[Eo(h)];(typeof Ce!="string"||Ce!==Z)&&cs(h,Z)}let ne=x==="next"?1:-1,pe=Eo(h)+ne;ip(h,q,o,pe),ks(h);return}if(x==="submit-all"){if(!Bt.current)return;let L=h.getAttribute("data-tool-call-id")??"",q=Bt.current.getMessages().find(Ce=>Ce.toolCall?.id===L);if(!q)return;let Z=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";Z&&cs(h,Z);let ne=rp(h,q);Bt.current.persistAskUserQuestionProgress(q,{answers:ne,currentIndex:Eo(h)});let pe=rb(ne);Li(h,pe||"(submitted)",{source:"submit-all",structured:ne});return}if(x==="skip"){if(!Bt.current)return;let L=h.getAttribute("data-tool-call-id")??"",q=Bt.current.getMessages().find(He=>He.toolCall?.id===L);if(!q)return;let te=ls(h),Z=Eo(h),ne=aa(h),pe=Z>=ne-1;if(!te){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),la(ki,L),q.agentMetadata?.awaitingLocalTool&&(Bt.current.markAskUserQuestionResolved(q),Bt.current.resolveAskUserQuestion(q,"(dismissed)"));return}cs(h,"");let Ce=h.querySelector('[data-ask-free-text-input="true"]');if(Ce&&(Ce.value=""),pe){let He=rp(h,q),wt=rb(He);Li(h,wt||"(skipped)",{source:"submit-all",structured:He});return}ip(h,q,o,Z+1),ks(h);return}}),ki.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let f=i.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;i.preventDefault();let x=f.value;if(x.trim()){if(ls(h)){cs(h,x.trim()),ks(h),vm(h);return}Li(h,x,{source:"free-text"})}});let sb=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let c=i.target;if(c?.tagName==="INPUT"||c?.tagName==="TEXTAREA"||c?.isContentEditable)return;let f=ki.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let h=Number(i.key),L=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[h-1];L&&(i.preventDefault(),L.click())};document.addEventListener("keydown",sb);let Qo=null,Ut=null,Ya=null,jc=null,Kc=()=>{},ib=!1,Gc="",Yc="";function Cm(){jc?.(),jc=null}let AE=()=>{let i=$i&&Gs?.isConnected?Gs:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},ab=()=>{if(!Qo||!Ut)return;let i=t.classList.contains("persona-artifact-welded-split"),c=t.ownerDocument.defaultView??window,f=c.innerWidth<=640;if(!i||t.classList.contains("persona-artifact-narrow-host")||f){Ut.style.removeProperty("position"),Ut.style.removeProperty("left"),Ut.style.removeProperty("top"),Ut.style.removeProperty("bottom"),Ut.style.removeProperty("width"),Ut.style.removeProperty("z-index");return}let h=Qo.firstElementChild;if(!h||h===Ut)return;let x=10;Ut.style.position="absolute",Ut.style.top="0",Ut.style.bottom="0",Ut.style.width=`${x}px`,Ut.style.zIndex="5";let L=ny(Qo,c),q=h.offsetWidth+L/2-x/2;Ut.style.left=`${Math.max(0,q)}px`},Qc=()=>{},ME=()=>{let i=t.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>f?!1:ce||rn(o)},Xc=()=>!jn(o)||!qc()||t.classList.contains("persona-artifact-narrow-host")||ME()||(t.ownerDocument.defaultView??window).innerWidth<IB?"none":Zh(o)?"detached":"welded",Wo=()=>{if(!ft||!jn(o))return;kc(t,o),Lc(t,o),Qc();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=_e.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let f=qc();ft.setVisible(f),ft.update(yo),gr?(ft.setMobileOpen(!1),ft.element.classList.add("persona-hidden"),ft.backdrop?.classList.add("persona-hidden"),Ro=!1,Ga=!1):yo.artifacts.length>0&&ob()?(ft.element.classList.remove("persona-hidden"),ft.setMobileOpen(!0)):(ft.setMobileOpen(!1),ft.element.classList.add("persona-hidden"),ft.backdrop?.classList.add("persona-hidden"),Ro=!1,Ga=!1);let h=o.features?.artifacts?.layout?.showExpandToggle===!0;if(ft.setExpandToggleVisible(h),ft.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),ft.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),ft.setCustomActions(o.features?.artifacts?.toolbarActions??[]),ft.setTabFade(o.features?.artifacts?.layout?.tabFade),ft.setRenderTabBar(o.features?.artifacts?.renderTabBar),!h&&!Ga&&(Ro=!1),Ro!==ib){let L=ft.element;Ro?(Gc=L.style.width,Yc=L.style.maxWidth,L.style.removeProperty("width"),L.style.removeProperty("max-width")):(Gc&&(L.style.width=Gc),Yc&&(L.style.maxWidth=Yc),Gc="",Yc=""),ib=Ro}t.classList.toggle("persona-artifact-expanded",Ro),ft.setExpanded(Ro);let x=Xc();x!==Ka&&(Ka=x,Es()),Kc()};if(jn(o)){_e.style.position="relative";let i=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(Le),Qo=c,c.appendChild(i),_e.appendChild(c);let f=x=>{nb||ft||(ft=x.createArtifactPane(o,{onSelect:L=>Bt.current?.selectArtifact(L),onDismiss:()=>{gr=!0,Wo()},onToggleExpand:()=>{let L=!Ro,q=yo.selectedId??yo.artifacts[yo.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:q,expanded:L})!==!0&&(Ro=L,L||(Ga=!1),Wo())}}),ft.element.classList.add("persona-hidden"),c.appendChild(ft.element),ft.backdrop&&_e.appendChild(ft.backdrop),Kc(),Wo())},h=Dr();h?f(h):(Xh(()=>{let x=Dr();x&&f(x)}),ju().catch(()=>{})),Kc=()=>{if(!Qo||!ft)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Ya?.(),Ya=null,Cm(),Ut&&(Ut.remove(),Ut=null),ft.element.style.removeProperty("width"),ft.element.style.removeProperty("maxWidth");return}if(!Ut){let L=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");L.setAttribute("role","separator"),L.setAttribute("aria-orientation","vertical"),L.setAttribute("aria-label","Resize artifacts panel"),L.tabIndex=0;let q=t.ownerDocument,te=q.defaultView??window,Z=ne=>{if(!ft||ne.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||te.innerWidth<=640)return;ne.preventDefault(),Cm();let pe=ne.clientX,Ce=ft.element.getBoundingClientRect().width,He=o.features?.artifacts?.layout,wt=Ft=>{let xn=Qo.getBoundingClientRect().width,pn=t.classList.contains("persona-artifact-welded-split"),Jt=ny(Qo,te),Bn=pn?0:L.getBoundingClientRect().width||6,Mt=Ce-(Ft.clientX-pe),On=rT(Mt,xn,Jt,Bn,He?.resizableMinWidth,He?.resizableMaxWidth,AE());ft.element.style.width=`${On}px`,ft.element.style.maxWidth="none",ab()},Ot=()=>{q.removeEventListener("pointermove",wt),q.removeEventListener("pointerup",Ot),q.removeEventListener("pointercancel",Ot),jc=null;try{L.releasePointerCapture(ne.pointerId)}catch{}};jc=Ot,q.addEventListener("pointermove",wt),q.addEventListener("pointerup",Ot),q.addEventListener("pointercancel",Ot);try{L.setPointerCapture(ne.pointerId)}catch{}};L.addEventListener("pointerdown",Z),Ut=L,Qo.insertBefore(L,ft.element),Ya=()=>{L.removeEventListener("pointerdown",Z)}}if(Ut){let L=qc();Ut.classList.toggle("persona-hidden",!L),ab()}},Qc=()=>{if(!ce||!ft||(o.launcher?.sidebarMode??!1)||rn(o)&&Lo(o).reveal==="emerge")return;let L=t.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,te=o.launcher?.mobileBreakpoint??640;if(q&&L.innerWidth<=te||!JM(o,ce))return;let Z=o.launcher?.width??o.launcherWidth??Rr,ne=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";qc()?(_e.style.width=ne,_e.style.maxWidth=ne):(_e.style.width=Z,_e.style.maxWidth=Z)},typeof ResizeObserver<"u"&&(ja=new ResizeObserver(()=>{Wo()}),ja.observe(_e))}else _e.appendChild(Le);Ee()&&Kt&&(Ze.peekBanner&&Kt.appendChild(Ze.peekBanner),Kt.appendChild(We)),t.appendChild(it),Kt&&t.appendChild(Kt);let wm=()=>{if(Ee()){_e.style.width="100%",_e.style.maxWidth="100%";let st=o.launcher?.composerBar??{},Ue=it.dataset.state==="expanded",_n=st.expandedSize??"anchored";if(!(Ue&&_n!=="fullscreen")){Le.style.background="",Le.style.border="",Le.style.borderRadius="",Le.style.overflow="",Le.style.boxShadow="";return}let Zn=o.theme?.components?.panel,eo=Ca(o),Rt=(on,to)=>on==null||on===""?to:zn(eo,on)??on,Dt="1px solid var(--persona-border)",rt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Lr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Le.style.background="var(--persona-surface, #ffffff)",Le.style.border=Rt(Zn?.border,Dt),Le.style.borderRadius=Rt(Zn?.borderRadius,Lr),Le.style.boxShadow=Rt(Zn?.shadow,rt),Le.style.overflow="hidden";return}let i=rn(o),c=o.launcher?.sidebarMode??!1,f=i||c||(o.launcher?.fullHeight??!1),h=o.launcher?.enabled===!1,x=o.launcher?.detachedPanel===!0,L=o.theme?.components?.panel,q=Ca(o),te=(st,Ue)=>st==null||st===""?Ue:zn(q,st)??st,Z=t.ownerDocument.defaultView??window,ne=o.launcher?.mobileFullscreen??!0,pe=o.launcher?.mobileBreakpoint??640,Ce=Z.innerWidth<=pe,He=ne&&Ce&&ce,wt=i&&ne&&Ce,Ot=o.launcher?.position??"bottom-left",Ft=Ot==="bottom-left"||Ot==="top-left",xn=o.launcher?.zIndex??Hn,pn="var(--persona-panel-border, 1px solid var(--persona-border))",Jt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",Bn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Mt=x&&!He&&!wt;Mt?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let On=Mt?pn:c||He?"none":pn,or=Mt?Jt:He?"none":c?Ft?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":h?"none":Jt;i&&!He&&!Mt&&(or="none",On="none");let kr=Mt?Bn:c||He?"0":Bn,Do=te(L?.border,On),Sl=te(L?.shadow,or),ei=te(L?.borderRadius,kr),_o=Xc(),Ln=_o==="detached",No=_o==="welded";t.classList.toggle("persona-artifact-detached-split",Ln),t.classList.toggle("persona-artifact-welded-split",No);let Zi="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",qe=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&jn(o)&&Zh(o)&&h&&!i;t.classList.toggle("persona-artifact-chat-flush",qe);let xe=Ln||qe?"none":Sl,Zt=Ln?pn:No?"none":Do,un=Ln?Bn:ei;qe&&(Zt="none",un="0");let Pn=L?.borderRadius!=null&&L.borderRadius!=="",mn=qe&&!Pn?"0":ei,bn=ie.scrollTop;t.style.cssText="",it.style.cssText="",_e.style.cssText="",Le.style.cssText="",ie.style.cssText="",Ti||(We.style.cssText=""),Tt&&(ie.style.display="none"),(f||h)&&(t.style.minWidth="0");let en=()=>{if(bn<=0)return;(ie.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ie.scrollTop===bn)return;let Ue=ie.scrollHeight-ie.clientHeight;Ue<=0||(ie.scrollTop=Math.min(bn,Ue))})};if(He){it.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),it.style.cssText=`
1174
+ `,U.addEventListener("click",()=>{m=W,E.forEach((B,O)=>{let R=O<W;B.classList.toggle("selected",R),B.setAttribute("aria-checked",O===W-1?"true":"false")})}),E.push(U),M.appendChild(U)}g.appendChild(M);let T=null;if(c){let W=document.createElement("div");W.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=s,T.rows=3,T.setAttribute("aria-label","Additional comments"),W.appendChild(T),g.appendChild(W)}let H=document.createElement("div");H.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=l,A.addEventListener("click",()=>{n?.(),u.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=a,D.addEventListener("click",async()=>{if(m===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let W=T?.value.trim()||void 0;await e(m,W),u.remove()}catch(W){D.disabled=!1,D.textContent=a,console.error("[CSAT Feedback] Failed to submit:",W)}}),H.appendChild(A),H.appendChild(D),g.appendChild(H),u.appendChild(g),u}function e0(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:c=!0,lowLabel:p="Not likely",highLabel:u="Very likely"}=t,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=null,h=document.createElement("div");h.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,b.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,b.appendChild(M),h.appendChild(b);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let T=document.createElement("div");T.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=p;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=u,T.appendChild(H),T.appendChild(A);let D=document.createElement("div");D.className="persona-feedback-numbers";let W=[];for(let S=0;S<=10;S++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-number-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`Rating ${S} out of 10`),x.textContent=String(S),x.dataset.rating=String(S),S<=6?x.classList.add("persona-feedback-detractor"):S<=8?x.classList.add("persona-feedback-passive"):x.classList.add("persona-feedback-promoter"),x.addEventListener("click",()=>{g=S,W.forEach((P,L)=>{P.classList.toggle("selected",L===S),P.setAttribute("aria-checked",L===S?"true":"false")})}),W.push(x),D.appendChild(x)}E.appendChild(T),E.appendChild(D),h.appendChild(E);let U=null;if(c){let S=document.createElement("div");S.className="persona-feedback-comment-container",U=document.createElement("textarea"),U.className="persona-feedback-comment",U.placeholder=s,U.rows=3,U.setAttribute("aria-label","Additional comments"),S.appendChild(U),h.appendChild(S)}let B=document.createElement("div");B.className="persona-feedback-actions";let O=document.createElement("button");O.type="button",O.className="persona-feedback-btn persona-feedback-btn-skip",O.textContent=l,O.addEventListener("click",()=>{n?.(),m.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(g===null){D.classList.add("persona-feedback-shake"),setTimeout(()=>D.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let S=U?.value.trim()||void 0;await e(g,S),m.remove()}catch(S){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",S)}}),B.appendChild(O),B.appendChild(R),h.appendChild(B),m.appendChild(h),m}var Ja="persona-chat-history",tD=30*1e3,nD=641,Za="data-persona-composer-reason",oD={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function rD(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){e.push(r);continue}let s=oD[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function Tm(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function sD(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function iD(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var yb=t=>!t||typeof t!="object"?{}:{...t},t0=t=>t.map(e=>({...e,streaming:!1})),n0=(t,e,n)=>{let o=t?.markdown?Pp(t.markdown):null,r=Ip(t?.sanitize);t?.postprocessMessage&&r&&t?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let s=!1,a=l=>{let c=l.text??"",p=l.message.rawContent??null;if(e){let g=e.process({text:c,raw:p??c,message:l.message,streaming:l.streaming});g!==null&&(c=g.text,g.persist||(l.message.__skipPersist=!0),g.resubmit&&!l.streaming&&n&&n())}let u=Ro()!==null,m;if(t?.postprocessMessage){let g=t.postprocessMessage({...l,text:c,raw:p??l.text??""});m=r?r(g):g}else if(o){let g=l.streaming?Ow(c):c,h=o(g);m=r&&u?r(h):h}else m=$r(c);return m};return l=>{try{return a(l)}catch(c){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),$r(l.text??"")}}};function o0(t){let e=v("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",s=t?.iconStrokeWidth??.5,a=ke(n,o,r,s);if(a&&e.appendChild(a),t?.label){let l=v("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var aD=(t,e)=>{let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];n[o]=s?{...s,...r}:r}return n},lD=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:aD(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),r0=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=gp(e),r=new Set,s=new Set,a=Aw((i,d)=>{mn.delete(i);let f=Array.from(We.querySelectorAll("[data-message-id]")).find(y=>y.dataset.messageId===i);f&&(d==="tool"?Cy(i,f,r,o):hy(i,f,s))}),l=new Map,c=()=>{hS({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};c();let p=o.features;o=Yy(o);let u=Jy.getForInstance(o.plugins),m=KA(t),g=[],h=!1,b=nT(()=>o),C=null,M=null,E=null,T=!1,H=null,A=i=>{C=i,i.initApprovalUi({webMcpToolTitle:Rp});let d=i.createBuiltInApprovalPlugin(l);M=d.plugin,E=d.teardown},D=()=>{if(C)return C;let i=yT();return i?(A(i),i):(hT().then(d=>{T||C||(A(d),H?.())}).catch(()=>{}),null)},W=!1,U=!1,B=null,O=(i,d,f,y)=>{if(!i.querySelector("[data-tv-form]"))return;let w=vE();if(w){w.enhanceWithForms(i,d,f,y);return}bE().then(()=>{W||U||!B||(U=!0,B())}).catch(()=>{})};o.components&&Yo.registerAll(o.components);let R=SE(),x=o.persistState===!1?null:o.storageAdapter??ME(),P=!!o.clientToken&&typeof o.reconnectStream!="function",L={},G=null,V,K=new Promise(i=>{V=i}),ee,oe=!1,ne=i=>{if(o.onStateLoaded)try{let d=o.onStateLoaded(i);if(d&&typeof d=="object"&&"state"in d){let{state:f,open:y}=d;return y&&(oe=!0),f}return d}catch(d){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",d)}return i};if(x?.load)try{let i=x.load();if(i&&typeof i.then=="function")G=i.then(d=>ne(d??{messages:[],metadata:{}}));else{let f=ne(i??{messages:[],metadata:{}});f.metadata&&(L=yb(f.metadata)),f.messages?.length&&(o={...o,initialMessages:f.messages}),f.artifacts?.length&&(o={...o,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),ee=f.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=ne({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}G||V();let le=()=>L,de=i=>{L=i({...L})??{},Zi()},ve=o.actionParsers&&o.actionParsers.length?o.actionParsers:[eb],Le=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[jc.message,jc.messageAndClick],se=tb({parsers:ve,handlers:Le,getSessionMetadata:le,updateSessionMetadata:de,emit:R.emit,documentRef:typeof document<"u"?document:null});se.syncFromMetadata();let _=o.launcher?.enabled??!0,Te=o.launcher?.autoExpand??!1,He=o.autoFocusInput??!1,ut=Te,At=_,Wt=o.layout?.header?.layout,bt=!1,xe=()=>Ec(o),Ne=()=>_||xe(),Ae=xe()?!1:_?Te:!0,vt=!1,X=null,I=()=>{vt=!0,X&&clearTimeout(X),X=setTimeout(()=>{vt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),vt=!1)},1e4)},j=n0(o,se,I),J=o.features?.showReasoning??!0,Y=o.features?.showToolCalls??!0,ie=o.features?.showEventStreamToggle??!1,Me=o.features?.scrollToBottom??{},Ee=o.features?.scrollBehavior??{},Oe=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Ot=`${Oe()}event-stream`,rt=null,Ze=o.features?.eventStream?.maxEvents??2e3,ct=null,Rt=null,Z=null,Fe=!1,Re=null,nt=!1,Bt=null,Ie=0,Be=(i,d)=>{ct?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(d)})},qe=(i,d)=>{Rt?.processEvent(i,d),ct?Be(i,d):Z&&(Z.length>=Ze&&Z.shift(),Z.push({type:i,payload:d}))},Tt=()=>{ct||!ie||(Z??(Z=[]),Iy().then(i=>{if(Fe||ct||!ie)return;rt=new i.EventStreamStore(Ot),ct=new i.EventStreamBuffer(Ze,rt),Rt=Rt??new i.ThroughputTracker,rt.open().then(()=>ct?.restore()).catch(f=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let d=Z??[];Z=null;for(let f of d)Rt?.processEvent(f.type,f.payload),Be(f.type,f.payload)}).catch(()=>{}))};ie&&Tt();let mt=!1,xt=null,Mn=()=>{},ft=()=>{},_t=()=>{},Vt=()=>{},pn=()=>{},ao=()=>nt||mt&&xt==="panel",Gn={onCopy:i=>{R.emit("message:copy",i),N?.isClientTokenMode()&&N.submitMessageFeedback(i.id,"copy").catch(d=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",d)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{R.emit("message:feedback",i),N?.isClientTokenMode()&&N.submitMessageFeedback(i.messageId,i.type).catch(d=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",d)}),o.messageActions?.onFeedback?.(i)}},Zc=o.statusIndicator??{},_s=(i,d=o.statusIndicator??{})=>i==="idle"?d.idleText??dn.idle:i==="connecting"?d.connectingText??dn.connecting:i==="connected"?d.connectedText??dn.connected:i==="error"?d.errorText??dn.error:i==="paused"?d.pausedText??dn.paused:i==="resuming"?d.resumingText??dn.resuming:dn[i];function Qo(i,d,f,y){if(!xe()&&(f.mode==="transient"||i.classList.contains("persona-mb-2"))&&(Eg(i,Tn,f),xi(i,f,y)),!i.hasAttribute(Za))if(y==="idle"&&f.idleLink){i.textContent="";let w=document.createElement("a");w.href=f.idleLink,w.target="_blank",w.rel="noopener noreferrer",w.textContent=d,w.style.color="inherit",w.style.textDecoration="none",i.appendChild(w)}else i.textContent=d}let Cn=tT({config:o,showClose:Ne()}),{wrapper:dt,panel:Se,pillRoot:Nt}=Cn.shell,ot=Cn.panelElements,{container:Pe,body:pe,messagesWrapper:We,starterSuggestions:Ns,transcriptSuggestions:Xo,suggestions:lo,textarea:we,sendButton:Ve,composerForm:Tn,statusText:pt,welcomeHost:gn,welcomeIconHolder:km,greetingHost:z,introKicker:ge,introTitle:Ue,introSubtitle:at,closeButton:Ce,iconHolder:St,headerTitle:Bn,headerSubtitle:Yn,header:$e,footer:Qe,actionsRow:y0}=ot,Pm=ot.leftActions,ed=ot.rightActions,Jo=ot.sendButtonWrapper,Ab=ot.setSendButtonMode,ye=ot.micButton,co=ot.micButtonWrapper,on=ot.attachmentButton,Qn=ot.attachmentButtonWrapper,Xt=ot.attachmentInput,Xn=ot.attachmentPreviewsContainer;Pe.classList.add("persona-relative"),pe.classList.add("persona-relative");let b0=12,tl=()=>Me.label??"",v0=()=>Me.iconName??"arrow-down",C0=()=>Me.enabled!==!1,po=()=>Ee.mode??"anchor-top",Jr=()=>po()==="follow"||po()==="anchor-top"&&ul,nl=()=>Ee.anchorTopOffset??16,w0=()=>Ee.restorePosition??"bottom",Mb=()=>Ee.pauseOnInteraction===!0,Tb=()=>Ee.showActivityWhilePinned!==!1,Eb=()=>Ee.announce===!0,Lm=()=>Ee.scrollbar??"on-scroll",hn=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");hn.type="button",hn.style.display="none",hn.setAttribute("data-persona-scroll-to-bottom","true");let ol=v("span","persona-flex persona-items-center"),Im=v("span",""),Fs=v("span","");Fs.setAttribute("data-persona-scroll-to-bottom-count",""),Fs.style.display="none",hn.append(ol,Im,Fs),Pe.appendChild(hn);let Co=v("div","persona-stream-anchor-spacer");Co.setAttribute("aria-hidden","true"),Co.setAttribute("data-persona-anchor-spacer",""),Co.style.flexShrink="0",Co.style.pointerEvents="none",Co.style.height="0px",Co.style.display="none",pe.appendChild(Co);let xr=v("div","persona-sr-only");xr.setAttribute("aria-live","polite"),xr.setAttribute("aria-atomic","true"),xr.setAttribute("role","status"),xr.setAttribute("data-persona-live-region",""),Object.assign(xr.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Pe.appendChild(xr);let rl=null,td=null,nd=i=>{!Eb()||!i||(td=i,rl===null&&(rl=setTimeout(()=>{rl=null,td&&Eb()&&(xr.textContent=td),td=null},400)))},sl=()=>{let i=t.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&i.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(_||nn(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!nn(o)},Vs=()=>om(o,sl()),od="empty",rd=0,Rm=()=>rd||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,$s=()=>{let d=Qe.style.display==="none"?0:Qe.offsetHeight;hn.style.bottom=`${d+Rm()+b0}px`};$s();let Hm=()=>{ji||(Qe.style.marginBottom=rd>0?`${rd}px`:"")},sd=()=>{let i=Fh(o,xe()),d=Vs();t.setAttribute("data-persona-welcome-fullscreen",String(sl())),t.setAttribute("data-persona-welcome-layout",d.layout??"top"),t.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),t.setAttribute("data-persona-welcome-anchor",d.anchor??"bottom");let y=Qe.style.display==="none"?0:Qe.offsetHeight,w=d.anchor==="center"&&od==="empty"?hc(d.anchorComposerTop)??hc("44%"):null,k=w!==null&&d.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,q=k?getComputedStyle(pe):null,te=parseFloat(t.style.getPropertyValue("--persona-composer-overlay-height"))||0,Q=parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,re=Math.max(0,(parseFloat(q?.paddingBottom??"")||0)-(i==="overlay"?te+Q:0)),ce=k?pe.getBoundingClientRect().top-Pe.getBoundingClientRect().top:0,he=!k||gn.hidden?0:(gn.querySelector("[data-persona-welcome-plugin]")??gn).offsetHeight,De=w===null||xe()?0:k?Math.max(0,Math.round((Pe.clientHeight-ce-he-re-y)/2)):UA({columnHeight:Pe.clientHeight,footerHeight:y,fraction:w});t.style.setProperty("--persona-composer-overlay-height",`${y}px`),t.style.setProperty("--persona-composer-lift",`${i==="overlay"?De:0}px`),rd=i==="block"?De:0,Hm(),$s()},kb=()=>{let i=!!tl();hn.setAttribute("aria-label",tl()||"Jump to latest"),hn.title=tl(),hn.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),ol.innerHTML="";let d=ke(v0(),"14px","currentColor",2);d?(ol.appendChild(d),ol.style.display=""):ol.style.display="none",Im.textContent=tl(),Im.style.display=i?"":"none"};kb();let Lt=null,un=null,ze=dS(),x0=i=>{try{Pe.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};ze.subscribe(x0);let Zo=()=>{ze.setText(we?.value??"")},zs=()=>{ze.setMentionRefs(un?.getMentionRefs()??[])},S0=i=>({id:i.id,name:i.file.name,mimeType:i.file.type,size:i.file.size,status:i.status,progress:i.progress,error:i.error}),Pb=i=>{let d=Object.freeze(i.map(S0));ze.setAttachments(d);try{o.attachments?.onChange?.(d)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}cf()};ze.setSelectedModelId(o.composer?.selectedModelId);let il=()=>o.composer?.modes??[],$i=()=>_S(il(),o.composer?.modeGroups);{let i=hu(o.composer?.defaultActiveModeIds??[],il());i.length&&ze.setActiveModeIds(i)}function Lb(i){if(ze.getState().selectedModelId!==i){ze.setSelectedModelId(i),Zr?.repaint();try{o.composer?.onModelChange?.(i)}catch(d){console.error("[AgentWidget] composer.onModelChange failed:",d)}}}function id(i){ze.setActiveModeIds(i),Sr?.render(i,$i()),zi.forEach(d=>d.repaint()),tr?.resolve(),Id(),_o()}function Wm(i){id(NS(ze.getState().activeModeIds,i,il(),o.composer?.modeGroups))}let Zr=null,Bm=null,Sr=null,zi=new Map,es=null;function er(i){ze.setQuote(i),es?.render(ze.getState().quote),_o(),wv()}let Ib=!1;function Dm(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!Ib&&o.debug===!0&&(Ib=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let ts=null;function Ui(i){ze.setPendingSubmission(i),ts?.render(ze.getState().pendingSubmission),_o()}let A0=i=>{let d=zi.get(i);if(d)return d;let f=$S({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(y=>y.id===i),getModes:()=>il().filter(y=>y.groupId===i),getActiveIds:()=>ze.getState().activeModeIds,onSelect:y=>Wm(y)});return zi.set(i,f),f},M0=()=>{let i=[],d=ze.getState().activeModeIds,f=new Set;if(il().forEach((y,w)=>{if(gu(y.groupId,o.composer?.modeGroups)){let k=y.groupId;if(f.has(k))return;f.add(k);let q=A0(k);q.action.order=Ch(w),q.action.label=o.composer?.modeGroups?.find(te=>te.id===k)?.label??k,i.push(q.action);return}i.push({id:DS(y.id),kind:"button",placement:"start",order:Ch(w),presentation:y.presentation??"auto",label:y.label,shortLabel:y.shortLabel,iconName:y.iconName,pressed:d.includes(y.id),onSelect:()=>Wm(y.id)})}),o.composer?.models?.length&&!u.some(y=>y.renderComposer)){let y=o.composer?.modelPicker?.presentation??"native";(!Zr||Bm!==y)&&(Bm=y,Zr=WS({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>ze.getState().selectedModelId,onSelect:w=>Lb(w),presentation:y,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(Zr.action)}return i},Om=null,Rb=u.find(i=>i.renderHeader);if(Rb?.renderHeader){let i=Rb.renderHeader({config:o,defaultRenderer:()=>{let d=Pi({config:o,showClose:Ne()});return Pc(Pe,d,o),d.header},onClose:()=>qt(!1,"user")});if(i){let d=$e;d&&(d.replaceWith(i),$e=i,Cn.header.element=i)}}let Hb=()=>{Re&&(pe.style.display="none",Qe.parentNode?.insertBefore(Re.element,Qe),Re.update())},_m=()=>{if(!ct){Tt();return}if(nt=!0,Re?Hb():Iy().then(d=>{Re||!nt||!ct||(Re=d.createEventStreamView({buffer:ct,getFullHistory:()=>ct.getAllFromStore(),onClose:()=>qi(),config:o,plugins:u,getThroughput:()=>Rt?.getMetric()??{status:"idle"},renderIconByName:ke}),Hb())}).catch(()=>{qi()}),Ht){Ht.style.boxShadow=`inset 0 0 0 1.5px ${qn.actionIconColor}`;let d=o.features?.eventStream?.classNames?.toggleButtonActive;d&&d.split(/\s+/).forEach(f=>f&&Ht.classList.add(f))}let i=()=>{if(!nt)return;let d=Date.now();d-Ie>=200&&(Re?.update(),Ie=d),Bt=requestAnimationFrame(i)};Ie=0,Bt=requestAnimationFrame(i),xn(),R.emit("eventStream:opened",{timestamp:Date.now()})},qi=()=>{if(nt){if(nt=!1,Re&&Re.element.remove(),pe.style.display="",Ht){Ht.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(d=>d&&Ht.classList.remove(d))}Bt!==null&&(cancelAnimationFrame(Bt),Bt=null),xn(),R.emit("eventStream:closed",{timestamp:Date.now()})}},Ht=null;if(ie){let i=o.features?.eventStream?.classNames,d="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");Ht=v("button",d),Ht.style.width="28px",Ht.style.height="28px",Ht.style.color=qn.actionIconColor,Ht.type="button",Ht.setAttribute("aria-label","Event Stream"),Ht.title="Event Stream";let f=Ge(Xr.Activity,"18px","currentColor",1.5);f&&Ht.appendChild(f);let y=ot.clearChatButtonWrapper,w=ot.closeButtonWrapper,k=y||w;k&&k.parentNode===$e?$e.insertBefore(Ht,k):$e.appendChild(Ht),Ht.addEventListener("click",()=>{nt?qi():_m()})}let Wb=i=>{let d=o.attachments;if(!d?.enabled)return;let f=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!f){f=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let w=i.querySelector("[data-persona-composer-form]");w?.parentNode?w.parentNode.insertBefore(f,w):i.insertBefore(f,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let w=v("input");w.type="file",w.setAttribute("data-persona-composer-attachment-input",""),w.accept=(d.allowedTypes??Ur).join(","),w.multiple=(d.maxFiles??4)>1,w.style.display="none",w.setAttribute("aria-label",d.buttonTooltipText??"Attach files"),i.appendChild(w)}},ji=!1,Bb=i=>{let d=u.find(w=>w.renderComposer);if(!d?.renderComposer)return null;let f=o.composer,y=h?N.isStreaming():!1;return d.renderComposer({config:o,defaultRenderer:i,requestRender:()=>ZC(),storage:b(d.id),onSubmit:w=>{!N||N.isStreaming()||rp(w.trim(),{consumeDraft:!1})},streaming:y,disabled:y,openAttachmentPicker:()=>{sr()||Xt?.click()},models:f?.models,selectedModelId:ze.getState().selectedModelId??f?.selectedModelId,onModelChange:w=>Lb(w),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Om?.()}:void 0})},Db=Bb(()=>Ic({config:o}).footer);Db&&(Cn.replaceComposer(Db),Qe=Cn.composer.footer,ji=!0);let Et=null,T0=i=>{Tn=i.form,we=i.input,Jo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Ve=i.sendButton),i.micButton&&(ye=i.micButton,co=i.micButton.parentElement),i.found.status&&(pt=i.found.status),i.found.suggestions&&(lo=i.found.suggestions),i.attachmentButton&&(on=i.attachmentButton,Qn=i.attachmentButton.parentElement),Xt=i.attachmentInput??null,Xn=i.attachmentPreviews??null,i.found.actionsRow&&(y0=i.found.actionsRow),Pm=i.found.actionsStart,ed=i.found.actionsEnd};function Nm(){let i=we;if(!i)return;let d=o.composer?.inputAttributes,f=!d?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;ru(i,d),f&&i.setAttribute("aria-label",f),ou(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:rc(i)}),vS(i,nu(o.composer?.maxLines,xe()?5:3))}let Ob=i=>{Et=uS(i,{debug:o.debug===!0}),Et&&T0(Et),Nm()};Wb(Qe),Ob(Qe),Zo();let al=Is(o,xe());al&&(We.style.maxWidth=al,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",z.style.maxWidth=al,z.style.marginLeft="auto",z.style.marginRight="auto",z.style.width="100%",Ns.style.maxWidth=al,Xo.style.maxWidth=al,Xo.style.marginLeft="auto",Xo.style.marginRight="auto",Xo.style.width="100%");let _b=()=>{let i=Is(o,xe());if(!(!i||xe()))for(let d of[Tn,lo,Xn,pt])d&&(d.style.maxWidth=i,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%")};_b();let Nb=()=>{!o.attachments?.enabled||!Xt||!Xn||(Lt?Lt.remountPreviews(Xn):(Lt=oc.fromConfig(o.attachments,Pb),Lt.setPreviewsContainer(Xn)),Et?.addListener(Xt,"change",i=>{let d=i.target;Lt?.handleFileSelect(d.files),d.value=""}),Pe.querySelector(".persona-attachment-drop-overlay")||Pe.appendChild(o0(o.attachments.dropOverlay)))};Nb();let E0=()=>un?.prefetch(),Fb=()=>{if(!o.contextMentions?.enabled||!we)return;let i=Et?.header??null,d=i?vh(i):void 0;if(un=OA({config:o,textarea:we,anchor:Tn??we,getMessages:()=>N.getMessages(),liveRegionHost:Pe,chipRow:d}),un&&!d){let f=we;f.parentElement?.insertBefore(un.contextRow,f)}};Fb();let tr=null,k0={getState:()=>ze.getState(),getValue:()=>we?.value??"",setValue:i=>{we&&(we.value=i,we.dispatchEvent(new Event("input",{bubbles:!0})),Zo())},submit:()=>{sc(Et?.form??null)},openAttachmentPicker:()=>{sr()||Xt?.click()},toggleVoice:()=>{Om?.()},requestRender:()=>tr?.resolve()},P0=()=>{let i=[];return(un?.affordanceButtons??[]).forEach((f,y)=>{i.push({id:`core:mention-${y}`,placement:"start",order:yr.mention+y,element:f,managed:!0})}),Qn&&i.push({id:"core:attachment",placement:"start",order:yr.attachment,element:Qn}),co&&i.push({id:"core:mic",placement:"end",order:yr.mic,element:co}),Jo&&i.push({id:"core:send",placement:"end",order:yr.send,element:Jo}),i},Vb=()=>{tr?.destroy(),tr=IS({getBindings:()=>Et,collect:()=>({builtIns:P0(),configActions:[...M0(),...o.composer?.actions??[]],plugins:u,contributionContext:{config:o,getState:()=>ze.getState(),requestRender:()=>tr?.resolve()},debug:o.debug===!0}),actionContext:k0,getState:()=>ze.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,d)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${d.actionId}" failed:`,i)}}),tr.resolve()};Vb();let Fm=()=>{if(Sr?.destroy(),Sr=null,!$i().length)return;let i=Et?.header;i&&(Sr=BS({row:vh(i),onRemove:d=>Wm(d),initialIds:ze.getState().activeModeIds}),Sr.render(ze.getState().activeModeIds,$i()))};Fm();let $b=()=>{es?.destroy(),es=null,ts?.destroy(),ts=null;let i=Et?.header;i&&(es=zS({onDismiss:()=>er(void 0)}),i.appendChild(es.element),es.render(ze.getState().quote),Dm()==="defer-one"&&(ts=US({onEdit:()=>nP(),onRemove:()=>Ui(void 0)}),i.appendChild(ts.element),ts.render(ze.getState().pendingSubmission)))};$b();let Vm=QS(),L0=()=>{let i=Et?.header?.querySelector(bh);if(i)return i.childElementCount>0;let d=ze.getState();return d.mentionRefs.length>0||hu(d.activeModeIds,$i()).length>0};function _o(){let i=ze.getState(),d=Vm.observe(XS(we),i.text);Qe.toggleAttribute("data-persona-composer-compact",YS({text:i.text,wrapped:d,hasAttachments:i.attachments.length>0,hasChips:L0(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0}))}function zb(){o.composer?.layout==="single-row"&&!xe()?Qe.setAttribute("data-persona-composer-layout","single-row"):Qe.removeAttribute("data-persona-composer-layout")}zb(),ze.subscribe(()=>{tr?.sync(),cf(),Pd(),_o(),wv()}),Pd();let Ub=!1,I0=i=>{if(Ub||o.debug!==!0)return;let d=["messages","composer"].filter(f=>i[f]);d.length&&(Ub=!0,console.warn(`[persona] layout.slots.${d.join(" and layout.slots.")} ${d.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let i=o.layout?.slots??{};I0(i);let d=y=>{switch(y){case"body-top":return pe.querySelector("[data-persona-intro-card]");case"messages":return We;case"footer-top":return lo;case"composer":return Tn;case"footer-bottom":return pt;default:return null}},f=(y,w)=>{switch(y){case"header-left":case"header-center":case"header-right":if(y==="header-left")$e.insertBefore(w,$e.firstChild);else if(y==="header-right")$e.appendChild(w);else{let k=$e.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(w,k.nextSibling):$e.appendChild(w)}break;case"body-top":{let k=pe.querySelector("[data-persona-intro-card]");k?k.replaceWith(w):pe.insertBefore(w,pe.firstChild);break}case"body-bottom":pe.appendChild(w);break;case"footer-top":lo.replaceWith(w);break;case"footer-bottom":pt.replaceWith(w);break;default:break}};for(let[y,w]of Object.entries(i))if(w)try{let k=w({config:o,defaultContent:()=>d(y)});k&&f(y,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${y}":`,k)}})(),We.addEventListener("click",i=>{let d=i.target;if(!(d instanceof Element))return;let f=d.closest("button[data-persona-copy-tool-detail]");f&&(i.preventDefault(),i.stopPropagation(),sT(f))});let $m=i=>{let f=i.target.closest('button[data-expand-header="true"]');if(!f)return;let y=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let w=y.getAttribute("data-message-id");if(!w)return;is(),na();let k=f.getAttribute("data-bubble-type");if(y.classList.contains("persona-activity-row")){a.manual(w);let q=y.parentElement?.closest("[data-persona-tool-group]");q?.dataset.messageId&&a.manual(q.dataset.messageId)}if(k==="reasoning")s.has(w)?s.delete(w):s.add(w),hy(w,y,s);else if(k==="tool")r.has(w)?r.delete(w):r.add(w),Cy(w,y,r,o);else if(k==="approval"&&C){let te=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Q=l.get(w)??te;l.set(w,!Q),C.updateApprovalDetailsUI(w,y,o,l)}mn.delete(w)};We.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),$m(i))}),We.addEventListener("click",i=>{i.detail===0&&i.target.closest(".persona-activity-row")&&$m(i)}),We.addEventListener("keydown",i=>{let d=i.target;(i.key==="Enter"||i.key===" ")&&d.closest('button[data-expand-header="true"]')&&(i.preventDefault(),$m(i))}),We.addEventListener("copy",i=>{let{clipboardData:d}=i;if(!d)return;let f=We.getRootNode(),y=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let w=y.toString(),k=YA(w);!k||k===w||(d.setData("text/plain",k),i.preventDefault())});let zm=new Map,qb=null,jb="idle",R0={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},H0=(i,d)=>{let{icon:f,label:y}=R0[d];i.setAttribute("aria-label",y),i.title=y,i.setAttribute("aria-pressed",d==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",d!=="idle"),i.classList.toggle("persona-message-action-loading",d==="loading");let w=ke(f,14,"currentColor",2);w&&(i.innerHTML="",i.appendChild(w))},Kb=()=>{We.querySelectorAll('[data-action="read-aloud"]').forEach(d=>{let y=d.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;H0(d,y&&y===qb?jb:"idle")})};We.addEventListener("click",i=>{let f=i.target.closest(".persona-message-action-btn[data-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.closest("[data-actions-for]");if(!y)return;let w=y.getAttribute("data-actions-for");if(!w)return;let k=f.getAttribute("data-action");if(k==="copy"){let te=N.getMessages().find(Q=>Q.id===w);if(te&&Gn.onCopy){let Q=te.content||"";navigator.clipboard.writeText(Q).then(()=>{f.classList.add("persona-message-action-success");let re=Ge(Xr.Check,14,"currentColor",2);re&&(f.innerHTML="",f.appendChild(re)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let ce=Ge(Xr.Copy,14,"currentColor",2);ce&&(f.innerHTML="",f.appendChild(ce))},2e3)}).catch(re=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",re)}),Gn.onCopy(te)}}else if(k==="read-aloud")N.toggleReadAloud(w);else if(k==="upvote"||k==="downvote"){let te=(zm.get(w)??null)===k,Q=k==="upvote"?"thumbs-up":"thumbs-down";if(te){zm.delete(w),f.classList.remove("persona-message-action-active");let re=ke(Q,14,"currentColor",2);re&&(f.innerHTML="",f.appendChild(re))}else{let re=k==="upvote"?"downvote":"upvote",ce=y.querySelector(`[data-action="${re}"]`);if(ce){ce.classList.remove("persona-message-action-active");let kt=ke(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);kt&&(ce.innerHTML="",ce.appendChild(kt))}zm.set(w,k),f.classList.add("persona-message-action-active");let he=ke(Q,14,"currentColor",2);he&&(he.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(he)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let lt=N.getMessages().find(It=>It.id===w);lt&&Gn.onFeedback&&Gn.onFeedback({type:k,messageId:lt.id,message:lt})}}else if(k==="regenerate")ad?.regenerate(w);else if(k==="edit")ad?.edit(w);else if(k==="quote")ad?.quote(w);else if(k?.startsWith(Zu)){let q=k.slice(Zu.length),te=o.messageActions?.custom?.find(re=>re.id===q),Q=N.getMessages().find(re=>re.id===w);if(!te||!Q)return;try{te.onSelect(Q)}catch(re){console.error(`[AgentWidget] messageActions.custom "${q}" onSelect failed:`,re)}}});let ad=null;We.addEventListener("click",i=>{let f=i.target.closest("button[data-approval-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.closest(".persona-approval-bubble");if(!y)return;let w=y.getAttribute("data-message-id");if(!w)return;let k=f.getAttribute("data-approval-action");if(!k)return;let q=k==="approve"?"approved":"denied",Q=N.getMessages().find(ce=>ce.id===w);if(!Q?.approval)return;let re=y.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(he=>{he.disabled=!0,he.style.opacity="0.5",he.style.cursor="not-allowed"}),Q.approval.toolType==="webmcp"?N.resolveWebMcpApproval(w,q):N.resolveApproval(Q.approval,q)});let gt=null,Gb=!1,ll=null,Us=()=>{},cl="none",ld=null,wo={artifacts:[],selectedId:null},Ar=!1,No=!1,dl=!1,Ki=!1,Yb=()=>Ki||wo.artifacts.some(i=>Cs(o.features?.artifacts,i)==="panel"),cd=()=>wo.artifacts.length>0&&!Ar&&Yb(),Ft={current:null},Um=(i,d)=>{let f=N.getArtifactById(d),y=f?.markdown,w=f?.title||"artifact",k=f?.file,q=f?.artifactType??"markdown";if(!y){let re=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(re){let he=N.getMessages().find(De=>De.id===re);if(he?.rawContent)try{let De=JSON.parse(he.rawContent);y=De?.props?.markdown,w=De?.props?.title||w,De?.props?.file&&typeof De.props.file=="object"&&(k=De.props.file),!f&&typeof De?.props?.artifactType=="string"&&(q=De.props.artifactType)}catch{}}}return{markdown:y,title:w,file:k,artifactType:q}};We.addEventListener("click",i=>{let f=i.target.closest("[data-download-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-download-artifact");if(!y||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:y})===!0)return;let{markdown:k,title:q,file:te}=Um(f,y);if(!k)return;let Q=Gr();Q&&Q.triggerArtifactDownload(Q.downloadInfoFor({title:q,markdown:k,file:te}))}),We.addEventListener("click",i=>{let f=i.target.closest("[data-artifact-custom-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-artifact-custom-action");if(!y)return;let w=f.closest("[data-artifact-inline]"),k=w?null:f.closest("[data-open-artifact]"),q=w?w.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,Q=(w?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(It=>It.id===y);if(!Q)return;let{markdown:re,title:ce,file:he,artifactType:De}=Um(f,q??""),lt={artifactId:q,title:ce,artifactType:De,markdown:re,file:he};try{Promise.resolve(Q.onClick(lt)).catch(()=>{})}catch{}}),We.addEventListener("click",i=>{let f=i.target.closest("[data-copy-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-copy-artifact");if(!y)return;let w=N.getArtifactById(y),k=Gr();if(!k)return;let q="";if(w)q=k.artifactCopyText(w);else{let{markdown:te,file:Q,artifactType:re}=Um(f,y);re==="markdown"&&(q=k.artifactCopyText({id:y,artifactType:"markdown",status:"complete",markdown:te??"",...Q?{file:Q}:{}}))}q&&navigator.clipboard.writeText(q).then(()=>{let te=Ge(Xr.Check,16,"currentColor",2);te&&(f.replaceChildren(te),setTimeout(()=>{let Q=Ge(Xr.Copy,16,"currentColor",2);Q&&f.replaceChildren(Q)},1500))}).catch(()=>{})}),We.addEventListener("click",i=>{let f=i.target.closest("[data-expand-artifact-inline]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-expand-artifact-inline");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(Ar=!1,Ki=!0,No=!0,dl=!0,N.selectArtifact(y),Fo())}),We.addEventListener("click",i=>{let d=i.target;if(d.closest("[data-download-artifact]")||d.closest("[data-artifact-custom-action]"))return;let f=d.closest("[data-open-artifact]");if(!f)return;let y=f.getAttribute("data-open-artifact");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(i.preventDefault(),i.stopPropagation(),Ar=!1,Ki=!0,N.selectArtifact(y),Fo())}),We.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let d=i.target;!d.hasAttribute("data-open-artifact")&&!d.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),d.click())});let Gi=ot.composerOverlay,Yi=(i,d,f)=>{let y=d.trim();if(!y||!Ft.current)return;let w=i.getAttribute("data-tool-call-id")??"",k=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:w,answer:y,answers:f.structured,values:f.values??(f.source==="multi"?y.split(", "):[y]),isFreeText:k,source:f.source},bubbles:!0,composed:!0})),La(Gi,w);let q=Ft.current.getMessages().find(te=>te.toolCall?.id===w);q?.agentMetadata?.awaitingLocalTool?Ft.current.resolveAskUserQuestion(q,f.structured??y):Ft.current.sendMessage(y)},qs=i=>{let d=Ft.current;if(!d)return;let f=i.getAttribute("data-tool-call-id")??"",y=d.getMessages().find(w=>w.toolCall?.id===f);y&&d.persistAskUserQuestionProgress(y,{answers:Op(i,y),currentIndex:Wo(i)})},Qb=i=>Object.entries(i).map(([d,f])=>`${d}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),qm=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let d=Wo(i),f=Pa(i);if(d>=f-1)return;let y=Ft.current?.getMessages().find(w=>w.toolCall?.id===i.getAttribute("data-tool-call-id"));y&&(Np(i,y,o,d+1),qs(i))};Gi.addEventListener("click",i=>{let f=i.target.closest("[data-ask-user-action]");if(!f)return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;let w=f.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),w==="dismiss"){let k=y.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),La(Gi,k);let q=Ft.current?.getMessages().find(te=>te.toolCall?.id===k);q?.agentMetadata?.awaitingLocalTool&&(Ft.current?.markAskUserQuestionResolved(q),Ft.current?.resolveAskUserQuestion(q,"(dismissed)"));return}if(w==="pick"){let k=f.getAttribute("data-option-label");if(!k)return;let q=y.getAttribute("data-multi-select")==="true",te=xs(y);if(te&&q){let Q=Mi(y)[Wo(y)],re=new Set(Array.isArray(Q)?Q:[]);re.has(k)?re.delete(k):re.add(k),Ss(y,Array.from(re)),qs(y);return}if(te){Ss(y,k),qs(y),qm(y);return}if(q){let Q=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",Q?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!Q);let re=y.querySelector('[data-ask-user-action="submit-multi"]');re&&(re.disabled=Fg(y).length===0);return}Yi(y,k,{source:"pick",values:[k]});return}if(w==="submit-multi"){let k=Fg(y);if(k.length===0)return;Yi(y,k.join(", "),{source:"multi",values:k});return}if(w==="open-free-text"){let k=y.querySelector('[data-ask-free-text-row="true"]');k&&(k.classList.remove("persona-hidden"),k.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(w==="focus-free-text"){y.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(w==="submit-free-text"){let q=y.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!q.trim())return;if(xs(y)){Ss(y,q.trim()),qs(y),qm(y);return}Yi(y,q,{source:"free-text"});return}if(w==="next"||w==="back"){if(!Ft.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Ft.current.getMessages().find(he=>he.toolCall?.id===k);if(!q)return;let Q=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(Q){let he=Mi(y)[Wo(y)];(typeof he!="string"||he!==Q)&&Ss(y,Q)}let re=w==="next"?1:-1,ce=Wo(y)+re;Np(y,q,o,ce),qs(y);return}if(w==="submit-all"){if(!Ft.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Ft.current.getMessages().find(he=>he.toolCall?.id===k);if(!q)return;let Q=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";Q&&Ss(y,Q);let re=Op(y,q);Ft.current.persistAskUserQuestionProgress(q,{answers:re,currentIndex:Wo(y)});let ce=Qb(re);Yi(y,ce||"(submitted)",{source:"submit-all",structured:re});return}if(w==="skip"){if(!Ft.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Ft.current.getMessages().find(De=>De.toolCall?.id===k);if(!q)return;let te=xs(y),Q=Wo(y),re=Pa(y),ce=Q>=re-1;if(!te){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),La(Gi,k),q.agentMetadata?.awaitingLocalTool&&(Ft.current.markAskUserQuestionResolved(q),Ft.current.resolveAskUserQuestion(q,"(dismissed)"));return}Ss(y,"");let he=y.querySelector('[data-ask-free-text-input="true"]');if(he&&(he.value=""),ce){let De=Op(y,q),lt=Qb(De);Yi(y,lt||"(skipped)",{source:"submit-all",structured:De});return}Np(y,q,o,Q+1),qs(y);return}}),Gi.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let f=i.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;i.preventDefault();let w=f.value;if(w.trim()){if(xs(y)){Ss(y,w.trim()),qs(y),qm(y);return}Yi(y,w,{source:"free-text"})}});let Xb=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let d=i.target;if(d?.tagName==="INPUT"||d?.tagName==="TEXTAREA"||d?.isContentEditable)return;let f=Gi.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let y=Number(i.key),k=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];k&&(i.preventDefault(),k.click())};document.addEventListener("keydown",Xb);let nr=null,en=null,pl=null,dd=null,pd=()=>{},Jb=!1,ud="",md="";function jm(){dd?.(),dd=null}let W0=()=>{let i=ca&&pi?.isConnected?pi:null,d=i?i.getBoundingClientRect().width:0;return d<=0?200:d+360},Zb=()=>{if(!nr||!en)return;let i=t.classList.contains("persona-artifact-welded-split"),d=t.ownerDocument.defaultView??window,f=d.innerWidth<=640;if(!i||t.classList.contains("persona-artifact-narrow-host")||f){en.style.removeProperty("position"),en.style.removeProperty("left"),en.style.removeProperty("top"),en.style.removeProperty("bottom"),en.style.removeProperty("width"),en.style.removeProperty("z-index");return}let y=nr.firstElementChild;if(!y||y===en)return;let w=10;en.style.position="absolute",en.style.top="0",en.style.bottom="0",en.style.width=`${w}px`,en.style.zIndex="5";let k=Qy(nr,d),q=y.offsetWidth+k/2-w/2;en.style.left=`${Math.max(0,q)}px`},fd=()=>{},ev=()=>{let i=t.ownerDocument.defaultView??window,d=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640;return!d||i.innerWidth>f?!1:_||nn(o)},gd=()=>!Kn(o)||!cd()||t.classList.contains("persona-artifact-narrow-host")||ev()||(t.ownerDocument.defaultView??window).innerWidth<nD?"none":Ky(o)?"detached":"welded",Fo=()=>{if(!gt||!Kn(o))return;Uc(t,o),qc(t,o),fd();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,d=Se.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",d>0&&d<=i);let f=cd();gt.setVisible(f),gt.update(wo),Ar?(gt.setMobileOpen(!1),gt.element.classList.add("persona-hidden"),gt.backdrop?.classList.add("persona-hidden"),No=!1,dl=!1):wo.artifacts.length>0&&Yb()?(gt.element.classList.remove("persona-hidden"),gt.setMobileOpen(!0)):(gt.setMobileOpen(!1),gt.element.classList.add("persona-hidden"),gt.backdrop?.classList.add("persona-hidden"),No=!1,dl=!1);let y=o.features?.artifacts?.layout?.showExpandToggle===!0;if(gt.setExpandToggleVisible(y),gt.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),gt.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),gt.setCustomActions(o.features?.artifacts?.toolbarActions??[]),gt.setTabFade(o.features?.artifacts?.layout?.tabFade),gt.setRenderTabBar(o.features?.artifacts?.renderTabBar),!y&&!dl&&(No=!1),No!==Jb){let k=gt.element;No?(ud=k.style.width,md=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(ud&&(k.style.width=ud),md&&(k.style.maxWidth=md),ud="",md=""),Jb=No}t.classList.toggle("persona-artifact-expanded",No),gt.setExpanded(No);let w=gd();w!==cl&&(cl=w,Us()),pd()};if(Kn(o)){Se.style.position="relative";let i=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),d=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(Pe),nr=d,d.appendChild(i),Se.appendChild(d);let f=w=>{Gb||gt||(gt=w.createArtifactPane(o,{onSelect:k=>Ft.current?.selectArtifact(k),onDismiss:()=>{Ar=!0,Fo()},onToggleExpand:()=>{let k=!No,q=wo.selectedId??wo.artifacts[wo.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:q,expanded:k})!==!0&&(No=k,k||(dl=!1),Fo())}}),gt.element.classList.add("persona-hidden"),d.appendChild(gt.element),gt.backdrop&&Se.appendChild(gt.backdrop),pd(),Fo())},y=Gr();y?f(y):(qy(()=>{let w=Gr();w&&f(w)}),ym().catch(()=>{})),pd=()=>{if(!nr||!gt)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){pl?.(),pl=null,jm(),en&&(en.remove(),en=null),gt.element.style.removeProperty("width"),gt.element.style.removeProperty("maxWidth");return}if(!en){let k=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");k.setAttribute("role","separator"),k.setAttribute("aria-orientation","vertical"),k.setAttribute("aria-label","Resize artifacts panel"),k.tabIndex=0;let q=t.ownerDocument,te=q.defaultView??window,Q=re=>{if(!gt||re.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||te.innerWidth<=640)return;re.preventDefault(),jm();let ce=re.clientX,he=gt.element.getBoundingClientRect().width,De=o.features?.artifacts?.layout,lt=kt=>{let no=nr.getBoundingClientRect().width,Jt=t.classList.contains("persona-artifact-welded-split"),rn=Qy(nr,te),Vn=Jt?0:k.getBoundingClientRect().width||6,ln=he-(kt.clientX-ce),$t=mE(ln,no,rn,Vn,De?.resizableMinWidth,De?.resizableMaxWidth,W0());gt.element.style.width=`${$t}px`,gt.element.style.maxWidth="none",Zb()},It=()=>{q.removeEventListener("pointermove",lt),q.removeEventListener("pointerup",It),q.removeEventListener("pointercancel",It),dd=null;try{k.releasePointerCapture(re.pointerId)}catch{}};dd=It,q.addEventListener("pointermove",lt),q.addEventListener("pointerup",It),q.addEventListener("pointercancel",It);try{k.setPointerCapture(re.pointerId)}catch{}};k.addEventListener("pointerdown",Q),en=k,nr.insertBefore(k,gt.element),pl=()=>{k.removeEventListener("pointerdown",Q)}}if(en){let k=cd();en.classList.toggle("persona-hidden",!k),Zb()}},fd=()=>{if(!_||!gt||(o.launcher?.sidebarMode??!1)||nn(o)&&Do(o).reveal==="emerge")return;let k=t.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,te=o.launcher?.mobileBreakpoint??640;if(q&&k.innerWidth<=te||!aE(o,_))return;let Q=Ri(o).width,re=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";cd()?(Se.style.width=re,Se.style.maxWidth=re):(Se.style.width=Q,Se.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(ll=new ResizeObserver(()=>{Fo()}),ll.observe(Se))}else Se.appendChild(Pe);xe()&&Nt&&(ot.peekBanner&&Nt.appendChild(ot.peekBanner),Nt.appendChild(Qe)),t.appendChild(dt),Nt&&t.appendChild(Nt);let Km=()=>{let i=ev()||xe()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!nn(o);if(We.style.gap=i?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",We.style.setProperty("--persona-transcript-gap",We.style.gap),xe()){Se.style.width="100%",Se.style.maxWidth="100%";let Ye=o.launcher?.composerBar??{},st=dt.dataset.state==="expanded",tt=Ye.expandedSize??"anchored";if(!(st&&tt!=="fullscreen")){Pe.style.background="",Pe.style.border="",Pe.style.borderRadius="",Pe.style.overflow="",Pe.style.boxShadow="";return}let bn=o.theme?.components?.panel,oo=qr(o),Or=(_r,bi)=>_r==null||_r===""?bi:Hn(oo,_r)??_r,ug="1px solid var(--persona-border)",yi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",mg="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Pe.style.background="var(--persona-surface, #ffffff)",Pe.style.border=Or(bn?.border,ug),Pe.style.borderRadius=Or(bn?.borderRadius,mg),Pe.style.boxShadow=Or(bn?.shadow,yi),Pe.style.overflow="hidden";return}let d=nn(o),f=o.launcher?.sidebarMode??!1,y=d||f||(o.launcher?.fullHeight??!1),w=o.launcher?.enabled===!1,k=o.launcher?.detachedPanel===!0,q=o.theme?.components?.panel,te=o.darkTheme?.components?.panel,Q=fc(o)==="dark"?jo(q??{},te??{}):q,re=qr(o),ce=(Ye,st)=>Ye==null||Ye===""?st:Hn(re,Ye)??Ye,he=t.ownerDocument.defaultView??window,De=o.launcher?.mobileFullscreen??!0,lt=o.launcher?.mobileBreakpoint??640,It=he.innerWidth<=lt,kt=De&&It&&_,no=d&&De&&It,Jt=o.launcher?.position??"bottom-left",rn=Jt==="bottom-left"||Jt==="top-left",Vn=o.launcher?.zIndex??On,ln=(Ye,st,tt)=>`var(--persona-components-panel-modes-${Ye}-${st}, ${tt})`,$t=Q?.modes?.floating,cr=ce($t?.border??Q?.border,ln("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),dr=ce($t?.shadow??Q?.shadow,ln("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),Po=ce($t?.borderRadius??Q?.borderRadius,ln("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),Lo=k&&!kt&&!no,gs=kt||no?"mobile":Lo?"floating":d?"docked":f?"sidebar":w?"inline":"floating",pr=Q?.modes?.[gs];Lo?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let zo=Lo?cr:f||kt?"none":cr,hs=Lo?dr:kt?"none":f?rn?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":w?"none":dr;d&&!kt&&!Lo&&(hs="none",zo="none");let Ol=Lo?Po:f||kt?"0":Po,hi=ce(pr?.border??Q?.border,ln(gs,"border",zo)),$=ce(pr?.shadow??Q?.shadow,ln(gs,"shadow",hs)),Xe=ce(pr?.borderRadius??Q?.borderRadius,ln(gs,"borderRadius",Ol)),Je=gd(),fe=Je==="detached",zt=Je==="welded";t.classList.toggle("persona-artifact-detached-split",fe),t.classList.toggle("persona-artifact-welded-split",zt);let fn="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",jt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Kn(o)&&Ky(o)&&w&&!d;t.classList.toggle("persona-artifact-chat-flush",jt);let cn=fe||jt?"none":$,Sn=fe?cr:zt?"none":hi,Ke=fe?Po:Xe;jt&&(Sn="none",Ke="0");let Kt=pr?.borderRadius!=null&&pr.borderRadius!==""||Q?.borderRadius!=null&&Q.borderRadius!=="",et=jt&&!Kt?"0":Xe,An=pe.scrollTop;t.style.cssText="",dt.style.cssText="",Se.style.cssText="",Pe.style.cssText="",pe.style.cssText="",ji||(Qe.style.cssText=""),nt&&(pe.style.display="none"),(y||w)&&(t.style.minWidth="0");let Io=()=>{if(An<=0)return;(pe.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(pe.scrollTop===An)return;let st=pe.scrollHeight-pe.clientHeight;st<=0||(pe.scrollTop=Math.min(An,st))})};if(kt){dt.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),dt.style.cssText=`
1174
1175
  position: fixed !important;
1175
1176
  inset: 0 !important;
1176
1177
  width: 100% !important;
@@ -1180,9 +1181,9 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1180
1181
  padding: 0 !important;
1181
1182
  display: flex !important;
1182
1183
  flex-direction: column !important;
1183
- z-index: ${xn} !important;
1184
+ z-index: ${Vn} !important;
1184
1185
  background-color: var(--persona-surface, #ffffff) !important;
1185
- `,_e.style.cssText=`
1186
+ `,Se.style.cssText=`
1186
1187
  position: relative !important;
1187
1188
  display: flex !important;
1188
1189
  flex-direction: column !important;
@@ -1195,7 +1196,7 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1195
1196
  padding: 0 !important;
1196
1197
  box-shadow: none !important;
1197
1198
  border-radius: 0 !important;
1198
- `,Le.style.cssText=`
1199
+ `,Pe.style.cssText=`
1199
1200
  display: flex !important;
1200
1201
  flex-direction: column !important;
1201
1202
  flex: 1 1 0% !important;
@@ -1206,33 +1207,33 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1206
1207
  overflow: hidden !important;
1207
1208
  border-radius: 0 !important;
1208
1209
  border: none !important;
1209
- `,ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",We.style.flexShrink="0",lm(),nt=!0,en();return}let tt=o?.launcher?.width??o?.launcherWidth??Rr;if(!c&&!i)h&&f?(_e.style.width="100%",_e.style.maxWidth="100%"):(_e.style.width=tt,_e.style.maxWidth=tt);else if(i)if(Lo(o).reveal==="emerge"&&!x){let Ue=Lo(o).width;_e.style.width=Ue,_e.style.maxWidth=Ue}else _e.style.width="100%",_e.style.maxWidth="100%";if(Qc(),_e.style.boxShadow=xe,_e.style.borderRadius=mn,Ln?_e.style.border="none":No&&(_e.style.border=Do),Le.style.border=Zt,Le.style.borderRadius=un,Le.style.boxShadow=Ln&&!qe?Zi:"",qe&&(Le.style.background="transparent",ie.style.background="transparent",We.style.background="transparent",We.style.borderTop="none"),No){let st=o.features?.artifacts?.layout;Uc=st?.unifiedSplitOuterRadius?.trim()||st?.paneBorderRadius?.trim()||ei}else Uc=null;if(i&&!He&&!Mt&&!Ln&&!No&&L?.border===void 0&&(Le.style.border="none",Lo(o).side==="right"?Le.style.borderLeft="1px solid var(--persona-border)":Le.style.borderRight="1px solid var(--persona-border)"),i&&!He&&No&&L?.border===void 0&&(Lo(o).side==="right"?_e.style.borderLeft="1px solid var(--persona-border)":_e.style.borderRight="1px solid var(--persona-border)"),f&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",h&&(t.style.width="100%"),it.style.display="flex",it.style.flexDirection="column",it.style.flex="1 1 0%",it.style.minHeight="0",it.style.maxHeight="100%",it.style.height="100%",h&&(it.style.overflow="hidden"),_e.style.display="flex",_e.style.flexDirection="column",_e.style.flex="1 1 0%",_e.style.minHeight="0",_e.style.maxHeight="100%",_e.style.height="100%",Ln||(_e.style.overflow="hidden"),Le.style.display="flex",Le.style.flexDirection="column",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.maxHeight="100%",Le.style.overflow="hidden",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",We.style.flexShrink="0"),h&&(Mt||Ln||qe)&&!i&&(qe||(it.style.padding="var(--persona-panel-inset)"),it.style.background="var(--persona-panel-canvas-bg)"),it.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!c&&!h&&!i&&(go[Ot]??go["bottom-right"]).split(" ").forEach(Ue=>it.classList.add(Ue)),c){let st=o.launcher?.sidebarWidth??"420px";x?it.style.cssText=`
1210
+ `,pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.overflowY="auto",Qe.style.flexShrink="0",Hm(),bt=!0,Io();return}let kn=Ri(o);if(!f&&!d)w&&y?(Se.style.width="100%",Se.style.maxWidth="100%"):(Se.style.width=kn.width,Se.style.maxWidth=kn.maxWidth);else if(d)if(Do(o).reveal==="emerge"&&!k){let st=Do(o).width;Se.style.width=st,Se.style.maxWidth=st}else Se.style.width="100%",Se.style.maxWidth="100%";if(fd(),Se.style.boxShadow=cn,Se.style.borderRadius=et,fe?Se.style.border="none":zt&&(Se.style.border=hi),Pe.style.border=Sn,Pe.style.borderRadius=Ke,Pe.style.boxShadow=fe&&!jt?fn:"",jt&&(Pe.style.background="transparent",pe.style.background="transparent",Qe.style.background="transparent",Qe.style.borderTop="none"),zt){let Ye=o.features?.artifacts?.layout;ld=Ye?.unifiedSplitOuterRadius?.trim()||Ye?.paneBorderRadius?.trim()||Xe}else ld=null;let Ut=pr?.border!=null||Q?.border!=null;if(d&&!kt&&!Lo&&!fe&&!zt&&!Ut&&(Pe.style.border="none",Do(o).side==="right"?Pe.style.borderLeft="1px solid var(--persona-border)":Pe.style.borderRight="1px solid var(--persona-border)"),d&&!kt&&zt&&!Ut&&(Do(o).side==="right"?Se.style.borderLeft="1px solid var(--persona-border)":Se.style.borderRight="1px solid var(--persona-border)"),y&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",w&&(t.style.width="100%"),dt.style.display="flex",dt.style.flexDirection="column",dt.style.flex="1 1 0%",dt.style.minHeight="0",dt.style.maxHeight="100%",dt.style.height="100%",w&&(dt.style.overflow="hidden"),Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.height="100%",fe||(Se.style.overflow="hidden"),Pe.style.display="flex",Pe.style.flexDirection="column",Pe.style.flex="1 1 0%",Pe.style.minHeight="0",Pe.style.maxHeight="100%",Pe.style.overflow="hidden",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.overflowY="auto",Qe.style.flexShrink="0"),w&&(Lo||fe||jt)&&!d&&(jt||(dt.style.padding="var(--persona-panel-inset)"),dt.style.background="var(--persona-panel-canvas-bg)"),dt.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!f&&!w&&!d&&(vo[Jt]??vo["bottom-right"]).split(" ").forEach(st=>dt.classList.add(st)),f){let Ye=Nr(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":Hn(qr(o),"components.panel.width")??"420px";k?dt.style.cssText=`
1210
1211
  position: fixed !important;
1211
1212
  top: var(--persona-panel-inset) !important;
1212
1213
  bottom: var(--persona-panel-inset) !important;
1213
- width: ${st} !important;
1214
+ width: ${Ye} !important;
1214
1215
  height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
1215
1216
  max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
1216
1217
  margin: 0 !important;
1217
1218
  padding: 0 !important;
1218
1219
  display: flex !important;
1219
1220
  flex-direction: column !important;
1220
- z-index: ${xn} !important;
1221
- ${Ft?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
1222
- `:it.style.cssText=`
1221
+ z-index: ${Vn} !important;
1222
+ ${rn?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
1223
+ `:dt.style.cssText=`
1223
1224
  position: fixed !important;
1224
1225
  top: 0 !important;
1225
1226
  bottom: 0 !important;
1226
- width: ${st} !important;
1227
+ width: ${Ye} !important;
1227
1228
  height: 100vh !important;
1228
1229
  max-height: 100vh !important;
1229
1230
  margin: 0 !important;
1230
1231
  padding: 0 !important;
1231
1232
  display: flex !important;
1232
1233
  flex-direction: column !important;
1233
- z-index: ${xn} !important;
1234
- ${Ft?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
1235
- `,_e.style.cssText=`
1234
+ z-index: ${Vn} !important;
1235
+ ${rn?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
1236
+ `,Se.style.cssText=`
1236
1237
  position: relative !important;
1237
1238
  display: flex !important;
1238
1239
  flex-direction: column !important;
@@ -1243,10 +1244,10 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1243
1244
  min-height: 0 !important;
1244
1245
  margin: 0 !important;
1245
1246
  padding: 0 !important;
1246
- box-shadow: ${xe} !important;
1247
- border-radius: ${mn} !important;
1248
- ${Ln?"border: none !important;":No?`border: ${Do} !important;`:""}
1249
- `,_e.style.setProperty("width","100%","important"),_e.style.setProperty("max-width","100%","important"),Le.style.cssText=`
1247
+ box-shadow: ${cn} !important;
1248
+ border-radius: ${et} !important;
1249
+ ${fe?"border: none !important;":zt?`border: ${hi} !important;`:""}
1250
+ `,Se.style.setProperty("width","100%","important"),Se.style.setProperty("max-width","100%","important"),Pe.style.cssText=`
1250
1251
  display: flex !important;
1251
1252
  flex-direction: column !important;
1252
1253
  flex: 1 1 0% !important;
@@ -1255,16 +1256,16 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1255
1256
  min-height: 0 !important;
1256
1257
  max-height: 100% !important;
1257
1258
  overflow: hidden !important;
1258
- border-radius: ${un} !important;
1259
- border: ${Zt} !important;
1260
- ${Ln&&!qe?`box-shadow: ${Zi} !important;`:""}
1261
- ${qe?"background: transparent !important;":""}
1262
- `,Ti||(We.style.cssText=`
1259
+ border-radius: ${Ke} !important;
1260
+ border: ${Sn} !important;
1261
+ ${fe&&!jt?`box-shadow: ${fn} !important;`:""}
1262
+ ${jt?"background: transparent !important;":""}
1263
+ `,ji||(Qe.style.cssText=`
1263
1264
  flex-shrink: 0 !important;
1264
1265
  border-top: none !important;
1265
1266
  padding: 8px 16px 12px 16px !important;
1266
- ${qe?"background: transparent !important;":""}
1267
- `)}if(!h&&!i){let st="max-height: -moz-available !important; max-height: stretch !important;",Ue=c?"":"padding-top: 1.25em !important;",_n=c?"":`z-index: ${o.launcher?.zIndex??Hn} !important;`;it.style.cssText+=st+Ue+_n}lm(),en()},xm=()=>{t.style.setProperty("--persona-content-max-width",ys(o,Ee()))},lb=!1,cb=()=>{let i=Gg(o,Ee());Ee()&&o.composer?.placement&&o.debug===!0&&!lb&&(lb=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=Br(o);t.setAttribute("data-persona-composer-placement",i),t.setAttribute("data-persona-conversation-state",Nc),t.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",c.composerGap??iu),Vc()},db=()=>{if(Ee())return;let i=rn(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!ce)return;let h=t.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640;if(x&&h.innerWidth<=L)return;let q=h.innerHeight,te=64,Z=o.launcher?.heightOffset??0,ne=Math.max(200,q-te),pe=Math.min(640,ne);_e.style.height=`${Math.max(200,pe-Z)}px`};wm(),Zl(t,o),kc(t,o),Lc(t,o),xm(),cb(),Es=()=>{wm(),db(),Zl(t,o),kc(t,o),Lc(t,o),xm(),cb(),Uc?t.style.setProperty("--persona-artifact-welded-outer-radius",Uc):t.style.removeProperty("--persona-artifact-welded-outer-radius"),ut(),Ke()};let De=[];De.push(()=>{nb=!0}),De.push(()=>{d.forEach(i=>i()),l.destroy()}),De.push(()=>{document.removeEventListener("keydown",sb)}),De.push(()=>{za!==null&&clearTimeout(za)});let Xo=null,Jo=null;De.push(()=>{Xo?.(),Xo=null,Jo?.(),Jo=null}),ja&&De.push(()=>{ja?.disconnect(),ja=null}),De.push(()=>{Ya?.(),Ya=null,Cm(),Ut&&(Ut.remove(),Ut=null),ft?.element.style.removeProperty("width"),ft?.element.style.removeProperty("maxWidth"),ft?.destroy()}),P&&De.push(()=>{Je=!0,ot=null,ee!==null&&(cancelAnimationFrame(ee),ee=null),mt?.destroy(),mt=null,je?.destroy(),je=null,Te=null});let Ls=null,pb=()=>{Ls&&(Ls(),Ls=null),o.colorScheme==="auto"&&(Ls=su(()=>{Zl(t,o)}))};pb(),De.push(()=>{Ls&&(Ls(),Ls=null)}),De.push(()=>{b=!0,g?.()}),De.push(()=>{A=!0});let ub=!1;De.push(()=>{ub=!0});let Sm=(i,c)=>{let f=oc(i,c);return f||!ZS.includes(i)?f:(bA().then(h=>{if(ub)return;ii(h.wipe),ii(h.glyphCycle);let x=oc(i,c);x&&ic(x,t)}).catch(()=>{}),null)},Jc=o.features?.streamAnimation;if(Jc?.type&&Jc.type!=="none"){let i=Sm(Jc.type,Jc.plugins);i&&ic(i,t),De.push(()=>eA(t))}let hr=uc(Io),mb=uc(wi),fb=uc(Vr),Ps=[hr,mb,fb];De.push(()=>{Ps.forEach(i=>i.destroy())});let Is=null,_,Hs=null,gb=!1,hb=0,yb=null,bb=i=>i.reduce((c,f)=>f.role==="user"?c+1:c,0),vb=i=>{for(let c=i.length-1;c>=0;c--)if(Pl(i[c]))return i[c].id??null;return null},Cb=!1,TE=()=>{Cb||o.debug!==!0||(Cb=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},wb=!1,xb=!1,Sb=(i,c)=>{wb||o.debug!==!0||!c.enabled||c.expose||gb||xb&&(_.isStreaming()||i.some(Pl)||(wb=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},Pi=i=>{if(!_)return;let c=i??_.getMessages(),f=ne=>{ne.render([],_,Ae,c)},h=ne=>{Ps.forEach(pe=>{pe!==ne&&f(pe)})};Hs&&(bb(c)>hb||vb(c)!==yb)&&(Hs=null);let x=ps(o);Sb(c,x);let L=x.enabled?ow(c):null,q=Hs??L,te=Hs?"host":"agent";if(q){let ne=o.suggestions?.followUps,pe=ne?.placement??(ne?"auto":"composer"),He=(pe==="auto"?Ee()?"composer":"after-message":pe)==="after-message"?fb:hr;h(He),He.render(q,_,Ae,c,o.suggestionChipsConfig,{source:te,surface:"followUp",variant:ne?.variant??"chip",behavior:ne?.behavior??"send",overflow:ne?.overflow??"wrap",maxItems:ne?.maxItems??4,config:o,plugins:a,submitPrompt:Nd});return}if(c.some(ne=>ne.role==="user")){Ps.forEach(f);return}let Z=o.suggestions?.starters;if(Z){let ne=Ma(Br(o),c),pe=Z.placement??"auto",Ce=pe==="auto"?ne?"welcome":"composer":pe;if(Ce==="welcome"&&!ne){TE(),Ps.forEach(f);return}let He=Ce==="welcome"?mb:hr;h(He),He.render(Z.items??o.suggestionChips,_,Ae,c,o.suggestionChipsConfig,{surface:"starter",variant:Z.variant??"card",behavior:Z.behavior??"send",overflow:Z.overflow??"wrap",maxItems:Z.maxItems??4,config:o,plugins:a,submitPrompt:Nd});return}h(hr),hr.render(o.suggestionChips,_,Ae,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a,submitPrompt:Nd})},Ab=()=>{Hs&&(Hs=null,Pi())},EE=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){Ab();return}let f=_?_.getMessages():[];Hs=c,gb=!0,hb=bb(f),yb=vb(f),Pi(f)},lo=!1,cn=qS(),Ii=new Map,Rs=new Map,Kr=new Map,Ws=null,Gr=null;function Bs(){if(!Ws)return;let i=Ws;Ws=null,Gr?.destroy(),Gr=null,cn.delete(i),Le.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),_&&bo(Re,_.getMessages(),Ge)}let Os=0,kE=Mo()!==null,co=pu(),po=0,Yr=null,Yn=!1,Zc=!1,Qr=0,hn=null,Ds=null,Am=!1,Hi=!1,_s=null,Qa=!0,ed=!1,Ri=null,td=!1,Ns=()=>{td=!0,HE()},Mm=null,LE=4,yr=24,PE=80,IE=1e3,br=null,Mb=()=>{t.setAttribute("data-persona-scrollbar",sm()),sm()!=="on-scroll"&&(br!==null&&clearTimeout(br),br=null,ie.removeAttribute("data-persona-scrollbar-visible"))},HE=()=>{sm()==="on-scroll"&&(ie.setAttribute("data-persona-scrollbar-visible",""),br!==null&&clearTimeout(br),br=setTimeout(()=>{br=null,Wr(ie,yr)&&ie.removeAttribute("data-persona-scrollbar-visible")},IE))};Mb(),De.push(()=>{br!==null&&clearTimeout(br)});let Tm=new Map,gt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Yy=()=>gt.active,Ho();let Tb=o.voiceRecognition?.autoResume??!1,vr=i=>{k.emit("voice:state",{active:gt.active,source:i,timestamp:Date.now()})},Bo=()=>{Y(i=>({...i,voiceState:{active:gt.active,timestamp:Date.now(),manuallyDeactivated:gt.manuallyDeactivated}}))},RE=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Sy(R.voiceState),c=!!i.active,f=Number(i.timestamp??0);gt.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-f<PB&&setTimeout(()=>{gt.active||(gt.manuallyDeactivated=!1,no(o.voiceRecognition?.provider)?_.toggleVoice().then(()=>{gt.active=_.isVoiceActive(),vr("restore"),_.isVoiceActive()&&Xi()}):$d("restore"))},1e3)},WE=()=>_?jT(_.getMessages()).filter(i=>!i.__skipPersist):[],nd=null,Eb=(i,c)=>{typeof console<"u"&&console.error(i,c)},od=(i,c)=>{let f=()=>{try{let q=i();return!q||typeof q.then!="function"?null:Promise.resolve(q).catch(te=>{Eb(c,te)})}catch(q){return Eb(c,q),null}},h=nd,x=h?h.then(()=>f()??void 0):f();if(!x)return;let L=x.finally(()=>{nd===L&&(nd=null)});nd=L};function Wi(i){if(!W?.save)return;let c=i?jT(i):_?WE():[],f=V&&_?.getResumableHandle();f&&(R={...R,durableResume:{executionId:f.executionId,after:f.lastEventId}});let h={messages:c,metadata:R,artifacts:yo.artifacts,selectedArtifactId:yo.selectedId,...Fs?{draft:Fs}:{}};od(()=>W.save(h),"[AgentWidget] Failed to persist state:")}let Fs,rd=()=>!W?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Xa=Vx({write:()=>{if(!rd())return;let i=ze.getState(),c=Nx({text:i.text,mentionRefs:i.mentionRefs,contentSegments:Sf(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(Fs)&&(Fs=c,Wi())}});function kb(){rd()&&Xa.schedule()}function Em(){Xa.flush()}function Lb(i){if(!rd())return;let c=Fx(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(f=>f.id),modelIds:(o.composer?.models??[]).map(f=>f.id),modes:o.composer?.modes??[]});c&&(Fs=i,Ae&&!Ae.value&&(Ae.value=c.text,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Ko()),c.selectedModelId&&(ze.setSelectedModelId(c.selectedModelId),Ur?.repaint()),$c(c.activeModeIds??[]),c.quote&&Go(c.quote),Xa.cancel())}function sd(){Xa.cancel(),Fs&&(Fs=void 0,rd()&&Wi())}let Bi=null,Pb=()=>it.querySelector("#persona-scroll-container")||ie,Oi=()=>{Bi!==null&&(cancelAnimationFrame(Bi),Bi=null),Yn=!1},Ib=()=>{Yr!==null&&(cancelAnimationFrame(Yr),Yr=null),Zc=!1,Oi()},BE=()=>lo&&Lm()&&(ao()!=="anchor-top"||Hy()),km=()=>{let i=Fa()||"Jump to latest",c=BE();ln.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),Qr>0?(As.textContent=String(Qr),As.style.display="",ln.setAttribute("aria-label",`${i} (${Qr} new)`)):(As.textContent="",As.style.display="none",ln.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},Hb=()=>{Qr!==0&&(Qr=0,km())},OE=()=>{let i=hn?.spacerHeight??0;return i<=0?Wr(ie,yr):cd(i)-ie.scrollTop-ie.clientHeight<=yr},Lm=()=>zr()?!co.isFollowing():!OE(),Pm=()=>!!_&&_.getMessages().length>0,yn=()=>{if(!dE()||Wt()){ln.parentNode&&ln.remove(),ln.style.display="none";return}ln.parentNode!==Le&&Le.appendChild(ln),Ms();let c=cr(ie)>0&&Lm()&&Pm();c?km():Hb(),ln.style.display=c?"":"none"},Ja=()=>{co.pause()&&(Ib(),yn())},Qn=()=>{co.resume(),Hb(),yn()},Xr=(i=!1)=>{zr()&&Pm()&&co.isFollowing()&&(!i&&!lo||(Yr!==null&&(cancelAnimationFrame(Yr),Yr=null),Zc=!0,Yr=requestAnimationFrame(()=>{Yr=null,Zc=!1,co.isFollowing()&&DE(Pb(),i?220:140)})))},Rb=(i,c,f,h=()=>!0)=>{let x=i.scrollTop,L=c(),q=L-x;if(Oi(),Math.abs(q)<1){Yn=!0,i.scrollTop=L,po=i.scrollTop,Yn=!1;return}let te=performance.now();Yn=!0;let Z=pe=>1-Math.pow(1-pe,3),ne=pe=>{if(!h()){Oi();return}let Ce=c();Ce!==L&&(L=Ce,q=L-x);let He=pe-te,wt=Math.min(He/f,1),Ot=Z(wt),Ft=x+q*Ot;i.scrollTop=Ft,po=i.scrollTop,wt<1?Bi=requestAnimationFrame(ne):(i.scrollTop=L,po=i.scrollTop,Bi=null,Yn=!1)};Bi=requestAnimationFrame(ne)},DE=(i,c=500)=>{let f=cr(i)-i.scrollTop;if(Math.abs(f)<1){po=i.scrollTop;return}if(Math.abs(f)>=PE){Oi(),Yn=!0,i.scrollTop=cr(i),po=i.scrollTop,Yn=!1;return}Rb(i,()=>cr(i),c,()=>co.isFollowing())},id=()=>{if(!Pm()){yn();return}let i=Pb();Yn=!0,i.scrollTop=cr(i),po=i.scrollTop,Yn=!1,yn()},Vs=i=>{let c=0,f=i;for(;f&&f!==ie;)c+=f.offsetTop,f=f.offsetParent;return c},_E=()=>{let i=ie.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ie.ownerDocument.getSelection()},ad=()=>QS(_E(),ie),Im=()=>{if(pE()!=="last-user-turn")return!1;let i=_?.getMessages()??[];if(i.length<2)return!1;let c=[...i].reverse().find(L=>L.role==="user");if(!c)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=ie.querySelector(`[data-message-id="${f}"]`);if(!h)return!1;let x=Math.min(Math.max(0,Vs(h)-Va()),cr(ie));return Yn=!0,ie.scrollTop=x,po=ie.scrollTop,Yn=!1,ao()==="follow"&&!Wr(ie,yr)&&co.pause(),yn(),!0},ld=i=>{let c=Math.max(0,Math.round(i));ho.style.height=`${c}px`,ho.style.display=c>0?"":"none",hn&&(hn.spacerHeight=Math.max(0,i))},cd=i=>{let c=parseFloat(getComputedStyle(ie).paddingBottom)||0,f=0;for(let x of Array.from(ie.children)){if(x===ho||x.offsetHeight===0)continue;let L=Vs(x)+x.offsetHeight;L>f&&(f=L)}let h=ie.scrollHeight-i;return f>0?Math.min(f+c,h):h},NE=()=>{if(!hn||hn.spacerHeight<=0)return;let i=cd(hn.spacerHeight),c=Math.max(0,Math.round(ie.scrollTop)+ie.clientHeight-i+yr);c<hn.spacerHeight&&(ld(c),yn())},Oo=()=>{Ds!==null&&(cancelAnimationFrame(Ds),Ds=null),Oi(),hn=null,ho.style.height="0px",ho.style.display="none"},Wb=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Hm=i=>ie.querySelector(`[data-message-id="${Wb(i)}"]`),Bb=i=>{Ds!==null&&cancelAnimationFrame(Ds),Ds=requestAnimationFrame(()=>{Ds=null;let c=Wb(i),f=ie.querySelector(`[data-message-id="${c}"]`);if(!f)return;let h=Vs(f),x=hn?.spacerHeight??0,L=cd(x),{targetScrollTop:q,spacerHeight:te}=Xg({anchorOffsetTop:h,topOffset:Va(),viewportHeight:ie.clientHeight,contentHeight:L,slack:yr});hn={initialSpacerHeight:te,contentHeightAtAnchor:L,spacerHeight:te},ld(te),Rb(ie,()=>f.isConnected?Math.max(0,Vs(f)-Va()):q,220)})},Xn=()=>{if(ao()!=="anchor-top"||!hn||!Ri)return;let i=Hm(Ri);if(!i)return;Oi();let c=hn.spacerHeight,f=cd(c),{targetScrollTop:h,spacerHeight:x}=Xg({anchorOffsetTop:Vs(i),topOffset:Va(),viewportHeight:ie.clientHeight,contentHeight:f,slack:yr});hn={initialSpacerHeight:x,contentHeightAtAnchor:f,spacerHeight:x},ld(x),Yn=!0,ie.scrollTop=h,po=ie.scrollTop,Yn=!1,yn()},FE=()=>{if(zr()){if(!co.isFollowing()||Wr(ie,1))return;Xr(!lo);return}if(hn&&hn.initialSpacerHeight>0){let i=ie.scrollHeight-hn.spacerHeight,c=XS({initialSpacerHeight:hn.initialSpacerHeight,contentHeightAtAnchor:hn.contentHeightAtAnchor,currentContentHeight:i});c!==hn.spacerHeight&&ld(c)}yn()},VE=i=>{let c=ao();c==="follow"?(Qn(),Xr(!0)):c==="anchor-top"&&(Qa=!1,ed=!0,td=!1,Ri=i,Bb(i))},$E=()=>{if(ao()==="anchor-top"){if(ed){Qa=!1;return}Qa=!0,Oo(),Qn(),Xr(!0)}},zE=96,UE=i=>{if(_s===null)return!0;let c=Hm(_s),f=Hm(i);if(!c||!f)return!0;let h=Vs(f)-Vs(c);return Va()+h>ie.clientHeight-zE},qE=i=>{if(ao()!=="anchor-top"||!ed||td||ad())return;let c=_s===null;for(let f of i){if(!c){f.id===_s&&(c=!0);continue}if(YS(f)){if(f.id===Ri||!UE(f.id))return;Ri=f.id,Bb(f.id);return}}},jE=i=>{let c=new Map;i.forEach(f=>{let h=Tm.get(f.id);c.set(f.id,{streaming:f.streaming,role:f.role}),!h&&f.role==="assistant"&&(k.emit("assistant:message",f),!Hi&&(ao()!=="anchor-top"||Hy())&&Lm()&&(Qr+=1,km(),yn(),_c(Qr===1?"1 new message below.":`${Qr} new messages below.`))),f.role==="assistant"&&h?.streaming&&f.streaming===!1&&k.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(h?f.approval.status!=="pending"&&k.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):k.emit("approval:requested",{approval:f.approval,message:f}))}),Tm.clear(),c.forEach((f,h)=>{Tm.set(h,f)})},Za=(i,c)=>{let f=c==="user"?"user":"assistant",h=o.layout?.messages?.[f],x=h?.width??"content",L=h?.maxWidth??(x==="full"?"100%":void 0);i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${c}`,`persona-message-width-${x}`),i.classList.toggle("persona-justify-end",c==="user"),i.setAttribute("data-message-role",c),i.setAttribute("data-message-width",x),L?i.style.setProperty("--persona-message-row-max-width",L):i.style.removeProperty("--persona-message-row-max-width")},Cr=(i,c)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${i}`,f.setAttribute("data-wrapper-id",i),Za(f,c),f},KE=(i,c,f)=>{let h=document.createElement("div"),L=(()=>{let U=a.find(ct=>ct.renderLoadingIndicator);if(U?.renderLoadingIndicator)return U.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),q=(U,ct)=>ct==null?!1:typeof ct=="string"?(U.textContent=ct,!0):(U.appendChild(ct),!0),te=new Set,Z=new Map,ne=new Set,pe=a.some(U=>U.renderAskUserQuestion),Ce=[],He=[],wt=o.enableComponentStreaming!==!1,Ot=o.approval!==!1,Ft=[],xn=o.messageActions,pn=xn?.showRegenerate===!0&&xn.enabled!==!1&&Bt.current?.isStreaming()!==!0?Ww(c):null,Jt=xn?.showEdit===!0&&xn.enabled!==!1,Bn=xn?.showQuote===!0&&xn.enabled!==!1,Mt=null,On=o.features?.reasoningDisplay?.completedVisibility,or=U=>On==="removed"?!0:On==="removed-when-short"?iw(U,o.features?.reasoningDisplay?.shortThinkThreshold):!1,kr=o.features?.toolCallDisplay?.completedVisibility==="removed",Do=U=>U.variant==="reasoning"&&U.reasoning?.status==="complete"?or(U.reasoning):kr&&U.variant==="tool"&&U.toolCall?.status==="complete";if(c.forEach(U=>{if(Do(U))return;if(te.add(U.id),Z.set(U.id,U.role),Ws===U.id&&Gr){let Ue=Cr(U.id,U.role);Ue.setAttribute("data-persona-message-edit-stub","true"),Ue.setAttribute("data-preserve-runtime","true"),h.appendChild(Ue),Mt={messageId:U.id,element:Gr.element};return}let ct=pe&&ni(U),qe=Ot&&U.variant==="approval"&&!!U.approval,xe=!ct&&U.role==="assistant"&&!U.variant&&wt&&xy(U);!qe&&Kr.has(U.id)&&(i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),Kr.delete(U.id)),!xe&&Rs.has(U.id)&&(i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),Rs.delete(U.id));let Zt=ni(U)?`:${U.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${U.agentMetadata?.askUserQuestionAnswers?Object.keys(U.agentMetadata.askUserQuestionAnswers).length:0}`:"",un={canRegenerate:pn===U.id,canEdit:Jt&&ng(U),canQuote:Bn&&!U.variant&&(U.content?.trim().length??0)>0},Pn=`${un.canRegenerate?"r":""}${un.canEdit?"e":""}${un.canQuote?"q":""}`,mn=US(U,Os)+Zt+`:${Pn}`,bn=ct||qe||xe?null:jS(cn,U.id,mn);if(bn){h.appendChild(bn.cloneNode(!0)),ni(U)&&U.toolCall?.id&&U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(ne.add(U.toolCall.id),sp(U,o,Ze.composerOverlay));return}let en=null,Dn=a.find(Ue=>!!(U.variant==="reasoning"&&Ue.renderReasoning||U.variant==="tool"&&Ue.renderToolCall||!U.variant&&Ue.renderMessage)),tt=o.layout?.messages;if(ni(U)&&U.agentMetadata?.askUserQuestionAnswered===!0){Ii.delete(U.id),i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime");return}if(Pl(U)&&ps(o).enabled)return;if(ni(U)&&o.features?.askUserQuestion?.enabled!==!1){let Ue=a.find(_n=>typeof _n.renderAskUserQuestion=="function");if(Ue&&Bt.current){let _n=Ii.get(U.id),rs=_n!==mn,Zn=null;if(rs){let{payload:Dt,complete:rt}=ia(U),Lr=U.id,on=()=>Bt.current?.getMessages().find(to=>to.id===Lr);Zn=Ue.renderAskUserQuestion({message:U,payload:Dt,complete:rt,resolve:to=>{let Al=on();Al&&Bt.current?.resolveAskUserQuestion(Al,to)},dismiss:()=>{let to=on();to?.agentMetadata?.awaitingLocalTool&&(Bt.current?.markAskUserQuestionResolved(to),Bt.current?.resolveAskUserQuestion(to,"(dismissed)"))},config:o})}let eo=_n!=null;if(rs&&Zn===null&&!eo){U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(ne.add(U.toolCall.id),sp(U,o,Ze.composerOverlay));return}let Rt=Cr(U.id,U.role);Rt.setAttribute("data-ask-plugin-stub","true"),Rt.setAttribute("data-preserve-runtime","true"),h.appendChild(Rt),Ce.push({messageId:U.id,fingerprint:mn,bubble:Zn});return}else{U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(ne.add(U.toolCall.id),sp(U,o,Ze.composerOverlay));return}}else if(qe){let Ue=T();if(!Ue){h.appendChild(Cr(U.id,U.role));return}let _n=a.find(Rt=>typeof Rt.renderApproval=="function")??y,Zn=Kr.get(U.id)!==mn,eo=null;if(Zn&&_n?.renderApproval){let Rt=U.id,Dt=(rt,Lr)=>{let on=Bt.current?.getMessages().find(to=>to.id===Rt);on?.approval&&(on.approval.toolType==="webmcp"?Bt.current?.resolveWebMcpApproval(on.id,rt):Bt.current?.resolveApproval(on.approval,rt,Lr))};eo=_n.renderApproval({message:U,defaultRenderer:()=>Ue.createApprovalBubble(U,o),config:o,approve:rt=>Dt("approved",rt),deny:rt=>Dt("denied",rt)})}if(Zn&&eo===null)i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),Kr.delete(U.id),en=Ue.createApprovalBubble(U,o);else{let Rt=Cr(U.id,U.role);Rt.setAttribute("data-approval-plugin-stub","true"),Rt.setAttribute("data-preserve-runtime","true"),h.appendChild(Rt),Ft.push({messageId:U.id,fingerprint:mn,bubble:eo});return}}else if(Dn)if(U.variant==="reasoning"&&U.reasoning&&Dn.renderReasoning){if(!yt)return;en=Dn.renderReasoning({message:U,defaultRenderer:()=>Mh(U,o),config:o})}else if(U.variant==="tool"&&U.toolCall&&Dn.renderToolCall){if(!X)return;en=Dn.renderToolCall({message:U,defaultRenderer:()=>Eh(U,o),config:o})}else Dn.renderMessage&&(en=Dn.renderMessage({message:U,defaultRenderer:()=>{let Ue=fh(U,f,tt,o.messageActions,St,{loadingIndicatorRenderer:L,widgetConfig:o,actionEligibility:un});return U.role!=="user"&&O(Ue,U,o,_),Ue},config:o}));if(!en&&xe){let Ue=zT(U);if(Ue){let _n=Rs.get(U.id),rs=_n!==mn,Zn=o.wrapComponentDirectiveInBubble!==!1&&zo.getOptions(Ue.component)?.bubbleChrome!==!1,eo=null;if(rs){let Rt=VT(Ue,{config:o,message:U,transform:f});if(Rt&&Ue.component==="PersonaArtifactInline"){let Dt=Rt.hasAttribute("data-artifact-inline")?Rt:Rt.querySelector("[data-artifact-inline]"),rt=Dt?.getAttribute("data-artifact-inline")??"",Lr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(rt):rt,on=rt?i.querySelector(`#wrapper-${U.id}`)?.querySelector(`[data-artifact-inline="${Lr}"]`)??null:null;Dt&&on&&on!==Dt&&Dr()?.hasLiveInlineArtifactBlock(on)&&(Dt===Rt?Rt=on:Dt.replaceWith(on))}if(Rt)if(Zn){let Dt=document.createElement("div");if(Dt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Dt.id=`bubble-${U.id}`,Dt.setAttribute("data-message-id",U.id),U.content&&U.content.trim()){let rt=document.createElement("div");rt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",rt.innerHTML=f({text:U.content,message:U,streaming:!!U.streaming,raw:U.rawContent}),Dt.appendChild(rt)}Dt.appendChild(Rt),eo=Dt}else{let Dt=document.createElement("div");if(Dt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Dt.id=`bubble-${U.id}`,Dt.setAttribute("data-message-id",U.id),Dt.setAttribute("data-persona-component-directive","true"),U.content&&U.content.trim()){let rt=document.createElement("div");rt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",rt.innerHTML=f({text:U.content,message:U,streaming:!!U.streaming,raw:U.rawContent}),Dt.appendChild(rt)}Dt.appendChild(Rt),eo=Dt}}if(eo||_n!=null){let Rt=Cr(U.id,U.role);Rt.setAttribute("data-component-directive-stub","true"),Rt.setAttribute("data-preserve-runtime","true"),h.appendChild(Rt),He.push({messageId:U.id,fingerprint:mn,bubble:eo});return}}}if(!en)if(U.variant==="reasoning"&&U.reasoning){if(!yt)return;en=Mh(U,o)}else if(U.variant==="tool"&&U.toolCall){if(!X)return;en=Eh(U,o)}else if(U.variant==="approval"&&U.approval){if(o.approval===!1)return;let Ue=T();if(!Ue)return;en=Ue.createApprovalBubble(U,o)}else{let Ue=o.layout?.messages;Ue?.renderUserMessage&&U.role==="user"?en=Ue.renderUserMessage({message:U,config:o,streaming:!!U.streaming}):Ue?.renderAssistantMessage&&U.role==="assistant"?en=Ue.renderAssistantMessage({message:U,config:o,streaming:!!U.streaming}):en=fh(U,f,Ue,o.messageActions,St,{loadingIndicatorRenderer:L,widgetConfig:o,actionEligibility:un}),U.role!=="user"&&en&&O(en,U,o,_)}let st=Cr(U.id,U.role);st.appendChild(en),KS(cn,U.id,mn,st),h.appendChild(st)}),Ze.composerOverlay&&Ze.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ct=>{let qe=ct.getAttribute("data-persona-ask-sheet-for");qe&&!ne.has(qe)&&la(Ze.composerOverlay,qe)}),o.features?.toolCallDisplay?.grouped){let U=[],ct=[],qe=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(xe=>{if(xe.variant==="tool"&&xe.toolCall&&X){if(kr&&xe.toolCall.status==="complete")return;ct.push(xe);return}xe.variant==="reasoning"&&(!yt||xe.reasoning?.status==="complete"&&or(xe.reasoning))||((ct.length>1||qe&&ct.length>0)&&U.push(ct),ct=[])}),(ct.length>1||qe&&ct.length>0)&&U.push(ct),U.forEach(xe=>{let Zt=xe.map(tt=>Array.from(h.children).find(st=>st instanceof HTMLElement&&st.getAttribute("data-wrapper-id")===tt.id)).filter(tt=>!!tt);if(Zt.length<(qe?1:2))return;let un=Cr(`tool-group-${xe[0].id}`,"assistant");un.setAttribute("data-persona-tool-group-row","true");let Pn=document.createElement("div");Pn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Pn.setAttribute("data-persona-tool-group","true");let mn=document.createElement("div");mn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",mn.id=`tool-group-summary-${xe[0].id}`;let bn=`Called ${xe.length} ${xe.length===1?"tool":"tools"}`,en=o.toolCall?.renderGroupedSummary?.({messages:xe,toolCalls:xe.map(tt=>tt.toolCall).filter(tt=>!!tt),defaultSummary:bn,config:o});q(mn,en)||(mn.textContent=bn);let Dn=document.createElement("div");Dn.className="persona-tool-group-stack persona-flex persona-flex-col",Dn.id=`tool-group-stack-${xe[0].id}`,Dn.setAttribute("data-persona-tool-group-stack","true"),Pn.appendChild(mn),qe||Pn.appendChild(Dn),un.appendChild(Pn),Zt[0].before(un),Zt.forEach((tt,st)=>{if(qe){tt.remove();return}tt.style.setProperty("--persona-message-row-max-width","100%");let Ue=document.createElement("div");Ue.className="persona-tool-group-item persona-relative",Ue.setAttribute("data-persona-tool-group-item","true"),st<Zt.length-1&&Ue.setAttribute("data-persona-tool-group-connector","true"),Ue.appendChild(tt),Dn.appendChild(Ue)})})}GS(cn,te);let Sl=U=>U.variant==="tool"&&!X||U.variant==="reasoning"&&!yt||Do(U),ei=c.some(U=>U.role==="assistant"&&U.streaming&&!Sl(U)),_o=c.length-1;for(;_o>=0&&Sl(c[_o]);)_o--;let Ln=_o>=0?c[_o]:void 0,No=_o<c.length-1,Zi=Ln?.role==="assistant"&&!Ln.streaming&&Ln.variant!=="approval"&&!No;if(lo&&c.some(U=>U.role==="user")&&!ei&&!Zi){let U={config:o,streaming:!0,location:"standalone",defaultRenderer:hc},ct=a.find(xe=>xe.renderLoadingIndicator),qe=null;if(ct?.renderLoadingIndicator&&(qe=ct.renderLoadingIndicator(U)),qe===null&&o.loadingIndicator?.render&&(qe=o.loadingIndicator.render(U)),qe===null&&(qe=hc()),qe){let xe=document.createElement("div"),Zt=o.loadingIndicator?.showBubble!==!1,un=o.layout?.messages?.layout??"bubble";xe.className=Zt?yc("assistant",un).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),xe.setAttribute("data-typing-indicator","true"),Zt&&(xe.style.color="var(--persona-message-assistant-text, var(--persona-text))",un!=="flat"&&(xe.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",xe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),xe.appendChild(qe);let Pn=Cr("typing-indicator","assistant");Pn.appendChild(xe),h.appendChild(Pn)}}if(!lo&&c.length>0){let U=c[c.length-1],ct={config:o,lastMessage:U,messageCount:c.length},qe=a.find(Zt=>Zt.renderIdleIndicator),xe=null;if(qe?.renderIdleIndicator&&(xe=qe.renderIdleIndicator(ct)),xe===null&&o.loadingIndicator?.renderIdle&&(xe=o.loadingIndicator.renderIdle(ct)),xe){let Zt=document.createElement("div"),un=o.loadingIndicator?.showBubble!==!1;Zt.className=un?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Zt.setAttribute("data-idle-indicator","true"),Zt.appendChild(xe);let Pn=Cr("idle-indicator","assistant");Pn.appendChild(Zt),h.appendChild(Pn)}}if(kC(h),du(i,h),Vf(i),Mt){let{messageId:U,element:ct}=Mt,qe=i.querySelector(`#wrapper-${U}`);qe&&ct.parentElement!==qe&&(Za(qe,Z.get(U)??"user"),qe.replaceChildren(ct))}if(Ce.length>0)for(let{messageId:U,fingerprint:ct,bubble:qe}of Ce){let xe=i.querySelector(`#wrapper-${U}`);xe&&(Za(xe,Z.get(U)??"assistant"),qe!==null&&(xe.replaceChildren(qe),xe.setAttribute("data-bubble-fp",ct),Ii.set(U,ct)))}if(Ii.size>0)for(let U of Ii.keys())te.has(U)||Ii.delete(U);if(He.length>0)for(let{messageId:U,fingerprint:ct,bubble:qe}of He){let xe=i.querySelector(`#wrapper-${U}`);xe&&(Za(xe,Z.get(U)??"assistant"),qe!==null&&(xe.replaceChildren(qe),xe.setAttribute("data-bubble-fp",ct),Rs.set(U,ct)))}if(Rs.size>0)for(let U of Rs.keys())te.has(U)||Rs.delete(U);if(Ft.length>0)for(let{messageId:U,fingerprint:ct,bubble:qe}of Ft){let xe=i.querySelector(`#wrapper-${U}`);xe&&(Za(xe,Z.get(U)??"assistant"),qe!==null&&(xe.replaceChildren(qe),xe.setAttribute("data-bubble-fp",ct),Kr.set(U,ct)))}if(Kr.size>0)for(let U of Kr.keys())te.has(U)||Kr.delete(U)},Rm=!1,dd=()=>{Rm||(Rm=!0,CC().catch(()=>{Rm=!1}))},bo=(i,c,f)=>{c.length>0&&dd(),KE(i,c,f),tb()},el=null,GE=()=>{if(el)return;let i=f=>{let h=f.composedPath();h.includes(it)||Kt&&h.includes(Kt)||Nt(!1,"user")};el=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},Ob=()=>{if(!el)return;(t.ownerDocument??document).removeEventListener("pointerdown",el,!0),el=null};De.push(()=>Ob());let tl=null,YE=()=>{if(tl)return;let i=f=>{f.key==="Escape"&&(f.isComposing||Nt(!1,"user"))};tl=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},Db=()=>{if(!tl)return;(t.ownerDocument??document).removeEventListener("keydown",tl,!0),tl=null};De.push(()=>Db());let nl=!1,_b=new Set,QE=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Di=()=>{if(!Ee())return;let i=Ze.peekBanner,c=Ze.peekTextNode;if(!i||!c)return;if(Pe){i.classList.remove("persona-pill-peek--visible");return}let f=_?.getMessages()??[],h;for(let pn=f.length-1;pn>=0;pn--){let Jt=f[pn];if(Jt.role==="assistant"&&Jt.content){h=Jt;break}}if(!h){i.classList.remove("persona-pill-peek--visible");return}let x=h.content,L=!!h.streaming,q=QE(),te=fu(q),Z=te.type!=="none"?Sm(te.type,q?.plugins):null,ne=Z?.isAnimating?.(h)===!0,pe=Z!==null&&(L||ne);pe&&Z&&!_b.has(Z.name)&&(ic(Z,t),_b.add(Z.name));let Ce=pe&&Z?.containerClass?Z.containerClass:null,He=c.dataset.personaPeekStreamClass??null;He&&He!==Ce&&(c.classList.remove(He),delete c.dataset.personaPeekStreamClass),Ce&&He!==Ce&&(c.classList.add(Ce),c.dataset.personaPeekStreamClass=Ce),pe?(c.style.setProperty("--persona-stream-step",`${te.speed}ms`),c.style.setProperty("--persona-stream-duration",`${te.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let wt=pe?gu(x,te.buffer,Z,h,L):x;if(pe&&te.placeholder==="skeleton"&&L&&(!wt||!wt.trim())){let pn=document.createElement("div"),Jt=sc();Jt.classList.add("persona-pill-peek__skeleton"),pn.appendChild(Jt),du(c,pn)}else{let pn=Math.max(0,wt.length-100),Jt=wt.length>100?wt.slice(-100):wt,Bn=Pr(Jt);if(!pe||!Z){let Mt=wt.length>100?`\u2026${Jt}`:Jt;c.textContent!==Mt&&(c.textContent=Mt)}else{let Mt=Bn;(Z.wrap==="char"||Z.wrap==="word")&&(Mt=rc(Bn,Z.wrap,`peek-${h.id}`,{skipTags:Z.skipTags,startIndex:pn}));let On=document.createElement("div");if(On.innerHTML=Mt,Z.useCaret&&Jt.length>0){let or=hu(),kr=On.querySelectorAll(".persona-stream-char, .persona-stream-word"),Do=kr[kr.length-1];Do?.parentNode?Do.parentNode.insertBefore(or,Do.nextSibling):On.appendChild(or)}du(c,On),Z.onAfterRender?.({container:c,bubble:i,messageId:h.id,message:h,speed:te.speed,duration:te.duration})}}let xn=lo||nl;i.classList.toggle("persona-pill-peek--visible",xn)};if(Ee()){let i=Ze.peekBanner;if(i){let h=x=>{x.preventDefault(),x.stopPropagation(),Nt(!0,"user")};i.addEventListener("pointerdown",h),De.push(()=>{i.removeEventListener("pointerdown",h)})}let c=()=>{nl||(nl=!0,Di())},f=()=>{nl&&(nl=!1,Di())};_e.addEventListener("pointerenter",c),_e.addEventListener("pointerleave",f),De.push(()=>{_e.removeEventListener("pointerenter",c),_e.removeEventListener("pointerleave",f)}),Kt&&(Kt.addEventListener("pointerenter",c),Kt.addEventListener("pointerleave",f),De.push(()=>{Kt.removeEventListener("pointerenter",c),Kt.removeEventListener("pointerleave",f)}))}let XE=i=>{let c=o.launcher?.composerBar??{},f=c.expandedSize??"anchored",h=c.bottomOffset??"16px",x=c.collapsedMaxWidth,L=c.expandedMaxWidth??"880px",q=c.expandedTopOffset??"5vh",te=c.modalMaxWidth??"880px",Z=c.modalMaxHeight??"min(90vh, 800px)",ne="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",Ce=it.style;if(Ce.left="",Ce.right="",Ce.top="",Ce.bottom="",Ce.transform="",Ce.width="",Ce.maxWidth="",Ce.height="",Ce.maxHeight="",Kt){let He=Kt.style;He.bottom=h,He.width=x??""}if(i&&f!=="fullscreen"){if(f==="modal"){Ce.top="50%",Ce.left="50%",Ce.transform="translate(-50%, -50%)",Ce.bottom="auto",Ce.right="auto",Ce.width=te,Ce.maxWidth=ne,Ce.maxHeight=Z,Ce.height=Z;return}Ce.left="50%",Ce.transform="translateX(-50%)",Ce.bottom=`calc(${h} + ${pe})`,Ce.top=q,Ce.width=L,Ce.maxWidth=ne}},ol=()=>{if(Pe&&dd(),!Ne())return;if(Ee()){let ne=(o.launcher?.composerBar??{}).expandedSize??"anchored",pe=Pe?"expanded":"collapsed";it.dataset.state=pe,it.dataset.expandedSize=ne,Kt&&(Kt.dataset.state=pe,Kt.dataset.expandedSize=ne),it.style.removeProperty("display"),it.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),XE(Pe),Le.style.display=Pe?"flex":"none",Es(),Pe?(GE(),YE()):(Ob(),Db()),Di();return}let i=rn(o),c=t.ownerDocument.defaultView??window,f=o.launcher?.mobileBreakpoint??640,h=o.launcher?.mobileFullscreen??!0,x=c.innerWidth<=f,L=h&&x&&ce,q=Lo(o).reveal;Pe?(it.style.removeProperty("display"),it.style.display=i?"flex":"",it.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-95","persona-opacity-0"),_e.classList.add("persona-scale-100","persona-opacity-100"),Qt?(Qt.setPanelOpen(!0),Qt.element.style.display="none"):Fn&&(Fn.style.display="none")):(i?i&&(q==="overlay"||q==="push")&&!L?(it.style.removeProperty("display"),it.style.display="flex",it.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(it.style.setProperty("display","none","important"),it.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(it.style.display="",it.classList.add("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-100","persona-opacity-100"),_e.classList.add("persona-scale-95","persona-opacity-0")),Qt?(Qt.setPanelOpen(!1),Qt.element.style.display=i?"none":""):Fn&&(Fn.style.display=i?"none":""))},Nt=(i,c="user")=>{if(!Ne()||Pe===i)return;let f=Pe;Pe=i,ol();let h=(()=>{let L=o.launcher?.sidebarMode??!1,q=t.ownerDocument.defaultView??window,te=o.launcher?.mobileFullscreen??!0,Z=o.launcher?.mobileBreakpoint??640,ne=q.innerWidth<=Z,pe=rn(o)&&te&&ne,Ce=Ee()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return L||te&&ne&&ce||pe||Ce})();if(Pe&&h){if(!Xo){let L=t.getRootNode(),q=L instanceof ShadowRoot?L.host:t.closest(".persona-host");q&&(Xo=rh(q,o.launcher?.zIndex??Hn))}Jo||(Jo=sh(t.ownerDocument))}else Pe||(Xo?.(),Xo=null,Jo?.(),Jo=null);Pe&&(Cl(),Im()||(ao()==="follow"?Xr(!0):id()));let x={open:Pe,source:c,timestamp:Date.now()};Pe&&!f?k.emit("widget:opened",x):!Pe&&f&&k.emit("widget:closed",x),k.emit("widget:state",{open:Pe,launcherEnabled:ce,voiceActive:gt.active,streaming:_.isStreaming()})},Jr={inputDisabled:!1,sendDisabled:!1},Zo=()=>Jr.inputDisabled,Wm=()=>no(o.voiceRecognition?.provider)&&!!_&&(_.isBargeInActive()||["listening","processing","speaking"].includes(_.getVoiceStatus())),$s=()=>Jr.inputDisabled||Jr.sendDisabled,JE=()=>(Jr.inputDisabled?Jr.inputReason:void 0)??(Jr.sendDisabled?Jr.sendReason:void 0);function Bm(){if(!Ve)return;if(ze.getState().phase==="streaming"){Ve.disabled=!1;return}let i=At?!At.isReady():!1;Ve.disabled=$s()||i}function pd(){if(!jo)return;let i=ze.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;jo.toggleAttribute("data-persona-send-hidden",c)}function ZE(){let i=JE();if(Ee()){let c=Wn??We;i?c.setAttribute("title",i):c.removeAttribute("title"),We.toggleAttribute(Oa,!!i);return}if(i){bt.setAttribute("role","status"),bt.setAttribute("aria-live","polite"),bt.setAttribute(Oa,""),bt.textContent=i;return}if(bt.hasAttribute(Oa)&&(bt.removeAttribute("role"),bt.removeAttribute("aria-live"),bt.removeAttribute(Oa),p)){let c=_.getStatus();Rn(bt,sn(c),o.statusIndicator??{},c)}}function Om(){let i=wg(o.composer?.inputDisabled),c=wg(o.composer?.sendDisabled);Jr={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},ze.setInputDisabled(i.disabled),ze.setSendDisabled(c.disabled);let f=ze.getState().phase==="streaming",h=i.disabled,x=f||h;Ae&&(Ae instanceof HTMLTextAreaElement?Ae.disabled=h:Ae.setAttribute("contenteditable",h?"false":"true"),Ae.setAttribute("aria-disabled",h?"true":"false")),Gt&&(Gt.disabled=h),zt&&(zt.disabled=h);for(let L of nn?.affordanceButtons??[])L.querySelectorAll("button").forEach(q=>{q.disabled=h});fe&&(fe.disabled=h||f&&!Wm()),Ps.forEach(L=>{L.elements.forEach(q=>{q.toggleAttribute("data-disabled",x),q instanceof HTMLButtonElement||q.setAttribute("aria-disabled",x?"true":"false")}),L.buttons.forEach(q=>{q.disabled=x})}),Vm.forEach(L=>{L.toggleAttribute("data-disabled",x),L instanceof HTMLButtonElement?L.disabled=x:L.setAttribute("aria-disabled",x?"true":"false"),L.querySelectorAll("button").forEach(q=>{q.disabled=x})}),We.dataset.personaComposerStreaming=f?"true":"false",We.dataset.personaComposerInputDisabled=h?"true":"false",We.dataset.personaComposerSendDisabled=$s()?"true":"false",We.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(L=>{(L instanceof HTMLButtonElement||L instanceof HTMLInputElement||L instanceof HTMLTextAreaElement||L instanceof HTMLSelectElement)&&(L.disabled=f)}),Bm(),ZE()}let rl=i=>{ze.setStreaming(i),Py(i?"stop":"send"),Om()},zs=()=>{gt.active||Ae&&Ae.focus()};k.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>zs(),200)});let Us=null,sl=!1,Dm=!an.hidden,Zr=null,_m=!w,ud=null;De.push(()=>{ud?.cancel(),ud=null});let ek=i=>{let c=NA(i);if(c===Nc)return;Nc=c,t.setAttribute("data-persona-conversation-state",c);let f=am();Vc(),_m&&(ud?.cancel(),ud=DA(We,c==="active"?f:am(),c==="active"?"drop":"rise")),Xn()},Nb=null,Fb,Vb=null,_i=null,Nm=!1,il=i=>{let c=Br(o),f=`${c.variant}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(f!==Nb||c.icon!==Fb)&&(Nb=f,Fb=c.icon,Au({host:an,iconHolder:_a,kicker:Na,title:om,subtitle:rm,starterSuggestions:wi},c));let h=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;h!==Vb&&(Vb=h,Mu(kn,c.message,o));let x=i??(_?_.getMessages():o.initialMessages);ek(x);let L=sl,q=!L&&Ma(c,x),te=q!==Dm;if(Dm=q,_i){Zr?.cancel(),Zr=null,L!==Nm&&(Nm=L,L?yh(ie,an,null):hh(ie,an,_i)),Aa(ie,an,!L);return}if(te&&!q&&!L&&c.dismiss==="on-first-message"&&_m){Zr=OA(an,ne=>{Zr===ne&&(Zr=null),!Dm&&!_i&&(Aa(ie,an,!1),Xn()),ne?.cancel()});return}if(Zr){if(!q&&!L)return;Zr.cancel(),Zr=null}let Z=!an.hidden;Aa(ie,an,q),!q&&Z&&Xn()},Fm=[],Vm=[],$m=!1,$b=null,zb,Ub=()=>{Vm.length=0;let i=Fm.splice(0,Fm.length);for(let c of i)try{c()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};De.push(Ub);let tk=(i,c)=>{let f=ah(i,c);if(!f)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let h=o.suggestions?.starters,x=lh({item:{...f,behavior:f.behavior??h?.behavior??"send"},index:c,surface:"starter",source:"config",variant:h?.variant??"card",streaming:p?_.isStreaming():!1,config:o,plugins:a,chipsConfig:o.suggestionChipsConfig,session:_,getTextarea:()=>Ae,eventTarget:an,submitPrompt:Nd});return Vm.push(x),x},zm=()=>{if($m)return;$m=!0;let i=Br(o);$b=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,zb=i.icon;try{Ub(),yh(ie,an,_i),_i=null,Nm=!1;let c=_?_.getMessages():o.initialMessages,f=Ma(i,c),h=0,x=null;for(let L of a)if(L.renderWelcome&&(x=L.renderWelcome({config:i,variant:i.variant,visible:f,defaultRenderer:()=>an,sendMessage:q=>{if(!_||_.isStreaming())return;let te=q.trim();te&&_.sendMessage(te)},requestRender:()=>zm(),renderStarter:q=>tk(q,h++),storage:u(L.id),onCleanup:q=>{Fm.push(q)}}),x))break;x&&x!==an&&(_i=x,hh(ie,an,x))}finally{$m=!1}il()},nk=()=>{let i=Br(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===$b&&i.icon===zb||zm()},md=()=>{il(),Ti||(Ae.placeholder=Wx(ze.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(Ve.textContent=o.copy?.sendButtonLabel??"Send")),Ae.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Ae.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},ok=!!o.setStoredConversationId,Ni=i=>Y(c=>{let f={...c};return delete f[i],f}),fd=i=>{let c=R[i];return typeof c=="string"?c:null},qb=()=>{let i=R.durableResume;if(!i||typeof i!="object")return null;let c=i;return typeof c.executionId=="string"&&c.executionId.length>0&&typeof c.after=="string"&&c.after.length>0?{executionId:c.executionId,after:c.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>fd("sessionId"),setStoredSessionId:i=>{Y(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Ni("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>fd("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{Y(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Ni("conversationId"))});let jb=()=>o.clientToken??null,Kb=i=>bT(i,Q(),o.persistState===!1),Gb=jb(),vo=Gb?Kb(Gb):null,wr={...vo?{visitorStore:vo}:{},historyBootstrapReady:H,getStoredMessageCursor:()=>fd("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){Ni("historyMessageCursor");return}Y(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=R.pendingDisplayProjections;if(!i||typeof i!="object")return null;let c=i;return typeof c.conversationId!="string"||!Array.isArray(c.messageIds)?null:{conversationId:c.conversationId,messageIds:c.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:i=>{if(!i){Ni("pendingDisplayProjections");return}Y(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:qb,setStoredResumableHandle:i=>{if(!i){Ni("durableResume");return}Y(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>V&&qb()!==null,...ok?{}:{getStoredConversationRevision:()=>fd("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){Ni("conversationRevision");return}Y(c=>({...c,conversationRevision:i}))}}};if(V){let i=o.onExecutionState,c=t.ownerDocument.defaultView,f=!1,h=()=>f=!0,x=()=>f=!1;c?.addEventListener("pagehide",h),c?.addEventListener("pageshow",x),De.push(()=>{c?.removeEventListener("pagehide",h),c?.removeEventListener("pageshow",x)}),o={...o,reconnectStream:o.reconnectStream??(L=>_.getClient().reconnectClientTokenStream(L)),onExecutionState:L=>{(L||!f)&&wr.setStoredResumableHandle?.(L?{executionId:L.executionId,after:L.lastEventId}:null),i?.(L)}}}let rk=()=>{let i=jb();if(i&&vo?.matches(i,Q(),o.persistState===!1)||!i&&!vo)return;vo?.destroy(),vo=i?Kb(i):null;let c={...wr};vo?c.visitorStore=vo:delete c.visitorStore,wr=c,_.setHistoryInternals(wr)},qs=null,sk=()=>{qs==null&&(qs=setInterval(()=>{let i=Re.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(qs),qs=null;return}let c=Date.now();i.forEach(f=>{let h=Number(f.getAttribute("data-tool-elapsed"));h&&(f.textContent=lp(c-h))})},100))},Um=(i,c)=>{if(Object.is(i,c))return!0;if(i===null||c===null||typeof i!="object"||typeof c!="object")return!1;if(Array.isArray(i)||Array.isArray(c))return!Array.isArray(i)||!Array.isArray(c)||i.length!==c.length?!1:i.every((q,te)=>Um(q,c[te]));let f=i,h=c,x=Object.keys(f),L=Object.keys(h);return x.length===L.length&&x.every(q=>Object.prototype.hasOwnProperty.call(h,q)&&Um(f[q],h[q]))},Yb=i=>{let{content:c,rawContent:f,llmContent:h,...x}=i;return x},qm=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!xy(i),ik=(i,c,f)=>{if(i.length!==c.length)return!1;let h=i[f.index],x=c[f.index];return!h||!x||h.id!==f.id||x.id!==f.id?!1:(!Object.is(h.content,x.content)||!Object.is(h.rawContent,x.rawContent)||!Object.is(h.llmContent,x.llmContent))&&qm(h)&&qm(x)&&Um(Yb(h),Yb(x))},jm=null,Fi=null,js=null,xr=null,Km=null,ak=i=>{if(!V)return Wi(i);Km=i,queueMicrotask(()=>{Km===i&&(Km=null,Wi(i))})},gd=i=>{jm=i;let c,f;Fi=null;for(let x=i.length-1;x>=0;x-=1){let L=i[x];if(!c&&L.role==="user"&&(c=L),!f&&L.role==="assistant"&&(f=L),!Fi&&qm(L)&&(Fi={index:x,id:L.id}),c&&f&&Fi)break}bo(Re,i,Ge),Dr()?.updateInlineArtifactBlocks(Re,yo.artifacts,{suppressTransition:lo}),sk(),il(i),Pi(i),Xr(!lo),jE(i),i.length===0&&(Oo(),Qa=!0,ed=!1,Ri=null,td=!1),!Am||Hi?(Am=!0,_s=c?.id??null,Mm=f?.id??null):c&&c.id!==_s?(_s=c.id,VE(c.id)):f&&f.id!==Mm&&$E(),f&&(Mm=f.id),qE(i);let h=gt.lastUserMessageId;c&&c.id!==h&&(gt.lastUserMessageId=c.id,k.emit("user:message",c)),gt.lastUserMessageWasVoice=!!c?.viaVoice,ak(i),Di()},Gm=()=>{xr!==null&&(cancelAnimationFrame(xr),xr=null);let i=js;js=null,i&&gd(i)},Qb=()=>{xr!==null&&cancelAnimationFrame(xr),xr=null,js=null},lk=i=>{let c=js??jm;if(lo&&c&&Fi&&ik(c,i,Fi)){js=i,xr===null&&(xr=requestAnimationFrame(()=>{xr=null;let f=js;js=null,f&&gd(f)}));return}if(i.length===0){Qb(),gd(i);return}Gm(),gd(i)};_=new vp(o,{onMessagesChanged(i){lk(i)},onStatusChanged(i){let c=o.statusIndicator??{};Rn(bt,(h=>h==="idle"?c.idleText??fn.idle:h==="connecting"?c.connectingText??fn.connecting:h==="connected"?c.connectedText??fn.connected:h==="error"?c.errorText??fn.error:h==="paused"?c.pausedText??fn.paused:h==="resuming"?c.resumingText??fn.resuming:fn[h])(i),c,i),wn()},onStreamingChanged(i){i||(_?.getMessages().length===0?Qb():Gm()),lo=i,rl(i),wn(),_&&bo(Re,_.getMessages(),Ge),i||(Xr(!0),NE(),xb=!0,_&&Sb(_.getMessages(),ps(o))),yn(),_c(i?"Responding\u2026":"Response complete."),Di()},onVoiceStatusChanged(i){if(k.emit("voice:status",{status:i,timestamp:Date.now()}),!(i!=="disconnected"&&!no(o.voiceRecognition?.provider)))switch(i){case"listening":Er(),Xi();break;case"processing":Er(),d0();break;case"speaking":Er(),p0();break;default:i==="idle"&&_.isBargeInActive()?(Er(),Xi(),fe?.setAttribute("aria-label","End voice session")):(gt.active=!1,Er(),vr("system"),Bo());break}},onArtifactsState(i){yo=i,i.artifacts.length===0&&(Ei=!1),Dr()?.updateInlineArtifactBlocks(Re,i.artifacts,{suppressTransition:lo}),Wo(),Wi()},onHistoryStateChanged(i){vn(i)},onHistoryNotice(i){Cn(i)},onReconnect(i){let{executionId:c,lastEventId:f}=i.handle;i.phase==="paused"?k.emit("stream:paused",{executionId:c,after:f}):i.phase==="resuming"?k.emit("stream:resuming",{executionId:c,after:f,attempt:i.attempt??1}):k.emit("stream:resumed",{executionId:c,after:f})}},wr),Bt.current=_,De.push(()=>_.cancel()),De.push(()=>{_.destroy(),vo?.destroy(),vo=null});let Ym=null;if(_.onReadAloudChange((i,c)=>{Zy=i,eb=c,tb();let f=i??Ym;i&&(Ym=i);let h=f?_.getMessages().find(x=>x.id===f)??null:null;k.emit("message:read-aloud",{messageId:f,message:h,state:c,timestamp:Date.now()}),c==="idle"&&(Ym=null)}),p=!0,Am=!0,o.voiceRecognition?.enabled===!0&&no(o.voiceRecognition.provider))try{_.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let ck=720,dk=250,Ct=ly(o.features?.history?.copy),uo=null,Qm=!1,Ht=null,hd=null,yd="conversation",Xm=null,Nn=null,er=null,bd=_.getHistoryState(),Jm=null,al=0,Zm=null,vd=null,Cd=null,ef=`persona-history-${Math.random().toString(36).slice(2,8)}`,tf=()=>o.features?.history?.enabled===!0,tr=()=>tf()&&!!uo&&!Qm,Xb=()=>{let i=_.getStatus();return lo||i==="paused"||i==="resuming"},nf=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",f=uo?.capabilities.scopes;return!f||f.includes(c)?c:f[0]??c},Vi=()=>hd?.scope??nf(),Jb=()=>_.getClientSession()?.targetId??null,Zb=i=>`${i.state}:${"reason"in i?i.reason:""}`,pk=i=>{let c=Zb(i);c!==Jm&&(Jm=c,k.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},wd=i=>{i&&(mr.textContent="",mr.textContent=i)},ev=null,tv=null,uk=()=>{if(!tf())return null;let i=NT();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(ev!==c&&(ev=c,tv=c()),tv):_.isClientTokenMode()?FT({client:_.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:f=>_.bindActivatedSession(f),getClient:()=>_.getClient()}):null},nv=()=>{vd?.(),vd=null,Cd?.(),Cd=null,Qm=!1,uo=uk();let i={...wr};uo?i.historyProvider=uo:delete i.historyProvider,wr=i,_.setHistoryInternals(wr),uo&&(vd=uo.subscribeAvailability?.(c=>{Qm=!c,c||Jn({restoreFocus:!1}),ts()})??null,Cd=uo.subscribeIdentityStatus(c=>pk(c)),Jm=Zb(uo.getIdentityStatus()))},of=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!ce||rn(o)))return"panel";let c=Qo??Le;return(c.getBoundingClientRect().width||c.clientWidth)>=ck?"rail":"panel"},Co=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},xd="data-persona-history-suppressed",mo=null,es=null,Ks=null,ll=null,rf=null,ov="",rv=()=>he===rf?ov:o.layout?.showHeader===!1?"none":"",mk=()=>Se==="panel"&&!!Ks&&ll===Ks.element&&o.layout?.showHeader!==!1&&rv()!=="none",fk=()=>{for(let i of Array.from(he.children))i!==mo&&i.setAttribute(xd,"")},gk=()=>{for(let i of Array.from(Le.querySelectorAll(`[${xd}]`)))i.removeAttribute(xd)},hk=()=>{let i=Ks;if(!i)return;if(Array.from(he.children).some(h=>h!==mo&&!h.hasAttribute(xd))){es&&es!==he&&(es.style.removeProperty("min-height"),es=null);let h=he.offsetHeight;h>0&&(he.style.minHeight=`${h}px`,es=he)}mo||(mo=v("div","persona-history-header-host")),i.setHeaderPlacement("external");let f=i.getHeaderElement();f.parentNode!==mo&&mo.replaceChildren(f),mo.parentNode!==he&&he.appendChild(mo),fk()},sv=()=>{es&&(es.style.removeProperty("min-height"),es=null),mo&&(Ks?.setHeaderPlacement("inline"),mo.remove(),mo=null,gk())},Sd=null,sf=()=>{if(Sd){if(ie.style.display="none",Co(ie,!0),We.hidden=!0,Co(We,!0),mk()){hk(),he.style.display=rv(),Co(he,!1);return}sv(),he.style.display="none",Co(he,!0)}};Ke=sf;let yk=i=>{let c=ie.style.display,f=We.hidden,h=We,x=he,L=he.style.display;rf=x,ov=L,Sd=()=>{Sd=null,sv(),rf=null,ie.style.display=c,Co(ie,!1),h.hidden=f,Co(h,!1),We!==h&&(We.hidden=!1,Co(We,!1)),x.style.display=L,Co(x,!1),he!==x&&(he.style.display=o.layout?.showHeader===!1?"none":"",Co(he,!1))},We.parentNode?.insertBefore(i,We),sf()},$i=null,Gs=null,cl=null,zi=null,iv=()=>[he,Ze.closeButtonWrapper,Ze.clearChatButtonWrapper,ie,We],bk=52,Ad=()=>o.features?.history?.rail?.collapsible!==!1,Ui=()=>o.features?.history?.rail?.side==="right"?"right":"left",af=200,lf=400,cf=i=>Math.min(lf,Math.max(af,Math.round(i))),vk=()=>o.features?.history?.rail?.resizable===!0,dl,Ck=()=>{if(dl===void 0&&(dl=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${Q()}rail-width`));i&&(dl=i)}catch{}return dl},pl=()=>cf(Ck()??o.features?.history?.rail?.width??260),wk=i=>{if(dl=i,o.persistState!==!1)try{window.localStorage.setItem(`${Q()}rail-width`,String(i))}catch{}},Md=()=>Ad()&&o.features?.history?.rail?.collapsedBehavior==="overlay",dn=!1,av=i=>{let c=v("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},xk=()=>{let i=o.features?.history?.rail?.brand;if(!i)return;let c=!1,f;return h=>{if(i.render)try{return i.render({collapsed:h})??null}catch(x){return c||(c=!0,console.warn("[persona] history rail brand threw",x)),null}return f===void 0&&(i.iconUrl?f=av(i.iconUrl):f=i.icon?Ie(i.icon,20):null),f?f.cloneNode(!0):null}},Sk=()=>o.features?.history?.rail?.sections?.map(i=>{let c=!1,f=h=>{c||(c=!0,console.warn("[persona] history rail section threw",i.id,h))};return{id:i.id,title:i.title,placement:i.placement??"above-conversations",items:i.items.map(h=>{let x;return{id:h.id,label:h.label,badge:h.badge,iconNode:()=>{if(x!==void 0)return x;try{h.renderIcon?x=h.renderIcon()??null:h.iconUrl?x=av(h.iconUrl):x=h.icon?Ie(h.icon,20):null}catch(L){f(L),x=null}return x},onSelect:()=>{try{h.onSelect()}catch(L){f(L)}}}})}})??[],Ak=i=>{let c=Sk();for(let f of i)c.some(h=>h.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):c.push(f);return c.length?c:void 0},ul=null,lv=()=>`${Q()}rail-collapsed`,df=()=>{if(ul===null&&(ul=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(lv());i&&(ul=i==="1")}catch{}return ul},pf=i=>{if(ul=i,o.persistState!==!1)try{window.localStorage.setItem(lv(),i?"1":"0")}catch{}},ml=()=>Se==="rail"&&Ad()&&!Md()&&df(),uf=()=>{},cv=()=>{if(Md()){uf();return}pf(!df()),Ht?.view.setCollapsed(ml()),ut(),Xn()},mf=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!lu(i)?null:{combo:i,hint:cu(i),aria:tc(i)}},dv=()=>{d.forEach(c=>c()),d=[];let i=mf();i&&d.push(l.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>ve&&Se==="rail"&&Ad()||ji(),run:()=>Md()?uf():cv()}));for(let c of o.layout?.header?.trailingActions??[])c.shortcut&&d.push(l.register({id:`header-action-${c.id}`,combo:c.shortcut,run:()=>{let f=t.querySelector(`[data-persona-header-action="${c.id}"]`);f?f.click():o.layout?.header?.onAction?.(c.id)}}));for(let c of a)for(let f of c.shortcuts??[])d.push(l.register({...f,id:`${c.id}:${f.id}`}))};dv();let Mk=300,Td="var(--persona-history-overlay-margin,8px)",wo=null,Sr=null,Ed=0,Ar=null,qi=null,Ys=!1,ff=0,pv=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,ji=()=>tr()&&Md()&&(Se??of())==="rail",Tk=()=>ve&&!dn,fl=()=>{qi!==null&&clearTimeout(qi),qi=null},Ek=()=>{by().catch(()=>{})},uv=()=>{fl(),dn&&(qi=setTimeout(()=>{qi=null,!(Ys||!dn)&&(Ar?.contains(document.activeElement)||Jn({restoreFocus:!1}))},Mk))},kk=(i,c)=>{let f=Ar?.getBoundingClientRect();if(!f)return!1;let h=wo?.getBoundingClientRect(),x=h?Math.min(h.top,f.top):f.top;return i>=f.left&&i<=f.right&&c>=x&&c<=f.bottom||!!h&&i>=h.left&&i<=h.right&&c>=h.top&&c<=h.bottom},gf=i=>{dn&&(Ys=kk(i.clientX,i.clientY),Ys?fl():qi===null&&uv())},mv=i=>{ve||!ji()||(dn=!0,hl({invoker:wo,keyboard:i?.keyboard===!0}).then(()=>{ve?!Ys&&document.activeElement!==wo&&Jn():dn=!1}))},fv=()=>{let i=ll?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",dn?Ct.expandLabel:Ct.collapseLabel),i.setAttribute("aria-expanded",dn?"false":"true"))},gv=()=>{pf(!1);let i=Ht;if(!dn||!i){hl({invoker:wo});return}let c=document.activeElement===wo;dn=!1,kd(),i.element.remove(),yf(i.element),fv(),c&&Pd(),Xn(),ts()},Lk=()=>{pf(!0),Jn()};uf=()=>{!ve||dn?gv():Lk()};let Pk=()=>{let i=mf(),c=ai({ariaLabel:Ct.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":ef,...i?{"aria-keyshortcuts":i.aria}:{}}}),f=c.button;f.addEventListener("mouseenter",()=>{Ys=!0,fl(),!(pv()||Date.now()<ff)&&mv()}),f.addEventListener("mouseleave",()=>{Ys=!1,ff=0,uv()}),f.addEventListener("focus",()=>{ve||Ek()}),f.addEventListener("click",h=>{tr()&&(h.detail!==0&&pv()&&!ve?mv():gv())}),wo=f,Sr=c.wrapper},gl=()=>{if(Sr&&!Sr.isConnected&&(Sr=null,wo=null),!ji()){Sr?.remove(),Sr=null,wo=null;return}wo||Pk();let i=Sr,c=wo;if(!i||!c)return;let f=Ui()!=="right"?he.firstChild:null;(f??he.lastChild)!==i&&he.insertBefore(i,f),i.style.display=Tk()||Ed>0?"none":"",c.setAttribute("aria-label",Ct.expandLabel),c.setAttribute("aria-expanded",ve?"true":"false"),Ar&&ut()},hv=i=>{if(!dn)return;let c=i.target;c instanceof Node&&(Ar?.contains(c)||Sr?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||Jn({restoreFocus:!1}))};document.addEventListener("pointerdown",hv,!0),De.push(()=>{document.removeEventListener("pointerdown",hv,!0),document.removeEventListener("pointermove",gf),Ki?.(),fl()});let hf=null,Ki=null,yv=16,bv=i=>{wk(cf(i)),ut(),Xn()},Ik=()=>{let i=v("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(af)),i.setAttribute("aria-valuemax",String(lf)),i.addEventListener("pointerdown",c=>{let f=Gs;if(!f||c.button!==0)return;c.preventDefault(),Ki?.();let h=c.clientX,x=f.getBoundingClientRect().width||pl(),L=Ui()==="right"?-1:1,q=x,te=t.ownerDocument;f.style.transition="none";let Z=pe=>{q=cf(x+L*(pe.clientX-h)),f.style.flex=`0 0 ${q}px`,i.setAttribute("aria-valuenow",String(q))},ne=()=>{Ki=null,te.removeEventListener("pointermove",Z),te.removeEventListener("pointerup",ne),te.removeEventListener("pointercancel",ne),f.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}bv(q)};Ki=ne,te.addEventListener("pointermove",Z),te.addEventListener("pointerup",ne),te.addEventListener("pointercancel",ne);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let f=Ui()==="right"?-yv:yv,h=pl(),x=c.key==="ArrowRight"?h+f:c.key==="ArrowLeft"?h-f:c.key==="Home"?af:c.key==="End"?lf:null;x!==null&&(c.preventDefault(),bv(x))}),i},Hk=(i,c)=>{if(!vk()||ml()){Ki?.(),hf?.remove();return}let f=hf??Ik();hf=f,f.setAttribute("aria-label",Ct.resizeLabel),f.setAttribute("aria-valuenow",String(pl())),f.nextElementSibling!==c&&i.insertBefore(f,c)};ut=()=>{Ht?.view.setRailSide(Ui());let i=Ui()==="right",c=Ar;if(c){let te=wo?wo.getBoundingClientRect().bottom-Le.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(te))}px + ${Td})`,c.style.width=`${pl()}px`,c.style.left=i?"":Td,c.style.right=i?Td:""}let f=Gs,h=$i,x=cl;if(!f||!h||!x)return;f.style.flex=`0 0 ${ml()?bk:pl()}px`;let L="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=i?"":L,f.style.borderLeft=i?L:"";let q=i?x:f;h.firstElementChild!==q&&h.append(q,i?f:x),Hk(h,i?f:x)};let vv=i=>{if(zi&&Gs){zi.replaceWith(i),zi=null,ut();return}let c=v("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=v("div","persona-history-rail-conversation");f.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let h=v("div","persona-history-rail-host");h.style.cssText="display:flex;min-height:0;overflow:hidden",Le.insertBefore(c,he.parentNode===Le?he:ie);for(let x of iv())x?.parentNode===Le&&f.appendChild(x);c.append(h,f),h.appendChild(i),$i=c,Gs=h,cl=f,ut()},Rk=()=>{if($i)return;let i=v("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",zi=i,vv(i),Xn()},Cv=()=>{zi&&(kd(),Xn())},Wk=i=>{let c=v("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${Td};display:flex;overflow:hidden;z-index:${fa-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,Le.style.position="relative",Le.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",gf),Ar=c,ut(),fv()},kd=()=>{Sd?.(),Ar&&(Ys&&(ff=Date.now()+150),document.removeEventListener("pointermove",gf),Ar.remove(),Ar=null);let i=$i;if(i){Ki?.();for(let c of iv())c&&i.contains(c)&&Le.insertBefore(c,i);i.remove(),$i=null,Gs=null,cl=null,zi=null}},wv=i=>{ll=i,i.id=ef,i.style.flex="1 1 auto",i.style.minHeight="0"},yf=i=>{wv(i),(Se!=="rail"||dn)&&Cv(),Se!=="rail"?yk(i):dn?Wk(i):vv(i)},Ld=()=>{if(gl(),Hv(),!ve||!Ht)return;let i=of();if(i===Se)return;let c=document.activeElement,f=c instanceof HTMLElement&&(Ht.element.contains(c)||mo?.contains(c)===!0)?c:null;kd(),Ht.element.remove(),Ht.view.setHeaderPlacement("inline"),Se=i,Ht.view.setPresentation(i),Ht.view.setCollapsed(ml()),Ht.requestRender(),Ht.element.isConnected||yf(Ht.element),f?.isConnected?f.focus():Pd(),yn(),Xn(),ts()},xv=(i,c)=>mo?.querySelector(c)??i.querySelector(c),Pd=()=>{let i=Ht?.element??ll;if(!i)return;let c=xv(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let f=xv(i,".persona-history-title")??i;f.tabIndex=-1,f.focus()},hl=async i=>{if(!tr()||ve)return;let c=uo;if(!c)return;if(!dn&&ji()&&df()){gl();return}Id();let f=++al;yd=i?.returnSurface??"conversation",Xm=i?.invoker??Nn;let h=ji()&&!dn;h&&(Ed+=1,gl(),Rk());let x;try{x=await by()}catch{wd(Ct.openHistoryLabel),h&&(Ed-=1,f===al&&(Cv(),gl()));return}if(h&&(Ed-=1),f!==al||ve)return;hd={scope:nf()},Se=of(),ve=!0;let L=Se==="panel"&&o.layout?.showHeader!==!1&&he.style.display!=="none"?"external":"inline",q=o.features?.history?.rowAvatar,te=mf(),Z=te?{hint:te.hint,aria:te.aria}:null,ne={provider:c,context:hd,targetId:Jb(),presentation:Se,collapsible:Ad(),collapsed:ml(),railSide:Ui(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:xk(),onToggleCollapse:cv,...Z?{collapseShortcut:Z}:{},headerPlacement:L,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:q===!1?!1:typeof q=="string"?q:o.launcher?.iconUrl,activeConversationId:_.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:pe=>vf(pe,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:pe=>Qs(pe),attachTooltip:Mn,onStartNew:()=>Cf({focusComposer:!0}),onClose:()=>Jn(),onRequestDeleteConversation:pe=>Iv(pe),onRequestClearHistory:()=>Fk(),...c.resetDevice?{onRequestResetIdentity:()=>Vk()}:{}};Ht=_T({plugins:a,config:o,getPresentation:()=>Se??"panel",getReturnSurface:()=>yd,close:()=>Jn(),createView:({slots:pe,renderDom:Ce,onModelChange:He,railSections:wt})=>(Ks=x.createHistoryView({...ne,railSections:Ak(wt),slots:pe,renderDom:Ce,onModelChange:He,onAnnounce:wd}),Ks),onElementChanged:(pe,Ce)=>{if(!Ce?.isConnected)return yf(pe);wv(pe),Ce.replaceWith(pe),sf()}}),Ht.view.setNewConversationRequired(bd.recovery==="new_conversation_required"),i?.focus!==!1&&(Se!=="rail"||i?.keyboard===!0)&&Pd(),yn(),Xn(),ts(),k.emit("history:opened",{presentation:Se,returnSurface:yd,timestamp:Date.now()})},Id=()=>{},Jn=i=>{if(!ve)return;al+=1;let c=yd,f=Xm,h=Ht,x=i?.restoreFocus!==!1;ve=!1;let L=!1,q=null,te=()=>{if(!L){if(L=!0,Id=()=>{},q!==null&&clearTimeout(q),dn=!1,fl(),kd(),h?.dispose(),h?.view.destroy(),h?.element.remove(),Ht===h&&(Ht=null,Ks=null,ll=null,Se=null,hd=null,Xm=null),yn(),Xn(),ts(),x){let ne=f??Nn;ne?.isConnected?ne.focus():zs()}k.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},Z=h&&h.element===h.view.element?h.view.playExit():null;if(!Z){te();return}Id=te,q=setTimeout(te,dk),Z.then(te)},Sv=i=>{if(!(i.key!=="Escape"||!ve||!Ht)){if(Se==="rail"){let c=i.target;if(!(c instanceof Node)||!(Ht.element.contains(c)||dn&&Sr?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),Jn()}};Le.addEventListener("keydown",Sv),De.push(()=>Le.removeEventListener("keydown",Sv));let Hd=null,Av=!1,yl=()=>{if(!Be)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&Hd?.trim()||null;Be.textContent=c??o.launcher?.title??"Chat Assistant";let f=Be.closest(".persona-combo-btn");if(!f)return;let h=!i||_.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",h?"false":"true"),f.setAttribute("aria-haspopup",h?"true":"false"),h||f.setAttribute("aria-expanded","false"),f.style.cursor=h?"pointer":"default";let x=f.querySelector("svg");x&&(x.style.display=h?"":"none")},Bk=i=>{i!==Hd&&(Hd=i,yl())},Qs=i=>{Av=i?.starred===!0,Bk(i&&i.title.trim()||null),yl()};yl(),Le.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,f=_.getActiveConversationId();f&&(c==="delete"?Iv(f):c==="star"&&_.canUpdateConversations()&&wf(f,{starred:!Av}).catch(()=>{}))});let Rd=0,Ok=250,Wd=null,Bd=()=>{Wd&&clearTimeout(Wd),Wd=null};De.push(Bd);let Mv=()=>{Bd();let i=Us;i&&(sl=!0,i.hidden=!1,Re.style.display="none",il())},Od=()=>{Rd+=1,Bd(),Us&&(Us.remove(),Us=null,sl=!1,Re.style.removeProperty("display"),Co(We,!1),il())},Dk=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Re.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},bf=(i,c)=>$("div",{className:Vt("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),Tv=()=>$("div",{className:"persona-conversation-loading-body"},bf("58%",!1),bf("72%",!0),bf("44%",!1)),Ev=i=>{Us?.remove(),Us=i,i.hidden=!sl,ie.insertBefore(i,Re),Bd(),sl||(Wd=setTimeout(Mv,Ok)),Co(We,!0)},_k=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Tv},c=null,f=a.find(h=>h.renderLoadingIndicator);f?.renderLoadingIndicator&&(c=f.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),Ev($("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ct.openConversationLoadingLabel}},c??Tv()))},Nk=i=>{let c=()=>{vf(i,{focusComposer:!0}).catch(()=>{})},f=tr()?()=>{Od(),hl()}:void 0,h=(te,Z)=>{let ne=$("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:te});return ne.addEventListener("click",Z),ne},x=()=>$("div",{className:"persona-conversation-loading-error-body"},$("p",{className:"persona-conversation-loading-error-title",text:Ct.openConversationErrorTitle}),$("div",{className:"persona-conversation-loading-error-actions"},h(Ct.openConversationRetryLabel,c),f?h(Ct.openConversationBackLabel,f):null)),L=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Ct.openConversationErrorTitle,retryLabel:Ct.openConversationRetryLabel,backLabel:Ct.openConversationBackLabel}),retry:c,...f?{back:f}:{},defaultRenderer:x}),q=null;for(let te of a)if(te.renderHistoryOpenError){try{q=te.renderHistoryOpenError(L)}catch(Z){console.warn("[persona] renderHistoryOpenError threw",Z),q=null}if(q)break}Ev($("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},q??x())),Mv()};k.on("history:closed",()=>{Us&&Co(We,!0)});let vf=async(i,{focusComposer:c=!1}={})=>{let f=Vi(),h=!!Ht;Ht?.view.setActiveConversationId(i),Od();let x=Rd;_k(),ve&&(Se==="panel"||dn)&&Jn({restoreFocus:!1}),Hi=!0;try{await _.openConversation(i,{scope:f})}catch(L){throw x===Rd&&Nk(i),L}finally{Hi=!1}x===Rd&&(Od(),cn.clear(),Oo(),Qn(),Im()||id(),Dk(),Mr(),h||Qs(null),k.emit("history:conversationOpened",{conversationId:i,title:Hd,scope:f,timestamp:Date.now()}),c&&zs())},Cf=async({focusComposer:i=!1}={})=>{Od(),await _.startNewConversation({scope:Vi()}),Qs(null),cn.clear(),Oo(),Qn(),id(),Mr();let c=_.getActiveConversationId();Ht?.view.setActiveConversationId(c),k.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),ve&&(Se==="panel"||dn)&&Jn({restoreFocus:!1}),i&&zs()},wf=async(i,c)=>{let f=await _.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return Ht?.view.applyConversationSummary(f),!Ht&&i===_.getActiveConversationId()&&Qs(f),f},kv=async i=>{let c=Vi(),f=_.getActiveConversationId()===i;await _.deleteConversation(i,{scope:c}),Ht?.view.removeConversationSummary(i),f&&(Qs(null),cn.clear(),Oo(),Qn(),Mr()),k.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:f,timestamp:Date.now()})},Lv=async i=>{let c=i?.scope??Vi(),f=i?.allTargets?null:i?.targetId??Jb(),h=await _.clearConversationHistory({...f?{targetId:f}:{},scope:c});return Qs(null),cn.clear(),Oo(),Qn(),Mr(),k.emit("history:cleared",{deleted:h.deleted,scope:c,targetId:f,timestamp:Date.now()}),h},Pv=async()=>{if(!uo?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await _.resetHistoryDevice()).remoteRevocationConfirmed}finally{Qs(null),_.clearArtifacts(),cn.clear(),jm=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),R={},se.syncFromMetadata(),W?.clear&&od(()=>W.clear(),"[AgentWidget] Failed to clear storage adapter:"),Oo(),Qn(),Mr(),Jn({restoreFocus:!1}),zs(),Pe||Qt?.launcher.element.focus()}return wd(i?Ct.identityResetNotice:Ct.identityResetUnconfirmedNotice),k.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},xf=()=>Qo?_e:Le,Iv=async i=>await em({host:xf(),title:Ct.deleteConversationConfirmTitle,description:Ct.deleteConversationConfirm,confirmLabel:Ct.deleteConversationConfirmLabel,cancelLabel:Ct.confirmCancelLabel})?(await kv(i),"deleted"):"cancelled",Fk=async()=>{let i=Vi()==="verified-user";return await em({host:xf(),title:Ct.clearHistoryConfirmTitle,description:i?Ct.clearHistoryVerifiedConfirm:Ct.clearHistoryConfirm,confirmLabel:Ct.clearHistoryConfirmLabel,cancelLabel:Ct.confirmCancelLabel})?(await Lv(),"cleared"):"cancelled"},Vk=async()=>{if(!await em({host:xf(),title:Ct.resetIdentityConfirmTitle,description:Ct.resetIdentityConfirm,confirmLabel:Ct.resetIdentityConfirmLabel,cancelLabel:Ct.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await Pv();return{outcome:"reset",remoteRevocationConfirmed:c}},xo=v("button","persona-history-earlier");xo.type="button",xo.textContent=Ct.showEarlierMessagesLabel,xo.setAttribute("data-persona-history-earlier",""),Object.assign(xo.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let Mr=()=>{if(!(tr()&&!!bd.nextMessageCursor&&!!_.getActiveConversationId())){xo.remove();return}xo.textContent=Ct.showEarlierMessagesLabel,xo.parentNode!==ie&&ie.insertBefore(xo,ie.firstChild)};xo.addEventListener("click",()=>{let i=_.getActiveConversationId(),c=bd.nextMessageCursor;if(!i||!c||xo.disabled)return;xo.disabled=!0;let f=ie.scrollHeight,h=ie.scrollTop;_.loadOlderMessages(i,c,{scope:Vi()}).then(()=>{ie.scrollTop=h+(ie.scrollHeight-f),Xn()}).catch(()=>{}).finally(()=>{xo.disabled=!1,Mr()})});let $k=()=>{let i=ai({ariaLabel:Ct.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return i.button.addEventListener("click",c=>{if(!(!tr()||Xb())){if(ve){Jn();return}hl({invoker:i.button,keyboard:c.detail===0})}}),i},Hv=()=>{if(!tr()){er?.remove(),Nn=null,er=null;return}if(er&&!er.isConnected&&(Nn=null,er=null),!Nn&&he){let h=$k();Nn=h.button,er=h.wrapper;let x=Ze.clearChatButtonWrapper||Ze.closeButtonWrapper;x?.parentNode&&he.contains(x)?x.parentNode.insertBefore(er,x):he.appendChild(er)}if(!Nn||!er)return;let i=ji()||ve&&Se==="rail";if(er.style.display=i?"none":"",i){document.activeElement===Nn&&Pd();return}let c=Xb();Nn.disabled=c,Nn.setAttribute("aria-disabled",c?"true":"false");let f=c?Ct.openHistoryBusyLabel:Ct.openHistoryLabel;Nn.setAttribute("aria-label",f),(o.features?.history?.presentation??"panel")==="panel"?(Nn.removeAttribute("aria-expanded"),Nn.removeAttribute("aria-controls")):(Nn.setAttribute("aria-expanded",ve?"true":"false"),Nn.setAttribute("aria-controls",ef))},Dd=!1,zk=()=>{let i=Ze.clearChatButton;if(i){if(tr()){Dd||(Zm=i.getAttribute("aria-label")??"",Dd=!0),i.setAttribute("aria-label",Ct.newConversationLabel),i.removeAttribute("title");return}Dd&&(Dd=!1,Zm&&i.setAttribute("aria-label",Zm))}},ts=()=>{Ct=ly(o.features?.history?.copy),Hv(),gl(),zk(),Mr()};wn=ts,vn=i=>{bd=i,Ht?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),rl(i.sendBlocked||lo),Mr()},Cn=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(cn.clear(),Oo(),Qn()),wd(i.message),Ht?.view.refresh()},nv(),ts(),De.push(()=>{vd?.(),Cd?.(),al+=1,Id(),Ht?.dispose(),Ht?.view.destroy(),Ht=null}),o.clientToken&&_.initClientSession().then(()=>{if(tr())return _.reconcileBootConversation({scope:nf()})}).then(()=>{Mr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(P||o.onSSEEvent)&&_.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),pt(i,c)});let Rv=()=>{let i=o.resume??(V?wr.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(i)};w?w.then(i=>{if(i){if(i.metadata&&(R=Sy(i.metadata),se.syncFromMetadata()),i.messages?.length){Hi=!0;try{_.hydrateMessages(i.messages)}finally{Hi=!1}dd()}i.artifacts?.length&&_.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),Lb(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{_m=!0,E(),Rv()}):(Lb(D),Rv());let Uk=()=>{!Ee()||Pe||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Nt(!0,"auto")},qk=(i,c)=>i?c?{refs:[...i.refs,...c.refs],finalize:async()=>{let[f,h]=await Promise.allSettled([i.finalize(),c.finalize()]),x=[];return f.status==="fulfilled"?x.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),h.status==="fulfilled"?x.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),DB(x)}}:i:c,Sf=()=>{let c=Ae.getInlineMessageFields?.();return c&&c.contentSegments.some(h=>h.kind==="mention")?c.contentSegments:void 0},Tr=!1,Xs=null,_d=()=>{Ae.value="",Ae.style.height="auto",Ko(),vl()},Af="data-persona-composer-notice",Gi=null;function jk(i){_c(i),!(Ee()||!bt)&&(bt.hasAttribute(Oa)||(bt.setAttribute(Af,""),bt.setAttribute("role","status"),bt.setAttribute("aria-live","polite"),bt.textContent=i,Gi&&clearTimeout(Gi),Gi=setTimeout(()=>{if(Gi=null,!!bt?.hasAttribute(Af)&&(bt.removeAttribute(Af),bt.removeAttribute("role"),bt.removeAttribute("aria-live"),p)){let c=_.getStatus();Rn(bt,sn(c),o.statusIndicator??{},c)}},4e3)))}function Kk(){let i=ze.getState().pendingSubmission;i&&(Ai(void 0),Ae&&(Ae.value=i.text,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Ko()),i.options.selectedModelId&&(ze.setSelectedModelId(i.options.selectedModelId),Ur?.repaint()),i.options.activeModeIds?.length&&$c(i.options.activeModeIds),i.options.quote&&Go(i.options.quote),Ae?.focus())}let Gk=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},Wv=(i={})=>{let c=(i.overrideText??Ae?.value??"").trim();return i.resolveInlineCommand&&c?(nn?.takeInlineCommand(c)??Promise.resolve(null)).then(f=>Bv(i,c,f)):Bv(i,c,null)},Bv=(i,c,f)=>{if(f?.kind==="action"){_d(),nn?.clear(),Ts();return}let h=f?.kind==="server"?f.mentions:null,x=f?.kind==="prompt"?f.sendText:c,L=i.pending?.contentParts,q=(At?.hasAttachments()??!1)||(L?.length??0)>0;if(!Kx({text:x,hasAttachments:q,attachmentsReady:At?.isReady()??!0,hasMentions:nn?.hasMentions()??!1,hasServerMentions:!!h,inputDisabled:Zo(),sendDisabled:$s()}))return;let te=_.isStreaming()?pm():"block";if(te==="defer-one"&&!i.pending){if(ze.getState().pendingSubmission){jk("One message is already queued. Edit or remove it first.");return}Yk({intent:i,sendText:x,serverMentions:h});return}let Z={text:x,mentionRefs:[...nn?.getMentionRefs()??[],...h?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:Sf(),options:{...ze.getState().selectedModelId&&{selectedModelId:ze.getState().selectedModelId},...ze.getState().activeModeIds.length>0&&{activeModeIds:[...ze.getState().activeModeIds]},...ze.getState().quote&&{quote:{...ze.getState().quote}}},viaVoice:i.viaVoice};i.pending&&(Z.options={...i.pending.options},Z.contentSegments=i.pending.contentSegments,Z.mentionRefs=[...i.pending.mentionRefs],Z.viaVoice=i.pending.viaVoice);let ne=()=>{if(L?.length)return[...L];if(!At?.hasAttachments())return;let Ft=[...At.getContentParts()];return Z.text&&Ft.push(sr(Z.text)),Ft};Z.contentParts=ne();let pe=()=>{Bs(),Uk();let Ft=nn?.collectForSubmit()??null,xn=qk(Ft,h),pn=ne();i.consumeDraft!==!1&&_d();let Jt={selectedModelId:Z.options.selectedModelId,activeModeIds:Z.options.activeModeIds},Bn=te==="interrupt";Bn&&_.cancel(),_.sendMessage(Z.text,{contentParts:pn,mentions:xn??void 0,contentSegments:Z.contentSegments,viaVoice:Z.viaVoice,composerOptions:Jt,...Z.options.quote&&{quote:Z.options.quote},...Bn&&{interrupt:!0}}),At?.hasAttachments()&&At.clearAttachments(),Ft&&nn?.clear(),Ts();let Mt=ze.getState().activeModeIds,On=Rx(Mt,o.composer?.modes);On.length!==Mt.length&&$c(On),ze.getState().quote&&Go(void 0),sd(),hm.release(),Ho()},Ce=o.composer?.onBeforeSend;if(!Ce){pe();return}let He=new AbortController;Xs=He;let wt=Ft=>{if(Xs=null,Ft.status==="error"){Gk(Ft.error);return}Ft.status==="proceed"&&pe()},Ot=Gx(Ce,Z,He.signal);if(!(Ot instanceof Promise)){wt(Ot);return}return ze.setPreparing(!0),Ot.then(wt).finally(()=>ze.setPreparing(!1))};function Yk(i){let c=ze.getState(),f=At?.hasAttachments()??!1,h=f?[...At.getContentParts()]:[];f&&i.sendText&&h.push(sr(i.sendText));let x=Hg({text:i.sendText,contentParts:h.length?h:void 0,mentionRefs:[...nn?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:Sf(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});Ai(x),i.intent.consumeDraft!==!1&&_d(),f&&At.clearAttachments(),nn?.clear(),Ts(),c.quote&&Go(void 0),sd(),hm.release(),Ho(),_c("Message queued. It sends when the response finishes.")}function Qk(){let i=ze.getState().pendingSubmission;i&&(Ai(void 0),Fd(i.text,{consumeDraft:!1,pending:i}))}function Xk(i){if(o.messageActions?.showEdit!==!0)return;let c=_.getMessages().find(f=>f.id===i);!c||!ng(c)||Ws!==i&&(Bs(),Ws=i,Gr=_x({messageId:i,initialText:c.content,onSave:f=>Jk(i,f),onCancel:()=>Bs()}),cn.delete(i),bo(Re,_.getMessages(),Ge),Gr.focus())}function Jk(i,c){let f=Gr;if(Ws=null,Gr=null,f?.destroy(),cn.delete(i),!_.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){bo(Re,_.getMessages(),Ge);return}Xn()}function Zk(i){if(_.isStreaming())return;let c=tg(_.getMessages(),i);c&&(Bs(),_.resubmitFrom(c,{reason:"retry"})&&Xn())}zc={regenerate:Zk,edit:Xk,quote:i=>{let f=_.getMessages().find(h=>h.id===i)?.content?.trim();f&&(Go({text:f,messageId:i}),Ae?.focus())}};let bl=async i=>{if(!Tr){Tr=!0;try{await Wv({resolveInlineCommand:!0,...i})}finally{Tr=!1}}};function Nd(i){$s()||(_d(),Fd(i,{consumeDraft:!1}))}let Fd=(i,c)=>{if(Tr)return;Tr=!0;let f=()=>{Tr=!1};try{let h=Wv({...c,overrideText:i});h instanceof Promise?h.finally(f):f()}catch(h){throw f(),h}},e0=i=>{if(i.preventDefault(),_.isStreaming()){_.cancel(),lt?.reset(),mt?.update();return}Tr||bl()},t0=()=>o.features?.composerHistory!==!1,Mf={...Qg},Tf=!1,vl=()=>{Mf={...Qg}},n0=()=>_.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),o0=i=>{if(!Ae)return;Tf=!0,Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Tf=!1;let c=Ae.value.length;Ae.setSelectionRange(c,c)},r0=i=>{Tf||(i.isComposing||nn?.handleInput(i.inputType??void 0),vl())},s0=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:ql(Ae)}),i0=i=>{if(Ae&&!Zo()&&!(!i.isComposing&&nn?.handleKeydown(i))){if(t0()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let c=Ae.selectionStart===0&&Ae.selectionEnd===0,f=zS({direction:i.key==="ArrowUp"?"up":"down",history:n0(),currentValue:Ae.value,atStart:c,state:Mf});if(Mf=f.state,f.handled){i.preventDefault(),f.value!==void 0&&o0(f.value);return}}if(fx(i,s0())){if(_.isStreaming()){if(i.preventDefault(),pm()==="block"||Tr||$s())return;vl(),bl();return}if(Tr){i.preventDefault();return}if($s()){i.preventDefault();return}vl(),i.preventDefault(),Ve.click()}}},Ov=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(Le)){if(Xs){Xs.abort(),Xs=null,i.preventDefault(),i.stopImmediatePropagation();return}_.isStreaming()&&(_.cancel(),lt?.reset(),mt?.update(),vl(),i.preventDefault(),i.stopImmediatePropagation())}},a0=async i=>{if(o.attachments?.enabled!==!0||!At||Zo())return;let c=RB(i.clipboardData);c.length!==0&&(i.preventDefault(),await At.handleFiles(c))},So=null,nr=!1,Yi=null,qt=null,Ef=()=>o.voiceRecognition?.completionBehavior==="review";function Js(i){fe?.setAttribute("data-state",i),i==="recording"?c0():If()}let Dv="--persona-voice-level",kf=.5,Qi=null,Lf=-1,Vd=0,_v=()=>{let i=[],c=io??fe?.parentElement??null;return c&&i.push(c),We&&i.push(We),i},Pf=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==Lf){Lf=c;for(let f of _v())f.style.setProperty(Dv,String(c))}},l0=()=>{Lf=-1,Vd=0;for(let i of _v())i.style.removeProperty(Dv)};function c0(){if(Qi!==null)return;if(typeof requestAnimationFrame!="function"){Pf(p?_.getVoiceLevel()??kf:kf);return}let i=()=>{Qi=requestAnimationFrame(i);let c=p?_.getVoiceLevel():null;if(c===null){Pf(kf);return}Vd+=(c-Vd)*.3,Pf(Vd)};Qi=requestAnimationFrame(i)}function If(){Qi!==null&&(cancelAnimationFrame(Qi),Qi=null),l0()}let Nv=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,$d=(i="user")=>{if(nr||_.isStreaming())return;let c=Nv();if(!c)return;So=new c;let f=o.voiceRecognition??{},h=f.pauseDuration??2e3;So.continuous=f.provider?.browser?.continuous??!0,So.interimResults=!0,So.lang=f.provider?.browser?.language??"en-US";let x=Ae.value;So.onresult=L=>{let q="",te="";for(let ne=0;ne<L.results.length;ne++){let pe=L.results[ne],Ce=pe[0].transcript;pe.isFinal?q+=Ce+" ":te=Ce}let Z=x+q+te;Ae.value=Z,Ko(),Yi&&clearTimeout(Yi),(q||te)&&(Yi=window.setTimeout(()=>{if(Ae.value.trim()&&So&&nr){if(ns(),Ef())return;bl({viaVoice:!0})}},h))},So.onerror=L=>{L.error!=="no-speech"&&ns()},So.onend=()=>{if(nr){let L=Ae.value.trim();!Ef()&&L&&L!==x.trim()&&bl({viaVoice:!0}),ns()}};try{if(So.start(),nr=!0,gt.active=!0,i!=="system"&&(gt.manuallyDeactivated=!1),vr(i),Bo(),Ho(),fe){let L=o.voiceRecognition??{};qt={backgroundColor:fe.style.backgroundColor,color:fe.style.color,borderColor:fe.style.borderColor,iconName:L.iconName??"mic",iconSize:parseFloat(L.iconSize??"")||$n};let q=L.recordingBackgroundColor,te=L.recordingIconColor,Z=L.recordingBorderColor;if(fe.classList.add("persona-voice-recording"),Js("recording"),fe.style.backgroundColor=q??"var(--persona-voice-recording-bg, #ef4444)",fe.style.color=te??"var(--persona-voice-recording-indicator, #ffffff)",te){let ne=fe.querySelector("svg");ne&&ne.setAttribute("stroke",te)}Z&&(fe.style.borderColor=Z),fe.setAttribute("aria-label","Stop voice recognition")}}catch{ns("system")}},ns=(i="user")=>{if(nr){if(nr=!1,Yi&&(clearTimeout(Yi),Yi=null),So){try{So.stop()}catch{}So=null}if(gt.active=!1,vr(i),Bo(),Ho(),fe){if(fe.classList.remove("persona-voice-recording"),Js("idle"),qt){fe.style.backgroundColor=qt.backgroundColor,fe.style.color=qt.color,fe.style.borderColor=qt.borderColor;let c=fe.querySelector("svg");c&&c.setAttribute("stroke",qt.color||"currentColor"),qt=null}fe.setAttribute("aria-label","Start voice recognition")}}},Hf=()=>{if(!fe||qt)return;let i=o.voiceRecognition??{};qt={backgroundColor:fe.style.backgroundColor,color:fe.style.color,borderColor:fe.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||$n}},Rf=(i,c)=>{if(!fe)return;let f=fe.querySelector("svg");f&&f.remove();let h=qt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||$n),x=Ie(i,h,c,1.5);x&&fe.appendChild(x)},zd=()=>{fe&&fe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Xi=()=>{if(!fe)return;Hf();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,f=i.recordingIconColor,h=i.recordingBorderColor;if(zd(),fe.classList.add("persona-voice-recording"),Js("recording"),fe.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",fe.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let x=fe.querySelector("svg");x&&x.setAttribute("stroke",f)}h&&(fe.style.borderColor=h),fe.setAttribute("aria-label","Stop voice recognition")},d0=()=>{if(!fe)return;Hf();let i=o.voiceRecognition??{},c=_.getVoiceInterruptionMode(),f=i.processingIconName??"loader",h=i.processingIconColor??qt?.color??"",x=i.processingBackgroundColor??qt?.backgroundColor??"",L=i.processingBorderColor??qt?.borderColor??"";zd(),fe.classList.add("persona-voice-processing"),Js("processing"),fe.style.backgroundColor=x,fe.style.borderColor=L;let q=h||"currentColor";fe.style.color=q,Rf(f,q),fe.setAttribute("aria-label","Processing voice input"),c==="none"&&(fe.style.cursor="default")},p0=()=>{if(!fe)return;Hf();let i=o.voiceRecognition??{},c=_.getVoiceInterruptionMode(),f=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",h=i.speakingIconName??f,x=i.speakingIconColor??(c==="barge-in"?i.recordingIconColor??qt?.color??"":qt?.color??""),L=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":qt?.backgroundColor??""),q=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":qt?.borderColor??"");zd(),fe.classList.add("persona-voice-speaking"),Js("speaking"),fe.style.backgroundColor=L,fe.style.borderColor=q;let te=x||"currentColor";fe.style.color=te,Rf(h,te);let Z=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";fe.setAttribute("aria-label",Z),c==="none"&&(fe.style.cursor="default"),c==="barge-in"&&fe.classList.add("persona-voice-recording")},Er=()=>{fe&&(zd(),Js("idle"),qt&&(fe.style.backgroundColor=qt.backgroundColor??"",fe.style.color=qt.color??"",fe.style.borderColor=qt.borderColor??"",Rf(qt.iconName,qt.color||"currentColor"),qt=null),fe.style.cursor="",fe.setAttribute("aria-label","Start voice recognition"))},Wf=()=>{if(!Zo()){if(no(o.voiceRecognition?.provider)){let i=_.getVoiceStatus(),c=_.getVoiceInterruptionMode();if(c==="none"&&(i==="processing"||i==="speaking"))return;if(c==="cancel"&&(i==="processing"||i==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Bo(),vr("user"),Er()});return}_.toggleVoice().then(()=>{gt.active=_.isVoiceActive(),gt.manuallyDeactivated=!_.isVoiceActive(),Bo(),vr("user"),_.isVoiceActive()?Xi():Er()});return}if(nr){let i=Ae.value.trim();gt.manuallyDeactivated=!0,Bo(),ns("user"),i&&!Ef()&&bl()}else gt.manuallyDeactivated=!1,Bo(),$d("user")}};um=Wf,fe&&De.push(()=>{no(o.voiceRecognition?.provider)?(_.isVoiceActive()&&_.toggleVoice(),Er()):ns("system")});let u0=k.on("assistant:complete",()=>{ze.getState().pendingSubmission&&setTimeout(()=>{_.isStreaming()||Qk()},0)});De.push(u0);let m0=k.on("assistant:complete",()=>{Tb&&(gt.active||gt.manuallyDeactivated||Tb==="assistant"&&!gt.lastUserMessageWasVoice||setTimeout(()=>{!gt.active&&!gt.manuallyDeactivated&&(no(o.voiceRecognition?.provider)?_.toggleVoice().then(()=>{gt.active=_.isVoiceActive(),vr("auto"),_.isVoiceActive()&&Xi()}):$d("auto"))},600))});De.push(m0);let f0=k.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});De.push(f0);let Fv=()=>{Nt(!Pe,"user")},Qt=null,Fn=null;if(ce&&!Ee()){let{instance:i,element:c}=Sh({config:o,plugins:a,onToggle:Fv});Qt=i,i||(Fn=c)}Qt?t.appendChild(Qt.element):Fn&&t.appendChild(Fn),ol(),Pi(),md(),zm(),rl(_.isStreaming()),Im()||(ao()==="follow"?Xr(!0):id()),RE(),ge&&(!ce||Ee()?setTimeout(()=>zs(),0):Pe&&setTimeout(()=>zs(),200));let Zs=null,Vv=()=>{Zs&&(Zs.disconnect(),Zs.observe(We),Zs.observe(Le))},Cl=()=>{if(Ee()){Ms(),ol();return}let i=rn(o),c=o.launcher?.sidebarMode??!1,f=t.ownerDocument.defaultView??window,h=o.launcher?.mobileFullscreen??!0,x=o.launcher?.mobileBreakpoint??640,L=f.innerWidth<=x,q=h&&L&&ce;try{if(q){Es(),Ka=Xc();return}let te=!1;nt&&(nt=!1,Es(),te=!0);let Z=Xc();if(!te&&Z!==Ka&&(Es(),te=!0),Ka=Z,te&&Kc(),!ce&&!i){_e.style.height="",_e.style.width="";return}if(!c&&!i){let pe=o?.launcher?.width??o?.launcherWidth??Rr;_e.style.width=pe,_e.style.maxWidth=pe}Qc(),db()}finally{if(Ms(),Vc(),ol(),Pe&&ce){let Z=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ne=o.launcher?.sidebarMode??!1,pe=o.launcher?.mobileFullscreen??!0,Ce=rn(o)&&pe&&Z,He=ne||pe&&Z&&ce||Ce;if(He&&!Jo){let wt=t.getRootNode(),Ot=wt instanceof ShadowRoot?wt.host:t.closest(".persona-host");Ot&&!Xo&&(Xo=rh(Ot,o.launcher?.zIndex??Hn)),Jo=sh(t.ownerDocument)}else He||(Xo?.(),Xo=null,Jo?.(),Jo=null)}}};Cl();let Ud=t.ownerDocument.defaultView??window;if(Ud.addEventListener("resize",Cl),De.push(()=>Ud.removeEventListener("resize",Cl)),typeof ResizeObserver<"u"){Zs=new ResizeObserver(()=>{Vc()}),Vv(),De.push(()=>{Zs?.disconnect(),Zs=null});let i=new ResizeObserver(()=>{Ld()});i.observe(Le),De.push(()=>i.disconnect())}Ud.addEventListener("resize",Ld),De.push(()=>Ud.removeEventListener("resize",Ld)),po=ie.scrollTop;let $v=cr(ie),zv=()=>{let i=ie.scrollTop,c=cr(ie),f=c<$v;if($v=c,!zr()){po=i,yn();return}let{action:h,nextLastScrollTop:x}=uu({following:co.isFollowing(),currentScrollTop:i,lastScrollTop:po,nearBottom:Wr(ie,yr),userScrollThreshold:LE,isAutoScrolling:Yn||Zc||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(po=x,h==="resume"){ad()||Qn();return}h==="pause"&&Ja()};if(ie.addEventListener("scroll",zv,{passive:!0}),De.push(()=>ie.removeEventListener("scroll",zv)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{FE(),Vf(Re)});i.observe(Re),i.observe(ie),De.push(()=>i.disconnect())}let Uv=()=>{zr()&&co.isFollowing()&&ad()&&Ja()},qv=ie.ownerDocument;qv.addEventListener("selectionchange",Uv),De.push(()=>{qv.removeEventListener("selectionchange",Uv)});let g0=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),jv=i=>{g0.has(i.key)&&(Ns(),Iy()&&zr()&&co.isFollowing()&&Ja())},Kv=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Ns(),Iy()&&zr()&&co.isFollowing()&&Ja())};ie.addEventListener("keydown",jv),ie.addEventListener("focusin",Kv),De.push(()=>{ie.removeEventListener("keydown",jv),ie.removeEventListener("focusin",Kv)});let Gv=i=>{if(i.deltaY!==0&&Ns(),!zr())return;let c=mu({following:co.isFollowing(),deltaY:i.deltaY,nearBottom:Wr(ie,yr),resumeWhenNearBottom:!0});c==="pause"?Ja():c==="resume"&&!ad()&&Qn()};ie.addEventListener("wheel",Gv,{passive:!0}),ie.addEventListener("touchmove",Ns,{passive:!0}),ie.addEventListener("pointerdown",Ns,{passive:!0}),De.push(()=>{ie.removeEventListener("touchmove",Ns),ie.removeEventListener("pointerdown",Ns)}),De.push(()=>ie.removeEventListener("wheel",Gv)),ln.addEventListener("click",()=>{Oo(),ie.scrollTop=ie.scrollHeight,po=ie.scrollTop,Qn(),Xr(!0),yn()}),De.push(()=>ln.remove()),De.push(()=>{Ib(),Oo()});let Yv=()=>{F&&(Is&&(F.removeEventListener("click",Is),Is=null),Ne()?(F.style.display="",Is=()=>{Nt(!1,"user")},F.addEventListener("click",Is)):F.style.display="none")};Yv(),(()=>{let{clearChatButton:i}=Ze;i&&i.addEventListener("click",()=>{if(tr()){Cf({focusComposer:!0}).catch(f=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}_.clearMessages(),cn.clear(),Qn(),la(Ze.composerOverlay);try{localStorage.removeItem(Ba),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ba}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ba)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),W?.clear&&od(()=>W.clear(),"[AgentWidget] Failed to clear storage adapter:"),R={},se.syncFromMetadata(),At?.clearAttachments(),sd(),Ai(void 0),Go(void 0),Bs(),je?.clear(),lt?.reset(),mt?.update()})})();let Qv=[["keydown",i0],["input",r0],["input",Ko],["input",Ts],["keyup",Ts],["paste",a0],["focus",yE]],Xv=i=>{if(i)for(let[c,f]of Qv)Lt?.addListener(i,c,f)},h0=i=>{if(i)for(let[c,f]of Qv)Lt?.removeListener(i,c,f)},Jv=()=>{Lt&&(Lt.addListener(Lt.form,"submit",e0),Lt.addListener(Lt.footer,"click",Ts),Xv(Ae),fe&&Lt.addListener(fe,"click",Wf))};Jv();let Zv=()=>{nn?.onComposerSwap((i,c)=>{h0(c),Ae=i,Lt&&(Lt.input=i),Xv(i),fm(),Om(),Ko()})};Zv();let Bf=!1;function eC(){if(!Bf){Bf=!0;try{let i=Ae?.value??"",c=We.ownerDocument??document,f=Ae?c.activeElement===Ae:!1;If(),Lt?.destroy(),Lt=null,nn?.destroy(),nn=null;let h=null,x=()=>(h=Ee()?wu({config:o}):gc({config:o}),h.footer),L=Vy(x)??x();tn.replaceComposer(L),We=tn.composer.footer;let q=h!==null&&L===h.footer;Ti=!q,Py=q?h.setSendButtonMode:()=>{},Fy(We),zy(We),Uy(),qy(),jy(),Zv(),Ky(),gm(),Gy(),Jv();let te=Ps.indexOf(hr);hr.destroy(),hr=uc(Io),te>=0&&(Ps[te]=hr),Ae&&(Ae.value=i),Ko(),Ts(),md(),Pi(),rl(_.isStreaming()),gt.active&&Js("recording"),Es(),Vv(),Ms(),Ho(),pd(),f&&Ae?.focus()}finally{Bf=!1}}}let wl=t.ownerDocument??document;wl.addEventListener("keydown",Ov,!0);let tC=()=>{Em()},nC=()=>{wl.visibilityState==="hidden"&&Em()};typeof window<"u"&&(window.addEventListener("pagehide",tC),wl.addEventListener("visibilitychange",nC),De.push(()=>{window.removeEventListener("pagehide",tC),wl.removeEventListener("visibilitychange",nC)}));let oC="persona-attachment-drop-active",xl=0,Of=()=>{xl=0,Le.classList.remove(oC)},Ji=()=>o.attachments?.enabled===!0&&At!==null&&!Zo(),rC=i=>{!tm(i.dataTransfer)||!Ji()||(xl++,xl===1&&Le.classList.add(oC))},sC=i=>{!tm(i.dataTransfer)||!Ji()||(xl--,xl<=0&&Of())},iC=i=>{!tm(i.dataTransfer)||!Ji()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},aC=i=>{if(!tm(i.dataTransfer)||!Ji())return;i.preventDefault(),i.stopPropagation(),Of();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&At.handleFiles(c)},os=!0;Le.addEventListener("dragenter",rC,os),Le.addEventListener("dragleave",sC,os),t.addEventListener("dragover",iC,os),t.addEventListener("drop",aC,os);let qd=t.ownerDocument,lC=i=>{Ji()&&i.preventDefault()},cC=i=>{Ji()&&i.preventDefault()};qd.addEventListener("dragover",lC),qd.addEventListener("drop",cC),De.push(()=>{Lt?.destroy(),Lt=null,If(),Yo?.destroy(),Yo=null,fr?.destroy(),fr=null,qr?.destroy(),qr=null,jr?.destroy(),jr=null,Ur=null,dm=null,Em(),Xa.destroy(),Gi&&clearTimeout(Gi),Bs(),Xs?.abort(),Xs=null,At?.destroy(),At=null,ze.destroy(),wl.removeEventListener("keydown",Ov,!0),nn?.destroy()}),De.push(()=>{Le.removeEventListener("dragenter",rC,os),Le.removeEventListener("dragleave",sC,os),t.removeEventListener("dragover",iC,os),t.removeEventListener("drop",aC,os),qd.removeEventListener("dragover",lC),qd.removeEventListener("drop",cC),Of()}),De.push(()=>{_.cancel()}),Qt?De.push(()=>{Qt?.destroy()}):Fn&&De.push(()=>{Fn?.remove()});let Xt={update(i){let c=o.toolCall,f=o.messageActions,h=o.layout?.messages,x=o.colorScheme,L=o.loadingIndicator,q=o.iterationDisplay,te=o.features?.showReasoning,Z=o.features?.showToolCalls,ne=o.features?.toolCallDisplay,pe=o.features?.reasoningDisplay,Ce=o.features?.streamAnimation?.type,He=o.features?.history?.enabled===!0,wt=o.features?.history?.provider,Ot=o.getIdentityProof,Ft=o.clientToken,xn=o.contextMentions;o=mT({...o,features:s},i),s=o.features,o=ty(o),r(),wm(),Zl(t,o),kc(t,o),Lc(t,o),ut(),Wo(),o.colorScheme!==x&&pb();let pn=ry.getForInstance(o.plugins);a.length=0,a.push(...pn),dv(),ce=o.launcher?.enabled??!0,we=o.launcher?.autoExpand??!1,yt=o.features?.showReasoning??!0,X=o.features?.showToolCalls??!0,j=o.features?.scrollToBottom??{};let Jt=ao();J=o.features?.scrollBehavior??{},Jt!==ao()&&(Oo(),Qn()),Mb(),Wy(),yn();let Bn=P;if(P=o.features?.showEventStreamToggle??!1,P&&!Bn){if(je||(_t(),_.setSSEEventCallback((ue,ht)=>{o.onSSEEvent?.(ue,ht),pt(ue,ht)})),!kt&&he){let ue=o.features?.eventStream?.classNames,ht="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ue?.toggleButton?" "+ue.toggleButton:"");kt=v("button",ht),kt.style.width="28px",kt.style.height="28px",kt.style.color=Un.actionIconColor,kt.type="button",kt.setAttribute("aria-label","Event Stream"),kt.title="Event Stream";let vt=Qe(Fr.Activity,"18px","currentColor",1.5);vt&&kt.appendChild(vt);let Pt=Ze.clearChatButtonWrapper,jt=Ze.closeButtonWrapper,In=Pt||jt;In&&In.parentNode===he?he.insertBefore(kt,In):he.appendChild(kt),kt.addEventListener("click",()=>{Tt?Mi():mm()})}}else!P&&Bn&&(Mi(),kt&&(kt.remove(),kt=null),je?.clear(),Te?.destroy(),je=null,Te=null,lt?.reset(),lt=null,ot=null);if(o.launcher?.enabled===!1&&Qt&&(Qt.destroy(),Qt=null),o.launcher?.enabled===!1&&Fn&&(Fn.remove(),Fn=null),o.launcher?.enabled!==!1&&!Qt&&!Fn){let{instance:ue,element:ht}=Sh({config:o,plugins:a,onToggle:Fv});Qt=ue,ue||(Fn=ht),t.appendChild(ht)}Qt&&Qt.update(o),yl(),et&&o.launcher?.subtitle!==void 0&&(et.textContent=o.launcher.subtitle);let Mt=o.layout?.header;if(Mt?.layout!==ke&&he){let ue=Mt?vu(o,Mt,{showClose:Ne(),onClose:()=>Nt(!1,"user")}):li({config:o,showClose:Ne(),onClose:()=>Nt(!1,"user")});tn.replaceHeader(ue),he=tn.header.element,le=tn.header.iconHolder,Be=tn.header.headerTitle,et=tn.header.headerSubtitle,F=tn.header.closeButton,ke=Mt?.layout,yl()}else if(Mt){if(le&&(le.style.display=Mt.showIcon===!1?"none":""),Be&&(Be.style.display=Mt.showTitle===!1?"none":""),et&&(et.style.display=Mt.showSubtitle===!1?"none":""),F){let ue=Ne()&&Mt.showCloseButton!==!1;F.style.display=ue?"":"none"}if(Ze.clearChatButtonWrapper){let ue=Mt.showClearChat;if(ue!==void 0){Ze.clearChatButtonWrapper.style.display=ue?"":"none";let{closeButtonWrapper:ht}=Ze;ht&&!ht.classList.contains("persona-absolute")&&(ue?ht.classList.remove("persona-ml-auto"):ht.classList.add("persona-ml-auto"))}}}let or=o.layout?.showHeader!==!1;he&&(he.style.display=or?"":"none");let kr=o.layout?.showFooter!==!1;We&&(We.style.display=kr?"":"none"),Ms(),yn(),ce!==ye?ce?Nt(we,"auto"):(Pe=!0,ol()):we!==N&&Nt(we,"auto"),N=we,ye=ce,Cl(),Yv();let ei=JSON.stringify(o.toolCall)!==JSON.stringify(c),_o=JSON.stringify(o.messageActions)!==JSON.stringify(f),Ln=JSON.stringify(o.layout?.messages)!==JSON.stringify(h),No=o.loadingIndicator?.render!==L?.render||o.loadingIndicator?.renderIdle!==L?.renderIdle||o.loadingIndicator?.showBubble!==L?.showBubble,Zi=o.iterationDisplay!==q,U=(o.features?.showReasoning??!0)!==(te??!0)||(o.features?.showToolCalls??!0)!==(Z??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ne)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(pe);(ei||_o||Ln||No||Zi||U)&&_&&(Os++,bo(Re,_.getMessages(),Ge));let qe=o.features?.streamAnimation?.type;if(qe!==Ce&&qe&&qe!=="none"){let ue=Sm(qe,o.features?.streamAnimation?.plugins);ue&&ic(ue,t)}let xe=o.launcher??{},Zt=xe.headerIconHidden??!1,un=o.layout?.header?.showIcon,Pn=Zt||un===!1,mn=xe.headerIconName,bn=xe.headerIconSize??"48px";if(le){let ue=he,ht=ue?.querySelector(".persona-flex-col");if(Pn)le.style.display="none",ue&&ht&&!ue.contains(ht)&&ue.insertBefore(ht,ue.firstChild);else{if(le.style.display="",le.style.height=bn,le.style.width=bn,ue&&ht&&(ue.contains(le)?le.nextSibling!==ht&&(le.remove(),ue.insertBefore(le,ht)):ue.insertBefore(le,ht)),mn){let Pt=parseFloat(bn)||24,jt=Ie(mn,Pt*.6,"currentColor",1);jt?le.replaceChildren(jt):le.textContent=xe.agentIconText??"\u{1F4AC}"}else if(xe.iconUrl){let Pt=le.querySelector("img");if(Pt)Pt.src=xe.iconUrl,Pt.style.height=bn,Pt.style.width=bn;else{let jt=document.createElement("img");jt.src=xe.iconUrl,jt.alt="",jt.className="persona-rounded-xl persona-object-cover",jt.style.height=bn,jt.style.width=bn,le.replaceChildren(jt)}}else{let Pt=le.querySelector("svg"),jt=le.querySelector("img");(Pt||jt)&&le.replaceChildren(),le.textContent=xe.agentIconText??"\u{1F4AC}"}let vt=le.querySelector("img");vt&&(vt.style.height=bn,vt.style.width=bn)}}let en=o.layout?.header?.showTitle,Dn=o.layout?.header?.showSubtitle;if(Be&&(Be.style.display=en===!1?"none":""),et&&(et.style.display=Dn===!1?"none":""),F){let ue=Ne()&&o.layout?.header?.showCloseButton!==!1;if(F.style.display=ue?"":"none",!Ee()){let Sn=xe.closeButtonSize??"";F.style.height=Sn,F.style.width=Sn,F.style.minWidth=Sn,F.style.minHeight=Sn}let ht=xe.closeButtonPlacement??"inline",{closeButtonWrapper:vt}=Ze,Pt=ht==="top-right",jt=vt?.classList.contains("persona-absolute");if(vt&&Pt!==jt)if(vt.remove(),Pt){vt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Sn=cl??Le;Sn.style.position="relative",Sn.appendChild(vt)}else{let Sn=xe.clearChat?.placement??"inline",An=xe.clearChat?.enabled??!0;vt.className=An&&Sn==="inline"?"":"persona-ml-auto",he&&he.appendChild(vt)}if(F.style.color=xe.closeButtonColor||Un.actionIconColor,xe.closeButtonBackgroundColor?(F.style.backgroundColor=xe.closeButtonBackgroundColor,F.classList.remove("hover:persona-bg-gray-100")):(F.style.backgroundColor="",F.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let Sn=xe.closeButtonBorderWidth||"0px",An=xe.closeButtonBorderColor||"transparent";F.style.border=`${Sn} solid ${An}`,F.classList.remove("persona-border-none")}else F.style.border="",F.classList.add("persona-border-none");xe.closeButtonBorderRadius?(F.style.borderRadius=xe.closeButtonBorderRadius,F.classList.remove("persona-rounded-full")):(F.style.borderRadius="",F.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(F.style.paddingLeft=xe.closeButtonPaddingX,F.style.paddingRight=xe.closeButtonPaddingX):(F.style.paddingLeft="",F.style.paddingRight=""),xe.closeButtonPaddingY?(F.style.paddingTop=xe.closeButtonPaddingY,F.style.paddingBottom=xe.closeButtonPaddingY):(F.style.paddingTop="",F.style.paddingBottom=""),yu(F,xe.closeButtonIconName??"x",{iconSize:Ee()?vh:void 0,iconText:xe.closeButtonIconText??"\xD7"});let In=xe.closeButtonTooltipText??"Close chat",Fo=xe.closeButtonShowTooltip??!0;F.setAttribute("aria-label",In),vt&&Mn({anchor:F,trigger:vt,text:()=>F?.getAttribute("aria-label")??In,enabled:Fo})}let{clearChatButton:tt,clearChatButtonWrapper:st}=Ze;if(tt){let ue=xe.clearChat??{},ht=ue.enabled??!0,vt=o.layout?.header?.showClearChat,Pt=vt!==void 0?vt:ht,jt=ue.placement??"inline";if(st){st.style.display=Pt?"":"none";let{closeButtonWrapper:In}=Ze;!Ee()&&In&&!In.classList.contains("persona-absolute")&&(Pt?In.classList.remove("persona-ml-auto"):In.classList.add("persona-ml-auto"));let Fo=jt==="top-right",Sn=st.classList.contains("persona-absolute");if(!Ee()&&Fo!==Sn&&Pt){if(st.remove(),Fo){st.className="persona-absolute persona-top-4 persona-z-50",st.style.right="48px";let rr=cl??Le;rr.style.position="relative",rr.appendChild(st)}else{st.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",st.style.right="";let rr=Ze.closeButtonWrapper;he&&rr&&rr.parentElement===he?he.insertBefore(st,rr):he&&he.appendChild(st)}let An=Ze.closeButtonWrapper;An&&!An.classList.contains("persona-absolute")&&(Fo?An.classList.add("persona-ml-auto"):An.classList.remove("persona-ml-auto"))}}if(Pt){if(!Ee()){let An=ue.size??"";tt.style.height=An,tt.style.width=An,tt.style.minWidth=An,tt.style.minHeight=An}let In=ue.iconColor??"";if(tt.style.color=In||Un.actionIconColor,yu(tt,ue.iconName??"refresh-cw",{iconSize:Ee()?Ch:void 0}),ue.backgroundColor?(tt.style.backgroundColor=ue.backgroundColor,tt.classList.remove("hover:persona-bg-gray-100")):(tt.style.backgroundColor="",tt.classList.add("hover:persona-bg-gray-100")),ue.borderWidth||ue.borderColor){let An=ue.borderWidth||"0px",rr=ue.borderColor||"transparent";tt.style.border=`${An} solid ${rr}`,tt.classList.remove("persona-border-none")}else tt.style.border="",tt.classList.add("persona-border-none");ue.borderRadius?(tt.style.borderRadius=ue.borderRadius,tt.classList.remove("persona-rounded-full")):(tt.style.borderRadius="",tt.classList.add("persona-rounded-full")),ue.paddingX?(tt.style.paddingLeft=ue.paddingX,tt.style.paddingRight=ue.paddingX):(tt.style.paddingLeft="",tt.style.paddingRight=""),ue.paddingY?(tt.style.paddingTop=ue.paddingY,tt.style.paddingBottom=ue.paddingY):(tt.style.paddingTop="",tt.style.paddingBottom="");let Fo=ue.tooltipText??"Clear chat",Sn=ue.showTooltip??!0;tt.setAttribute("aria-label",Fo),st&&Mn({anchor:tt,trigger:st,text:()=>tt?.getAttribute("aria-label")??Fo,enabled:Sn})}}let Ue=o.actionParsers&&o.actionParsers.length?o.actionParsers:[iy],_n=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Pc.message,Pc.messageAndClick];se=ay({parsers:Ue,handlers:_n,getSessionMetadata:K,updateSessionMetadata:Y,emit:k.emit,documentRef:typeof document<"u"?document:null}),Ge=KT(o,se,xt),rk(),_.updateConfig(o),(o.features?.history?.enabled===!0!==He||o.features?.history?.provider!==wt||o.getIdentityProof!==Ot||o.clientToken!==Ft)&&(Jn({restoreFocus:!1}),nv()),ts(),Ld(),bo(Re,_.getMessages(),Ge),Pi(),md(),nk(),rl(_.isStreaming()),xn!==o.contextMentions&&eC();let rs=o.voiceRecognition?.enabled===!0,Zn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),eo=no(o.voiceRecognition?.provider);if(rs&&(Zn||eo))if(!fe||!io){let ue=ha(o);if(ue){fe=ue.button,io=ue.wrapper;let ht=jo&&jo.parentElement===$r?jo:null;$r?$r.insertBefore(io,ht):Wn?.appendChild(io),Lt&&(Lt.micButton=fe),Lt?.addListener(fe,"click",Wf),fe.disabled=Zo()||_.isStreaming()&&!Wm()}}else{let ue=o.voiceRecognition??{},ht=o.sendButton??{},vt=ue.iconName??"mic",Pt=ue.iconSize,jt=parseFloat(Pt??"")||$n;fe.classList.add(fo),fe.classList.toggle($o,!Pt),fe.style.width=Pt??"",fe.style.height=Pt??"",fe.style.minWidth=Pt??"",fe.style.minHeight=Pt??"";let In=ue.iconColor??ht.textColor;fe.innerHTML="";let Fo=Ie(vt,jt,In||"currentColor",1.5);Fo?fe.appendChild(Fo):fe.textContent="\u{1F3A4}";let Sn=ue.backgroundColor??ht.backgroundColor;Sn?fe.style.backgroundColor=Sn:fe.style.backgroundColor="",In?fe.style.color=In:fe.style.color="var(--persona-text, #111827)",ue.borderWidth?(fe.style.borderWidth=ue.borderWidth,fe.style.borderStyle="solid"):(fe.style.borderWidth="",fe.style.borderStyle=""),ue.borderColor?fe.style.borderColor=ue.borderColor:fe.style.borderColor="",ue.paddingX?(fe.style.paddingLeft=ue.paddingX,fe.style.paddingRight=ue.paddingX):(fe.style.paddingLeft="",fe.style.paddingRight=""),ue.paddingY?(fe.style.paddingTop=ue.paddingY,fe.style.paddingBottom=ue.paddingY):(fe.style.paddingTop="",fe.style.paddingBottom="");let An=ue.tooltipText??"Start voice recognition",rr=ue.showTooltip??!1;fe.setAttribute("aria-label",An),io&&Mn({anchor:fe,trigger:io,text:()=>fe?.getAttribute("aria-label")??An,enabled:rr}),io.style.display="",fe.disabled=Zo()||_.isStreaming()&&!Wm()}else fe&&io&&(io.style.display="none",no(o.voiceRecognition?.provider)?_.isVoiceActive()&&_.toggleVoice():nr&&ns());if(o.attachments?.enabled===!0){if(!Kn||!Gt){let ue=o.attachments??{};Gn||(Gn=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Gn.style.display="none",(Ae.parentElement??Wn).insertBefore(Gn,Ae)),zt||(zt=document.createElement("input"),zt.type="file",zt.accept=(ue.allowedTypes??Hr).join(","),zt.multiple=(ue.maxFiles??4)>1,zt.style.display="none",zt.setAttribute("aria-label","Attach files"),(Ae.parentElement??Wn).insertBefore(zt,Ae)),Kn=v("div","persona-send-button-wrapper"),Gt=v("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${fo} ${$o}`),Gt.type="button",Gt.setAttribute("aria-label",ue.buttonTooltipText??"Attach file");let ht=ue.buttonIconName??"paperclip";Gt.style.fontSize="18px",Gt.style.lineHeight="1";let vt=Ie(ht,$n,"currentColor",1.5);vt?Gt.appendChild(vt):Gt.textContent="\u{1F4CE}",Gt.addEventListener("click",jt=>{jt.preventDefault(),zt?.click()}),Kn.appendChild(Gt);let Pt=ue.buttonTooltipText??"Attach file";Mn({anchor:Gt,trigger:Kn,text:()=>Gt?.getAttribute("aria-label")??Pt}),qo?qo.append(Kn):Wn.appendChild(Kn),Lt&&(Lt.attachmentButton=Gt,Lt.attachmentInput=zt??void 0,Lt.attachmentPreviews=Gn??void 0),!At&&zt&&Gn&&(At=$l.fromConfig(ue,By),At.setPreviewsContainer(Gn),Lt?.addListener(zt,"change",async()=>{At&&zt?.files&&(await At.handleFileSelect(zt.files),zt.value="")}))}else{Kn.style.display="";let ue=o.attachments??{};zt&&(zt.accept=(ue.allowedTypes??Hr).join(","),zt.multiple=(ue.maxFiles??4)>1),At&&At.updateConfig({allowedTypes:ue.allowedTypes,maxFileSize:ue.maxFileSize,maxFiles:ue.maxFiles,adapter:ue.adapter})}if(Le.querySelector(".persona-attachment-drop-overlay")?.remove(),Le.appendChild(GT(o.attachments?.dropOverlay)),Gt){let ue=o.attachments??{},ht=ue.buttonTooltipText??"Attach file";Gt.setAttribute("aria-label",ht),Gt.textContent="";let vt=Ie(ue.buttonIconName??"paperclip",$n,"currentColor",1.5);vt?Gt.appendChild(vt):Gt.textContent="\u{1F4CE}",Kn&&Mn({anchor:Gt,trigger:Kn,text:()=>Gt?.getAttribute("aria-label")??ht})}}else Kn&&(Kn.style.display="none"),At&&At.clearAttachments(),Le.querySelector(".persona-attachment-drop-overlay")?.remove();let rt=o.sendButton??{},Lr=rt.useIcon??!1,on=rt.iconText??"\u2191",to=rt.iconName,Al=rt.tooltipText??"Send message",v0=rt.showTooltip??!1,Ml=rt.size,C0=parseFloat(Ml??"")||Sg,jd=rt.backgroundColor,Tl=rt.textColor;if(Lr){if(Ve.style.width=Ml??"",Ve.style.height=Ml??"",Ve.style.minWidth=Ml??"",Ve.style.minHeight=Ml??"",Ve.style.fontSize="18px",Ve.style.lineHeight="1",Tl?Ve.style.color=Tl:Ve.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!_.isStreaming())if(Ve.innerHTML="",to){let ue=parseFloat(rt.iconSize??"")||Math.round(C0*.5),ht=Tl?.trim()||"currentColor",vt=rt.iconStrokeWidth??2,Pt=Ie(to,ue,ht,vt),jt=Ie(rt.stopIconName??"square",ue,ht,vt);Pt&&jt?Ve.appendChild(Ag(Pt,jt)):Pt?Ve.appendChild(Pt):Ve.textContent=on}else Ve.textContent=on;Ve.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${fo}`,jd?(Ve.style.backgroundColor=jd,Ve.classList.remove("persona-bg-persona-primary")):(Ve.style.backgroundColor="",Ve.classList.add("persona-bg-persona-primary"))}else Ve.textContent=o.copy?.sendButtonLabel??"Send",Ve.style.width="",Ve.style.height="",Ve.style.minWidth="",Ve.style.minHeight="",Ve.style.fontSize="",Ve.style.lineHeight="",Ve.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",jd?(Ve.style.backgroundColor=jd,Ve.classList.remove("persona-bg-persona-accent")):Ve.classList.add("persona-bg-persona-accent"),Tl?Ve.style.color=Tl:Ve.classList.add("persona-text-white");rt.borderWidth?(Ve.style.borderWidth=rt.borderWidth,Ve.style.borderStyle="solid"):(Ve.style.borderWidth="",Ve.style.borderStyle=""),rt.borderColor?Ve.style.borderColor=rt.borderColor:Ve.style.borderColor="",rt.paddingX?(Ve.style.paddingLeft=rt.paddingX,Ve.style.paddingRight=rt.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),rt.paddingY?(Ve.style.paddingTop=rt.paddingY,Ve.style.paddingBottom=rt.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom=""),_.isStreaming()||Ve.setAttribute("aria-label",Al),pd(),jo&&Mn({anchor:Ve,trigger:jo,text:()=>Ve.getAttribute("aria-label")??Al,enabled:v0}),Qy();let dC=$p(ze.getState().activeModeIds,o.composer?.modes);ze.setActiveModeIds(dC),xi().length>0!==!!fr&&gm(),fr?.render(dC,xi());for(let ue of[...Si.keys()])Vp(ue,o.composer?.modeGroups)||Si.delete(ue);Si.forEach(ue=>ue.repaint()),Ur?.repaint(),Yo?.resolve();let Kd=ys(o,Ee());if(xm(),Kd){Re.style.maxWidth=Kd,Re.style.marginLeft="auto",Re.style.marginRight="auto",Re.style.width="100%",kn.style.maxWidth=Kd,kn.style.marginLeft="auto",kn.style.marginRight="auto",kn.style.width="100%";for(let ue of[Wn,Io,Gn,bt])ue&&(ue.style.maxWidth=Kd,ue.style.marginLeft="auto",ue.style.marginRight="auto",ue.style.width="100%")}else{Re.style.maxWidth="",Re.style.marginLeft="",Re.style.marginRight="",Re.style.width="",kn.style.maxWidth="",kn.style.marginLeft="",kn.style.marginRight="",kn.style.width="";for(let ue of[Wn,Io,Gn,bt])ue&&(ue.style.maxWidth="",ue.style.marginLeft="",ue.style.marginRight="",ue.style.width="")}let ss=o.statusIndicator??{},w0=ss.visible??!0;if(bt.style.display=w0?"":"none",_){let ue=_.getStatus();Rn(bt,(vt=>vt==="idle"?ss.idleText??fn.idle:vt==="connecting"?ss.connectingText??fn.connecting:vt==="connected"?ss.connectedText??fn.connected:vt==="error"?ss.errorText??fn.error:fn[vt])(ue),ss,ue)}bt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let x0=ss.align==="left"?"persona-text-left":ss.align==="center"?"persona-text-center":"persona-text-right";bt.classList.add(x0),fm(),Om(),Ho(),Ke()},open(){Ne()&&Nt(!0,"api")},close(){Ne()&&Nt(!1,"api")},toggle(){Ne()&&Nt(!Pe,"api")},reconnect(){_.reconnectNow()},clearChat(){gr=!1,_.clearMessages(),cn.clear(),Qn();try{localStorage.removeItem(Ba),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ba}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ba)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),W?.clear&&od(()=>W.clear(),"[AgentWidget] Failed to clear storage adapter:"),R={},se.syncFromMetadata(),At?.clearAttachments(),sd(),Ai(void 0),Go(void 0),Bs(),je?.clear(),lt?.reset(),mt?.update()},setMessage(i){return!Ae||_.isStreaming()||Zo()?!1:(!Pe&&Ne()&&Nt(!0,"system"),Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(_.isStreaming()||$s())return!1;let c=i?.trim()||Ae.value.trim();return c?(!Pe&&Ne()&&Nt(!0,"system"),Ae.value="",Ae.style.height="auto",Ko(),Fd(c,{consumeDraft:!1}),!0):!1},getComposerState(){return ze.getState()},setQuote(i){let c=i?.text?.trim();c&&Go({...i,text:c})},clearQuote(){Go(void 0)},startVoiceRecognition(){return _.isStreaming()?!1:no(o.voiceRecognition?.provider)?(_.isVoiceActive()||_.isBargeInActive()||(!Pe&&Ne()&&Nt(!0,"system"),gt.manuallyDeactivated=!1,Bo(),_.toggleVoice().then(()=>{gt.active=_.isVoiceActive(),vr("user"),_.isVoiceActive()&&Xi()})),!0):nr?!0:Nv()?(!Pe&&Ne()&&Nt(!0,"system"),gt.manuallyDeactivated=!1,Bo(),$d("user"),!0):!1},stopVoiceRecognition(){return no(o.voiceRecognition?.provider)?!_.isVoiceActive()&&!_.isBargeInActive()?!1:((_.isBargeInActive()?_.deactivateBargeIn():_.toggleVoice()).then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Bo(),vr("user"),Er()}),!0):nr?(gt.manuallyDeactivated=!0,Bo(),ns("user"),!0):!1},injectMessage(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectMessage(i)},injectAssistantMessage(i){!Pe&&Ne()&&Nt(!0,"system");let c=_.injectAssistantMessage(i);return dt&&(dt=!1,Xe&&(clearTimeout(Xe),Xe=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),c},injectUserMessage(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectUserMessage(i)},injectSystemMessage(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectSystemMessage(i)},injectMessageBatch(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectMessageBatch(i)},injectComponentDirective(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectComponentDirective(i)},injectTestMessage(i){!Pe&&Ne()&&Nt(!0,"system"),_.injectTestEvent(i)},async connectStream(i,c){return _.connectStream(i,c)},__pushEventStreamEvent(i){P&&(_t(),pt(i.type,i.payload))},showEventStream(){P&&mm()},hideEventStream(){Tt&&Mi()},isEventStreamVisible(){return Tt},listConversations(i){return _.listConversations(i)},getActiveConversationId(){return _.getActiveConversationId()},openConversation(i,c){return vf(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return Cf({focusComposer:i?.focus===!0})},deleteConversation(i){return kv(i)},renameConversation(i,c){return wf(i,{title:c})},setConversationStarred(i,c){return wf(i,{starred:c})},clearConversationHistory(i){return Lv(i)},resetHistoryIdentity(){return Pv()},async getVisitorToken(){let i=vo;if(!i)return null;let c=await i.get();return i===vo?c:null},getHistoryIdentityStatus(){return uo?uo.getIdentityStatus():tf()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return hl({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){Jn(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return ve},showArtifacts(){jn(o)&&(gr=!1,Ei=!0,Wo(),ft?.setMobileOpen(!0))},hideArtifacts(){jn(o)&&(gr=!0,Wo())},upsertArtifact(i){return jn(o)?(is(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(gr=!1,Ei=!0),_.upsertArtifact(i)):null},selectArtifact(i){jn(o)&&_.selectArtifact(i)},clearArtifacts(){jn(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return ce&&!Pe&&!Ee()||!Ae?!1:(Ae.focus(),!0)},async resolveApproval(i,c,f){let x=_.getMessages().find(L=>L.variant==="approval"&&L.approval?.id===i);if(!x?.approval)throw new Error(`Approval not found: ${i}`);if(x.approval.toolType==="webmcp"){_.resolveWebMcpApproval(x.id,c);return}return _.resolveApproval(x.approval,c,f)},setFollowUpSuggestions(i){EE(i)},clearFollowUpSuggestions(){Ab()},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...R}},updatePersistentMetadata(i){Y(i)},on(i,c){return k.on(i,c)},off(i,c){k.off(i,c)},isOpen(){return Ne()&&Pe},isVoiceActive(){return gt.active},toggleReadAloud(i){_.toggleReadAloud(i)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(i){return _.getReadAloudState(i)},onReadAloudChange(i){return _.onReadAloudChange(i)},getState(){return{open:Ne()&&Pe,launcherEnabled:ce,voiceActive:gt.active,streaming:_.isStreaming()}},showCSATFeedback(i){!Pe&&Ne()&&Nt(!0,"system");let c=Re.querySelector(".persona-feedback-container");c&&c.remove();let f=UT({onSubmit:async(h,x)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(h,x),i?.onSubmit?.(h,x)},onDismiss:i?.onDismiss,...i});Re.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Pe&&Ne()&&Nt(!0,"system");let c=Re.querySelector(".persona-feedback-container");c&&c.remove();let f=qT({onSubmit:async(h,x)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(h,x),i?.onSubmit?.(h,x)},onDismiss:i?.onDismiss,...i});Re.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,c){return _.submitCSATFeedback(i,c)},async submitNPSFeedback(i,c){return _.submitNPSFeedback(i,c)},destroy(){Gm(),qs!=null&&(clearInterval(qs),qs=null),De.forEach(i=>i()),it.remove(),Kt?.remove(),Qt?.destroy(),Fn?.remove(),Is&&F.removeEventListener("click",Is)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:Xt,getMessages:Xt.getMessages,getStatus:Xt.getStatus,getMetadata:Xt.getPersistentMetadata,updateMetadata:Xt.updatePersistentMetadata,clearHistory:()=>Xt.clearChat(),setVoiceActive:f=>f?Xt.startVoiceRecognition():Xt.stopVoiceRecognition()};window.AgentWidgetBrowser=c,De.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),c=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.focusInput()};if(window.addEventListener("persona:focusInput",c),De.push(()=>{window.removeEventListener("persona:focusInput",c)}),P){let ne=Ce=>{let He=Ce.detail;(!He?.instanceId||He.instanceId===i)&&Xt.showEventStream()},pe=Ce=>{let He=Ce.detail;(!He?.instanceId||He.instanceId===i)&&Xt.hideEventStream()};window.addEventListener("persona:showEventStream",ne),window.addEventListener("persona:hideEventStream",pe),De.push(()=>{window.removeEventListener("persona:showEventStream",ne),window.removeEventListener("persona:hideEventStream",pe)})}let f=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.showHistory()},h=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",h),De.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",h)});let x=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.showArtifacts()},L=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.hideArtifacts()},q=ne=>{let pe=ne.detail;pe?.instanceId&&pe.instanceId!==i||pe?.artifact&&Xt.upsertArtifact(pe.artifact)},te=ne=>{let pe=ne.detail;pe?.instanceId&&pe.instanceId!==i||typeof pe?.id=="string"&&Xt.selectArtifact(pe.id)},Z=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.clearArtifacts()};window.addEventListener("persona:showArtifacts",x),window.addEventListener("persona:hideArtifacts",L),window.addEventListener("persona:upsertArtifact",q),window.addEventListener("persona:selectArtifact",te),window.addEventListener("persona:clearArtifacts",Z),De.push(()=>{window.removeEventListener("persona:showArtifacts",x),window.removeEventListener("persona:hideArtifacts",L),window.removeEventListener("persona:upsertArtifact",q),window.removeEventListener("persona:selectArtifact",te),window.removeEventListener("persona:clearArtifacts",Z)})}let Ao=WB(o.persistState);if(Ao&&Ne()){let i=BB(Ao.storage),c=`${Ao.keyPrefix}widget-open`,f=`${Ao.keyPrefix}widget-voice`,h=`${Ao.keyPrefix}widget-voice-mode`;if(i){let x=Ao.persist?.openState&&i.getItem(c)==="true",L=Ao.persist?.voiceState&&i.getItem(f)==="true",q=Ao.persist?.voiceState&&i.getItem(h)==="true";if(x&&(Qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Xt.open(),setTimeout(()=>{if(L||q)Xt.startVoiceRecognition();else if(Ao.persist?.focusInput){let te=t.querySelector("textarea");te&&te.focus()}},100)},0)),Ao.persist?.openState&&(k.on("widget:opened",()=>{i.setItem(c,"true")}),k.on("widget:closed",()=>{i.setItem(c,"false")})),Ao.persist?.voiceState&&(k.on("voice:state",te=>{i.setItem(f,te.active?"true":"false")}),k.on("user:message",te=>{i.setItem(h,te.viaVoice?"true":"false")})),Ao.clearOnChatClear){let te=()=>{i.removeItem(c),i.removeItem(f),i.removeItem(h)},Z=()=>te();window.addEventListener("persona:clear-chat",Z),De.push(()=>{window.removeEventListener("persona:clear-chat",Z)})}}}if(G&&Ne()&&(Qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Xt.open()},0)),Di(),!kE){let i=ea(()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge))});De.push(i)}C=()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge))},_.getMessages().length>0&&dd(),M=()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge))};let y0=Jw(()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge))});De.push(y0);let b0=Xh(()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge),Dr()?.updateInlineArtifactBlocks(Re,yo.artifacts,{suppressTransition:!0}),Wo())});return De.push(b0),Xt};fs();var QT=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,e*parseFloat(r[1])/100):420},_B=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},NB=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},FB=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},XT=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},Ey=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},JT=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Ey(t)},Ay=t=>{t.style.transition=""},My=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Ty=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},nm=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},VB=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},$B=(t,e,n,o,r,s)=>{let a=s?e:t;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},zB=t=>{let e=Ca(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:zn(e,r)??r;return{inset:o(n?.inset,ou),canvasBackground:o(n?.canvasBackground,ru)}},ZT=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},UB=(t,e,n,o,r,s,a,l)=>{let d=Lo(s),p=d.reveal==="push",u=l!=null,m=l?.inset??"",y=l?.canvasBackground??"";VB(t,e,n,o,p),$B(t,e,n,o,d.side,p),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=d.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let g=t.ownerDocument.defaultView,b=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,S=g!=null?g.innerWidth<=C:!1;if(b&&S&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),My(e),Ay(o),JT(o),Ty(n),nm(r,o),ZT(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Hn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),JT(o),_B(o,d.maxHeight),ZT(o,u&&a,m,y),d.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",My(e),Ay(o),Ty(n),nm(r,o);let A=d.animate?"transform 180ms ease":"none",I=d.side==="right"?"translateX(100%)":"translateX(-100%)",M=a?"translateX(0)":I;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=A,o.style.transform=M,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Ay(o),Ey(o),nm(r,o);let A=QT(d.width,t.clientWidth),I=Math.max(0,t.clientWidth),M=d.animate?"margin-left 180ms ease":"none",O=d.side==="right"?a?-A:0:a?0:-A;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${I+A}px`,e.style.transition=M,e.style.marginLeft=`${O}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${I}px`,n.style.maxWidth=`${I}px`,n.style.minWidth=`${I}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",My(e),Ey(o),Ty(n),nm(r,o);let A=d.reveal==="emerge";A?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let I=a?d.width:"0px",M=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",O=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${I}`,o.style.width=I,o.style.maxWidth=I,o.style.minWidth=I,o.style.minHeight="0",NB(o,d.maxHeight),o.style.overflow=A||O?"hidden":"visible",o.style.transition=M,A){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let k=u?`calc(${QT(d.width,t.clientWidth)}px - (2 * ${m}))`:d.width;r.style.width=k,r.style.minWidth=k,r.style.maxWidth=k,r.style.boxSizing="border-box"}}},qB=(t,e)=>{let n=t.ownerDocument.createElement("div");return XT(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){XT(n,o)},destroy(){n.remove()}}},jB=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=n.createElement("div"),l=n.createElement("div"),d=n.createElement("div"),p=n.createElement("aside"),u=n.createElement("div"),m=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",p.appendChild(u),o.insertBefore(a,t),d.appendChild(t);let y=null,g=()=>{y?.disconnect(),y=null},b=null,C=()=>{b=e?.launcher?.detachedPanel===!0?zB(e):null};C();let S=()=>{UB(a,l,d,p,u,e,m,b)},T=null,A=()=>{T?.(),T=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(T=su(()=>{C(),S()}))},I=()=>{g(),Lo(e).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{S()}),y.observe(a)))},M=!1,O=()=>{S(),I(),m&&!M&&a.dataset.personaDockMobileFullscreen!=="true"&&(M=!0,FB(a,Lo(e)))},k=a.ownerDocument.defaultView,B=()=>{O()};return k?.addEventListener("resize",B),Lo(e).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),O(),A(),{mode:"docked",host:u,shell:a,syncWidgetState(W){let V=W.launcherEnabled?W.open:!0;m!==V&&(m=V,O())},updateConfig(W){e=W,(e?.launcher?.enabled??!0)===!1&&(m=!0),C(),O(),A()},destroy(){k?.removeEventListener("resize",B),T?.(),T=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},eE=(t,e)=>rn(e)?jB(t,e):qB(t,e);var Oc={desktop:{w:1280,h:800},mobile:{w:390,h:844}},tE=.15,nE=1.5,ky="persona-preview-shell-theme",KB={load:()=>null,save:()=>{},clear:()=>{}},GB=["How do I get started?","Pricing & plans","Talk to support"];function Ly(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function YB(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function oE(t){let e=YB(t);return`* { box-sizing: border-box; }
1267
+ ${jt?"background: transparent !important;":""}
1268
+ `)}if(!w&&!d){let Ye="max-height: -moz-available !important; max-height: stretch !important;",st=f?"":"padding-top: 1.25em !important;",tt=f?"":`z-index: ${o.launcher?.zIndex??On} !important;`;dt.style.cssText+=Ye+st+tt}Hm(),Io()},Gm=()=>{t.style.setProperty("--persona-content-max-width",Is(o,xe()))},tv=!1;function nv(){o.layout?.topFade&&pe.scrollTop>1?pe.setAttribute("data-persona-top-fade","true"):pe.removeAttribute("data-persona-top-fade")}let Ym=()=>{nv();let i=Fh(o,xe());xe()&&o.composer?.placement&&o.debug===!0&&!tv&&(tv=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let d=Vs();t.setAttribute("data-persona-composer-placement",i),t.setAttribute("data-persona-conversation-state",od),t.setAttribute("data-persona-welcome-anchor",d.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",d.composerGap??Ou),sd()},ov=()=>{if(xe())return;let i=nn(o),d=o.launcher?.sidebarMode??!1;if(i||d||(o.launcher?.fullHeight??!1)||!_)return;let y=t.ownerDocument.defaultView??window,w=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(w&&y.innerWidth<=k)return;let q=Ri(o);Se.style.height=q.height,Se.style.maxHeight=q.maxHeight};Km(),gc(t,o),Uc(t,o),qc(t,o),Gm(),Ym(),Us=()=>{Km(),ov(),gc(t,o),Uc(t,o),qc(t,o),Gm(),Ym(),ld?t.style.setProperty("--persona-artifact-welded-outer-radius",ld):t.style.removeProperty("--persona-artifact-welded-outer-radius"),ft(),Mn()};let _e=[];_e.push(()=>{Gb=!0}),_e.push(()=>{g.forEach(i=>i()),m.destroy()}),_e.push(()=>{document.removeEventListener("keydown",Xb)}),_e.push(()=>{rl!==null&&clearTimeout(rl)});let or=null,rr=null;_e.push(()=>{or?.(),or=null,rr?.(),rr=null}),ll&&_e.push(()=>{ll?.disconnect(),ll=null}),_e.push(()=>{pl?.(),pl=null,jm(),en&&(en.remove(),en=null),gt?.element.style.removeProperty("width"),gt?.element.style.removeProperty("maxWidth"),gt?.destroy()}),ie&&_e.push(()=>{Fe=!0,Z=null,Bt!==null&&(cancelAnimationFrame(Bt),Bt=null),Re?.destroy(),Re=null,ct?.destroy(),ct=null,rt=null});let js=null,rv=()=>{js&&(js(),js=null),o.colorScheme==="auto"&&(js=Du(()=>{gc(t,o)}))};rv(),_e.push(()=>{js&&(js(),js=null)}),_e.push(()=>{T=!0,E?.()}),_e.push(()=>{W=!0});let sv=!1;_e.push(()=>{sv=!0});let Qm=(i,d)=>{let f=vc(i,d);return f||!iM.includes(i)?f:(MM().then(y=>{if(sv)return;Ei(y.wipe),Ei(y.glyphCycle);let w=vc(i,d);w&&xc(w,t)}).catch(()=>{}),null)},hd=o.features?.streamAnimation;if(hd?.type&&hd.type!=="none"){let i=Qm(hd.type,hd.plugins);i&&xc(i,t),_e.push(()=>aM(t))}let Mr=kc(lo),iv=kc(Ns),av=kc(Xo),Ks=[Mr,iv,av];_e.push(()=>{Ks.forEach(i=>i.destroy())});let Gs=null,N,Ys=null,lv=!1,cv=0,dv=null,pv=i=>i.reduce((d,f)=>f.role==="user"?d+1:d,0),uv=i=>{for(let d=i.length-1;d>=0;d--)if(ql(i[d]))return i[d].id??null;return null},mv=!1,B0=()=>{mv||o.debug!==!0||(mv=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},fv=!1,gv=!1,hv=(i,d)=>{fv||o.debug!==!0||!d.enabled||d.expose||lv||gv&&(N.isStreaming()||i.some(ql)||(fv=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},Qs=i=>{if(!N)return;let d=i??N.getMessages(),f=he=>{he.render([],N,we,d)},y=he=>{Ks.forEach(De=>{De!==he&&f(De)})};Ys&&(pv(d)>cv||uv(d)!==dv)&&(Ys=null);let w=Ms(o);hv(d,w);let k=w.enabled?gx(d):null,q=Ys??k,te=Ys?"host":"agent";if(q){let he=o.suggestions?.followUps,De=he?.placement??(he?"auto":"composer"),It=(De==="auto"?xe()?"composer":"after-message":De)==="after-message"?av:Mr;y(It),It.render(q,N,we,d,o.suggestionChipsConfig,{source:te,surface:"followUp",variant:he?.variant??"chip",behavior:he?.behavior??"send",overflow:he?.overflow??"wrap",maxItems:he?.maxItems??4,config:o,plugins:u,submitPrompt:op});return}if(d.some(he=>he.role==="user")){Ks.forEach(f);return}let Q=o.future?.v5Defaults===!0,re=sl(),ce=o.suggestions?.starters??(Q?{}:void 0);if(ce){let he=Ua(Vs(),d),De=ce.placement??"auto",lt=De==="auto"?he?"welcome":"composer":De;if(lt==="welcome"&&!he){B0(),Ks.forEach(f);return}let It=lt==="welcome"?iv:Mr;y(It),It.render(ce.items??o.suggestionChips,N,we,d,o.suggestionChipsConfig,{surface:"starter",variant:ce.variant??(Q&&!re?"chip":"card"),behavior:ce.behavior??"send",overflow:ce.overflow??"wrap",maxItems:ce.maxItems??(Q&&!re?3:4),config:o,plugins:u,submitPrompt:op});return}y(Mr),Mr.render(o.suggestionChips,N,we,d,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:u,submitPrompt:op})},yv=()=>{Ys&&(Ys=null,Qs())},D0=i=>{let d=Array.isArray(i)?[...i]:[];if(!d.length){yv();return}let f=N?N.getMessages():[];Ys=d,lv=!0,cv=pv(f),dv=uv(f),Qs(f)},uo=!1,mn=JA(),Qi=new Map,Xs=new Map,ns=new Map,Js=null,os=null;function Zs(){if(!Js)return;let i=Js;Js=null,os?.destroy(),os=null,mn.delete(i),Pe.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),N&&xo(We,N.getMessages(),j)}let ei=0,O0=Ro()!==null,mo=$u(),fo=0,rs=null,Jn=!1,yd=!1,ss=0,wn=null,ti=null,Xm=!1,Xi=!1,ni=null,ul=!0,bd=!1,Ji=null,vd=!1,is=()=>{vd=!0,V0()},Jm=null,_0=4,Tr=24,N0=80,F0=1e3,Er=null,bv=()=>{t.setAttribute("data-persona-scrollbar",Lm()),Lm()!=="on-scroll"&&(Er!==null&&clearTimeout(Er),Er=null,pe.removeAttribute("data-persona-scrollbar-visible"))},V0=()=>{Lm()==="on-scroll"&&(pe.setAttribute("data-persona-scrollbar-visible",""),Er!==null&&clearTimeout(Er),Er=setTimeout(()=>{Er=null,jr(pe,Tr)&&pe.removeAttribute("data-persona-scrollbar-visible")},F0))};bv(),_e.push(()=>{Er!==null&&clearTimeout(Er)});let Zm=new Map,wt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};_o();let vv=o.voiceRecognition?.autoResume??!1,kr=i=>{R.emit("voice:state",{active:wt.active,source:i,timestamp:Date.now()})},Vo=()=>{de(i=>({...i,voiceState:{active:wt.active,timestamp:Date.now(),manuallyDeactivated:wt.manuallyDeactivated}}))},$0=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=yb(L.voiceState),d=!!i.active,f=Number(i.timestamp??0);wt.manuallyDeactivated=!!i.manuallyDeactivated,d&&Date.now()-f<tD&&setTimeout(()=>{wt.active||(wt.manuallyDeactivated=!1,so(o.voiceRecognition?.provider)?N.toggleVoice().then(()=>{wt.active=N.isVoiceActive(),kr("restore"),N.isVoiceActive()&&ba()}):ip("restore"))},1e3)},z0=()=>N?t0(N.getMessages()).filter(i=>!i.__skipPersist):[],Cd=null,Cv=(i,d)=>{typeof console<"u"&&console.error(i,d)},wd=(i,d)=>{let f=()=>{try{let q=i();return!q||typeof q.then!="function"?null:Promise.resolve(q).catch(te=>{Cv(d,te)})}catch(q){return Cv(d,q),null}},y=Cd,w=y?y.then(()=>f()??void 0):f();if(!w)return;let k=w.finally(()=>{Cd===k&&(Cd=null)});Cd=k};function Zi(i){if(!x?.save)return;let d=i?t0(i):N?z0():[],f=P&&N?.getResumableHandle();f&&(L={...L,durableResume:{executionId:f.executionId,after:f.lastEventId}});let y={messages:d,metadata:L,artifacts:wo.artifacts,selectedArtifactId:wo.selectedId,...oi?{draft:oi}:{}};wd(()=>x.save(y),"[AgentWidget] Failed to persist state:")}let oi,xd=()=>!x?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,ml=GS({write:()=>{if(!xd())return;let i=ze.getState(),d=jS({text:i.text,mentionRefs:i.mentionRefs,contentSegments:Jf(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(d)!==JSON.stringify(oi)&&(oi=d,Zi())}});function wv(){xd()&&ml.schedule()}function ef(){ml.flush()}function xv(i){if(!xd())return;let d=KS(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(f=>f.id),modelIds:(o.composer?.models??[]).map(f=>f.id),modes:o.composer?.modes??[]});d&&(oi=i,we&&!we.value&&(we.value=d.text,we.dispatchEvent(new Event("input",{bubbles:!0})),Zo()),d.selectedModelId&&(ze.setSelectedModelId(d.selectedModelId),Zr?.repaint()),id(d.activeModeIds??[]),d.quote&&er(d.quote),ml.cancel())}function Sd(){ml.cancel(),oi&&(oi=void 0,xd()&&Zi())}let ea=null,Sv=()=>dt.querySelector("#persona-scroll-container")||pe,ta=()=>{ea!==null&&(cancelAnimationFrame(ea),ea=null),Jn=!1},Av=()=>{rs!==null&&(cancelAnimationFrame(rs),rs=null),yd=!1,ta()},U0=()=>uo&&nf()&&(po()!=="anchor-top"||Tb()),tf=()=>{let i=tl()||"Jump to latest",d=U0();hn.toggleAttribute("data-persona-scroll-to-bottom-streaming",d),ss>0?(Fs.textContent=String(ss),Fs.style.display="",hn.setAttribute("aria-label",`${i} (${ss} new)`)):(Fs.textContent="",Fs.style.display="none",hn.setAttribute("aria-label",d?`${i} (response streaming below)`:i))},Mv=()=>{ss!==0&&(ss=0,tf())},q0=()=>{let i=wn?.spacerHeight??0;return i<=0?jr(pe,Tr):Ed(i)-pe.scrollTop-pe.clientHeight<=Tr},nf=()=>Jr()?!mo.isFollowing():!q0(),of=()=>!!N&&N.getMessages().length>0,xn=()=>{if(!C0()||ao()){hn.parentNode&&hn.remove(),hn.style.display="none";return}hn.parentNode!==Pe&&Pe.appendChild(hn),$s();let d=br(pe)>0&&nf()&&of();d?tf():Mv(),hn.style.display=d?"":"none"},na=()=>{mo.pause()&&(Av(),xn())},Zn=()=>{mo.resume(),Mv(),xn()},as=(i=!1)=>{Jr()&&of()&&mo.isFollowing()&&(!i&&!uo||(rs!==null&&(cancelAnimationFrame(rs),rs=null),yd=!0,rs=requestAnimationFrame(()=>{rs=null,yd=!1,mo.isFollowing()&&j0(Sv(),i?220:140)})))},Tv=(i,d,f,y=()=>!0)=>{let w=i.scrollTop,k=d(),q=k-w;if(ta(),Math.abs(q)<1){Jn=!0,i.scrollTop=k,fo=i.scrollTop,Jn=!1;return}let te=performance.now();Jn=!0;let Q=ce=>1-Math.pow(1-ce,3),re=ce=>{if(!y()){ta();return}let he=d();he!==k&&(k=he,q=k-w);let De=ce-te,lt=Math.min(De/f,1),It=Q(lt),kt=w+q*It;i.scrollTop=kt,fo=i.scrollTop,lt<1?ea=requestAnimationFrame(re):(i.scrollTop=k,fo=i.scrollTop,ea=null,Jn=!1)};ea=requestAnimationFrame(re)},j0=(i,d=500)=>{let f=br(i)-i.scrollTop;if(Math.abs(f)<1){fo=i.scrollTop;return}if(Math.abs(f)>=N0){ta(),Jn=!0,i.scrollTop=br(i),fo=i.scrollTop,Jn=!1;return}Tv(i,()=>br(i),d,()=>mo.isFollowing())},Ad=()=>{if(!of()){xn();return}let i=Sv();Jn=!0,i.scrollTop=br(i),fo=i.scrollTop,Jn=!1,xn()},ri=i=>{let d=0,f=i;for(;f&&f!==pe;)d+=f.offsetTop,f=f.offsetParent;return d},K0=()=>{let i=pe.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??pe.ownerDocument.getSelection()},Md=()=>oM(K0(),pe),rf=()=>{if(w0()!=="last-user-turn")return!1;let i=N?.getMessages()??[];if(i.length<2)return!1;let d=[...i].reverse().find(k=>k.role==="user");if(!d)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(d.id):d.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=pe.querySelector(`[data-message-id="${f}"]`);if(!y)return!1;let w=Math.min(Math.max(0,ri(y)-nl()),br(pe));return Jn=!0,pe.scrollTop=w,fo=pe.scrollTop,Jn=!1,po()==="follow"&&!jr(pe,Tr)&&mo.pause(),xn(),!0},Td=i=>{let d=Math.max(0,Math.round(i));Co.style.height=`${d}px`,Co.style.display=d>0?"":"none",wn&&(wn.spacerHeight=Math.max(0,i))},Ed=i=>{let d=parseFloat(getComputedStyle(pe).paddingBottom)||0,f=0;for(let w of Array.from(pe.children)){if(w===Co||w.offsetHeight===0)continue;let k=ri(w)+w.offsetHeight;k>f&&(f=k)}let y=pe.scrollHeight-i;return f>0?Math.min(f+d,y):y},G0=()=>{if(!wn||wn.spacerHeight<=0)return;let i=Ed(wn.spacerHeight),d=Math.max(0,Math.round(pe.scrollTop)+pe.clientHeight-i+Tr);d<wn.spacerHeight&&(Td(d),xn())},$o=()=>{ti!==null&&(cancelAnimationFrame(ti),ti=null),ta(),wn=null,Co.style.height="0px",Co.style.display="none"},Ev=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),sf=i=>pe.querySelector(`[data-message-id="${Ev(i)}"]`),kv=i=>{ti!==null&&cancelAnimationFrame(ti),ti=requestAnimationFrame(()=>{ti=null;let d=Ev(i),f=pe.querySelector(`[data-message-id="${d}"]`);if(!f)return;let y=ri(f),w=wn?.spacerHeight??0,k=Ed(w),{targetScrollTop:q,spacerHeight:te}=zh({anchorOffsetTop:y,topOffset:nl(),viewportHeight:pe.clientHeight,contentHeight:k,slack:Tr});wn={initialSpacerHeight:te,contentHeightAtAnchor:k,spacerHeight:te},Td(te),Tv(pe,()=>f.isConnected?Math.max(0,ri(f)-nl()):q,220)})},eo=()=>{if(po()!=="anchor-top"||!wn||!Ji)return;let i=sf(Ji);if(!i)return;ta();let d=wn.spacerHeight,f=Ed(d),{targetScrollTop:y,spacerHeight:w}=zh({anchorOffsetTop:ri(i),topOffset:nl(),viewportHeight:pe.clientHeight,contentHeight:f,slack:Tr});wn={initialSpacerHeight:w,contentHeightAtAnchor:f,spacerHeight:w},Td(w),Jn=!0,pe.scrollTop=y,fo=pe.scrollTop,Jn=!1,xn()},Y0=()=>{if(Jr()){if(!mo.isFollowing()||jr(pe,1))return;as(!uo);return}if(wn&&wn.initialSpacerHeight>0){let i=pe.scrollHeight-wn.spacerHeight,d=rM({initialSpacerHeight:wn.initialSpacerHeight,contentHeightAtAnchor:wn.contentHeightAtAnchor,currentContentHeight:i});d!==wn.spacerHeight&&Td(d)}xn()},Q0=i=>{let d=po();d==="follow"?(Zn(),as(!0)):d==="anchor-top"&&(ul=!1,bd=!0,vd=!1,Ji=i,kv(i))},X0=()=>{if(po()==="anchor-top"){if(bd){ul=!1;return}ul=!0,$o(),Zn(),as(!0)}},J0=96,Z0=i=>{if(ni===null)return!0;let d=sf(ni),f=sf(i);if(!d||!f)return!0;let y=ri(f)-ri(d);return nl()+y>pe.clientHeight-J0},ek=i=>{if(po()!=="anchor-top"||!bd||vd||Md())return;let d=ni===null;for(let f of i){if(!d){f.id===ni&&(d=!0);continue}if(nM(f)){if(f.id===Ji||!Z0(f.id))return;Ji=f.id,kv(f.id);return}}},tk=i=>{let d=new Map;i.forEach(f=>{let y=Zm.get(f.id);d.set(f.id,{streaming:f.streaming,role:f.role}),!y&&f.role==="assistant"&&(R.emit("assistant:message",f),!Xi&&(po()!=="anchor-top"||Tb())&&nf()&&(ss+=1,tf(),xn(),nd(ss===1?"1 new message below.":`${ss} new messages below.`))),f.role==="assistant"&&y?.streaming&&f.streaming===!1&&R.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(y?f.approval.status!=="pending"&&R.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):R.emit("approval:requested",{approval:f.approval,message:f}))}),Zm.clear(),d.forEach((f,y)=>{Zm.set(y,f)})},fl=(i,d)=>{let f=d==="user"?"user":"assistant",y=o.layout?.messages?.[f],w=y?.width??"content",k=y?.maxWidth??(w==="full"?`var(--persona-message-${f}-max-width, 100%)`:void 0);i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${d}`,`persona-message-width-${w}`),i.classList.toggle("persona-justify-end",d==="user"),i.setAttribute("data-message-role",d),i.setAttribute("data-message-width",w),k?i.style.setProperty("--persona-message-row-max-width",k):i.style.removeProperty("--persona-message-row-max-width")},Pr=(i,d)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${i}`,f.setAttribute("data-wrapper-id",i),fl(f,d),f},nk=(i,d,f)=>{let y=new Set;for(let $ of d){let Xe=$.variant==="tool"?"tool":$.variant==="reasoning"?"reasoning":null;if(!Xe||vs(o,Xe)!=="row")continue;let Je=Xe==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;Je?.expandable!==!1&&(y.add($.id),a.observe($,Xe,Xe==="tool"?r:s,Je))}let w=document.createElement("div"),q=(()=>{let $=u.find(Xe=>Xe.renderLoadingIndicator);if($?.renderLoadingIndicator)return $.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),te=($,Xe)=>Xe==null?!1:typeof Xe=="string"?($.textContent=Xe,!0):($.appendChild(Xe),!0),Q=new Set,re=new Map,ce=new Set,he=u.some($=>$.renderAskUserQuestion),De=[],lt=[],It=o.enableComponentStreaming!==!1,kt=o.approval!==!1,no=[],Jt=o.messageActions,rn=Jt?.showRegenerate===!0&&Jt.enabled!==!1&&Ft.current?.isStreaming()!==!0?Kx(d):null,Vn=Jt?.showEdit===!0&&Jt.enabled!==!1,ln=Jt?.showQuote===!0&&Jt.enabled!==!1,$t=null,cr=o.features?.reasoningDisplay?.completedVisibility,dr=$=>cr==="removed"?!0:cr==="removed-when-short"?bx($,o.features?.reasoningDisplay?.shortThinkThreshold):!1,Po=o.features?.toolCallDisplay?.completedVisibility==="removed",Lo=$=>$.variant==="reasoning"&&$.reasoning?.status==="complete"?dr($.reasoning):Po&&$.variant==="tool"&&$.toolCall?.status==="complete";if(d.forEach($=>{if(Lo($))return;if(Q.add($.id),re.set($.id,$.role),Js===$.id&&os){let et=Pr($.id,$.role);et.setAttribute("data-persona-message-edit-stub","true"),et.setAttribute("data-preserve-runtime","true"),w.appendChild(et),$t={messageId:$.id,element:os.element};return}let Xe=he&&Ai($),Je=kt&&$.variant==="approval"&&!!$.approval,fe=!Xe&&$.role==="assistant"&&!$.variant&&It&&hb($);!Je&&ns.has($.id)&&(i.querySelector(`#wrapper-${$.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete($.id)),!fe&&Xs.has($.id)&&(i.querySelector(`#wrapper-${$.id}`)?.removeAttribute("data-preserve-runtime"),Xs.delete($.id));let zt=Ai($)?`:${$.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${$.agentMetadata?.askUserQuestionAnswers?Object.keys($.agentMetadata.askUserQuestionAnswers).length:0}`:"",fn={canRegenerate:rn===$.id,canEdit:Vn&&Yg($),canQuote:ln&&!$.variant&&($.content?.trim().length??0)>0},_n=`${fn.canRegenerate?"r":""}${fn.canEdit?"e":""}${fn.canQuote?"q":""}`,En=XA($,ei)+zt+`:${_n}`,jt=Xe||Je||fe?null:ZA(mn,$.id,En);if(jt){w.appendChild(jt.cloneNode(!0)),Ai($)&&$.toolCall?.id&&$.agentMetadata?.awaitingLocalTool===!0&&!$.agentMetadata?.askUserQuestionAnswered&&(ce.add($.toolCall.id),_p($,o,ot.composerOverlay));return}let cn=null,Sn=u.find(et=>!!($.variant==="reasoning"&&et.renderReasoning||$.variant==="tool"&&et.renderToolCall||!$.variant&&et.renderMessage)),Ke=o.layout?.messages;if(Ai($)&&$.agentMetadata?.askUserQuestionAnswered===!0){Qi.delete($.id),i.querySelector(`#wrapper-${$.id}`)?.removeAttribute("data-preserve-runtime");return}if(ql($)&&Ms(o).enabled)return;if(Ai($)&&o.features?.askUserQuestion?.enabled!==!1){let et=u.find(An=>typeof An.renderAskUserQuestion=="function");if(et&&Ft.current){let An=Qi.get($.id),Io=An!==En,kn=null;if(Io){let{payload:st,complete:tt}=ka($),ys=$.id,bn=()=>Ft.current?.getMessages().find(oo=>oo.id===ys);kn=et.renderAskUserQuestion({message:$,payload:st,complete:tt,resolve:oo=>{let Or=bn();Or&&Ft.current?.resolveAskUserQuestion(Or,oo)},dismiss:()=>{let oo=bn();oo?.agentMetadata?.awaitingLocalTool&&(Ft.current?.markAskUserQuestionResolved(oo),Ft.current?.resolveAskUserQuestion(oo,"(dismissed)"))},config:o})}let Ut=An!=null;if(Io&&kn===null&&!Ut){$.agentMetadata?.awaitingLocalTool===!0&&!$.agentMetadata?.askUserQuestionAnswered&&(ce.add($.toolCall.id),_p($,o,ot.composerOverlay));return}let Ye=Pr($.id,$.role);Ye.setAttribute("data-ask-plugin-stub","true"),Ye.setAttribute("data-preserve-runtime","true"),w.appendChild(Ye),De.push({messageId:$.id,fingerprint:En,bubble:kn});return}else{$.agentMetadata?.awaitingLocalTool===!0&&!$.agentMetadata?.askUserQuestionAnswered&&(ce.add($.toolCall.id),_p($,o,ot.composerOverlay));return}}else if(Je){let et=D();if(!et){w.appendChild(Pr($.id,$.role));return}let An=u.find(Ye=>typeof Ye.renderApproval=="function")??M,kn=ns.get($.id)!==En,Ut=null;if(kn&&An?.renderApproval){let Ye=$.id,st=(tt,ys)=>{let bn=Ft.current?.getMessages().find(oo=>oo.id===Ye);bn?.approval&&(bn.approval.toolType==="webmcp"?Ft.current?.resolveWebMcpApproval(bn.id,tt):Ft.current?.resolveApproval(bn.approval,tt,ys))};Ut=An.renderApproval({message:$,defaultRenderer:()=>et.createApprovalBubble($,o,l),config:o,approve:tt=>st("approved",tt),deny:tt=>st("denied",tt)})}if(kn&&Ut===null)i.querySelector(`#wrapper-${$.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete($.id),cn=et.createApprovalBubble($,o,l);else{let Ye=Pr($.id,$.role);Ye.setAttribute("data-approval-plugin-stub","true"),Ye.setAttribute("data-preserve-runtime","true"),w.appendChild(Ye),no.push({messageId:$.id,fingerprint:En,bubble:Ut});return}}else if(Sn)if($.variant==="reasoning"&&$.reasoning&&Sn.renderReasoning){if(!J)return;cn=Sn.renderReasoning({message:$,defaultRenderer:()=>yy($,o,s),config:o})}else if($.variant==="tool"&&$.toolCall&&Sn.renderToolCall){if(!Y)return;cn=Sn.renderToolCall({message:$,defaultRenderer:()=>wy($,o,r),config:o})}else Sn.renderMessage&&(cn=Sn.renderMessage({message:$,defaultRenderer:()=>{let et=iy($,f,Ke,o.messageActions,Gn,{loadingIndicatorRenderer:q,widgetConfig:o,actionEligibility:fn});return $.role!=="user"&&O(et,$,o,N),et},config:o}));if(!cn&&fe){let et=JE($);if(et){let An=Xs.get($.id),Io=An!==En,kn=o.wrapComponentDirectiveInBubble!==!1&&Yo.getOptions(et.component)?.bubbleChrome!==!1,Ut=null;if(Io){let Ye=QE(et,{config:o,message:$,transform:f});if(Ye&&et.component==="PersonaArtifactInline"){let st=Ye.hasAttribute("data-artifact-inline")?Ye:Ye.querySelector("[data-artifact-inline]"),tt=st?.getAttribute("data-artifact-inline")??"",ys=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(tt):tt,bn=tt?i.querySelector(`#wrapper-${$.id}`)?.querySelector(`[data-artifact-inline="${ys}"]`)??null:null;st&&bn&&bn!==st&&Gr()?.hasLiveInlineArtifactBlock(bn)&&(st===Ye?Ye=bn:st.replaceWith(bn))}if(Ye)if(kn){let st=document.createElement("div");if(st.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),st.id=`bubble-${$.id}`,st.setAttribute("data-message-id",$.id),$.content&&$.content.trim()){let tt=document.createElement("div");tt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",tt.innerHTML=f({text:$.content,message:$,streaming:!!$.streaming,raw:$.rawContent}),st.appendChild(tt)}st.appendChild(Ye),Ut=st}else{let st=document.createElement("div");if(st.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",st.id=`bubble-${$.id}`,st.setAttribute("data-message-id",$.id),st.setAttribute("data-persona-component-directive","true"),$.content&&$.content.trim()){let tt=document.createElement("div");tt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",tt.innerHTML=f({text:$.content,message:$,streaming:!!$.streaming,raw:$.rawContent}),st.appendChild(tt)}st.appendChild(Ye),Ut=st}}if(Ut||An!=null){let Ye=Pr($.id,$.role);Ye.setAttribute("data-component-directive-stub","true"),Ye.setAttribute("data-preserve-runtime","true"),w.appendChild(Ye),lt.push({messageId:$.id,fingerprint:En,bubble:Ut});return}}}if(!cn)if($.variant==="reasoning"&&$.reasoning){if(!J)return;cn=yy($,o,s)}else if($.variant==="tool"&&$.toolCall){if(!Y)return;cn=wy($,o,r)}else if($.variant==="approval"&&$.approval){if(o.approval===!1)return;let et=D();if(!et)return;cn=et.createApprovalBubble($,o,l)}else{let et=o.layout?.messages;et?.renderUserMessage&&$.role==="user"?cn=et.renderUserMessage({message:$,config:o,streaming:!!$.streaming}):et?.renderAssistantMessage&&$.role==="assistant"?cn=et.renderAssistantMessage({message:$,config:o,streaming:!!$.streaming}):cn=iy($,f,et,o.messageActions,Gn,{loadingIndicatorRenderer:q,widgetConfig:o,actionEligibility:fn}),$.role!=="user"&&cn&&O(cn,$,o,N)}let Kt=Pr($.id,$.role);Kt.appendChild(cn),eM(mn,$.id,En,Kt),w.appendChild(Kt)}),ot.composerOverlay&&ot.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Xe=>{let Je=Xe.getAttribute("data-persona-ask-sheet-for");Je&&!ce.has(Je)&&La(ot.composerOverlay,Je)}),o.features?.toolCallDisplay?.grouped){let $=[],Xe=[],Je=o.features.toolCallDisplay.groupedMode==="summary";d.forEach(fe=>{if(fe.variant==="tool"&&fe.toolCall&&Y){if(Po&&fe.toolCall.status==="complete")return;Xe.push(fe);return}fe.variant==="reasoning"&&(!J||fe.reasoning?.status==="complete"&&dr(fe.reasoning))||((Xe.length>1||Je&&Xe.length>0)&&$.push(Xe),Xe=[])}),(Xe.length>1||Je&&Xe.length>0)&&$.push(Xe),$.forEach(fe=>{let zt=fe.map(Ke=>Array.from(w.children).find(Kt=>Kt instanceof HTMLElement&&Kt.getAttribute("data-wrapper-id")===Ke.id)).filter(Ke=>!!Ke);if(zt.length<(Je?1:2))return;let fn=Pr(`tool-group-${fe[0].id}`,"assistant");if(fn.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let Ke=`tool-group-${fe[0].id}`,Kt=fe.some(Ut=>Ut.toolCall?.status!=="complete"),et={...fe[0],id:Ke,toolCall:{id:Ke,name:`${fe.length} tools`,status:Kt?"running":"complete",chunks:fe.flatMap(Ut=>Ut.toolCall?.chunks??[]),success:!fe.some(Ut=>Ut.toolCall?.success===!1)}};y.add(Ke),a.observe(et,"tool",r,o.features.toolCallDisplay);let An=`${Kt?"Using":"Used"} ${fe.length} tools`,Io=o.toolCall?.renderGroupedSummary?.({messages:fe,toolCalls:fe.map(Ut=>Ut.toolCall),defaultSummary:An,config:o}),kn=Mw(et,o,r.has(Ke),Io??An);kn.bubble.classList.add("persona-tool-group"),kn.body.dataset.personaToolGroupStack="true",zt[0].before(fn),fn.appendChild(kn.bubble),zt.forEach((Ut,Ye)=>{Ut.style.setProperty("--persona-message-row-max-width","100%"),Ut.style.setProperty("--persona-activity-stagger",`${Ye*40}ms`),Ut.classList.add("persona-activity-group-child"),kn.body.appendChild(Ut)});return}let _n=document.createElement("div");_n.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",_n.setAttribute("data-persona-tool-group","true");let En=document.createElement("div");En.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",En.id=`tool-group-summary-${fe[0].id}`;let jt=`Called ${fe.length} ${fe.length===1?"tool":"tools"}`,cn=o.toolCall?.renderGroupedSummary?.({messages:fe,toolCalls:fe.map(Ke=>Ke.toolCall).filter(Ke=>!!Ke),defaultSummary:jt,config:o});te(En,cn)||(En.textContent=jt);let Sn=document.createElement("div");Sn.className="persona-tool-group-stack persona-flex persona-flex-col",Sn.id=`tool-group-stack-${fe[0].id}`,Sn.setAttribute("data-persona-tool-group-stack","true"),_n.appendChild(En),Je||_n.appendChild(Sn),fn.appendChild(_n),zt[0].before(fn),zt.forEach((Ke,Kt)=>{if(Je){Ke.remove();return}Ke.style.setProperty("--persona-message-row-max-width","100%");let et=document.createElement("div");et.className="persona-tool-group-item persona-relative",et.setAttribute("data-persona-tool-group-item","true"),Kt<zt.length-1&&et.setAttribute("data-persona-tool-group-connector","true"),et.appendChild(Ke),Sn.appendChild(et)})})}a.prune(y),tM(mn,Q);let gs=$=>$.variant==="tool"&&!Y||$.variant==="reasoning"&&!J||Lo($),pr=d.some($=>$.role==="assistant"&&$.streaming&&!gs($)),zo=d.length-1;for(;zo>=0&&gs(d[zo]);)zo--;let hs=zo>=0?d[zo]:void 0,Ol=zo<d.length-1,hi=hs?.role==="assistant"&&!hs.streaming&&hs.variant!=="approval"&&!Ol;if(uo&&d.some($=>$.role==="user")&&!pr&&!hi){let $={config:o,streaming:!0,location:"standalone",defaultRenderer:Rc},Xe=u.find(fe=>fe.renderLoadingIndicator),Je=null;if(Xe?.renderLoadingIndicator&&(Je=Xe.renderLoadingIndicator($)),Je===null&&o.loadingIndicator?.render&&(Je=o.loadingIndicator.render($)),Je===null&&(Je=Rc()),Je){let fe=document.createElement("div"),zt=o.loadingIndicator?.showBubble!==!1,fn=o.layout?.messages?.layout??"bubble";fe.className=zt?Hc("assistant",fn).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),fe.setAttribute("data-typing-indicator","true"),zt&&(fe.style.color="var(--persona-message-assistant-text, var(--persona-text))",fn!=="flat"&&(fe.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),fe.appendChild(Je);let _n=Pr("typing-indicator","assistant");_n.appendChild(fe),w.appendChild(_n)}}if(!uo&&d.length>0){let $=d[d.length-1],Xe={config:o,lastMessage:$,messageCount:d.length},Je=u.find(zt=>zt.renderIdleIndicator),fe=null;if(Je?.renderIdleIndicator&&(fe=Je.renderIdleIndicator(Xe)),fe===null&&o.loadingIndicator?.renderIdle&&(fe=o.loadingIndicator.renderIdle(Xe)),fe){let zt=document.createElement("div"),fn=o.loadingIndicator?.showBubble!==!1;zt.className=fn?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),zt.setAttribute("data-idle-indicator","true"),zt.appendChild(fe);let _n=Pr("idle-indicator","assistant");_n.appendChild(zt),w.appendChild(_n)}}if(Vw(w),Vu(i,w),Rg(i),$t){let{messageId:$,element:Xe}=$t,Je=i.querySelector(`#wrapper-${$}`);Je&&Xe.parentElement!==Je&&(fl(Je,re.get($)??"user"),Je.replaceChildren(Xe))}if(De.length>0)for(let{messageId:$,fingerprint:Xe,bubble:Je}of De){let fe=i.querySelector(`#wrapper-${$}`);fe&&(fl(fe,re.get($)??"assistant"),Je!==null&&(fe.replaceChildren(Je),fe.setAttribute("data-bubble-fp",Xe),Qi.set($,Xe)))}if(Qi.size>0)for(let $ of Qi.keys())Q.has($)||Qi.delete($);if(lt.length>0)for(let{messageId:$,fingerprint:Xe,bubble:Je}of lt){let fe=i.querySelector(`#wrapper-${$}`);fe&&(fl(fe,re.get($)??"assistant"),Je!==null&&(fe.replaceChildren(Je),fe.setAttribute("data-bubble-fp",Xe),Xs.set($,Xe)))}if(Xs.size>0)for(let $ of Xs.keys())Q.has($)||Xs.delete($);if(no.length>0)for(let{messageId:$,fingerprint:Xe,bubble:Je}of no){let fe=i.querySelector(`#wrapper-${$}`);fe&&(fl(fe,re.get($)??"assistant"),Je!==null&&(fe.replaceChildren(Je),fe.setAttribute("data-bubble-fp",Xe),ns.set($,Xe)))}if(ns.size>0)for(let $ of ns.keys())Q.has($)||ns.delete($)},af=!1,kd=()=>{af||(af=!0,Hw().catch(()=>{af=!1}))},xo=(i,d,f)=>{d.length>0&&kd(),nk(i,d,f),Kb()},gl=null,ok=()=>{if(gl)return;let i=f=>{let y=f.composedPath();y.includes(dt)||Nt&&y.includes(Nt)||qt(!1,"user")};gl=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},Pv=()=>{if(!gl)return;(t.ownerDocument??document).removeEventListener("pointerdown",gl,!0),gl=null};_e.push(()=>Pv());let hl=null,rk=()=>{if(hl)return;let i=f=>{f.key==="Escape"&&(f.isComposing||qt(!1,"user"))};hl=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},Lv=()=>{if(!hl)return;(t.ownerDocument??document).removeEventListener("keydown",hl,!0),hl=null};_e.push(()=>Lv());let yl=!1,Iv=new Set,sk=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},oa=()=>{if(!xe())return;let i=ot.peekBanner,d=ot.peekTextNode;if(!i||!d)return;if(Ae){i.classList.remove("persona-pill-peek--visible");return}let f=N?.getMessages()??[],y;for(let Jt=f.length-1;Jt>=0;Jt--){let rn=f[Jt];if(rn.role==="assistant"&&rn.content){y=rn;break}}if(!y){i.classList.remove("persona-pill-peek--visible");return}let w=y.content,k=!!y.streaming,q=sk(),te=qu(q),Q=te.type!=="none"?Qm(te.type,q?.plugins):null,re=Q?.isAnimating?.(y)===!0,ce=Q!==null&&(k||re);ce&&Q&&!Iv.has(Q.name)&&(xc(Q,t),Iv.add(Q.name));let he=ce&&Q?.containerClass?Q.containerClass:null,De=d.dataset.personaPeekStreamClass??null;De&&De!==he&&(d.classList.remove(De),delete d.dataset.personaPeekStreamClass),he&&De!==he&&(d.classList.add(he),d.dataset.personaPeekStreamClass=he),ce?(d.style.setProperty("--persona-stream-step",`${te.speed}ms`),d.style.setProperty("--persona-stream-duration",`${te.duration}ms`)):(d.style.removeProperty("--persona-stream-step"),d.style.removeProperty("--persona-stream-duration"));let lt=ce?ju(w,te.buffer,Q,y,k):w;if(ce&&te.placeholder==="skeleton"&&k&&(!lt||!lt.trim())){let Jt=document.createElement("div"),rn=wc();rn.classList.add("persona-pill-peek__skeleton"),Jt.appendChild(rn),Vu(d,Jt)}else{let Jt=Math.max(0,lt.length-100),rn=lt.length>100?lt.slice(-100):lt,Vn=$r(rn);if(!ce||!Q){let ln=lt.length>100?`\u2026${rn}`:rn;d.textContent!==ln&&(d.textContent=ln)}else{let ln=Vn;(Q.wrap==="char"||Q.wrap==="word")&&(ln=Cc(Vn,Q.wrap,`peek-${y.id}`,{skipTags:Q.skipTags,startIndex:Jt}));let $t=document.createElement("div");if($t.innerHTML=ln,Q.useCaret&&rn.length>0){let cr=Ku(),dr=$t.querySelectorAll(".persona-stream-char, .persona-stream-word"),Po=dr[dr.length-1];Po?.parentNode?Po.parentNode.insertBefore(cr,Po.nextSibling):$t.appendChild(cr)}Vu(d,$t),Q.onAfterRender?.({container:d,bubble:i,messageId:y.id,message:y,speed:te.speed,duration:te.duration})}}let no=uo||yl;i.classList.toggle("persona-pill-peek--visible",no)};if(xe()){let i=ot.peekBanner;if(i){let y=w=>{w.preventDefault(),w.stopPropagation(),qt(!0,"user")};i.addEventListener("pointerdown",y),_e.push(()=>{i.removeEventListener("pointerdown",y)})}let d=()=>{yl||(yl=!0,oa())},f=()=>{yl&&(yl=!1,oa())};Se.addEventListener("pointerenter",d),Se.addEventListener("pointerleave",f),_e.push(()=>{Se.removeEventListener("pointerenter",d),Se.removeEventListener("pointerleave",f)}),Nt&&(Nt.addEventListener("pointerenter",d),Nt.addEventListener("pointerleave",f),_e.push(()=>{Nt.removeEventListener("pointerenter",d),Nt.removeEventListener("pointerleave",f)}))}let ik=i=>{let d=o.launcher?.composerBar??{},f=d.expandedSize??"anchored",y=d.bottomOffset??"16px",w=d.collapsedMaxWidth,k=d.expandedMaxWidth??"880px",q=d.expandedTopOffset??"5vh",te=d.modalMaxWidth??"880px",Q=d.modalMaxHeight??"min(90vh, 800px)",re="calc(100vw - 32px)",ce="var(--persona-pill-area-height, 80px)",he=dt.style;if(he.left="",he.right="",he.top="",he.bottom="",he.transform="",he.width="",he.maxWidth="",he.height="",he.maxHeight="",Nt){let De=Nt.style;De.bottom=y,De.width=w??""}if(i&&f!=="fullscreen"){if(f==="modal"){he.top="50%",he.left="50%",he.transform="translate(-50%, -50%)",he.bottom="auto",he.right="auto",he.width=te,he.maxWidth=re,he.maxHeight=Q,he.height=Q;return}he.left="50%",he.transform="translateX(-50%)",he.bottom=`calc(${y} + ${ce})`,he.top=q,he.width=k,he.maxWidth=re}},bl=()=>{if(Ae&&kd(),!Ne())return;if(xe()){let re=(o.launcher?.composerBar??{}).expandedSize??"anchored",ce=Ae?"expanded":"collapsed";dt.dataset.state=ce,dt.dataset.expandedSize=re,Nt&&(Nt.dataset.state=ce,Nt.dataset.expandedSize=re),dt.style.removeProperty("display"),dt.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ik(Ae),Pe.style.display=Ae?"flex":"none",Us(),Ae?(ok(),rk()):(Pv(),Lv()),oa();return}let i=nn(o),d=t.ownerDocument.defaultView??window,f=o.launcher?.mobileBreakpoint??640,y=o.launcher?.mobileFullscreen??!0,w=d.innerWidth<=f,k=y&&w&&_,q=Do(o).reveal;Ae?(dt.style.removeProperty("display"),dt.style.display=i?"flex":"",dt.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0"),Se.classList.add("persona-scale-100","persona-opacity-100"),sn?(sn.setPanelOpen(!0),sn.element.style.display="none"):Fn&&(Fn.style.display="none")):(i?i&&(q==="overlay"||q==="push")&&!k?(dt.style.removeProperty("display"),dt.style.display="flex",dt.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(dt.style.setProperty("display","none","important"),dt.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(dt.style.display="",dt.classList.add("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100"),Se.classList.add("persona-scale-95","persona-opacity-0")),sn?(sn.setPanelOpen(!1),sn.element.style.display=i?"none":""):Fn&&(Fn.style.display=i?"none":""))},qt=(i,d="user")=>{if(!Ne()||Ae===i)return;let f=Ae;Ae=i,bl();let y=(()=>{let k=o.launcher?.sidebarMode??!1,q=t.ownerDocument.defaultView??window,te=o.launcher?.mobileFullscreen??!0,Q=o.launcher?.mobileBreakpoint??640,re=q.innerWidth<=Q,ce=nn(o)&&te&&re,he=xe()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||te&&re&&_||ce||he})();if(Ae&&y){if(!or){let k=t.getRootNode(),q=k instanceof ShadowRoot?k.host:t.closest(".persona-host");q&&(or=Qh(q,o.launcher?.zIndex??On))}rr||(rr=Xh(t.ownerDocument))}else Ae||(or?.(),or=null,rr?.(),rr=null);Ae&&(Wl(),rf()||(po()==="follow"?as(!0):Ad()));let w={open:Ae,source:d,timestamp:Date.now()};Ae&&!f?R.emit("widget:opened",w):!Ae&&f&&R.emit("widget:closed",w),R.emit("widget:state",{open:Ae,launcherEnabled:_,voiceActive:wt.active,streaming:N.isStreaming()})},ls={inputDisabled:!1,sendDisabled:!1},sr=()=>ls.inputDisabled,lf=()=>so(o.voiceRecognition?.provider)&&!!N&&(N.isBargeInActive()||["listening","processing","speaking"].includes(N.getVoiceStatus())),si=()=>ls.inputDisabled||ls.sendDisabled,ak=()=>(ls.inputDisabled?ls.inputReason:void 0)??(ls.sendDisabled?ls.sendReason:void 0);function cf(){if(!Ve)return;if(ze.getState().phase==="streaming"){Ve.disabled=!1;return}let i=Lt?!Lt.isReady():!1;Ve.disabled=si()||i}function Pd(){if(!Jo)return;let i=ze.getState(),d=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;Jo.toggleAttribute("data-persona-send-hidden",d)}function lk(){let i=ak();if(xe()){let d=Tn??Qe;i?d.setAttribute("title",i):d.removeAttribute("title"),Qe.toggleAttribute(Za,!!i);return}if(i){pt.setAttribute("role","status"),pt.setAttribute("aria-live","polite"),pt.setAttribute(Za,""),pt.textContent=i,xi(pt,o.statusIndicator??{},"idle");return}if(pt.hasAttribute(Za)&&(pt.removeAttribute("role"),pt.removeAttribute("aria-live"),pt.removeAttribute(Za),h)){let d=N.getStatus();Qo(pt,_s(d),o.statusIndicator??{},d)}}function df(){let i=dh(o.composer?.inputDisabled),d=dh(o.composer?.sendDisabled);ls={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:d.disabled,sendReason:d.reason},ze.setInputDisabled(i.disabled),ze.setSendDisabled(d.disabled);let f=ze.getState().phase==="streaming",y=i.disabled,w=f||y;we&&(we instanceof HTMLTextAreaElement?we.disabled=y:we.setAttribute("contenteditable",y?"false":"true"),we.setAttribute("aria-disabled",y?"true":"false")),on&&(on.disabled=y),Xt&&(Xt.disabled=y);for(let k of un?.affordanceButtons??[])k.querySelectorAll("button").forEach(q=>{q.disabled=y});ye&&(ye.disabled=y||f&&!lf()),Ks.forEach(k=>{k.elements.forEach(q=>{q.toggleAttribute("data-disabled",w),q instanceof HTMLButtonElement||q.setAttribute("aria-disabled",w?"true":"false")}),k.buttons.forEach(q=>{q.disabled=w})}),gf.forEach(k=>{k.toggleAttribute("data-disabled",w),k instanceof HTMLButtonElement?k.disabled=w:k.setAttribute("aria-disabled",w?"true":"false"),k.querySelectorAll("button").forEach(q=>{q.disabled=w})}),Qe.dataset.personaComposerStreaming=f?"true":"false",Qe.dataset.personaComposerInputDisabled=y?"true":"false",Qe.dataset.personaComposerSendDisabled=si()?"true":"false",Qe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(k=>{(k instanceof HTMLButtonElement||k instanceof HTMLInputElement||k instanceof HTMLTextAreaElement||k instanceof HTMLSelectElement)&&(k.disabled=f)}),cf(),lk()}let vl=i=>{ze.setStreaming(i),Ab(i?"stop":"send"),df()},ii=()=>{wt.active||we&&we.focus()};R.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ii(),200)});let ai=null,Cl=!1,pf=!gn.hidden,cs=null,uf=!G,Ld=null;_e.push(()=>{Ld?.cancel(),Ld=null});let ck=i=>{let d=jM(i);if(d===od)return;od=d,t.setAttribute("data-persona-conversation-state",d);let f=Rm();sd(),uf&&(Ld?.cancel(),Ld=UM(Qe,d==="active"?f:Rm(),d==="active"?"drop":"rise",Vs().layout==="centered"?320:260)),eo()},Rv=null,Hv,Wv=null,ra=null,mf=!1,sa=i=>{let d=Vs(),f=`${d.variant}|${d.layout}|${d.dismiss}|${d.anchor??"bottom"}|${d.align??""}|${d.iconPlacement}|${d.kicker??""}|${d.title}|${d.subtitle}`;(f!==Rv||d.icon!==Hv)&&(Rv=f,Hv=d.icon,tm({host:gn,iconHolder:km,kicker:ge,title:Ue,subtitle:at,starterSuggestions:Ns},d));let y=d.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${d.message}`;y!==Wv&&(Wv=y,nm(z,d.message,o));let w=i??(N?N.getMessages():o.initialMessages);ck(w);let k=Cl,q=!k&&Ua(d,w),te=q!==pf;if(pf=q,ra){cs?.cancel(),cs=null,k!==mf&&(mf=k,k?cy(pe,gn,null):ly(pe,gn,ra)),za(pe,gn,!k);return}if(te&&!q&&!k&&d.dismiss==="on-first-message"&&uf){cs=zM(gn,re=>{cs===re&&(cs=null),!pf&&!ra&&(za(pe,gn,!1),eo()),re?.cancel()});return}if(cs){if(!q&&!k)return;cs.cancel(),cs=null}let Q=!gn.hidden;za(pe,gn,q),!q&&Q&&eo()},ff=[],gf=[],hf=!1,Bv=null,Dv,Ov=()=>{gf.length=0;let i=ff.splice(0,ff.length);for(let d of i)try{d()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};_e.push(Ov);let dk=(i,d)=>{let f=Zh(i,d);if(!f)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let y=o.suggestions?.starters,w=ey({item:{...f,behavior:f.behavior??y?.behavior??"send"},index:d,surface:"starter",source:"config",variant:y?.variant??"card",streaming:h?N.isStreaming():!1,config:o,plugins:u,chipsConfig:o.suggestionChipsConfig,session:N,getTextarea:()=>we,eventTarget:gn,submitPrompt:op});return gf.push(w),w},yf=()=>{if(hf)return;hf=!0;let i=Vs();Bv=`${i.variant}|${i.layout}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,Dv=i.icon;try{Ov(),cy(pe,gn,ra),ra=null,mf=!1;let d=N?N.getMessages():o.initialMessages,f=Ua(i,d),y=0,w=null;for(let k of u)if(k.renderWelcome&&(w=k.renderWelcome({config:i,variant:i.variant,visible:f,defaultRenderer:()=>gn,sendMessage:q=>{if(!N||N.isStreaming())return;let te=q.trim();te&&N.sendMessage(te)},requestRender:()=>yf(),renderStarter:q=>dk(q,y++),storage:b(k.id),onCleanup:q=>{ff.push(q)}}),w))break;w&&w!==gn&&(ra=w,ly(pe,gn,w))}finally{hf=!1}sa()},pk=()=>{let i=Vs();`${i.variant}|${i.layout}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Bv&&i.icon===Dv||yf()},Id=()=>{sa(),ji||(we.placeholder=VS(ze.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!N?.isStreaming()&&(Ve.textContent=o.copy?.sendButtonLabel??"Send")),we.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',we.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},uk=!!o.setStoredConversationId,ia=i=>de(d=>{let f={...d};return delete f[i],f}),Rd=i=>{let d=L[i];return typeof d=="string"?d:null},_v=()=>{let i=L.durableResume;if(!i||typeof i!="object")return null;let d=i;return typeof d.executionId=="string"&&d.executionId.length>0&&typeof d.after=="string"&&d.after.length>0?{executionId:d.executionId,after:d.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Rd("sessionId"),setStoredSessionId:i=>{de(d=>({...d,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>ia("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Rd("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{de(d=>({...d,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>ia("conversationId"))});let Nv=()=>o.clientToken??null,Fv=i=>EE(i,Oe(),o.persistState===!1),Vv=Nv(),So=Vv?Fv(Vv):null,Lr={...So?{visitorStore:So}:{},historyBootstrapReady:K,getStoredMessageCursor:()=>Rd("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){ia("historyMessageCursor");return}de(d=>({...d,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=L.pendingDisplayProjections;if(!i||typeof i!="object")return null;let d=i;return typeof d.conversationId!="string"||!Array.isArray(d.messageIds)?null:{conversationId:d.conversationId,messageIds:d.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:i=>{if(!i){ia("pendingDisplayProjections");return}de(d=>({...d,pendingDisplayProjections:i}))},getStoredResumableHandle:_v,setStoredResumableHandle:i=>{if(!i){ia("durableResume");return}de(d=>({...d,durableResume:i}))},shouldResumeDurableConversation:()=>P&&_v()!==null,...uk?{}:{getStoredConversationRevision:()=>Rd("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){ia("conversationRevision");return}de(d=>({...d,conversationRevision:i}))}}};if(P){let i=o.onExecutionState,d=t.ownerDocument.defaultView,f=!1,y=()=>f=!0,w=()=>f=!1;d?.addEventListener("pagehide",y),d?.addEventListener("pageshow",w),_e.push(()=>{d?.removeEventListener("pagehide",y),d?.removeEventListener("pageshow",w)}),o={...o,reconnectStream:o.reconnectStream??(k=>N.getClient().reconnectClientTokenStream(k)),onExecutionState:k=>{(k||!f)&&Lr.setStoredResumableHandle?.(k?{executionId:k.executionId,after:k.lastEventId}:null),i?.(k)}}}let mk=()=>{let i=Nv();if(i&&So?.matches(i,Oe(),o.persistState===!1)||!i&&!So)return;So?.destroy(),So=i?Fv(i):null;let d={...Lr};So?d.visitorStore=So:delete d.visitorStore,Lr=d,N.setHistoryInternals(Lr)},li=null,fk=()=>{li==null&&(li=setInterval(()=>{let i=We.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(li),li=null;return}let d=Date.now();i.forEach(f=>{let y=Number(f.getAttribute("data-tool-elapsed"));y&&(f.textContent=f.closest(".persona-activity-row")?Vl(d-y):Vp(d-y))})},100))},bf=(i,d)=>{if(Object.is(i,d))return!0;if(i===null||d===null||typeof i!="object"||typeof d!="object")return!1;if(Array.isArray(i)||Array.isArray(d))return!Array.isArray(i)||!Array.isArray(d)||i.length!==d.length?!1:i.every((q,te)=>bf(q,d[te]));let f=i,y=d,w=Object.keys(f),k=Object.keys(y);return w.length===k.length&&w.every(q=>Object.prototype.hasOwnProperty.call(y,q)&&bf(f[q],y[q]))},$v=i=>{let{content:d,rawContent:f,llmContent:y,...w}=i;return w},vf=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!hb(i),gk=(i,d,f)=>{if(i.length!==d.length)return!1;let y=i[f.index],w=d[f.index];return!y||!w||y.id!==f.id||w.id!==f.id?!1:(!Object.is(y.content,w.content)||!Object.is(y.rawContent,w.rawContent)||!Object.is(y.llmContent,w.llmContent))&&vf(y)&&vf(w)&&bf($v(y),$v(w))},Cf=null,aa=null,ci=null,Ir=null,wf=null,hk=i=>{if(!P)return Zi(i);wf=i,queueMicrotask(()=>{wf===i&&(wf=null,Zi(i))})},Hd=i=>{Cf=i;let d,f;aa=null;for(let w=i.length-1;w>=0;w-=1){let k=i[w];if(!d&&k.role==="user"&&(d=k),!f&&k.role==="assistant"&&(f=k),!aa&&vf(k)&&(aa={index:w,id:k.id}),d&&f&&aa)break}xo(We,i,j),Gr()?.updateInlineArtifactBlocks(We,wo.artifacts,{suppressTransition:uo}),fk(),sa(i),Qs(i),as(!uo),tk(i),i.length===0&&($o(),ul=!0,bd=!1,Ji=null,vd=!1),!Xm||Xi?(Xm=!0,ni=d?.id??null,Jm=f?.id??null):d&&d.id!==ni?(ni=d.id,Q0(d.id)):f&&f.id!==Jm&&X0(),f&&(Jm=f.id),ek(i);let y=wt.lastUserMessageId;d&&d.id!==y&&(wt.lastUserMessageId=d.id,R.emit("user:message",d)),wt.lastUserMessageWasVoice=!!d?.viaVoice,hk(i),oa()},xf=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null);let i=ci;ci=null,i&&Hd(i)},zv=()=>{Ir!==null&&cancelAnimationFrame(Ir),Ir=null,ci=null},yk=i=>{let d=ci??Cf;if(uo&&d&&aa&&gk(d,i,aa)){ci=i,Ir===null&&(Ir=requestAnimationFrame(()=>{Ir=null;let f=ci;ci=null,f&&Hd(f)}));return}if(i.length===0){zv(),Hd(i);return}xf(),Hd(i)};N=new Jp(o,{onMessagesChanged(i){yk(i)},onStatusChanged(i){let d=o.statusIndicator??{};Qo(pt,(y=>y==="idle"?d.idleText??dn.idle:y==="connecting"?d.connectingText??dn.connecting:y==="connected"?d.connectedText??dn.connected:y==="error"?d.errorText??dn.error:y==="paused"?d.pausedText??dn.paused:y==="resuming"?d.resumingText??dn.resuming:dn[y])(i),d,i),pn()},onStreamingChanged(i){i||(N?.getMessages().length===0?zv():xf()),uo=i,vl(i),pn(),N&&xo(We,N.getMessages(),j),i||(as(!0),G0(),gv=!0,N&&hv(N.getMessages(),Ms(o))),xn(),nd(i?"Responding\u2026":"Response complete."),oa()},onVoiceStatusChanged(i){if(R.emit("voice:status",{status:i,timestamp:Date.now()}),!(i!=="disconnected"&&!so(o.voiceRecognition?.provider)))switch(i){case"listening":Dr(),ba();break;case"processing":Dr(),vP();break;case"speaking":Dr(),CP();break;default:i==="idle"&&N.isBargeInActive()?(Dr(),ba(),ye?.setAttribute("aria-label","End voice session")):(wt.active=!1,Dr(),kr("system"),Vo());break}},onArtifactsState(i){wo=i,i.artifacts.length===0&&(Ki=!1),Gr()?.updateInlineArtifactBlocks(We,i.artifacts,{suppressTransition:uo}),Fo(),Zi()},onHistoryStateChanged(i){_t(i)},onHistoryNotice(i){Vt(i)},onReconnect(i){let{executionId:d,lastEventId:f}=i.handle;i.phase==="paused"?R.emit("stream:paused",{executionId:d,after:f}):i.phase==="resuming"?R.emit("stream:resuming",{executionId:d,after:f,attempt:i.attempt??1}):R.emit("stream:resumed",{executionId:d,after:f})}},Lr),Ft.current=N,_e.push(()=>N.cancel()),_e.push(()=>{N.destroy(),So?.destroy(),So=null});let Sf=null;if(N.onReadAloudChange((i,d)=>{qb=i,jb=d,Kb();let f=i??Sf;i&&(Sf=i);let y=f?N.getMessages().find(w=>w.id===f)??null:null;R.emit("message:read-aloud",{messageId:f,message:y,state:d,timestamp:Date.now()}),d==="idle"&&(Sf=null)}),h=!0,Xm=!0,o.voiceRecognition?.enabled===!0&&so(o.voiceRecognition.provider))try{N.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let bk=720,vk=250,Mt=nb(o.features?.history?.copy),go=null,Af=!1,Dt=null,Wd=null,Bd="conversation",Mf=null,Nn=null,ir=null,Dd=N.getHistoryState(),Tf=null,wl=0,Ef=null,Od=null,_d=null,kf=`persona-history-${Math.random().toString(36).slice(2,8)}`,Pf=()=>o.features?.history?.enabled===!0,ar=()=>Pf()&&!!go&&!Af,Uv=()=>{let i=N.getStatus();return uo||i==="paused"||i==="resuming"},Lf=()=>{let i=o.features?.history?.scope;if(i)return i;let d=o.getIdentityProof?"verified-user":"browser",f=go?.capabilities.scopes;return!f||f.includes(d)?d:f[0]??d},la=()=>Wd?.scope??Lf(),qv=()=>N.getClientSession()?.targetId??null,jv=i=>`${i.state}:${"reason"in i?i.reason:""}`,Ck=i=>{let d=jv(i);d!==Tf&&(Tf=d,R.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},Nd=i=>{i&&(xr.textContent="",xr.textContent=i)},Kv=null,Gv=null,wk=()=>{if(!Pf())return null;let i=GE();if(i)return i();let d=o.features?.history?.provider;return d?typeof d!="function"?d:(Kv!==d&&(Kv=d,Gv=d()),Gv):N.isClientTokenMode()?YE({client:N.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:f=>N.bindActivatedSession(f),getClient:()=>N.getClient()}):null},Yv=()=>{Od?.(),Od=null,_d?.(),_d=null,Af=!1,go=wk();let i={...Lr};go?i.historyProvider=go:delete i.historyProvider,Lr=i,N.setHistoryInternals(Lr),go&&(Od=go.subscribeAvailability?.(d=>{Af=!d,d||to({restoreFocus:!1}),ps()})??null,_d=go.subscribeIdentityStatus(d=>Ck(d)),Tf=jv(go.getIdentityStatus()))},If=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!_||nn(o)))return"panel";let d=nr??Pe;return(d.getBoundingClientRect().width||d.clientWidth)>=bk?"rail":"panel"},Ao=(i,d)=>{d?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},Fd="data-persona-history-suppressed",ho=null,ds=null,di=null,xl=null,Rf=null,Qv="",Xv=()=>$e===Rf?Qv:o.layout?.showHeader===!1?"none":"",xk=()=>xt==="panel"&&!!di&&xl===di.element&&o.layout?.showHeader!==!1&&Xv()!=="none",Sk=()=>{for(let i of Array.from($e.children))i!==ho&&i.setAttribute(Fd,"")},Ak=()=>{for(let i of Array.from(Pe.querySelectorAll(`[${Fd}]`)))i.removeAttribute(Fd)},Mk=()=>{let i=di;if(!i)return;if(Array.from($e.children).some(y=>y!==ho&&!y.hasAttribute(Fd))){ds&&ds!==$e&&(ds.style.removeProperty("min-height"),ds=null);let y=$e.offsetHeight;y>0&&($e.style.minHeight=`${y}px`,ds=$e)}ho||(ho=v("div","persona-history-header-host")),i.setHeaderPlacement("external");let f=i.getHeaderElement();f.parentNode!==ho&&ho.replaceChildren(f),ho.parentNode!==$e&&$e.appendChild(ho),Sk()},Jv=()=>{ds&&(ds.style.removeProperty("min-height"),ds=null),ho&&(di?.setHeaderPlacement("inline"),ho.remove(),ho=null,Ak())},Vd=null,Hf=()=>{if(Vd){if(pe.style.display="none",Ao(pe,!0),Qe.hidden=!0,Ao(Qe,!0),xk()){Mk(),$e.style.display=Xv(),Ao($e,!1);return}Jv(),$e.style.display="none",Ao($e,!0)}};Mn=Hf;let Tk=i=>{let d=pe.style.display,f=Qe.hidden,y=Qe,w=$e,k=$e.style.display;Rf=w,Qv=k,Vd=()=>{Vd=null,Jv(),Rf=null,pe.style.display=d,Ao(pe,!1),y.hidden=f,Ao(y,!1),Qe!==y&&(Qe.hidden=!1,Ao(Qe,!1)),w.style.display=k,Ao(w,!1),$e!==w&&($e.style.display=o.layout?.showHeader===!1?"none":"",Ao($e,!1))},Qe.parentNode?.insertBefore(i,Qe),Hf()},ca=null,pi=null,Sl=null,da=null,Zv=()=>[$e,ot.closeButtonWrapper,ot.clearChatButtonWrapper,pe,Qe],Ek=52,$d=()=>o.features?.history?.rail?.collapsible!==!1,pa=()=>o.features?.history?.rail?.side==="right"?"right":"left",Wf=200,Bf=400,Df=i=>Math.min(Bf,Math.max(Wf,Math.round(i))),kk=()=>o.features?.history?.rail?.resizable===!0,Al,Pk=()=>{if(Al===void 0&&(Al=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${Oe()}rail-width`));i&&(Al=i)}catch{}return Al},Ml=()=>Df(Pk()??o.features?.history?.rail?.width??260),Lk=i=>{if(Al=i,o.persistState!==!1)try{window.localStorage.setItem(`${Oe()}rail-width`,String(i))}catch{}},zd=()=>$d()&&o.features?.history?.rail?.collapsedBehavior==="overlay",yn=!1,eC=i=>{let d=v("img");return d.src=i,d.alt="",d.setAttribute("aria-hidden","true"),d},Ik=()=>{let i=o.features?.history?.rail?.brand;if(!i)return;let d=!1,f;return y=>{if(i.render)try{return i.render({collapsed:y})??null}catch(w){return d||(d=!0,console.warn("[persona] history rail brand threw",w)),null}return f===void 0&&(i.iconUrl?f=eC(i.iconUrl):f=i.icon?ke(i.icon,20):null),f?f.cloneNode(!0):null}},Rk=()=>o.features?.history?.rail?.sections?.map(i=>{let d=!1,f=y=>{d||(d=!0,console.warn("[persona] history rail section threw",i.id,y))};return{id:i.id,title:i.title,placement:i.placement??"above-conversations",items:i.items.map(y=>{let w;return{id:y.id,label:y.label,badge:y.badge,iconNode:()=>{if(w!==void 0)return w;try{y.renderIcon?w=y.renderIcon()??null:y.iconUrl?w=eC(y.iconUrl):w=y.icon?ke(y.icon,20):null}catch(k){f(k),w=null}return w},onSelect:()=>{try{y.onSelect()}catch(k){f(k)}}}})}})??[],Hk=i=>{let d=Rk();for(let f of i)d.some(y=>y.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):d.push(f);return d.length?d:void 0},Tl=null,tC=()=>`${Oe()}rail-collapsed`,Of=()=>{if(Tl===null&&(Tl=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(tC());i&&(Tl=i==="1")}catch{}return Tl},_f=i=>{if(Tl=i,o.persistState!==!1)try{window.localStorage.setItem(tC(),i?"1":"0")}catch{}},El=()=>xt==="rail"&&$d()&&!zd()&&Of(),Nf=()=>{},nC=()=>{if(zd()){Nf();return}_f(!Of()),Dt?.view.setCollapsed(El()),ft(),eo()},Ff=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!Nu(i)?null:{combo:i,hint:Fu(i),aria:yc(i)}},oC=()=>{g.forEach(d=>d()),g=[];let i=Ff();i&&g.push(m.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>mt&&xt==="rail"&&$d()||ma(),run:()=>zd()?Nf():nC()}));for(let d of o.layout?.header?.trailingActions??[])d.shortcut&&g.push(m.register({id:`header-action-${d.id}`,combo:d.shortcut,run:()=>{let f=t.querySelector(`[data-persona-header-action="${d.id}"]`);f?f.click():o.layout?.header?.onAction?.(d.id)}}));for(let d of u)for(let f of d.shortcuts??[])g.push(m.register({...f,id:`${d.id}:${f.id}`}))};oC();let Wk=300,Ud="var(--persona-history-overlay-margin,8px)",Mo=null,Rr=null,qd=0,Hr=null,ua=null,ui=!1,Vf=0,rC=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,ma=()=>ar()&&zd()&&(xt??If())==="rail",Bk=()=>mt&&!yn,kl=()=>{ua!==null&&clearTimeout(ua),ua=null},Dk=()=>{ub().catch(()=>{})},sC=()=>{kl(),yn&&(ua=setTimeout(()=>{ua=null,!(ui||!yn)&&(Hr?.contains(document.activeElement)||to({restoreFocus:!1}))},Wk))},Ok=(i,d)=>{let f=Hr?.getBoundingClientRect();if(!f)return!1;let y=Mo?.getBoundingClientRect(),w=y?Math.min(y.top,f.top):f.top;return i>=f.left&&i<=f.right&&d>=w&&d<=f.bottom||!!y&&i>=y.left&&i<=y.right&&d>=y.top&&d<=y.bottom},$f=i=>{yn&&(ui=Ok(i.clientX,i.clientY),ui?kl():ua===null&&sC())},iC=i=>{mt||!ma()||(yn=!0,Ll({invoker:Mo,keyboard:i?.keyboard===!0}).then(()=>{mt?!ui&&document.activeElement!==Mo&&to():yn=!1}))},aC=()=>{let i=xl?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",yn?Mt.expandLabel:Mt.collapseLabel),i.setAttribute("aria-expanded",yn?"false":"true"))},lC=()=>{_f(!1);let i=Dt;if(!yn||!i){Ll({invoker:Mo});return}let d=document.activeElement===Mo;yn=!1,jd(),i.element.remove(),Uf(i.element),aC(),d&&Gd(),eo(),ps()},_k=()=>{_f(!0),to()};Nf=()=>{!mt||yn?lC():_k()};let Nk=()=>{let i=Ff(),d=ki({ariaLabel:Mt.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":kf,...i?{"aria-keyshortcuts":i.aria}:{}}}),f=d.button;f.addEventListener("mouseenter",()=>{ui=!0,kl(),!(rC()||Date.now()<Vf)&&iC()}),f.addEventListener("mouseleave",()=>{ui=!1,Vf=0,sC()}),f.addEventListener("focus",()=>{mt||Dk()}),f.addEventListener("click",y=>{ar()&&(y.detail!==0&&rC()&&!mt?iC():lC())}),Mo=f,Rr=d.wrapper},Pl=()=>{if(Rr&&!Rr.isConnected&&(Rr=null,Mo=null),!ma()){Rr?.remove(),Rr=null,Mo=null;return}Mo||Nk();let i=Rr,d=Mo;if(!i||!d)return;let f=pa()!=="right"?$e.firstChild:null;(f??$e.lastChild)!==i&&$e.insertBefore(i,f),i.style.display=Bk()||qd>0?"none":"",d.setAttribute("aria-label",Mt.expandLabel),d.setAttribute("aria-expanded",mt?"true":"false"),Hr&&ft()},cC=i=>{if(!yn)return;let d=i.target;d instanceof Node&&(Hr?.contains(d)||Rr?.contains(d)||d instanceof Element&&d.closest('.persona-dropdown-menu,[role="alertdialog"]')||to({restoreFocus:!1}))};document.addEventListener("pointerdown",cC,!0),_e.push(()=>{document.removeEventListener("pointerdown",cC,!0),document.removeEventListener("pointermove",$f),fa?.(),kl()});let zf=null,fa=null,dC=16,pC=i=>{Lk(Df(i)),ft(),eo()},Fk=()=>{let i=v("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(Wf)),i.setAttribute("aria-valuemax",String(Bf)),i.addEventListener("pointerdown",d=>{let f=pi;if(!f||d.button!==0)return;d.preventDefault(),fa?.();let y=d.clientX,w=f.getBoundingClientRect().width||Ml(),k=pa()==="right"?-1:1,q=w,te=t.ownerDocument;f.style.transition="none";let Q=ce=>{q=Df(w+k*(ce.clientX-y)),f.style.flex=`0 0 ${q}px`,i.setAttribute("aria-valuenow",String(q))},re=()=>{fa=null,te.removeEventListener("pointermove",Q),te.removeEventListener("pointerup",re),te.removeEventListener("pointercancel",re),f.style.removeProperty("transition");try{i.releasePointerCapture(d.pointerId)}catch{}pC(q)};fa=re,te.addEventListener("pointermove",Q),te.addEventListener("pointerup",re),te.addEventListener("pointercancel",re);try{i.setPointerCapture(d.pointerId)}catch{}}),i.addEventListener("keydown",d=>{let f=pa()==="right"?-dC:dC,y=Ml(),w=d.key==="ArrowRight"?y+f:d.key==="ArrowLeft"?y-f:d.key==="Home"?Wf:d.key==="End"?Bf:null;w!==null&&(d.preventDefault(),pC(w))}),i},Vk=(i,d)=>{if(!kk()||El()){fa?.(),zf?.remove();return}let f=zf??Fk();zf=f,f.setAttribute("aria-label",Mt.resizeLabel),f.setAttribute("aria-valuenow",String(Ml())),f.nextElementSibling!==d&&i.insertBefore(f,d)};ft=()=>{Dt?.view.setRailSide(pa());let i=pa()==="right",d=Hr;if(d){let te=Mo?Mo.getBoundingClientRect().bottom-Pe.getBoundingClientRect().top:0;d.style.top=`calc(${Math.max(0,Math.round(te))}px + ${Ud})`,d.style.width=`${Ml()}px`,d.style.left=i?"":Ud,d.style.right=i?Ud:""}let f=pi,y=ca,w=Sl;if(!f||!y||!w)return;f.style.flex=`0 0 ${El()?Ek:Ml()}px`;let k="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=i?"":k,f.style.borderLeft=i?k:"";let q=i?w:f;y.firstElementChild!==q&&y.append(q,i?f:w),Vk(y,i?f:w)};let uC=i=>{if(da&&pi){da.replaceWith(i),da=null,ft();return}let d=v("div","persona-history-rail-shell");d.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=v("div","persona-history-rail-conversation");f.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let y=v("div","persona-history-rail-host");y.style.cssText="display:flex;min-height:0;overflow:hidden",Pe.insertBefore(d,$e.parentNode===Pe?$e:pe);for(let w of Zv())w?.parentNode===Pe&&f.appendChild(w);d.append(y,f),y.appendChild(i),ca=d,pi=y,Sl=f,ft()},$k=()=>{if(ca)return;let i=v("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",da=i,uC(i),eo()},mC=()=>{da&&(jd(),eo())},zk=i=>{let d=v("div","persona-history-rail-overlay");d.style.cssText=`position:absolute;bottom:${Ud};display:flex;overflow:hidden;z-index:${Ba-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,Pe.style.position="relative",Pe.appendChild(d),d.appendChild(i),document.addEventListener("pointermove",$f),Hr=d,ft(),aC()},jd=()=>{Vd?.(),Hr&&(ui&&(Vf=Date.now()+150),document.removeEventListener("pointermove",$f),Hr.remove(),Hr=null);let i=ca;if(i){fa?.();for(let d of Zv())d&&i.contains(d)&&Pe.insertBefore(d,i);i.remove(),ca=null,pi=null,Sl=null,da=null}},fC=i=>{xl=i,i.id=kf,i.style.flex="1 1 auto",i.style.minHeight="0"},Uf=i=>{fC(i),(xt!=="rail"||yn)&&mC(),xt!=="rail"?Tk(i):yn?zk(i):uC(i)},Kd=()=>{if(Pl(),MC(),!mt||!Dt)return;let i=If();if(i===xt)return;let d=document.activeElement,f=d instanceof HTMLElement&&(Dt.element.contains(d)||ho?.contains(d)===!0)?d:null;jd(),Dt.element.remove(),Dt.view.setHeaderPlacement("inline"),xt=i,Dt.view.setPresentation(i),Dt.view.setCollapsed(El()),Dt.requestRender(),Dt.element.isConnected||Uf(Dt.element),f?.isConnected?f.focus():Gd(),xn(),eo(),ps()},gC=(i,d)=>ho?.querySelector(d)??i.querySelector(d),Gd=()=>{let i=Dt?.element??xl;if(!i)return;let d=gC(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(d){d.focus();return}let f=gC(i,".persona-history-title")??i;f.tabIndex=-1,f.focus()},Ll=async i=>{if(!ar()||mt)return;let d=go;if(!d)return;if(!yn&&ma()&&Of()){Pl();return}Yd();let f=++wl;Bd=i?.returnSurface??"conversation",Mf=i?.invoker??Nn;let y=ma()&&!yn;y&&(qd+=1,Pl(),$k());let w;try{w=await ub()}catch{Nd(Mt.openHistoryLabel),y&&(qd-=1,f===wl&&(mC(),Pl()));return}if(y&&(qd-=1),f!==wl||mt)return;Wd={scope:Lf()},xt=If(),mt=!0;let k=xt==="panel"&&o.layout?.showHeader!==!1&&$e.style.display!=="none"?"external":"inline",q=o.features?.history?.rowAvatar,te=Ff(),Q=te?{hint:te.hint,aria:te.aria}:null,re={provider:d,context:Wd,targetId:qv(),presentation:xt,collapsible:$d(),collapsed:El(),railSide:pa(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:Ik(),onToggleCollapse:nC,...Q?{collapseShortcut:Q}:{},headerPlacement:k,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:q===!1?!1:typeof q=="string"?q:o.launcher?.iconUrl,activeConversationId:N.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:ce=>jf(ce,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:ce=>mi(ce),attachTooltip:In,onStartNew:()=>Kf({focusComposer:!0}),onClose:()=>to(),onRequestDeleteConversation:ce=>AC(ce),onRequestClearHistory:()=>Yk(),...d.resetDevice?{onRequestResetIdentity:()=>Qk()}:{}};Dt=KE({plugins:u,config:o,getPresentation:()=>xt??"panel",getReturnSurface:()=>Bd,close:()=>to(),createView:({slots:ce,renderDom:he,onModelChange:De,railSections:lt})=>(di=w.createHistoryView({...re,railSections:Hk(lt),slots:ce,renderDom:he,onModelChange:De,onAnnounce:Nd}),di),onElementChanged:(ce,he)=>{if(!he?.isConnected)return Uf(ce);fC(ce),he.replaceWith(ce),Hf()}}),Dt.view.setNewConversationRequired(Dd.recovery==="new_conversation_required"),i?.focus!==!1&&(xt!=="rail"||i?.keyboard===!0)&&Gd(),xn(),eo(),ps(),R.emit("history:opened",{presentation:xt,returnSurface:Bd,timestamp:Date.now()})},Yd=()=>{},to=i=>{if(!mt)return;wl+=1;let d=Bd,f=Mf,y=Dt,w=i?.restoreFocus!==!1;mt=!1;let k=!1,q=null,te=()=>{if(!k){if(k=!0,Yd=()=>{},q!==null&&clearTimeout(q),yn=!1,kl(),jd(),y?.dispose(),y?.view.destroy(),y?.element.remove(),Dt===y&&(Dt=null,di=null,xl=null,xt=null,Wd=null,Mf=null),xn(),eo(),ps(),w){let re=f??Nn;re?.isConnected?re.focus():ii()}R.emit("history:closed",{returnSurface:d,timestamp:Date.now()})}},Q=y&&y.element===y.view.element?y.view.playExit():null;if(!Q){te();return}Yd=te,q=setTimeout(te,vk),Q.then(te)},hC=i=>{if(!(i.key!=="Escape"||!mt||!Dt)){if(xt==="rail"){let d=i.target;if(!(d instanceof Node)||!(Dt.element.contains(d)||yn&&Rr?.contains(d)===!0))return}i.preventDefault(),i.stopPropagation(),to()}};Pe.addEventListener("keydown",hC),_e.push(()=>Pe.removeEventListener("keydown",hC));let Qd=null,yC=!1,Il=()=>{if(!Bn)return;let i=o.layout?.header?.titleSource==="conversation",d=i&&Qd?.trim()||null;Bn.textContent=d??o.launcher?.title??"Chat Assistant";let f=Bn.closest(".persona-combo-btn");if(!f)return;let y=!i||N.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",y?"false":"true"),f.setAttribute("aria-haspopup",y?"true":"false"),y||f.setAttribute("aria-expanded","false"),f.style.cursor=y?"pointer":"default";let w=f.querySelector("svg");w&&(w.style.display=y?"":"none")},Uk=i=>{i!==Qd&&(Qd=i,Il())},mi=i=>{yC=i?.starred===!0,Uk(i&&i.title.trim()||null),Il()};Il(),Pe.addEventListener("persona:title-menu-builtin",i=>{let d=i.detail?.actionId,f=N.getActiveConversationId();f&&(d==="delete"?AC(f):d==="star"&&N.canUpdateConversations()&&Gf(f,{starred:!yC}).catch(()=>{}))});let Xd=0,qk=250,Jd=null,Zd=()=>{Jd&&clearTimeout(Jd),Jd=null};_e.push(Zd);let bC=()=>{Zd();let i=ai;i&&(Cl=!0,i.hidden=!1,We.style.display="none",sa())},ep=()=>{Xd+=1,Zd(),ai&&(ai.remove(),ai=null,Cl=!1,We.style.removeProperty("display"),Ao(Qe,!1),sa())},jk=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;We.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},qf=(i,d)=>F("div",{className:Gt("persona-conversation-loading-bubble",d&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),vC=()=>F("div",{className:"persona-conversation-loading-body"},qf("58%",!1),qf("72%",!0),qf("44%",!1)),CC=i=>{ai?.remove(),ai=i,i.hidden=!Cl,pe.insertBefore(i,We),Zd(),Cl||(Jd=setTimeout(bC,qk)),Ao(Qe,!0)},Kk=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:vC},d=null,f=u.find(y=>y.renderLoadingIndicator);f?.renderLoadingIndicator&&(d=f.renderLoadingIndicator(i)),d===null&&o.loadingIndicator?.render&&(d=o.loadingIndicator.render(i)),CC(F("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Mt.openConversationLoadingLabel}},d??vC()))},Gk=i=>{let d=()=>{jf(i,{focusComposer:!0}).catch(()=>{})},f=ar()?()=>{ep(),Ll()}:void 0,y=(te,Q)=>{let re=F("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:te});return re.addEventListener("click",Q),re},w=()=>F("div",{className:"persona-conversation-loading-error-body"},F("p",{className:"persona-conversation-loading-error-title",text:Mt.openConversationErrorTitle}),F("div",{className:"persona-conversation-loading-error-actions"},y(Mt.openConversationRetryLabel,d),f?y(Mt.openConversationBackLabel,f):null)),k=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Mt.openConversationErrorTitle,retryLabel:Mt.openConversationRetryLabel,backLabel:Mt.openConversationBackLabel}),retry:d,...f?{back:f}:{},defaultRenderer:w}),q=null;for(let te of u)if(te.renderHistoryOpenError){try{q=te.renderHistoryOpenError(k)}catch(Q){console.warn("[persona] renderHistoryOpenError threw",Q),q=null}if(q)break}CC(F("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},q??w())),bC()};R.on("history:closed",()=>{ai&&Ao(Qe,!0)});let jf=async(i,{focusComposer:d=!1}={})=>{let f=la(),y=!!Dt;Dt?.view.setActiveConversationId(i),ep();let w=Xd;Kk(),mt&&(xt==="panel"||yn)&&to({restoreFocus:!1}),Xi=!0;try{await N.openConversation(i,{scope:f})}catch(k){throw w===Xd&&Gk(i),k}finally{Xi=!1}w===Xd&&(ep(),mn.clear(),$o(),Zn(),rf()||Ad(),jk(),Wr(),y||mi(null),R.emit("history:conversationOpened",{conversationId:i,title:Qd,scope:f,timestamp:Date.now()}),d&&ii())},Kf=async({focusComposer:i=!1}={})=>{ep(),await N.startNewConversation({scope:la()}),mi(null),mn.clear(),$o(),Zn(),Ad(),Wr();let d=N.getActiveConversationId();Dt?.view.setActiveConversationId(d),R.emit("history:conversationStarted",{conversationId:d,timestamp:Date.now()}),mt&&(xt==="panel"||yn)&&to({restoreFocus:!1}),i&&ii()},Gf=async(i,d)=>{let f=await N.updateConversation(i,{...d,...d.title!==void 0?{title:d.title.trim()}:{}});return Dt?.view.applyConversationSummary(f),!Dt&&i===N.getActiveConversationId()&&mi(f),f},wC=async i=>{let d=la(),f=N.getActiveConversationId()===i;await N.deleteConversation(i,{scope:d}),Dt?.view.removeConversationSummary(i),f&&(mi(null),mn.clear(),$o(),Zn(),Wr()),R.emit("history:conversationDeleted",{conversationId:i,scope:d,wasActive:f,timestamp:Date.now()})},xC=async i=>{let d=i?.scope??la(),f=i?.allTargets?null:i?.targetId??qv(),y=await N.clearConversationHistory({...f?{targetId:f}:{},scope:d});return mi(null),mn.clear(),$o(),Zn(),Wr(),R.emit("history:cleared",{deleted:y.deleted,scope:d,targetId:f,timestamp:Date.now()}),y},SC=async()=>{if(!go?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await N.resetHistoryDevice()).remoteRevocationConfirmed}finally{mi(null),N.clearArtifacts(),mn.clear(),Cf=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),L={},se.syncFromMetadata(),x?.clear&&wd(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),$o(),Zn(),Wr(),to({restoreFocus:!1}),ii(),Ae||sn?.launcher.element.focus()}return Nd(i?Mt.identityResetNotice:Mt.identityResetUnconfirmedNotice),R.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},Yf=()=>nr?Se:Pe,AC=async i=>await Mm({host:Yf(),title:Mt.deleteConversationConfirmTitle,description:Mt.deleteConversationConfirm,confirmLabel:Mt.deleteConversationConfirmLabel,cancelLabel:Mt.confirmCancelLabel})?(await wC(i),"deleted"):"cancelled",Yk=async()=>{let i=la()==="verified-user";return await Mm({host:Yf(),title:Mt.clearHistoryConfirmTitle,description:i?Mt.clearHistoryVerifiedConfirm:Mt.clearHistoryConfirm,confirmLabel:Mt.clearHistoryConfirmLabel,cancelLabel:Mt.confirmCancelLabel})?(await xC(),"cleared"):"cancelled"},Qk=async()=>{if(!await Mm({host:Yf(),title:Mt.resetIdentityConfirmTitle,description:Mt.resetIdentityConfirm,confirmLabel:Mt.resetIdentityConfirmLabel,cancelLabel:Mt.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:d}=await SC();return{outcome:"reset",remoteRevocationConfirmed:d}},To=v("button","persona-history-earlier");To.type="button",To.textContent=Mt.showEarlierMessagesLabel,To.setAttribute("data-persona-history-earlier",""),Object.assign(To.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let Wr=()=>{if(!(ar()&&!!Dd.nextMessageCursor&&!!N.getActiveConversationId())){To.remove();return}To.textContent=Mt.showEarlierMessagesLabel,To.parentNode!==pe&&pe.insertBefore(To,pe.firstChild)};To.addEventListener("click",()=>{let i=N.getActiveConversationId(),d=Dd.nextMessageCursor;if(!i||!d||To.disabled)return;To.disabled=!0;let f=pe.scrollHeight,y=pe.scrollTop;N.loadOlderMessages(i,d,{scope:la()}).then(()=>{pe.scrollTop=y+(pe.scrollHeight-f),eo()}).catch(()=>{}).finally(()=>{To.disabled=!1,Wr()})});let Xk=()=>{let i=ki({ariaLabel:Mt.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return i.button.addEventListener("click",d=>{if(!(!ar()||Uv())){if(mt){to();return}Ll({invoker:i.button,keyboard:d.detail===0})}}),i},MC=()=>{if(!ar()){ir?.remove(),Nn=null,ir=null;return}if(ir&&!ir.isConnected&&(Nn=null,ir=null),!Nn&&$e){let y=Xk();Nn=y.button,ir=y.wrapper;let w=ot.clearChatButtonWrapper||ot.closeButtonWrapper;w?.parentNode&&$e.contains(w)?w.parentNode.insertBefore(ir,w):$e.appendChild(ir)}if(!Nn||!ir)return;let i=ma()||mt&&xt==="rail";if(ir.style.display=i?"none":"",i){document.activeElement===Nn&&Gd();return}let d=Uv();Nn.disabled=d,Nn.setAttribute("aria-disabled",d?"true":"false");let f=d?Mt.openHistoryBusyLabel:Mt.openHistoryLabel;Nn.setAttribute("aria-label",f),(o.features?.history?.presentation??"panel")==="panel"?(Nn.removeAttribute("aria-expanded"),Nn.removeAttribute("aria-controls")):(Nn.setAttribute("aria-expanded",mt?"true":"false"),Nn.setAttribute("aria-controls",kf))},tp=!1,Jk=()=>{let i=ot.clearChatButton;if(i){if(ar()){tp||(Ef=i.getAttribute("aria-label")??"",tp=!0),i.setAttribute("aria-label",Mt.newConversationLabel),i.removeAttribute("title");return}tp&&(tp=!1,Ef&&i.setAttribute("aria-label",Ef))}},ps=()=>{Mt=nb(o.features?.history?.copy),MC(),Pl(),Jk(),Wr()};pn=ps,_t=i=>{Dd=i,Dt?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),vl(i.sendBlocked||uo),Wr()},Vt=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(mn.clear(),$o(),Zn()),Nd(i.message),Dt?.view.refresh()},Yv(),ps(),_e.push(()=>{Od?.(),_d?.(),wl+=1,Yd(),Dt?.dispose(),Dt?.view.destroy(),Dt=null}),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&N.initClientSession().then(()=>{if(ar())return N.reconcileBootConversation({scope:Lf()})}).then(()=>{Wr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)});let Qf=()=>N.warmClientSession(),TC=i=>{let d=o.sessionInit??"input",f=Et?.input??we,y=i.target;f&&(i.type==="input"?(d==="input"||d==="focus")&&y===f&&i.inputType&&f.value.trim():d==="focus"&&(i.type==="keyup"?y===f&&i.key==="Tab":(Et?.form??Tn)?.contains(y)))&&Qf()},EC=["input","pointerdown","keyup"];EC.forEach(i=>t.addEventListener(i,TC));let kC,Xf,PC=()=>{let i=Xf;Xf=void 0;try{typeof i=="function"&&i()}catch{}},LC=()=>{let i=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(i!==kC){PC(),kC=i;try{Xf=i?.({warm:Qf,mount:t})}catch{}}};LC(),_e.push(()=>{EC.forEach(i=>t.removeEventListener(i,TC)),PC()}),(ie||o.onSSEEvent)&&N.setSSEEventCallback((i,d)=>{o.onSSEEvent?.(i,d),qe(i,d)});let IC=()=>{let i=o.resume??(P?Lr.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&N.resumeFromHandle(i)};G?G.then(i=>{if(i){if(i.metadata&&(L=yb(i.metadata),se.syncFromMetadata()),i.messages?.length){Xi=!0;try{N.hydrateMessages(i.messages)}finally{Xi=!1}kd()}i.artifacts?.length&&N.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),xv(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{uf=!0,V(),IC()}):(xv(ee),IC());let Zk=()=>{!xe()||Ae||!(o.launcher?.composerBar?.expandOnSubmit??!0)||qt(!0,"auto")},eP=(i,d)=>i?d?{refs:[...i.refs,...d.refs],finalize:async()=>{let[f,y]=await Promise.allSettled([i.finalize(),d.finalize()]),w=[];return f.status==="fulfilled"?w.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),y.status==="fulfilled"?w.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),lD(w)}}:i:d,Jf=()=>{let d=we.getInlineMessageFields?.();return d&&d.contentSegments.some(y=>y.kind==="mention")?d.contentSegments:void 0},Br=!1,fi=null,np=()=>{we.value="",we.style.height="auto",Zo(),Hl()},Zf="data-persona-composer-notice",ga=null;function tP(i){nd(i),!(xe()||!pt)&&(pt.hasAttribute(Za)||(pt.setAttribute(Zf,""),pt.setAttribute("role","status"),pt.setAttribute("aria-live","polite"),pt.textContent=i,xi(pt,o.statusIndicator??{},"idle"),ga&&clearTimeout(ga),ga=setTimeout(()=>{if(ga=null,!!pt?.hasAttribute(Zf)&&(pt.removeAttribute(Zf),pt.removeAttribute("role"),pt.removeAttribute("aria-live"),h)){let d=N.getStatus();Qo(pt,_s(d),o.statusIndicator??{},d)}},4e3)))}function nP(){let i=ze.getState().pendingSubmission;i&&(Ui(void 0),we&&(we.value=i.text,we.dispatchEvent(new Event("input",{bubbles:!0})),Zo()),i.options.selectedModelId&&(ze.setSelectedModelId(i.options.selectedModelId),Zr?.repaint()),i.options.activeModeIds?.length&&id(i.options.activeModeIds),i.options.quote&&er(i.options.quote),we?.focus())}let oP=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},RC=(i={})=>{let d=(i.overrideText??we?.value??"").trim();return i.resolveInlineCommand&&d?(un?.takeInlineCommand(d)??Promise.resolve(null)).then(f=>HC(i,d,f)):HC(i,d,null)},HC=(i,d,f)=>{if(f?.kind==="action"){np(),un?.clear(),zs();return}let y=f?.kind==="server"?f.mentions:null,w=f?.kind==="prompt"?f.sendText:d,k=i.pending?.contentParts,q=(Lt?.hasAttachments()??!1)||(k?.length??0)>0;if(!eA({text:w,hasAttachments:q,attachmentsReady:Lt?.isReady()??!0,hasMentions:un?.hasMentions()??!1,hasServerMentions:!!y,inputDisabled:sr(),sendDisabled:si()}))return;let te=N.isStreaming()?Dm():"block";if(te==="defer-one"&&!i.pending){if(ze.getState().pendingSubmission){tP("One message is already queued. Edit or remove it first.");return}rP({intent:i,sendText:w,serverMentions:y});return}let Q={text:w,mentionRefs:[...un?.getMentionRefs()??[],...y?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:Jf(),options:{...ze.getState().selectedModelId&&{selectedModelId:ze.getState().selectedModelId},...ze.getState().activeModeIds.length>0&&{activeModeIds:[...ze.getState().activeModeIds]},...ze.getState().quote&&{quote:{...ze.getState().quote}}},viaVoice:i.viaVoice};i.pending&&(Q.options={...i.pending.options},Q.contentSegments=i.pending.contentSegments,Q.mentionRefs=[...i.pending.mentionRefs],Q.viaVoice=i.pending.viaVoice);let re=()=>{if(k?.length)return[...k];if(!Lt?.hasAttachments())return;let kt=[...Lt.getContentParts()];return Q.text&&kt.push(fr(Q.text)),kt};Q.contentParts=re();let ce=()=>{Zs(),Zk();let kt=un?.collectForSubmit()??null,no=eP(kt,y),Jt=re();i.consumeDraft!==!1&&np();let rn={selectedModelId:Q.options.selectedModelId,activeModeIds:Q.options.activeModeIds},Vn=te==="interrupt";Vn&&N.cancel(),N.sendMessage(Q.text,{contentParts:Jt,mentions:no??void 0,contentSegments:Q.contentSegments,viaVoice:Q.viaVoice,composerOptions:rn,...Q.options.quote&&{quote:Q.options.quote},...Vn&&{interrupt:!0}}),Lt?.hasAttachments()&&Lt.clearAttachments(),kt&&un?.clear(),zs();let ln=ze.getState().activeModeIds,$t=FS(ln,o.composer?.modes);$t.length!==ln.length&&id($t),ze.getState().quote&&er(void 0),Sd(),Vm.release(),_o()},he=o.composer?.onBeforeSend;if(!he){ce();return}let De=new AbortController;fi=De;let lt=kt=>{if(fi=null,kt.status==="error"){oP(kt.error);return}kt.status==="proceed"&&ce()},It=tA(he,Q,De.signal);if(!(It instanceof Promise)){lt(It);return}return ze.setPreparing(!0),It.then(lt).finally(()=>ze.setPreparing(!1))};function rP(i){let d=ze.getState(),f=Lt?.hasAttachments()??!1,y=f?[...Lt.getContentParts()]:[];f&&i.sendText&&y.push(fr(i.sendText));let w=wh({text:i.sendText,contentParts:y.length?y:void 0,mentionRefs:[...un?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:Jf(),options:{...d.selectedModelId&&{selectedModelId:d.selectedModelId},...d.activeModeIds.length>0&&{activeModeIds:[...d.activeModeIds]},...d.quote&&{quote:{...d.quote}}},viaVoice:i.intent.viaVoice});Ui(w),i.intent.consumeDraft!==!1&&np(),f&&Lt.clearAttachments(),un?.clear(),zs(),d.quote&&er(void 0),Sd(),Vm.release(),_o(),nd("Message queued. It sends when the response finishes.")}function sP(){let i=ze.getState().pendingSubmission;i&&(Ui(void 0),rp(i.text,{consumeDraft:!1,pending:i}))}function iP(i){if(o.messageActions?.showEdit!==!0)return;let d=N.getMessages().find(f=>f.id===i);!d||!Yg(d)||Js!==i&&(Zs(),Js=i,os=qS({messageId:i,initialText:d.content,onSave:f=>aP(i,f),onCancel:()=>Zs()}),mn.delete(i),xo(We,N.getMessages(),j),os.focus())}function aP(i,d){let f=os;if(Js=null,os=null,f?.destroy(),mn.delete(i),!N.resubmitFrom(i,{reason:"edit",replacement:{text:d,mentionRefs:[],options:{}}})){xo(We,N.getMessages(),j);return}eo()}function lP(i){if(N.isStreaming())return;let d=Gg(N.getMessages(),i);d&&(Zs(),N.resubmitFrom(d,{reason:"retry"})&&eo())}ad={regenerate:lP,edit:iP,quote:i=>{let f=N.getMessages().find(y=>y.id===i)?.content?.trim();f&&(er({text:f,messageId:i}),we?.focus())}};let Rl=async i=>{if(!Br){Br=!0;try{await RC({resolveInlineCommand:!0,...i})}finally{Br=!1}}};function op(i){si()||(np(),rp(i,{consumeDraft:!1}))}let rp=(i,d)=>{if(Br)return;Br=!0;let f=()=>{Br=!1};try{let y=RC({...d,overrideText:i});y instanceof Promise?y.finally(f):f()}catch(y){throw f(),y}},cP=i=>{if(i.preventDefault(),N.isStreaming()){N.cancel(),Rt?.reset(),Re?.update();return}Br||Rl()},dP=()=>o.features?.composerHistory!==!1,eg={...$h},tg=!1,Hl=()=>{eg={...$h}},pP=()=>N.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),uP=i=>{if(!we)return;tg=!0,we.value=i,we.dispatchEvent(new Event("input",{bubbles:!0})),tg=!1;let d=we.value.length;we.setSelectionRange(d,d)},mP=i=>{tg||(i.isComposing||un?.handleInput(i.inputType??void 0),Hl())},fP=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:rc(we)}),gP=i=>{if(we&&!sr()&&!(!i.isComposing&&un?.handleKeydown(i))){if(dP()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let d=we.selectionStart===0&&we.selectionEnd===0,f=QA({direction:i.key==="ArrowUp"?"up":"down",history:pP(),currentValue:we.value,atStart:d,state:eg});if(eg=f.state,f.handled){i.preventDefault(),f.value!==void 0&&uP(f.value);return}}if(wS(i,fP())){if(N.isStreaming()){if(i.preventDefault(),Dm()==="block"||Br||si())return;Hl(),Rl();return}if(Br){i.preventDefault();return}if(si()){i.preventDefault();return}Hl(),i.preventDefault(),Ve.click()}}},WC=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(Pe)){if(fi){fi.abort(),fi=null,i.preventDefault(),i.stopImmediatePropagation();return}N.isStreaming()&&(N.cancel(),Rt?.reset(),Re?.update(),Hl(),i.preventDefault(),i.stopImmediatePropagation())}},hP=async i=>{if(o.attachments?.enabled!==!0||!Lt||sr())return;let d=rD(i.clipboardData);d.length!==0&&(i.preventDefault(),await Lt.handleFiles(d))},Eo=null,lr=!1,ha=null,tn=null,ng=()=>o.voiceRecognition?.completionBehavior==="review";function gi(i){ye?.setAttribute("data-state",i),i==="recording"?bP():ig()}let BC="--persona-voice-level",og=.5,ya=null,rg=-1,sp=0,DC=()=>{let i=[],d=co??ye?.parentElement??null;return d&&i.push(d),Qe&&i.push(Qe),i},sg=i=>{let d=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(d!==rg){rg=d;for(let f of DC())f.style.setProperty(BC,String(d))}},yP=()=>{rg=-1,sp=0;for(let i of DC())i.style.removeProperty(BC)};function bP(){if(ya!==null)return;if(typeof requestAnimationFrame!="function"){sg(h?N.getVoiceLevel()??og:og);return}let i=()=>{ya=requestAnimationFrame(i);let d=h?N.getVoiceLevel():null;if(d===null){sg(og);return}sp+=(d-sp)*.3,sg(sp)};ya=requestAnimationFrame(i)}function ig(){ya!==null&&(cancelAnimationFrame(ya),ya=null),yP()}let OC=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ip=(i="user")=>{if(lr||N.isStreaming())return;let d=OC();if(!d)return;Eo=new d;let f=o.voiceRecognition??{},y=f.pauseDuration??2e3;Eo.continuous=f.provider?.browser?.continuous??!0,Eo.interimResults=!0,Eo.lang=f.provider?.browser?.language??"en-US";let w=we.value;Eo.onresult=k=>{let q="",te="";for(let re=0;re<k.results.length;re++){let ce=k.results[re],he=ce[0].transcript;ce.isFinal?q+=he+" ":te=he}let Q=w+q+te;we.value=Q,Zo(),ha&&clearTimeout(ha),(q||te)&&(ha=window.setTimeout(()=>{if(we.value.trim()&&Eo&&lr){if(us(),ng())return;Rl({viaVoice:!0})}},y))},Eo.onerror=k=>{k.error!=="no-speech"&&us()},Eo.onend=()=>{if(lr){let k=we.value.trim();!ng()&&k&&k!==w.trim()&&Rl({viaVoice:!0}),us()}};try{if(Eo.start(),lr=!0,wt.active=!0,i!=="system"&&(wt.manuallyDeactivated=!1),kr(i),Vo(),_o(),ye){let k=o.voiceRecognition??{};tn={backgroundColor:ye.style.backgroundColor,color:ye.style.color,borderColor:ye.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??"")||Un};let q=k.recordingBackgroundColor,te=k.recordingIconColor,Q=k.recordingBorderColor;if(ye.classList.add("persona-voice-recording"),gi("recording"),ye.style.backgroundColor=q??"var(--persona-voice-recording-bg, #ef4444)",ye.style.color=te??"var(--persona-voice-recording-indicator, #ffffff)",te){let re=ye.querySelector("svg");re&&re.setAttribute("stroke",te)}Q&&(ye.style.borderColor=Q),ye.setAttribute("aria-label","Stop voice recognition")}}catch{us("system")}},us=(i="user")=>{if(lr){if(lr=!1,ha&&(clearTimeout(ha),ha=null),Eo){try{Eo.stop()}catch{}Eo=null}if(wt.active=!1,kr(i),Vo(),_o(),ye){if(ye.classList.remove("persona-voice-recording"),gi("idle"),tn){ye.style.backgroundColor=tn.backgroundColor,ye.style.color=tn.color,ye.style.borderColor=tn.borderColor;let d=ye.querySelector("svg");d&&d.setAttribute("stroke",tn.color||"currentColor"),tn=null}ye.setAttribute("aria-label","Start voice recognition")}}},ag=()=>{if(!ye||tn)return;let i=o.voiceRecognition??{};tn={backgroundColor:ye.style.backgroundColor,color:ye.style.color,borderColor:ye.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||Un}},lg=(i,d)=>{if(!ye)return;let f=ye.querySelector("svg");f&&f.remove();let y=tn?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||Un),w=ke(i,y,d,1.5);w&&ye.appendChild(w)},ap=()=>{ye&&ye.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ba=()=>{if(!ye)return;ag();let i=o.voiceRecognition??{},d=i.recordingBackgroundColor,f=i.recordingIconColor,y=i.recordingBorderColor;if(ap(),ye.classList.add("persona-voice-recording"),gi("recording"),ye.style.backgroundColor=d??"var(--persona-voice-recording-bg, #ef4444)",ye.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let w=ye.querySelector("svg");w&&w.setAttribute("stroke",f)}y&&(ye.style.borderColor=y),ye.setAttribute("aria-label","Stop voice recognition")},vP=()=>{if(!ye)return;ag();let i=o.voiceRecognition??{},d=N.getVoiceInterruptionMode(),f=i.processingIconName??"loader",y=i.processingIconColor??tn?.color??"",w=i.processingBackgroundColor??tn?.backgroundColor??"",k=i.processingBorderColor??tn?.borderColor??"";ap(),ye.classList.add("persona-voice-processing"),gi("processing"),ye.style.backgroundColor=w,ye.style.borderColor=k;let q=y||"currentColor";ye.style.color=q,lg(f,q),ye.setAttribute("aria-label","Processing voice input"),d==="none"&&(ye.style.cursor="default")},CP=()=>{if(!ye)return;ag();let i=o.voiceRecognition??{},d=N.getVoiceInterruptionMode(),f=d==="cancel"?"square":d==="barge-in"?"mic":"volume-2",y=i.speakingIconName??f,w=i.speakingIconColor??(d==="barge-in"?i.recordingIconColor??tn?.color??"":tn?.color??""),k=i.speakingBackgroundColor??(d==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":tn?.backgroundColor??""),q=i.speakingBorderColor??(d==="barge-in"?i.recordingBorderColor??"":tn?.borderColor??"");ap(),ye.classList.add("persona-voice-speaking"),gi("speaking"),ye.style.backgroundColor=k,ye.style.borderColor=q;let te=w||"currentColor";ye.style.color=te,lg(y,te);let Q=d==="cancel"?"Stop playback and re-record":d==="barge-in"?"Speak to interrupt":"Agent is speaking";ye.setAttribute("aria-label",Q),d==="none"&&(ye.style.cursor="default"),d==="barge-in"&&ye.classList.add("persona-voice-recording")},Dr=()=>{ye&&(ap(),gi("idle"),tn&&(ye.style.backgroundColor=tn.backgroundColor??"",ye.style.color=tn.color??"",ye.style.borderColor=tn.borderColor??"",lg(tn.iconName,tn.color||"currentColor"),tn=null),ye.style.cursor="",ye.setAttribute("aria-label","Start voice recognition"))},cg=()=>{if(!sr()){if(so(o.voiceRecognition?.provider)){let i=N.getVoiceStatus(),d=N.getVoiceInterruptionMode();if(d==="none"&&(i==="processing"||i==="speaking"))return;if(d==="cancel"&&(i==="processing"||i==="speaking")){N.stopVoicePlayback();return}if(N.isBargeInActive()){N.stopVoicePlayback(),N.deactivateBargeIn().then(()=>{wt.active=!1,wt.manuallyDeactivated=!0,Vo(),kr("user"),Dr()});return}N.toggleVoice().then(()=>{wt.active=N.isVoiceActive(),wt.manuallyDeactivated=!N.isVoiceActive(),Vo(),kr("user"),N.isVoiceActive()?ba():Dr()});return}if(lr){let i=we.value.trim();wt.manuallyDeactivated=!0,Vo(),us("user"),i&&!ng()&&Rl()}else wt.manuallyDeactivated=!1,Vo(),ip("user")}};Om=cg,ye&&_e.push(()=>{so(o.voiceRecognition?.provider)?(N.isVoiceActive()&&N.toggleVoice(),Dr()):us("system")});let wP=R.on("assistant:complete",()=>{ze.getState().pendingSubmission&&setTimeout(()=>{N.isStreaming()||sP()},0)});_e.push(wP);let xP=R.on("assistant:complete",()=>{vv&&(wt.active||wt.manuallyDeactivated||vv==="assistant"&&!wt.lastUserMessageWasVoice||setTimeout(()=>{!wt.active&&!wt.manuallyDeactivated&&(so(o.voiceRecognition?.provider)?N.toggleVoice().then(()=>{wt.active=N.isVoiceActive(),kr("auto"),N.isVoiceActive()&&ba()}):ip("auto"))},600))});_e.push(xP);let SP=R.on("action:resubmit",()=>{setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)});_e.push(SP);let _C=()=>{qt(!Ae,"user")},sn=null,Fn=null;if(_&&!xe()){let{instance:i,element:d}=gy({config:o,plugins:u,onToggle:_C});sn=i,i||(Fn=d)}sn?t.appendChild(sn.element):Fn&&t.appendChild(Fn),bl(),Qs(),Id(),yf(),vl(N.isStreaming()),rf()||(po()==="follow"?as(!0):Ad()),$0(),He&&(!_||xe()?setTimeout(()=>ii(),0):Ae&&setTimeout(()=>ii(),200));let ms=null,NC=()=>{ms&&(ms.disconnect(),ms.observe(Qe),ms.observe(Pe),ms.observe(gn))},FC=sl(),Wl=()=>{if(xe()){$s(),bl();return}let i=nn(o),d=o.launcher?.sidebarMode??!1,f=t.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640,k=f.innerWidth<=w,q=y&&k&&_;try{if(q){Us(),cl=gd();return}let te=!1;bt&&(bt=!1,Us(),te=!0);let Q=gd();if(!te&&Q!==cl&&(Us(),te=!0),cl=Q,te&&pd(),!_&&!i){Se.style.height="",Se.style.width="";return}if(!d&&!i){let re=Ri(o);Se.style.width=re.width,Se.style.maxWidth=re.maxWidth}fd(),ov()}finally{$s(),sd();let te=sl();if(te!==FC&&(FC=te,sa(),Qs()),bl(),Ae&&_){let re=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ce=o.launcher?.sidebarMode??!1,he=o.launcher?.mobileFullscreen??!0,De=nn(o)&&he&&re,lt=ce||he&&re&&_||De;if(lt&&!rr){let It=t.getRootNode(),kt=It instanceof ShadowRoot?It.host:t.closest(".persona-host");kt&&!or&&(or=Qh(kt,o.launcher?.zIndex??On)),rr=Xh(t.ownerDocument)}else lt||(or?.(),or=null,rr?.(),rr=null)}}};Wl();let lp=t.ownerDocument.defaultView??window;if(lp.addEventListener("resize",Wl),_e.push(()=>lp.removeEventListener("resize",Wl)),typeof ResizeObserver<"u"){ms=new ResizeObserver(()=>{sd()}),NC(),_e.push(()=>{ms?.disconnect(),ms=null});let i=new ResizeObserver(()=>{Kd()});i.observe(Pe),_e.push(()=>i.disconnect())}lp.addEventListener("resize",Kd),_e.push(()=>lp.removeEventListener("resize",Kd)),fo=pe.scrollTop;let VC=br(pe),$C=()=>{nv();let i=pe.scrollTop,d=br(pe),f=d<VC;if(VC=d,!Jr()){fo=i,xn();return}let{action:y,nextLastScrollTop:w}=zu({following:mo.isFollowing(),currentScrollTop:i,lastScrollTop:fo,nearBottom:jr(pe,Tr),userScrollThreshold:_0,isAutoScrolling:Jn||yd||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(fo=w,y==="resume"){Md()||Zn();return}y==="pause"&&na()};if(pe.addEventListener("scroll",$C,{passive:!0}),_e.push(()=>pe.removeEventListener("scroll",$C)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Y0(),Rg(We)});i.observe(We),i.observe(pe),_e.push(()=>i.disconnect())}let zC=()=>{Jr()&&mo.isFollowing()&&Md()&&na()},UC=pe.ownerDocument;UC.addEventListener("selectionchange",zC),_e.push(()=>{UC.removeEventListener("selectionchange",zC)});let AP=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),qC=i=>{AP.has(i.key)&&(is(),Mb()&&Jr()&&mo.isFollowing()&&na())},jC=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(is(),Mb()&&Jr()&&mo.isFollowing()&&na())};pe.addEventListener("keydown",qC),pe.addEventListener("focusin",jC),_e.push(()=>{pe.removeEventListener("keydown",qC),pe.removeEventListener("focusin",jC)});let KC=i=>{if(i.deltaY!==0&&is(),!Jr())return;let d=Uu({following:mo.isFollowing(),deltaY:i.deltaY,nearBottom:jr(pe,Tr),resumeWhenNearBottom:!0});d==="pause"?na():d==="resume"&&!Md()&&Zn()};pe.addEventListener("wheel",KC,{passive:!0}),pe.addEventListener("touchmove",is,{passive:!0}),pe.addEventListener("pointerdown",is,{passive:!0}),_e.push(()=>{pe.removeEventListener("touchmove",is),pe.removeEventListener("pointerdown",is)}),_e.push(()=>pe.removeEventListener("wheel",KC)),hn.addEventListener("click",()=>{$o(),pe.scrollTop=pe.scrollHeight,fo=pe.scrollTop,Zn(),as(!0),xn()}),_e.push(()=>hn.remove()),_e.push(()=>{Av(),$o()});let GC=()=>{Ce&&(Gs&&(Ce.removeEventListener("click",Gs),Gs=null),Ne()?(Ce.style.display="",Gs=()=>{qt(!1,"user")},Ce.addEventListener("click",Gs)):Ce.style.display="none")};GC(),(()=>{let{clearChatButton:i}=ot;i&&i.addEventListener("click",()=>{if(ar()){Kf({focusComposer:!0}).catch(f=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}N.clearMessages(),o.layout?.topFade&&(pe.scrollTop=0),pe.removeAttribute("data-persona-top-fade"),mn.clear(),Zn(),La(ot.composerOverlay);try{localStorage.removeItem(Ja),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ja}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ja)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let d=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(d),x?.clear&&wd(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),L={},se.syncFromMetadata(),Lt?.clearAttachments(),Sd(),Ui(void 0),er(void 0),Zs(),ct?.clear(),Rt?.reset(),Re?.update()})})();let YC=[["keydown",gP],["input",mP],["input",Zo],["input",zs],["keyup",zs],["paste",hP],["focus",E0]],QC=i=>{if(i)for(let[d,f]of YC)Et?.addListener(i,d,f)},MP=i=>{if(i)for(let[d,f]of YC)Et?.removeListener(i,d,f)},XC=()=>{Et&&(Et.addListener(Et.form,"submit",cP),Et.addListener(Et.footer,"click",zs),QC(we),ye&&Et.addListener(ye,"click",cg))};XC();let JC=()=>{un?.onComposerSwap((i,d)=>{MP(d),we=i,Et&&(Et.input=i),QC(i),Nm(),df(),Zo()})};JC();let dg=!1;function ZC(){if(!dg){dg=!0;try{let i=we?.value??"",d=Qe.ownerDocument??document,f=we?d.activeElement===we:!1;ig(),Et?.destroy(),Et=null,un?.destroy(),un=null;let y=null,w=()=>(y=xe()?Ju({config:o}):Ic({config:o}),y.footer),k=Bb(w)??w();Cn.replaceComposer(k),Qe=Cn.composer.footer;let q=y!==null&&k===y.footer;ji=!q,Ab=q?y.setSendButtonMode:()=>{},Wb(Qe),Ob(Qe),_b(),Nb(),Fb(),JC(),Vb(),Fm(),$b(),XC();let te=Ks.indexOf(Mr);if(Mr.destroy(),Mr=kc(lo),te>=0&&(Ks[te]=Mr),we&&(we.value=i),Zo(),zs(),Id(),Qs(),vl(N.isStreaming()),o.statusIndicator?.mode==="transient"&&!xe()){let Q=N.getStatus();Qo(pt,_s(Q),o.statusIndicator,Q)}wt.active&&gi("recording"),Us(),NC(),$s(),_o(),Pd(),f&&we?.focus()}finally{dg=!1}}}let Bl=t.ownerDocument??document;Bl.addEventListener("keydown",WC,!0);let ew=()=>{ef()},tw=()=>{Bl.visibilityState==="hidden"&&ef()};typeof window<"u"&&(window.addEventListener("pagehide",ew),Bl.addEventListener("visibilitychange",tw),_e.push(()=>{window.removeEventListener("pagehide",ew),Bl.removeEventListener("visibilitychange",tw)}));let nw="persona-attachment-drop-active",Dl=0,pg=()=>{Dl=0,Pe.classList.remove(nw)},va=()=>o.attachments?.enabled===!0&&Lt!==null&&!sr(),ow=i=>{!Tm(i.dataTransfer)||!va()||(Dl++,Dl===1&&Pe.classList.add(nw))},rw=i=>{!Tm(i.dataTransfer)||!va()||(Dl--,Dl<=0&&pg())},sw=i=>{!Tm(i.dataTransfer)||!va()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},iw=i=>{if(!Tm(i.dataTransfer)||!va())return;i.preventDefault(),i.stopPropagation(),pg();let d=Array.from(i.dataTransfer.files??[]);d.length!==0&&Lt.handleFiles(d)},fs=!0;Pe.addEventListener("dragenter",ow,fs),Pe.addEventListener("dragleave",rw,fs),t.addEventListener("dragover",sw,fs),t.addEventListener("drop",iw,fs);let cp=t.ownerDocument,aw=i=>{va()&&i.preventDefault()},lw=i=>{va()&&i.preventDefault()};cp.addEventListener("dragover",aw),cp.addEventListener("drop",lw),_e.push(()=>{Et?.destroy(),Et=null,ig(),tr?.destroy(),tr=null,Sr?.destroy(),Sr=null,es?.destroy(),es=null,ts?.destroy(),ts=null,Zr=null,Bm=null,ef(),ml.destroy(),ga&&clearTimeout(ga),Zs(),fi?.abort(),fi=null,Lt?.destroy(),Lt=null,ze.destroy(),Bl.removeEventListener("keydown",WC,!0),un?.destroy()}),_e.push(()=>{Pe.removeEventListener("dragenter",ow,fs),Pe.removeEventListener("dragleave",rw,fs),t.removeEventListener("dragover",sw,fs),t.removeEventListener("drop",iw,fs),cp.removeEventListener("dragover",aw),cp.removeEventListener("drop",lw),pg()}),_e.push(()=>{N.cancel()}),sn?_e.push(()=>{sn?.destroy()}):Fn&&_e.push(()=>{Fn?.remove()});let an={update(i){let d=o.future?.v5Defaults===!0,f=o.toolCall,y=o.messageActions,w=o.layout?.messages,k=o.colorScheme,q=o.loadingIndicator,te=o.iterationDisplay,Q=o.features?.showReasoning,re=o.features?.showToolCalls,ce=o.features?.toolCallDisplay,he=o.features?.reasoningDisplay,De=o.features?.streamAnimation?.type,lt=o.features?.history?.enabled===!0,It=o.features?.history?.provider,kt=o.getIdentityProof,no=o.clientToken,Jt=o.contextMentions;o=xE({...o,features:p},i),p=o.features,o=Yy(o),c(),Km(),gc(t,o),Uc(t,o),qc(t,o),ft(),Fo(),o.colorScheme!==k&&rv();let rn=Jy.getForInstance(o.plugins);u.length=0,u.push(...rn),oC(),_=o.launcher?.enabled??!0,Te=o.launcher?.autoExpand??!1,J=o.features?.showReasoning??!0,Y=o.features?.showToolCalls??!0,Me=o.features?.scrollToBottom??{};let Vn=po();Ee=o.features?.scrollBehavior??{},Vn!==po()&&($o(),Zn()),bv(),kb(),xn();let ln=ie;if(ie=o.features?.showEventStreamToggle??!1,ie&&!ln){if(ct||(Tt(),N.setSSEEventCallback((ue,ht)=>{o.onSSEEvent?.(ue,ht),qe(ue,ht)})),!Ht&&$e){let ue=o.features?.eventStream?.classNames,ht="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ue?.toggleButton?" "+ue.toggleButton:"");Ht=v("button",ht),Ht.style.width="28px",Ht.style.height="28px",Ht.style.color=qn.actionIconColor,Ht.type="button",Ht.setAttribute("aria-label","Event Stream"),Ht.title="Event Stream";let yt=Ge(Xr.Activity,"18px","currentColor",1.5);yt&&Ht.appendChild(yt);let Pt=ot.clearChatButtonWrapper,Yt=ot.closeButtonWrapper,Dn=Pt||Yt;Dn&&Dn.parentNode===$e?$e.insertBefore(Ht,Dn):$e.appendChild(Ht),Ht.addEventListener("click",()=>{nt?qi():_m()})}}else!ie&&ln&&(qi(),Ht&&(Ht.remove(),Ht=null),ct?.clear(),rt?.destroy(),ct=null,rt=null,Rt?.reset(),Rt=null,Z=null);if(o.launcher?.enabled===!1&&sn&&(sn.destroy(),sn=null),o.launcher?.enabled===!1&&Fn&&(Fn.remove(),Fn=null),o.launcher?.enabled!==!1&&!sn&&!Fn){let{instance:ue,element:ht}=gy({config:o,plugins:u,onToggle:_C});sn=ue,ue||(Fn=ht),t.appendChild(ht)}sn&&sn.update(o),Il(),Yn&&o.launcher?.subtitle!==void 0&&(Yn.textContent=o.launcher.subtitle);let $t=o.layout?.header;if($t?.layout!==Wt&&$e){let ue=$t?Qu(o,$t,{showClose:Ne(),onClose:()=>qt(!1,"user")}):Pi({config:o,showClose:Ne(),onClose:()=>qt(!1,"user")});Cn.replaceHeader(ue),$e=Cn.header.element,St=Cn.header.iconHolder,Bn=Cn.header.headerTitle,Yn=Cn.header.headerSubtitle,Ce=Cn.header.closeButton,Wt=$t?.layout,Il()}else if($t){if(St&&(St.style.display=$t.showIcon===!1?"none":""),Bn&&(Bn.style.display=$t.showTitle===!1?"none":""),Yn&&(Yn.style.display=$t.showSubtitle===!1?"none":""),Ce){let ue=Ne()&&$t.showCloseButton!==!1;Ce.style.display=ue?"":"none"}if(ot.clearChatButtonWrapper){let ue=$t.showClearChat;if(ue!==void 0){ot.clearChatButtonWrapper.style.display=ue?"":"none";let{closeButtonWrapper:ht}=ot;ht&&!ht.classList.contains("persona-absolute")&&(ue?ht.classList.remove("persona-ml-auto"):ht.classList.add("persona-ml-auto"))}}}let dr=o.layout?.showHeader!==!1;$e&&($e.style.display=dr?"":"none");let Po=o.layout?.showFooter!==!1;Qe&&(Qe.style.display=Po?"":"none"),$s(),xn(),_!==At?_?qt(Te,"auto"):(Ae=!0,bl()):Te!==ut&&qt(Te,"auto"),ut=Te,At=_,Wl(),GC();let pr=JSON.stringify(o.toolCall)!==JSON.stringify(f),zo=JSON.stringify(o.messageActions)!==JSON.stringify(y),hs=JSON.stringify(o.layout?.messages)!==JSON.stringify(w),Ol=o.loadingIndicator?.render!==q?.render||o.loadingIndicator?.renderIdle!==q?.renderIdle||o.loadingIndicator?.showBubble!==q?.showBubble,hi=o.iterationDisplay!==te,$=(o.features?.showReasoning??!0)!==(Q??!0)||(o.features?.showToolCalls??!0)!==(re??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ce)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(he);(o.future?.v5Defaults===!0!==d||pr||zo||hs||Ol||hi||$)&&N&&(ei++,xo(We,N.getMessages(),j));let Je=o.features?.streamAnimation?.type;if(Je!==De&&Je&&Je!=="none"){let ue=Qm(Je,o.features?.streamAnimation?.plugins);ue&&xc(ue,t)}let fe=o.launcher??{},zt=fe.headerIconHidden??!1,fn=o.layout?.header?.showIcon,_n=zt||fn===!1,En=fe.headerIconName,jt=fe.headerIconSize??Fl;if(St){let ue=$e,ht=ue?.querySelector(".persona-flex-col");if(_n)St.style.display="none",ue&&ht&&!ue.contains(ht)&&ue.insertBefore(ht,ue.firstChild);else{if(St.style.display="",St.style.height=jt,St.style.width=jt,ue&&ht&&(ue.contains(St)?St.nextSibling!==ht&&(St.remove(),ue.insertBefore(St,ht)):ue.insertBefore(St,ht)),En){let Pt=parseFloat(jt)||24,Yt=ke(En,Pt*.6,"currentColor",1);Yt?(Yt.style.width=`calc(${Pt}px * var(--persona-components-header-iconScale, 0.6))`,Yt.style.height=`calc(${Pt}px * var(--persona-components-header-iconScale, 0.6))`,St.replaceChildren(Yt)):St.textContent=fe.agentIconText??"\u{1F4AC}"}else if(fe.iconUrl){let Pt=St.querySelector("img");if(Pt)Pt.src=fe.iconUrl,Pt.style.height=jt,Pt.style.width=jt;else{let Yt=document.createElement("img");Yt.src=fe.iconUrl,Yt.alt="",Yt.className="persona-rounded-xl persona-object-cover",Yt.style.height=jt,Yt.style.width=jt,St.replaceChildren(Yt)}}else{let Pt=St.querySelector("svg"),Yt=St.querySelector("img");(Pt||Yt)&&St.replaceChildren(),St.textContent=fe.agentIconText??"\u{1F4AC}"}let yt=St.querySelector("img");yt&&(yt.style.height=jt,yt.style.width=jt)}}let cn=o.layout?.header?.showTitle,Sn=o.layout?.header?.showSubtitle;if(Bn&&(Bn.style.display=cn===!1?"none":""),Yn&&(Yn.style.display=Sn===!1?"none":""),Ce){let ue=Ne()&&o.layout?.header?.showCloseButton!==!1;if(Ce.style.display=ue?"":"none",!xe()){let Pn=fe.closeButtonSize??"";Ce.style.height=Pn,Ce.style.width=Pn,Ce.style.minWidth=Pn,Ce.style.minHeight=Pn}let ht=fe.closeButtonPlacement??"inline",{closeButtonWrapper:yt}=ot,Pt=ht==="top-right",Yt=yt?.classList.contains("persona-absolute");if(yt&&Pt!==Yt)if(yt.remove(),Pt){yt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Pn=Sl??Pe;Pn.style.position="relative",Pn.appendChild(yt)}else{let Pn=fe.clearChat?.placement??"inline",Ln=fe.clearChat?.enabled??!0;yt.className=Ln&&Pn==="inline"?"":"persona-ml-auto",$e&&$e.appendChild(yt)}if(Ce.style.color=fe.closeButtonColor||qn.actionIconColor,fe.closeButtonBackgroundColor?(Ce.style.backgroundColor=fe.closeButtonBackgroundColor,Ce.classList.remove("hover:persona-bg-gray-100")):(Ce.style.backgroundColor="",Ce.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let Pn=fe.closeButtonBorderWidth||"0px",Ln=fe.closeButtonBorderColor||"transparent";Ce.style.border=`${Pn} solid ${Ln}`,Ce.classList.remove("persona-border-none")}else Ce.style.border="",Ce.classList.add("persona-border-none");fe.closeButtonBorderRadius?(Ce.style.borderRadius=fe.closeButtonBorderRadius,Ce.classList.remove("persona-rounded-full")):(Ce.style.borderRadius="",Ce.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(Ce.style.paddingLeft=fe.closeButtonPaddingX,Ce.style.paddingRight=fe.closeButtonPaddingX):(Ce.style.paddingLeft="",Ce.style.paddingRight=""),fe.closeButtonPaddingY?(Ce.style.paddingTop=fe.closeButtonPaddingY,Ce.style.paddingBottom=fe.closeButtonPaddingY):(Ce.style.paddingTop="",Ce.style.paddingBottom=""),Gu(Ce,fe.closeButtonIconName??"x",{iconSize:xe()?py:void 0,iconText:fe.closeButtonIconText??"\xD7"});let Dn=fe.closeButtonTooltipText??"Close chat",qo=fe.closeButtonShowTooltip??!0;Ce.setAttribute("aria-label",Dn),yt&&In({anchor:Ce,trigger:yt,text:()=>Ce?.getAttribute("aria-label")??Dn,enabled:qo})}let{clearChatButton:Ke,clearChatButtonWrapper:Kt}=ot;if(Ke){let ue=fe.clearChat??{},ht=ue.enabled??!0,yt=o.layout?.header?.showClearChat,Pt=yt!==void 0?yt:ht,Yt=ue.placement??"inline";if(Kt){Kt.style.display=Pt?"":"none";let{closeButtonWrapper:Dn}=ot;!xe()&&Dn&&!Dn.classList.contains("persona-absolute")&&(Pt?Dn.classList.remove("persona-ml-auto"):Dn.classList.add("persona-ml-auto"));let qo=Yt==="top-right",Pn=Kt.classList.contains("persona-absolute");if(!xe()&&qo!==Pn&&Pt){if(Kt.remove(),qo){Kt.className="persona-absolute persona-top-4 persona-z-50",Kt.style.right="48px";let ur=Sl??Pe;ur.style.position="relative",ur.appendChild(Kt)}else{Kt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Kt.style.right="";let ur=ot.closeButtonWrapper;$e&&ur&&ur.parentElement===$e?$e.insertBefore(Kt,ur):$e&&$e.appendChild(Kt)}let Ln=ot.closeButtonWrapper;Ln&&!Ln.classList.contains("persona-absolute")&&(qo?Ln.classList.add("persona-ml-auto"):Ln.classList.remove("persona-ml-auto"))}}if(Pt){if(!xe()){let Ln=ue.size??"";Ke.style.height=Ln,Ke.style.width=Ln,Ke.style.minWidth=Ln,Ke.style.minHeight=Ln}let Dn=ue.iconColor??"";if(Ke.style.color=Dn||qn.actionIconColor,Gu(Ke,ue.iconName??"refresh-cw",{iconSize:xe()?uy:void 0}),ue.backgroundColor?(Ke.style.backgroundColor=ue.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),ue.borderWidth||ue.borderColor){let Ln=ue.borderWidth||"0px",ur=ue.borderColor||"transparent";Ke.style.border=`${Ln} solid ${ur}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");ue.borderRadius?(Ke.style.borderRadius=ue.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),ue.paddingX?(Ke.style.paddingLeft=ue.paddingX,Ke.style.paddingRight=ue.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),ue.paddingY?(Ke.style.paddingTop=ue.paddingY,Ke.style.paddingBottom=ue.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let qo=ue.tooltipText??"Clear chat",Pn=ue.showTooltip??!0;Ke.setAttribute("aria-label",qo),Kt&&In({anchor:Ke,trigger:Kt,text:()=>Ke?.getAttribute("aria-label")??qo,enabled:Pn})}}let et=o.actionParsers&&o.actionParsers.length?o.actionParsers:[eb],An=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[jc.message,jc.messageAndClick];se=tb({parsers:et,handlers:An,getSessionMetadata:le,updateSessionMetadata:de,emit:R.emit,documentRef:typeof document<"u"?document:null}),j=n0(o,se,I),mk(),N.updateConfig(o),LC(),(o.features?.history?.enabled===!0!==lt||o.features?.history?.provider!==It||o.getIdentityProof!==kt||o.clientToken!==no)&&(to({restoreFocus:!1}),Yv()),ps(),Kd(),xo(We,N.getMessages(),j),Qs(),Id(),pk(),vl(N.isStreaming()),Jt!==o.contextMentions&&ZC();let Io=o.voiceRecognition?.enabled===!0,kn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Ut=so(o.voiceRecognition?.provider);if(Io&&(kn||Ut))if(!ye||!co){let ue=Da(o);if(ue){ye=ue.button,co=ue.wrapper;let ht=Jo&&Jo.parentElement===ed?Jo:null;ed?ed.insertBefore(co,ht):Tn?.appendChild(co),Et&&(Et.micButton=ye),Et?.addListener(ye,"click",cg),ye.disabled=sr()||N.isStreaming()&&!lf()}}else{let ue=o.voiceRecognition??{},ht=o.sendButton??{},yt=ue.iconName??"mic",Pt=ue.iconSize,Yt=parseFloat(Pt??"")||Un;ye.classList.add(yo),ye.classList.toggle(Go,!Pt),ye.style.width=Pt??"",ye.style.height=Pt??"",ye.style.minWidth=Pt??"",ye.style.minHeight=Pt??"";let Dn=ue.iconColor??ht.textColor;ye.innerHTML="";let qo=ke(yt,Yt,Dn||"currentColor",1.5);qo?ye.appendChild(qo):ye.textContent="\u{1F3A4}";let Pn=ue.backgroundColor??ht.backgroundColor;Pn?ye.style.backgroundColor=Pn:ye.style.backgroundColor="",Dn?ye.style.color=Dn:ye.style.color="var(--persona-text, #111827)",ue.borderWidth?(ye.style.borderWidth=ue.borderWidth,ye.style.borderStyle="solid"):(ye.style.borderWidth="",ye.style.borderStyle=""),ue.borderColor?ye.style.borderColor=ue.borderColor:ye.style.borderColor="",ue.paddingX?(ye.style.paddingLeft=ue.paddingX,ye.style.paddingRight=ue.paddingX):(ye.style.paddingLeft="",ye.style.paddingRight=""),ue.paddingY?(ye.style.paddingTop=ue.paddingY,ye.style.paddingBottom=ue.paddingY):(ye.style.paddingTop="",ye.style.paddingBottom="");let Ln=ue.tooltipText??"Start voice recognition",ur=ue.showTooltip??!1;ye.setAttribute("aria-label",Ln),co&&In({anchor:ye,trigger:co,text:()=>ye?.getAttribute("aria-label")??Ln,enabled:ur}),co.style.display="",ye.disabled=sr()||N.isStreaming()&&!lf()}else ye&&co&&(co.style.display="none",so(o.voiceRecognition?.provider)?N.isVoiceActive()&&N.toggleVoice():lr&&us());if(o.attachments?.enabled===!0){if(!Qn||!on){let ue=o.attachments??{};Xn||(Xn=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Xn.style.display="none",(we.parentElement??Tn).insertBefore(Xn,we)),Xt||(Xt=document.createElement("input"),Xt.type="file",Xt.accept=(ue.allowedTypes??Ur).join(","),Xt.multiple=(ue.maxFiles??4)>1,Xt.style.display="none",Xt.setAttribute("aria-label","Attach files"),(we.parentElement??Tn).insertBefore(Xt,we)),Qn=v("div","persona-send-button-wrapper"),on=v("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${yo} ${Go}`),on.type="button",on.setAttribute("aria-label",ue.buttonTooltipText??"Attach file");let ht=ue.buttonIconName??"paperclip";on.style.fontSize="18px",on.style.lineHeight="1";let yt=ke(ht,Un,"currentColor",1.5);yt?on.appendChild(yt):on.textContent="\u{1F4CE}",on.addEventListener("click",Yt=>{Yt.preventDefault(),Xt?.click()}),Qn.appendChild(on);let Pt=ue.buttonTooltipText??"Attach file";In({anchor:on,trigger:Qn,text:()=>on?.getAttribute("aria-label")??Pt}),Pm?Pm.append(Qn):Tn.appendChild(Qn),Et&&(Et.attachmentButton=on,Et.attachmentInput=Xt??void 0,Et.attachmentPreviews=Xn??void 0),!Lt&&Xt&&Xn&&(Lt=oc.fromConfig(ue,Pb),Lt.setPreviewsContainer(Xn),Et?.addListener(Xt,"change",async()=>{Lt&&Xt?.files&&(await Lt.handleFileSelect(Xt.files),Xt.value="")}))}else{Qn.style.display="";let ue=o.attachments??{};Xt&&(Xt.accept=(ue.allowedTypes??Ur).join(","),Xt.multiple=(ue.maxFiles??4)>1),Lt&&Lt.updateConfig({allowedTypes:ue.allowedTypes,maxFileSize:ue.maxFileSize,maxFiles:ue.maxFiles,adapter:ue.adapter})}if(Pe.querySelector(".persona-attachment-drop-overlay")?.remove(),Pe.appendChild(o0(o.attachments?.dropOverlay)),on){let ue=o.attachments??{},ht=ue.buttonTooltipText??"Attach file";on.setAttribute("aria-label",ht),on.textContent="";let yt=ke(ue.buttonIconName??"paperclip",Un,"currentColor",1.5);yt?on.appendChild(yt):on.textContent="\u{1F4CE}",Qn&&In({anchor:on,trigger:Qn,text:()=>on?.getAttribute("aria-label")??ht})}}else Qn&&(Qn.style.display="none"),Lt&&Lt.clearAttachments(),Pe.querySelector(".persona-attachment-drop-overlay")?.remove();let tt=o.sendButton??{},ys=tt.useIcon??!1,bn=tt.iconText??"\u2191",oo=tt.iconName,Or=tt.tooltipText??"Send message",ug=tt.showTooltip??!1,yi=tt.size,mg=parseFloat(yi??"")||uh,_r=tt.backgroundColor,bi=tt.textColor;if(ys){if(Ve.style.width=yi??"",Ve.style.height=yi??"",Ve.style.minWidth=yi??"",Ve.style.minHeight=yi??"",Ve.style.fontSize="18px",Ve.style.lineHeight="1",bi?Ve.style.color=bi:Ve.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!N.isStreaming())if(Ve.innerHTML="",oo){let ue=parseFloat(tt.iconSize??"")||Math.round(mg*.5),ht=bi?.trim()||"currentColor",yt=tt.iconStrokeWidth??2,Pt=ke(oo,ue,ht,yt),Yt=ke(tt.stopIconName??"square",ue,ht,yt);Pt&&Yt?Ve.appendChild(mh(Pt,Yt)):Pt?Ve.appendChild(Pt):Ve.textContent=bn}else Ve.textContent=bn;Ve.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${yo}`,_r?(Ve.style.backgroundColor=_r,Ve.classList.remove("persona-bg-persona-primary")):(Ve.style.backgroundColor="",Ve.classList.add("persona-bg-persona-primary"))}else Ve.textContent=o.copy?.sendButtonLabel??"Send",Ve.style.width="",Ve.style.height="",Ve.style.minWidth="",Ve.style.minHeight="",Ve.style.fontSize="",Ve.style.lineHeight="",Ve.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",_r?(Ve.style.backgroundColor=_r,Ve.classList.remove("persona-bg-persona-accent")):Ve.classList.add("persona-bg-persona-accent"),bi?Ve.style.color=bi:Ve.classList.add("persona-text-white");tt.borderWidth?(Ve.style.borderWidth=tt.borderWidth,Ve.style.borderStyle="solid"):(Ve.style.borderWidth="",Ve.style.borderStyle=""),tt.borderColor?Ve.style.borderColor=tt.borderColor:Ve.style.borderColor="",tt.paddingX?(Ve.style.paddingLeft=tt.paddingX,Ve.style.paddingRight=tt.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),tt.paddingY?(Ve.style.paddingTop=tt.paddingY,Ve.style.paddingBottom=tt.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom=""),N.isStreaming()||Ve.setAttribute("aria-label",Or),Pd(),Jo&&In({anchor:Ve,trigger:Jo,text:()=>Ve.getAttribute("aria-label")??Or,enabled:ug}),zb(),Ym();let cw=hu(ze.getState().activeModeIds,o.composer?.modes);ze.setActiveModeIds(cw),$i().length>0!==!!Sr&&Fm(),Sr?.render(cw,$i());for(let ue of[...zi.keys()])gu(ue,o.composer?.modeGroups)||zi.delete(ue);zi.forEach(ue=>ue.repaint()),Zr?.repaint(),tr?.resolve();let dp=Is(o,xe());if(Gm(),dp){We.style.maxWidth=dp,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",z.style.maxWidth=dp,z.style.marginLeft="auto",z.style.marginRight="auto",z.style.width="100%";for(let ue of[Tn,lo,Xn,pt])ue&&(ue.style.maxWidth=dp,ue.style.marginLeft="auto",ue.style.marginRight="auto",ue.style.width="100%")}else{We.style.maxWidth="",We.style.marginLeft="",We.style.marginRight="",We.style.width="",z.style.maxWidth="",z.style.marginLeft="",z.style.marginRight="",z.style.width="";for(let ue of[Tn,lo,Xn,pt])ue&&(ue.style.maxWidth="",ue.style.marginLeft="",ue.style.marginRight="",ue.style.width="")}let Uo=o.statusIndicator??{};if(Eg(pt,Tn,Uo),xi(pt,Uo,N?.getStatus()??"idle"),N){let ue=N.getStatus();Qo(pt,(yt=>yt==="idle"?Uo.idleText??dn.idle:yt==="connecting"?Uo.connectingText??dn.connecting:yt==="connected"?Uo.connectedText??dn.connected:yt==="error"?Uo.errorText??dn.error:yt==="paused"?Uo.pausedText??dn.paused:yt==="resuming"?Uo.resumingText??dn.resuming:dn[yt])(ue),Uo,ue)}pt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let kP=Uo.align==="left"?"persona-text-left":Uo.align==="center"?"persona-text-center":"persona-text-right";pt.classList.add(kP),Nm(),df(),_o(),Mn()},open(){Ne()&&qt(!0,"api")},close(){Ne()&&qt(!1,"api")},toggle(){Ne()&&qt(!Ae,"api")},reconnect(){N.reconnectNow()},clearChat(){Ar=!1,a.clear(),r.clear(),s.clear(),l.clear(),N.clearMessages(),o.layout?.topFade&&(pe.scrollTop=0),pe.removeAttribute("data-persona-top-fade"),mn.clear(),Zn();try{localStorage.removeItem(Ja),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ja}`)}catch(d){console.error("[AgentWidget] Failed to clear default localStorage:",d)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ja)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(d){console.error("[AgentWidget] Failed to clear custom localStorage:",d)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),x?.clear&&wd(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),L={},se.syncFromMetadata(),Lt?.clearAttachments(),Sd(),Ui(void 0),er(void 0),Zs(),ct?.clear(),Rt?.reset(),Re?.update()},setMessage(i){return!we||N.isStreaming()||sr()?!1:(!Ae&&Ne()&&qt(!0,"system"),we.value=i,we.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(N.isStreaming()||si())return!1;let d=i?.trim()||we.value.trim();return d?(!Ae&&Ne()&&qt(!0,"system"),we.value="",we.style.height="auto",Zo(),rp(d,{consumeDraft:!1}),!0):!1},getComposerState(){return ze.getState()},setQuote(i){let d=i?.text?.trim();d&&er({...i,text:d})},clearQuote(){er(void 0)},startVoiceRecognition(){return N.isStreaming()?!1:so(o.voiceRecognition?.provider)?(N.isVoiceActive()||N.isBargeInActive()||(!Ae&&Ne()&&qt(!0,"system"),wt.manuallyDeactivated=!1,Vo(),N.toggleVoice().then(()=>{wt.active=N.isVoiceActive(),kr("user"),N.isVoiceActive()&&ba()})),!0):lr?!0:OC()?(!Ae&&Ne()&&qt(!0,"system"),wt.manuallyDeactivated=!1,Vo(),ip("user"),!0):!1},stopVoiceRecognition(){return so(o.voiceRecognition?.provider)?!N.isVoiceActive()&&!N.isBargeInActive()?!1:((N.isBargeInActive()?N.deactivateBargeIn():N.toggleVoice()).then(()=>{wt.active=!1,wt.manuallyDeactivated=!0,Vo(),kr("user"),Dr()}),!0):lr?(wt.manuallyDeactivated=!0,Vo(),us("user"),!0):!1},injectMessage(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectMessage(i)},injectAssistantMessage(i){!Ae&&Ne()&&qt(!0,"system");let d=N.injectAssistantMessage(i);return vt&&(vt=!1,X&&(clearTimeout(X),X=null),setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)),d},injectUserMessage(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectUserMessage(i)},injectSystemMessage(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectSystemMessage(i)},injectMessageBatch(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectMessageBatch(i)},injectComponentDirective(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectComponentDirective(i)},injectTestMessage(i){!Ae&&Ne()&&qt(!0,"system"),N.injectTestEvent(i)},async connectStream(i,d){return N.connectStream(i,d)},__pushEventStreamEvent(i){ie&&(Tt(),qe(i.type,i.payload))},showEventStream(){ie&&_m()},hideEventStream(){nt&&qi()},isEventStreamVisible(){return nt},listConversations(i){return N.listConversations(i)},getActiveConversationId(){return N.getActiveConversationId()},openConversation(i,d){return jf(i,{focusComposer:d?.focus===!0})},startNewConversation(i){return Kf({focusComposer:i?.focus===!0})},warmSession(){Qf()},deleteConversation(i){return wC(i)},renameConversation(i,d){return Gf(i,{title:d})},setConversationStarred(i,d){return Gf(i,{starred:d})},clearConversationHistory(i){return xC(i)},resetHistoryIdentity(){return SC()},async getVisitorToken(){let i=So;if(!i)return null;let d=await i.get();return i===So?d:null},getHistoryIdentityStatus(){return go?go.getIdentityStatus():Pf()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return Ll({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){to(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return mt},showArtifacts(){Kn(o)&&(Ar=!1,Ki=!0,Fo(),gt?.setMobileOpen(!0))},hideArtifacts(){Kn(o)&&(Ar=!0,Fo())},upsertArtifact(i){return Kn(o)?(Cs(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Ar=!1,Ki=!0),N.upsertArtifact(i)):null},selectArtifact(i){Kn(o)&&N.selectArtifact(i)},clearArtifacts(){Kn(o)&&N.clearArtifacts()},getArtifacts(){return N?.getArtifacts()??[]},getSelectedArtifactId(){return N?.getSelectedArtifactId()??null},focusInput(){return _&&!Ae&&!xe()||!we?!1:(we.focus(),!0)},async resolveApproval(i,d,f){let w=N.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===i);if(!w?.approval)throw new Error(`Approval not found: ${i}`);if(w.approval.toolType==="webmcp"){N.resolveWebMcpApproval(w.id,d);return}return N.resolveApproval(w.approval,d,f)},setFollowUpSuggestions(i){D0(i)},clearFollowUpSuggestions(){yv()},getMessages(){return N.getMessages()},getStatus(){return N.getStatus()},getPersistentMetadata(){return{...L}},updatePersistentMetadata(i){de(i)},on(i,d){return R.on(i,d)},off(i,d){R.off(i,d)},isOpen(){return Ne()&&Ae},isVoiceActive(){return wt.active},toggleReadAloud(i){N.toggleReadAloud(i)},stopReadAloud(){N.stopSpeaking()},getReadAloudState(i){return N.getReadAloudState(i)},onReadAloudChange(i){return N.onReadAloudChange(i)},getState(){return{open:Ne()&&Ae,launcherEnabled:_,voiceActive:wt.active,streaming:N.isStreaming()}},showCSATFeedback(i){!Ae&&Ne()&&qt(!0,"system");let d=We.querySelector(".persona-feedback-container");d&&d.remove();let f=ZE({onSubmit:async(y,w)=>{N.isClientTokenMode()&&await N.submitCSATFeedback(y,w),i?.onSubmit?.(y,w)},onDismiss:i?.onDismiss,...i});We.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Ae&&Ne()&&qt(!0,"system");let d=We.querySelector(".persona-feedback-container");d&&d.remove();let f=e0({onSubmit:async(y,w)=>{N.isClientTokenMode()&&await N.submitNPSFeedback(y,w),i?.onSubmit?.(y,w)},onDismiss:i?.onDismiss,...i});We.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,d){return N.submitCSATFeedback(i,d)},async submitNPSFeedback(i,d){return N.submitNPSFeedback(i,d)},destroy(){xf(),li!=null&&(clearInterval(li),li=null),a.clear(),r.clear(),s.clear(),l.clear(),_e.forEach(i=>i()),dt.remove(),Nt?.remove(),sn?.destroy(),Fn?.remove(),Gs&&Ce.removeEventListener("click",Gs)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,d={controller:an,getMessages:an.getMessages,getStatus:an.getStatus,getMetadata:an.getPersistentMetadata,updateMetadata:an.updatePersistentMetadata,clearHistory:()=>an.clearChat(),setVoiceActive:f=>f?an.startVoiceRecognition():an.stopVoiceRecognition()};window.AgentWidgetBrowser=d,_e.push(()=>{window.AgentWidgetBrowser===d&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),d=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.focusInput()};if(window.addEventListener("persona:focusInput",d),_e.push(()=>{window.removeEventListener("persona:focusInput",d)}),ie){let re=he=>{let De=he.detail;(!De?.instanceId||De.instanceId===i)&&an.showEventStream()},ce=he=>{let De=he.detail;(!De?.instanceId||De.instanceId===i)&&an.hideEventStream()};window.addEventListener("persona:showEventStream",re),window.addEventListener("persona:hideEventStream",ce),_e.push(()=>{window.removeEventListener("persona:showEventStream",re),window.removeEventListener("persona:hideEventStream",ce)})}let f=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.showHistory()},y=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",y),_e.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",y)});let w=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.showArtifacts()},k=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.hideArtifacts()},q=re=>{let ce=re.detail;ce?.instanceId&&ce.instanceId!==i||ce?.artifact&&an.upsertArtifact(ce.artifact)},te=re=>{let ce=re.detail;ce?.instanceId&&ce.instanceId!==i||typeof ce?.id=="string"&&an.selectArtifact(ce.id)},Q=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.clearArtifacts()};window.addEventListener("persona:showArtifacts",w),window.addEventListener("persona:hideArtifacts",k),window.addEventListener("persona:upsertArtifact",q),window.addEventListener("persona:selectArtifact",te),window.addEventListener("persona:clearArtifacts",Q),_e.push(()=>{window.removeEventListener("persona:showArtifacts",w),window.removeEventListener("persona:hideArtifacts",k),window.removeEventListener("persona:upsertArtifact",q),window.removeEventListener("persona:selectArtifact",te),window.removeEventListener("persona:clearArtifacts",Q)})}let ko=sD(o.persistState);if(ko&&Ne()){let i=iD(ko.storage),d=`${ko.keyPrefix}widget-open`,f=`${ko.keyPrefix}widget-voice`,y=`${ko.keyPrefix}widget-voice-mode`;if(i){let w=ko.persist?.openState&&i.getItem(d)==="true",k=ko.persist?.voiceState&&i.getItem(f)==="true",q=ko.persist?.voiceState&&i.getItem(y)==="true";if(w&&(sn?.setPanelOpen(!0,"auto"),setTimeout(()=>{an.open(),setTimeout(()=>{if(k||q)an.startVoiceRecognition();else if(ko.persist?.focusInput){let te=t.querySelector("textarea");te&&te.focus()}},100)},0)),ko.persist?.openState&&(R.on("widget:opened",()=>{i.setItem(d,"true")}),R.on("widget:closed",()=>{i.setItem(d,"false")})),ko.persist?.voiceState&&(R.on("voice:state",te=>{i.setItem(f,te.active?"true":"false")}),R.on("user:message",te=>{i.setItem(y,te.viaVoice?"true":"false")})),ko.clearOnChatClear){let te=()=>{i.removeItem(d),i.removeItem(f),i.removeItem(y)},Q=()=>te();window.addEventListener("persona:clear-chat",Q),_e.push(()=>{window.removeEventListener("persona:clear-chat",Q)})}}}if(oe&&Ne()&&(sn?.setPanelOpen(!0,"auto"),setTimeout(()=>{an.open()},0)),oa(),!O0){let i=xa(()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j))});_e.push(i)}H=()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j))},N.getMessages().length>0&&kd(),B=()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j))};let TP=Sw(()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j))});_e.push(TP);let EP=qy(()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j),Gr()?.updateInlineArtifactBlocks(We,wo.artifacts,{suppressTransition:!0}),Fo())});return _e.push(EP),an};ks();var s0=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,e*parseFloat(r[1])/100):420},cD=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},dD=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},pD=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},i0=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},wb=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},a0=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",wb(t)},bb=t=>{t.style.transition=""},vb=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Cb=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Em=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},uD=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},mD=(t,e,n,o,r,s)=>{let a=s?e:t;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},fD=t=>{let e=qr(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Hn(e,r)??r;return{inset:o(n?.inset,Wu),canvasBackground:o(n?.canvasBackground,Bu)}},l0=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},gD=(t,e,n,o,r,s,a,l)=>{let c=Do(s),p=c.reveal==="push",u=l!=null,m=l?.inset??"",g=l?.canvasBackground??"";uD(t,e,n,o,p),mD(t,e,n,o,c.side,p),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=c.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let h=t.ownerDocument.defaultView,b=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,M=h!=null?h.innerWidth<=C:!1;if(b&&M&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),vb(e),bb(o),a0(o),Cb(n),Em(r,o),l0(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??On),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),a0(o),cD(o,c.maxHeight),l0(o,u&&a,m,g),c.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",vb(e),bb(o),Cb(n),Em(r,o);let T=c.animate?"transform 180ms ease":"none",H=c.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":H;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=c.width,o.style.maxWidth=c.width,o.style.minWidth=c.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=T,o.style.transform=A,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",c.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(c.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",bb(o),wb(o),Em(r,o);let T=s0(c.width,t.clientWidth),H=Math.max(0,t.clientWidth),A=c.animate?"margin-left 180ms ease":"none",D=c.side==="right"?a?-T:0:a?0:-T;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${H+T}px`,e.style.transition=A,e.style.marginLeft=`${D}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${H}px`,n.style.maxWidth=`${H}px`,n.style.minWidth=`${H}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=c.width,o.style.minWidth=c.width,o.style.maxWidth=c.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",vb(e),wb(o),Cb(n),Em(r,o);let T=c.reveal==="emerge";T?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let H=a?c.width:"0px",A=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",D=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${H}`,o.style.width=H,o.style.maxWidth=H,o.style.minWidth=H,o.style.minHeight="0",dD(o,c.maxHeight),o.style.overflow=T||D?"hidden":"visible",o.style.transition=A,T){o.style.alignItems=c.side==="right"?"flex-start":"flex-end";let W=u?`calc(${s0(c.width,t.clientWidth)}px - (2 * ${m}))`:c.width;r.style.width=W,r.style.minWidth=W,r.style.maxWidth=W,r.style.boxSizing="border-box"}}},hD=(t,e)=>{let n=t.ownerDocument.createElement("div");return i0(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){i0(n,o)},destroy(){n.remove()}}},yD=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=n.createElement("div"),l=n.createElement("div"),c=n.createElement("div"),p=n.createElement("aside"),u=n.createElement("div"),m=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",p.appendChild(u),o.insertBefore(a,t),c.appendChild(t);let g=null,h=()=>{g?.disconnect(),g=null},b=null,C=()=>{b=e?.launcher?.detachedPanel===!0?fD(e):null};C();let M=()=>{gD(a,l,c,p,u,e,m,b)},E=null,T=()=>{E?.(),E=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(E=Du(()=>{C(),M()}))},H=()=>{h(),Do(e).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{M()}),g.observe(a)))},A=!1,D=()=>{M(),H(),m&&!A&&a.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,pD(a,Do(e)))},W=a.ownerDocument.defaultView,U=()=>{D()};return W?.addEventListener("resize",U),Do(e).reveal==="push"?(l.appendChild(c),l.appendChild(p),a.appendChild(l)):(a.appendChild(c),a.appendChild(p)),D(),T(),{mode:"docked",host:u,shell:a,syncWidgetState(B){let O=B.launcherEnabled?B.open:!0;m!==O&&(m=O,D())},updateConfig(B){e=B,(e?.launcher?.enabled??!0)===!1&&(m=!0),C(),D(),T()},destroy(){W?.removeEventListener("resize",U),E?.(),E=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},c0=(t,e)=>nn(e)?yD(t,e):hD(t,e);var Jc={desktop:{w:1280,h:800},mobile:{w:390,h:844}},d0=.15,p0=1.5,xb="persona-preview-shell-theme",bD={load:()=>null,save:()=>{},clear:()=>{}},vD=["How do I get started?","Pricing & plans","Talk to support"];function Sb(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function CD(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function u0(t){let e=CD(t);return`* { box-sizing: border-box; }
1268
1269
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
1269
1270
  html { color-scheme: ${t}; }
1270
1271
  body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
@@ -1288,7 +1289,7 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1288
1289
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
1289
1290
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
1290
1291
  .preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
1291
- .preview-workspace-card.short { height: 96px; }`}function rE(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(ky);o||(o=n.createElement("style"),o.id=ky,n.head.appendChild(o)),o.textContent=oE(e)}var QB=`
1292
+ .preview-workspace-card.short { height: 96px; }`}function m0(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(xb);o||(o=n.createElement("style"),o.id=xb,n.head.appendChild(o)),o.textContent=u0(e)}var wD=`
1292
1293
  <div class="preview-iframe-mock" aria-hidden="true">
1293
1294
  <div class="preview-iframe-chrome">
1294
1295
  <span class="preview-iframe-dot"></span>
@@ -1307,7 +1308,7 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1307
1308
  <div class="preview-iframe-line body"></div>
1308
1309
  <div class="preview-iframe-line body"></div>
1309
1310
  </div>
1310
- </div>`,XB=`
1311
+ </div>`,xD=`
1311
1312
  <div class="preview-workspace-content-shell" aria-hidden="true">
1312
1313
  <div class="preview-iframe-line hero"></div>
1313
1314
  <div class="preview-iframe-line body"></div>
@@ -1320,8 +1321,8 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1320
1321
  <div class="preview-workspace-card short"></div>
1321
1322
  <div class="preview-workspace-card short"></div>
1322
1323
  </div>
1323
- </div>`;function sE(t,e,n,o){let r=`
1324
- ${QB}
1324
+ </div>`;function f0(t,e,n,o){let r=`
1325
+ ${wD}
1325
1326
  <div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,s=`
1326
1327
  <div class="preview-workspace-shell">
1327
1328
  <div class="preview-workspace-topbar">
@@ -1333,7 +1334,7 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1333
1334
  </div>
1334
1335
  <div class="preview-workspace-body">
1335
1336
  <div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
1336
- ${XB}
1337
+ ${xD}
1337
1338
  </div>
1338
1339
  </div>
1339
1340
  </div>`;return`<!DOCTYPE html>
@@ -1341,16 +1342,16 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1341
1342
  <head>
1342
1343
  <meta charset="UTF-8">
1343
1344
  <meta name="viewport" content="width=device-width, initial-scale=1">
1344
- <link rel="stylesheet" href="${Ly(o)}">
1345
- <style id="${ky}">${oE(e)}</style>
1345
+ <link rel="stylesheet" href="${Sb(o)}">
1346
+ <style id="${xb}">${u0(e)}</style>
1346
1347
  </head>
1347
1348
  <body>
1348
1349
  ${n?s:r}
1349
1350
  </body>
1350
- </html>`}var JB=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],ZB=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function e1(t,e,n=[]){if(t==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return t==="home"?[]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&ZB(e)?[...JB(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function t1(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:GB:t.suggestionChips,initialMessages:e1(e,t,n),storageAdapter:KB};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),e==="messages"&&(r.features={...r.features,history:{presentation:"panel",...r.features?.history,enabled:!0}}),r}function n1(t,e){let n=t.theme?va(t.theme,{validate:!1}):va();return{...It,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function Da(t,e){let n=t.scene??"conversation";return t1(n1(t,e),n,t.appendedMessages??[])}function iE(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Da(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Da(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Da(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Da(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Da(t,n),shellMode:n}]}function aE(t,e){let n={...e},o=[],r=[],s=null,a=!1,l=1,d=1,p=0;function u(){return n.device??"desktop"}function m(){return n.zoom??l}function y(){let A=getComputedStyle(t),I=parseFloat(A.paddingLeft)+parseFloat(A.paddingRight),M=parseFloat(A.paddingTop)+parseFloat(A.paddingBottom),O=40,k=(n.compareMode??"off")!=="off",B=(t.clientWidth-I-O)/(k?2:1),W=t.clientHeight-M-O;if(B<=0||W<=0)return 1;let V=Oc[u()]??Oc.desktop;return Math.min(B/V.w,W/V.h,1)}function g(){l=y();let A=Math.max(tE,Math.min(nE,m()));d=A;let I=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let M of I){let O=M.dataset.device??"desktop",k=Oc[O]??Oc.desktop;M.style.width=`${k.w*A}px`,M.style.height=`${k.h*A}px`,O==="mobile"&&(M.style.borderRadius=`${32*A}px`);let B=M.querySelector("iframe");B&&(B.style.width=`${k.w}px`,B.style.height=`${k.h}px`,B.style.transformOrigin="top left",B.style.transition="none",B.style.transform=`scale(${A})`)}n.onScaleChange?.(A)}function b(){n.onBeforeDestroy?.();for(let A of o)A.destroy();for(let A of r)A();o=[],r=[]}function C(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function S(){if(a)return;b();let A=++p,I=iE(n),M=u(),O=(n.compareMode??"off")!=="off",k=(n.scene??"conversation")==="minimized",B=n.widgetCssPath??"/widget-dist/widget.css",W=n.buildSrcdoc??sE,V=M==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",R=z=>`<div class="${V}" data-mount-id="${z.mountId}" data-device="${M}" data-shell-mode="${z.shellMode}">
1351
- ${O?`<div class="preview-frame-meta"><span class="preview-frame-label">${Ly(z.label)}</span></div>`:""}
1352
- <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${z.mountId}"></iframe>
1353
- </div>`,w=O?`<div class="preview-compare-grid">${I.map(z=>`<div class="preview-compare-cell">${R(z)}</div>`).join("")}</div>`:`<div class="preview-single">${R(I[0])}</div>`;n.morphContainer?n.morphContainer(t,w):t.innerHTML=w,g();let E=C(),H=0,D=E.length,G=()=>{if(a||A!==p)return;for(let K of E){let Y=K.dataset.mountId;if(!Y||!K.contentDocument)continue;let re=I.find(ge=>ge.mountId===Y);if(!re)continue;let oe=()=>{},se=rn(re.config),ce=se?(()=>{let ge=K.contentDocument?.getElementById(`preview-content-${Y}`);if(!ge)return null;let N=eE(ge,re.config),ye=K.contentDocument.createElement("div");ye.id=Y,ye.style.height="100%",ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1",ye.style.minHeight="0",N.host.appendChild(ye);let ke=()=>N.syncWidgetState(we.getState()),nt=oe;return oe=()=>{N.destroy(),nt()},ye.__syncDock=ke,ye.__hostLayout=N,ye})():K.contentDocument.getElementById(Y);if(!ce)continue;let we=YT(ce,re.config);if(o.push(we),se&&ce.__syncDock){let ge=ce.__syncDock,N=we.on("widget:opened",ge),ye=we.on("widget:closed",ge),ke=oe;oe=()=>{N(),ye(),ke()},ge()}r.push(oe),k&&we.close()}let z=n.scene??"conversation";if(z==="messages")for(let K of o)K.showHistory({focus:!1});if(z==="artifact"||n.config?.features?.artifacts?.enabled)for(let K of o)K.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
1351
+ </html>`}var SD=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],AD=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function MD(t,e,n=[]){if(t==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return t==="home"?[]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&AD(e)?[...SD(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function TD(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:vD:t.suggestionChips,initialMessages:MD(e,t,n),storageAdapter:bD};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),e==="messages"&&(r.features={...r.features,history:{presentation:"panel",...r.features?.history,enabled:!0}}),r}function ED(t,e){let n=fp(t.config),o=t.config?.future,r=t.theme?Na(t.theme,{validate:!1,future:o}):Na(void 0,{future:o});return{...n,...t.config,theme:r,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function el(t,e){let n=t.scene??"conversation";return TD(ED(t,e),n,t.appendedMessages??[])}function g0(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:el(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:el(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:el(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:el(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:el(t,n),shellMode:n}]}function h0(t,e){let n={...e},o=[],r=[],s=null,a=!1,l=1,c=1,p=0;function u(){return n.device??"desktop"}function m(){return n.zoom??l}function g(){let T=getComputedStyle(t),H=parseFloat(T.paddingLeft)+parseFloat(T.paddingRight),A=parseFloat(T.paddingTop)+parseFloat(T.paddingBottom),D=40,W=(n.compareMode??"off")!=="off",U=(t.clientWidth-H-D)/(W?2:1),B=t.clientHeight-A-D;if(U<=0||B<=0)return 1;let O=Jc[u()]??Jc.desktop;return Math.min(U/O.w,B/O.h,1)}function h(){l=g();let T=Math.max(d0,Math.min(p0,m()));c=T;let H=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let A of H){let D=A.dataset.device??"desktop",W=Jc[D]??Jc.desktop;A.style.width=`${W.w*T}px`,A.style.height=`${W.h*T}px`,D==="mobile"&&(A.style.borderRadius=`${32*T}px`);let U=A.querySelector("iframe");U&&(U.style.width=`${W.w}px`,U.style.height=`${W.h}px`,U.style.transformOrigin="top left",U.style.transition="none",U.style.transform=`scale(${T})`)}n.onScaleChange?.(T)}function b(){n.onBeforeDestroy?.();for(let T of o)T.destroy();for(let T of r)T();o=[],r=[]}function C(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function M(){if(a)return;b();let T=++p,H=g0(n),A=u(),D=(n.compareMode??"off")!=="off",W=(n.scene??"conversation")==="minimized",U=n.widgetCssPath??"/widget-dist/widget.css",B=n.buildSrcdoc??f0,O=A==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",R=V=>`<div class="${O}" data-mount-id="${V.mountId}" data-device="${A}" data-shell-mode="${V.shellMode}">
1352
+ ${D?`<div class="preview-frame-meta"><span class="preview-frame-label">${Sb(V.label)}</span></div>`:""}
1353
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${V.mountId}"></iframe>
1354
+ </div>`,S=D?`<div class="preview-compare-grid">${H.map(V=>`<div class="preview-compare-cell">${R(V)}</div>`).join("")}</div>`:`<div class="preview-single">${R(H[0])}</div>`;n.morphContainer?n.morphContainer(t,S):t.innerHTML=S,h();let x=C(),P=0,L=x.length,G=()=>{if(a||T!==p)return;for(let K of x){let ee=K.dataset.mountId;if(!ee||!K.contentDocument)continue;let oe=H.find(Le=>Le.mountId===ee);if(!oe)continue;let ne=()=>{},le=nn(oe.config),de=le?(()=>{let Le=K.contentDocument?.getElementById(`preview-content-${ee}`);if(!Le)return null;let se=c0(Le,oe.config),_=K.contentDocument.createElement("div");_.id=ee,_.style.height="100%",_.style.display="flex",_.style.flexDirection="column",_.style.flex="1",_.style.minHeight="0",se.host.appendChild(_);let Te=()=>se.syncWidgetState(ve.getState()),He=ne;return ne=()=>{se.destroy(),He()},_.__syncDock=Te,_.__hostLayout=se,_})():K.contentDocument.getElementById(ee);if(!de)continue;let ve=r0(de,oe.config);if(o.push(ve),le&&de.__syncDock){let Le=de.__syncDock,se=ve.on("widget:opened",Le),_=ve.on("widget:closed",Le),Te=ne;ne=()=>{se(),_(),Te()},Le()}r.push(ne),W&&ve.close()}let V=n.scene??"conversation";if(V==="messages")for(let K of o)K.showHistory({focus:!1});if(V==="artifact"||n.config?.features?.artifacts?.enabled)for(let K of o)K.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
1354
1355
 
1355
1356
  This is a preview of the artifact sidebar.
1356
1357
 
@@ -1358,4 +1359,4 @@ This is a preview of the artifact sidebar.
1358
1359
 
1359
1360
  - Markdown rendering
1360
1361
  - Document toolbar
1361
- - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:E,controllers:[...o]})};for(let z of E){let K=z.dataset.mountId;if(!K)continue;let Y=I.find(re=>re.mountId===K);Y&&(z.addEventListener("load",()=>{H++,H>=D&&G()},{once:!0}),z.srcdoc=W(K,Y.shellMode,rn(Y.config),B))}D===0&&G()}function T(){if(a)return;let A=iE(n);if(o.length!==A.length){S();return}if(A.some(M=>{let O=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${M.mountId}"]`);return!O||O.dataset.shellMode!==M.shellMode})){S();return}o.forEach((M,O)=>{M.update(A[O].config),(n.scene??"conversation")==="minimized"&&M.close()});for(let M of A){let O=t.querySelector(`iframe[data-mount-id="${M.mountId}"]`);O&&rE(O,M.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||g()}),s.observe(t)),S(),{update(A){if(a)return;let I=A.device!==void 0&&A.device!==n.device||A.scene!==void 0&&A.scene!==n.scene||A.compareMode!==void 0&&A.compareMode!==n.compareMode||A.widgetCssPath!==void 0&&A.widgetCssPath!==n.widgetCssPath;n={...n,...A},I?S():T()},destroy(){a||(a=!0,b(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},g())},getIframes(){return C()},getScale(){return d},setZoom(A){a||(n={...n,zoom:A},g())}}}0&&(module.exports={createThemePreview});
1362
+ - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:x,controllers:[...o]})};for(let V of x){let K=V.dataset.mountId;if(!K)continue;let ee=H.find(oe=>oe.mountId===K);ee&&(V.addEventListener("load",()=>{P++,P>=L&&G()},{once:!0}),V.srcdoc=B(K,ee.shellMode,nn(ee.config),U))}L===0&&G()}function E(){if(a)return;let T=g0(n);if(o.length!==T.length){M();return}if(T.some(A=>{let D=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${A.mountId}"]`);return!D||D.dataset.shellMode!==A.shellMode})){M();return}o.forEach((A,D)=>{A.update(T[D].config),(n.scene??"conversation")==="minimized"&&A.close()});for(let A of T){let D=t.querySelector(`iframe[data-mount-id="${A.mountId}"]`);D&&m0(D,A.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||h()}),s.observe(t)),M(),{update(T){if(a)return;let H=T.device!==void 0&&T.device!==n.device||T.scene!==void 0&&T.scene!==n.scene||T.compareMode!==void 0&&T.compareMode!==n.compareMode||T.widgetCssPath!==void 0&&T.widgetCssPath!==n.widgetCssPath;n={...n,...T},H?M():E()},destroy(){a||(a=!0,b(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},h())},getIframes(){return C()},getScale(){return c},setZoom(T){a||(n={...n,zoom:T},h())}}}0&&(module.exports={createThemePreview});