@runtypelabs/persona 4.19.0 → 4.21.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 (77) 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-CG-bLFmk.d.cts → types-B_JdVK9o.d.cts} +2 -0
  4. package/dist/animations/{types-CG-bLFmk.d.ts → types-B_JdVK9o.d.ts} +2 -0
  5. package/dist/animations/wipe.d.cts +1 -1
  6. package/dist/animations/wipe.d.ts +1 -1
  7. package/dist/animations-extra.d.cts +2 -0
  8. package/dist/animations-extra.d.ts +2 -0
  9. package/dist/approval-ui.d.cts +99 -5
  10. package/dist/approval-ui.d.ts +99 -5
  11. package/dist/artifacts-ui.d.cts +99 -5
  12. package/dist/artifacts-ui.d.ts +99 -5
  13. package/dist/codegen.cjs +1 -1
  14. package/dist/codegen.js +1 -1
  15. package/dist/context-mentions.d.cts +99 -5
  16. package/dist/context-mentions.d.ts +99 -5
  17. package/dist/event-stream-view.d.cts +99 -5
  18. package/dist/event-stream-view.d.ts +99 -5
  19. package/dist/forms-ui.d.cts +123 -9
  20. package/dist/forms-ui.d.ts +123 -9
  21. package/dist/history-view.d.cts +2 -0
  22. package/dist/history-view.d.ts +2 -0
  23. package/dist/index.cjs +51 -51
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +128 -10
  26. package/dist/index.d.ts +128 -10
  27. package/dist/index.global.js +34 -34
  28. package/dist/index.global.js.map +1 -1
  29. package/dist/index.js +51 -51
  30. package/dist/index.js.map +1 -1
  31. package/dist/launcher.global.js.map +1 -1
  32. package/dist/session-reconnect.d.cts +99 -5
  33. package/dist/session-reconnect.d.ts +99 -5
  34. package/dist/smart-dom-reader.d.cts +99 -5
  35. package/dist/smart-dom-reader.d.ts +99 -5
  36. package/dist/theme-editor-preview.cjs +53 -53
  37. package/dist/theme-editor-preview.d.cts +99 -5
  38. package/dist/theme-editor-preview.d.ts +99 -5
  39. package/dist/theme-editor-preview.js +31 -31
  40. package/dist/theme-editor.d.cts +99 -5
  41. package/dist/theme-editor.d.ts +99 -5
  42. package/dist/theme-reference.cjs +1 -1
  43. package/dist/theme-reference.d.cts +46 -5
  44. package/dist/theme-reference.d.ts +46 -5
  45. package/dist/theme-reference.js +1 -1
  46. package/dist/webmcp-runtime.d.cts +16 -0
  47. package/dist/webmcp-runtime.d.ts +16 -0
  48. package/dist/widget.css +1 -1
  49. package/package.json +1 -1
  50. package/src/client-visitor-history.test.ts +342 -3
  51. package/src/client.test.ts +141 -3
  52. package/src/client.ts +157 -39
  53. package/src/components/composer-actions.ts +27 -1
  54. package/src/components/composer-model-picker.ts +4 -14
  55. package/src/components/composer-overflow-menu.ts +14 -0
  56. package/src/components/composer-parts.ts +20 -0
  57. package/src/generated/runtype-openapi-contract.ts +2 -0
  58. package/src/index-core.ts +2 -0
  59. package/src/session.ts +139 -103
  60. package/src/session.webmcp.test.ts +48 -1
  61. package/src/styles/widget-styles.test.ts +83 -1
  62. package/src/styles/widget.css +50 -14
  63. package/src/theme-reference.ts +1 -1
  64. package/src/types/theme.ts +47 -5
  65. package/src/types.ts +63 -0
  66. package/src/ui.composer-action-visibility.test.ts +202 -0
  67. package/src/ui.composer-models.test.ts +37 -0
  68. package/src/ui.composer-modes.test.ts +82 -0
  69. package/src/ui.composer-overflow.test.ts +78 -0
  70. package/src/ui.history-lifecycle.test.ts +2 -2
  71. package/src/ui.ts +77 -6
  72. package/src/utils/__snapshots__/tokens-parity.test.ts.snap +1633 -686
  73. package/src/utils/composer-modes.test.ts +33 -0
  74. package/src/utils/composer-modes.ts +19 -2
  75. package/src/utils/tokens-parity.test.ts +20 -0
  76. package/src/utils/tokens.test.ts +76 -0
  77. package/src/utils/tokens.ts +4 -4
@@ -1,32 +1,32 @@
1
- "use strict";var AgentWidget=(()=>{var lT=Object.create;var sc=Object.defineProperty;var dT=Object.getOwnPropertyDescriptor;var cT=Object.getOwnPropertyNames;var uT=Object.getPrototypeOf,pT=Object.prototype.hasOwnProperty;var ho=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var ov=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),fT=(e,t)=>{for(var o in t)sc(e,o,{get:t[o],enumerable:!0})},nv=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of cT(t))!pT.call(e,r)&&r!==o&&sc(e,r,{get:()=>t[r],enumerable:!(n=dT(t,r))||n.enumerable});return e};var Zt=(e,t,o)=>(o=e!=null?lT(uT(e)):{},nv(t||!e||!e.__esModule?sc(o,"default",{value:e,enumerable:!0}):o,e)),mT=e=>nv(sc({},"__esModule",{value:!0}),e);var Rf=ov(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Allow=ye.ALL=ye.COLLECTION=ye.ATOM=ye.SPECIAL=ye.INF=ye._INFINITY=ye.INFINITY=ye.NAN=ye.BOOL=ye.NULL=ye.OBJ=ye.ARR=ye.NUM=ye.STR=void 0;ye.STR=1;ye.NUM=2;ye.ARR=4;ye.OBJ=8;ye.NULL=16;ye.BOOL=32;ye.NAN=64;ye.INFINITY=128;ye._INFINITY=256;ye.INF=ye.INFINITY|ye._INFINITY;ye.SPECIAL=ye.NULL|ye.BOOL|ye.INF|ye.NAN;ye.ATOM=ye.STR|ye.NUM|ye.SPECIAL;ye.COLLECTION=ye.ARR|ye.OBJ;ye.ALL=ye.ATOM|ye.COLLECTION;ye.Allow={STR:ye.STR,NUM:ye.NUM,ARR:ye.ARR,OBJ:ye.OBJ,NULL:ye.NULL,BOOL:ye.BOOL,NAN:ye.NAN,INFINITY:ye.INFINITY,_INFINITY:ye._INFINITY,INF:ye.INF,SPECIAL:ye.SPECIAL,ATOM:ye.ATOM,COLLECTION:ye.COLLECTION,ALL:ye.ALL};ye.default=ye.Allow});var pc=ov(ro=>{"use strict";var IT=ro&&ro.__createBinding||(Object.create?(function(e,t,o,n){n===void 0&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}):(function(e,t,o,n){n===void 0&&(n=o),e[n]=t[o]})),HT=ro&&ro.__exportStar||function(e,t){for(var o in e)o!=="default"&&!Object.prototype.hasOwnProperty.call(t,o)&&IT(t,e,o)};Object.defineProperty(ro,"__esModule",{value:!0});ro.Allow=ro.MalformedJSON=ro.PartialJSON=ro.parseJSON=ro.parse=void 0;var yo=Rf();Object.defineProperty(ro,"Allow",{enumerable:!0,get:function(){return yo.Allow}});HT(Rf(),ro);var cc=class extends Error{};ro.PartialJSON=cc;var uc=class extends Error{};ro.MalformedJSON=uc;function Lv(e,t=yo.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return RT(e.trim(),t)}ro.parseJSON=Lv;var RT=(e,t)=>{let o=e.length,n=0,r=y=>{throw new cc(`${y} at position ${n}`)},a=y=>{throw new uc(`${y} at position ${n}`)},i=()=>(m(),n>=o&&r("Unexpected end of input"),e[n]==='"'?d():e[n]==="{"?u():e[n]==="["?c():e.substring(n,n+4)==="null"||yo.Allow.NULL&t&&o-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||yo.Allow.BOOL&t&&o-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||yo.Allow.BOOL&t&&o-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||yo.Allow.INFINITY&t&&o-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||yo.Allow._INFINITY&t&&1<o-n&&o-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||yo.Allow.NAN&t&&o-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):p()),d=()=>{let y=n,h=!1;for(n++;n<o&&(e[n]!=='"'||h&&e[n-1]==="\\");)h=e[n]==="\\"?!h:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(y,++n-Number(h)))}catch(S){a(String(S))}else if(yo.Allow.STR&t)try{return JSON.parse(e.substring(y,n-Number(h))+'"')}catch{return JSON.parse(e.substring(y,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},u=()=>{n++,m();let y={};try{for(;e[n]!=="}";){if(m(),n>=o&&yo.Allow.OBJ&t)return y;let h=d();m(),n++;try{let S=i();y[h]=S}catch(S){if(yo.Allow.OBJ&t)return y;throw S}m(),e[n]===","&&n++}}catch{if(yo.Allow.OBJ&t)return y;r("Expected '}' at end of object")}return n++,y},c=()=>{n++;let y=[];try{for(;e[n]!=="]";)y.push(i()),m(),e[n]===","&&n++}catch{if(yo.Allow.ARR&t)return y;r("Expected ']' at end of array")}return n++,y},p=()=>{if(n===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(h){if(yo.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(h))}}let y=n;for(e[n]==="-"&&n++;e[n]&&",]}".indexOf(e[n])===-1;)n++;n==o&&!(yo.Allow.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(y,n))}catch{e.substring(y,n)==="-"&&r("Not sure what '-' is");try{return JSON.parse(e.substring(y,e.lastIndexOf("e")))}catch(S){a(String(S))}}},m=()=>{for(;n<o&&`
2
- \r `.includes(e[n]);)n++};return i()},WT=Lv;ro.parse=WT});var C0={};fT(C0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>qf,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Uf,ASK_USER_QUESTION_TOOL_NAME:()=>nl,AgentWidgetClient:()=>Os,AgentWidgetSession:()=>Da,AttachmentManager:()=>Fs,BrowserSpeechEngine:()=>Ds,DEFAULT_COMPONENTS:()=>ag,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>jc,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Vo,DEFAULT_PALETTE:()=>rg,DEFAULT_SEMANTIC:()=>sg,DEFAULT_WIDGET_CONFIG:()=>rt,HistoryProviderError:()=>ln,PRESETS:()=>vh,PRESET_FULLSCREEN:()=>bh,PRESET_MINIMAL:()=>yh,PRESET_SHOP:()=>hh,ReadAloudController:()=>Oa,SUGGEST_REPLIES_CLIENT_TOOL:()=>hc,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Nf,SUGGEST_REPLIES_TOOL_NAME:()=>Nn,THEME_ZONES:()=>OC,VERSION:()=>jr,WEBMCP_TOOL_PREFIX:()=>el,applyFeaturePreferences:()=>Jg,applyThemeVariables:()=>Us,attachHeaderToContainer:()=>js,buildComposer:()=>Ks,buildDefaultHeader:()=>wg,buildHeader:()=>pr,buildHeaderWithLayout:()=>Qa,buildMinimalHeader:()=>Ag,builtInClientToolsForDispatch:()=>Ra,canonicalArtifactDisplayMode:()=>Ho,collectEnrichedPageContext:()=>Nw,componentRegistry:()=>Cn,createActionManager:()=>ql,createAgentExperience:()=>$u,createAskUserQuestionBubble:()=>qv,createBubbleWithLayout:()=>vS,createCSATFeedback:()=>Fu,createComboButton:()=>yu,createComponentMiddleware:()=>bw,createComponentStreamParser:()=>Du,createDefaultSanitizer:()=>Ef,createDirectivePostprocessor:()=>lv,createDropdownMenu:()=>zs,createFlexibleJsonStreamParser:()=>Kv,createIconButton:()=>Vs,createImagePart:()=>Pc,createJsonStreamParser:()=>Mc,createLabelButton:()=>Sg,createLocalStorageAdapter:()=>Bu,createMarkdownProcessor:()=>Ji,createMarkdownProcessorFromConfig:()=>Zi,createMessageActions:()=>kg,createNPSFeedback:()=>Uu,createPlainTextParser:()=>wc,createRegexJsonParser:()=>Ac,createSplitButton:()=>uS,createStandardBubble:()=>Ya,createTextPart:()=>an,createTheme:()=>wl,createThemeObserver:()=>Va,createToggleGroup:()=>cS,createTypingIndicator:()=>Gs,createWidgetHostLayout:()=>jl,createXmlParser:()=>Tc,defaultActionHandlers:()=>Ys,defaultJsonActionParser:()=>Ul,defaultParseRules:()=>mh,detectColorScheme:()=>Al,directivePostprocessor:()=>dv,ensureAskUserQuestionSheet:()=>Ha,escapeHtml:()=>ir,extractComponentDirectiveFromMessage:()=>Nu,fileToImagePart:()=>Yv,formatEnrichedContext:()=>Fw,generateAssistantMessageId:()=>_r,generateMessageId:()=>Ev,generateStableSelector:()=>gh,generateUserMessageId:()=>La,getActiveTheme:()=>Vr,getColorScheme:()=>iu,getDisplayText:()=>Ec,getHeaderLayout:()=>Mg,getImageParts:()=>Qv,getPreset:()=>qw,hasComponentDirective:()=>$l,hasImages:()=>Ba,headerLayouts:()=>bu,initAgentWidget:()=>Pw,isAskUserQuestionMessage:()=>lr,isComponentDirectiveType:()=>yw,isDockedMountMode:()=>St,isHistoryProviderError:()=>xx,isSuggestRepliesMessage:()=>Bs,isWebMcpToolName:()=>Or,isWelcomeVisible:()=>Qr,latestAgentSuggestions:()=>yc,listRegisteredStreamAnimations:()=>gg,loadMarkdownParsers:()=>ic,markdownPostprocessor:()=>Tf,mergeWithDefaults:()=>ja,normalizeContent:()=>Xv,normalizeMediaType:()=>Dr,onMarkdownParsersReady:()=>Pa,parseAskUserQuestionPayload:()=>dr,parseSuggestRepliesPayload:()=>Ff,parseWidgetPreferenceSlice:()=>Yg,pickBestVoice:()=>cl,pluginRegistry:()=>Fl,registerIcons:()=>Hx,registerStreamAnimationPlugin:()=>Ka,removeAskUserQuestionSheet:()=>Ur,renderComponentDirective:()=>_u,renderLoadingIndicatorWithFallback:()=>Lg,renderLucideIcon:()=>ce,resolveArtifactDisplay:()=>Hf,resolveArtifactDisplayMode:()=>_n,resolveConfigPreferences:()=>Nl,resolveDockConfig:()=>Wo,resolveSanitizer:()=>lc,resolveTokens:()=>su,resolveWelcomeConfig:()=>xn,stripWebMcpPrefix:()=>If,themeToCssVariables:()=>au,unregisterStreamAnimationPlugin:()=>mg,validateImageFile:()=>Jv,validateTheme:()=>ig});var mt=e=>{let{fallbackImport:t,resetOnSetLoader:o=!1}=e,n=null,r=null,a=null;return{setLoader:p=>{n=p,o&&(r=null,a=null)},load:()=>r?Promise.resolve(r):a||(a=(n??t)().then(m=>(r=m,m)).catch(m=>{throw a=null,m}),a),provide:p=>{r=p},getSync:()=>r}};var{setLoader:gT,load:hT,provide:k0,getSync:Mf}=mt({fallbackImport:()=>import("./markdown-parsers-entry")}),ac=new Set,yT=()=>{let e=[...ac];ac.clear();for(let t of e)try{t()}catch{}},rv=gT,ic=()=>{let e=Mf();return e?Promise.resolve(e):hT().then(t=>(yT(),t))},Pa=e=>Mf()?()=>{}:(ac.add(e),()=>{ac.delete(e)});var Dn=Mf;var bT=e=>{if(!e)return;let t={},o=e;if(o.heading){let n=o.heading;t.heading=(r,a,i)=>n({type:"heading",raw:i,depth:a,text:r,tokens:[]})}if(o.code){let n=o.code;t.code=(r,a,i)=>n({type:"code",raw:"",text:r,lang:a,escaped:i})}if(o.blockquote){let n=o.blockquote;t.blockquote=r=>n({type:"blockquote",raw:"",text:r,tokens:[]})}if(o.table){let n=o.table;t.table=(r,a)=>n({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:a})}if(o.link){let n=o.link;t.link=(r,a,i)=>n({type:"link",raw:"",href:r,title:a??null,text:i,tokens:[]})}if(o.image){let n=o.image;t.image=(r,a,i)=>n({type:"image",raw:"",href:r,title:a??null,text:i})}if(o.list){let n=o.list;t.list=(r,a,i)=>n({type:"list",raw:"",ordered:a,start:i,loose:!1,items:[],itemsHtml:r})}if(o.listitem){let n=o.listitem;t.listitem=(r,a,i)=>n({type:"list_item",raw:"",task:a,checked:i,loose:!1,text:r,tokens:[]})}if(o.paragraph){let n=o.paragraph;t.paragraph=r=>n({type:"paragraph",raw:"",text:r,tokens:[]})}if(o.codespan){let n=o.codespan;t.codespan=r=>n({type:"codespan",raw:"",text:r})}if(o.strong){let n=o.strong;t.strong=r=>n({type:"strong",raw:"",text:r,tokens:[]})}if(o.em){let n=o.em;t.em=r=>n({type:"em",raw:"",text:r,tokens:[]})}if(o.del){let n=o.del;t.del=r=>n({type:"del",raw:"",text:r,tokens:[]})}if(o.html){let n=o.html;t.html=r=>n({type:"html",raw:r,text:r})}if(o.text){let n=o.text;t.text=r=>n({type:"text",raw:r,text:r})}if(o.checkbox){let n=o.checkbox;t.checkbox=r=>n({checked:r})}return o.hr&&(t.hr=o.hr),o.br&&(t.br=o.br),t},Ji=e=>{let t=null;return o=>{let n=Dn();if(!n)return ir(o);if(!t){let{Marked:r}=n,a=e?.markedOptions;t=new r({gfm:a?.gfm??!0,breaks:a?.breaks??!0,pedantic:a?.pedantic,silent:a?.silent});let i=bT(e?.renderer);i&&t.use({renderer:i})}return t.parse(o)}},Zi=e=>e?Ji({markedOptions:e.options,renderer:e.renderer}):Ji(),vT=Ji(),Tf=e=>vT(e),ir=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),av=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),sv=e=>`%%FORM_PLACEHOLDER_${e}%%`,iv=(e,t)=>{let o=e;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,r)=>{try{let a=JSON.parse(r.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let i=sv(t.length);return t.push({token:i,type:String(a.type)}),i}}catch{return n}return n}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,r)=>{let a=sv(t.length);return t.push({token:a,type:r}),a}),o},lv=e=>{let t=Zi(e);return o=>{let n=[],r=iv(o,n),a=t(r);return n.forEach(({token:i,type:d})=>{let u=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${av(d)}"></div>`;a=a.replace(u,p)}),a}},dv=e=>{let t=[],o=iv(e,t),n=Tf(o);return t.forEach(({token:r,type:a})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${av(a)}"></div>`;n=n.replace(i,u)}),n};var xT={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"]},CT=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ef=()=>{let e=null;return t=>{let o=Dn();if(!o)return ir(t);if(!e){let{DOMPurify:n}=o;e=n(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,a)=>{if(a.attrName==="src"||a.attrName==="href"){let i=a.attrValue;i.toLowerCase().startsWith("data:")&&!CT.test(i)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,xT)}},lc=e=>e===!1?null:typeof e=="function"?e:Ef();var cv=/^\s*\|?[\s:|-]*-[\s:|-]*$/,uv=e=>e.includes("|"),pv=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(o=>o.trim())},ST=e=>`| ${e.join(" | ")} |`,wT=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,AT=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),fv=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
3
- `),o=!1;for(let n=0;n<t.length-1;n++){let r=t[n],a=t[n+1];if(!uv(r)||cv.test(r)||!cv.test(a))continue;let i=pv(r).length;if(i<1)continue;let d=wT(i);t[n+1]!==d&&(t[n+1]=d,o=!0);let u=n+2;for(;u<t.length;u++){let c=t[u];if(c.trim()===""||!uv(c))break;let p=ST(AT(pv(c),i));t[u]!==p&&(t[u]=p,o=!0)}n=u-1}return o?t.join(`
4
- `):e};var mv="var(--persona-md-table-scroll-fade, 24px)",gv=new WeakSet;function yv(e){e.querySelectorAll("table").forEach(o=>{if(o.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",o.replaceWith(r),r.appendChild(o)})}function hv(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let n=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty("--persona-fade-l",n<=1?"0px":mv),e.style.setProperty("--persona-fade-r",r<=1?"0px":mv)}function Pf(e){gv.has(e)||(gv.add(e),e.addEventListener("scroll",t=>{let o=t.target;o?.classList?.contains("persona-table-scroll")&&hv(o)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(hv)}var el="webmcp:",Lf=new Map,vv=e=>{Lf.clear();for(let t of e){let o=t.title?.trim();o&&Lf.set(t.name,o)}},dc=e=>Lf.get(If(e)),kf=null,xv=e=>{kf=e};function Cv(e){if(e.length===0)return"0:empty";let t=e.map(o=>[o.name,o.description??"",o.parametersSchema?JSON.stringify(o.parametersSchema):"",o.origin??"",o.annotations?JSON.stringify(o.annotations):""].join("")).sort();return`${e.length}:${MT(t.join(""))}`}function bv(e,t){let o=3735928559^t,n=1103547991^t;for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);o=Math.imul(o^a,2654435761),n=Math.imul(n^a,1597334677)}return o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),4294967296*(2097151&n)+(o>>>0)}function MT(e){let t=bv(e,0).toString(36),o=bv(e,2654435761).toString(36);return`${t}.${o}`}var If=e=>e.startsWith(el)?e.slice(el.length):e,Or=e=>e.startsWith(el),Sv=()=>kf?kf():import("@mcp-b/webmcp-polyfill");var{setLoader:TT,load:ET}=mt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),wv=TT,Av=ET;function Ho(e){return e==="card"?"collapsed":e}function Dr(e){return e.split(";",1)[0].trim().toLowerCase()}function PT(e,t){if(!e)return;let o=Object.entries(e);for(let[r,a]of o)if(Dr(r)===t)return{mode:Ho(a),selector:Dr(r)};let n=`${t.split("/",1)[0]}/*`;for(let[r,a]of o)if(Dr(r)===n)return{mode:Ho(a),selector:n}}function Hf(e,t){let o=e?.display,n=typeof o=="string"?{default:o}:o??{};if(t.file&&n.files){if(typeof n.files=="string")return{mode:Ho(n.files),matchedBy:{type:"files"}};let d=t.file.mimeType?Dr(t.file.mimeType):void 0,u=d?PT(n.files.byMediaType,d):void 0;if(d&&u)return{mode:u.mode,matchedBy:{type:"mediaType",mediaType:d,selector:u.selector}};if(n.files.default)return{mode:Ho(n.files.default),matchedBy:{type:"files"}}}let r=n.byKind?.[t.artifactType];if(r)return{mode:Ho(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=n.byType?.[t.artifactType];if(a)return{mode:Ho(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:Ho(i),matchedBy:{type:"preferredMode"}}:n.default?{mode:Ho(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function _n(e,t){return Hf(e,t).mode}function tl(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var LT="agent_",kT="flow_";function Mv(e){return e.startsWith(LT)?{kind:"agentId",agentId:e}:e.startsWith(kT)?{kind:"flowId",flowId:e}:null}function Tv(e,t){let o=e.trim();if(!o)throw new Error("[Persona] `target` is empty.");let n=o.indexOf(":");if(n>0){let i=o.slice(0,n),d=o.slice(n+1);if(i==="runtype"){let c=Mv(d);if(c)return c;throw new Error(`[Persona] target "runtype:${d}" is not a valid Runtype agent_/flow_ id.`)}let u=t?.[i];if(!u)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:u(d).payload}}let r=Mv(o);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(o).payload};throw new Error(`[Persona] target "${o}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${o}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Ev(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function La(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function _r(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Pv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}var Nr=Zt(pc(),1);var I=(e,t)=>{let o=document.createElement(e);return t&&(o.className=t),o};var Y=(e,t={},...o)=>{let n=document.createElement(e);if(t.className&&(n.className=t.className),t.text!==void 0&&(n.textContent=t.text),t.attrs)for(let[a,i]of Object.entries(t.attrs))n.setAttribute(a,i);if(t.style){let a=n.style,i=t.style;for(let d of Object.keys(i)){let u=i[d];u!=null&&(a[d]=u)}}let r=o.filter(a=>a!=null);return r.length>0&&n.append(...r),n},bo=(...e)=>e.filter(Boolean).join(" ");var nl="ask_user_question",ol=8,ka="data-persona-ask-sheet-for",BT="Other",OT="Other\u2026",Iv="Type your own answer here",Hv="Send",DT="Next",_T="Back",NT="Submit all",FT="Skip",UT=3,Wf="data-ask-current-index",Bf="data-ask-question-count",Rv="data-ask-answers",Of="data-ask-grouped",Wv="data-ask-layout",qT=e=>e.layout==="pills"?"pills":"rows",$T=e=>e.getAttribute(Wv)==="pills"?"pills":"rows",kv=!1,Bv=e=>e.replace(/["\\]/g,"\\$&"),lr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===nl,fc=e=>e?.features?.askUserQuestion??{},dr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let o=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:o};let n=t.chunks;if(!n||n.length===0)return{payload:null,complete:o};try{let r=n.join(""),a=(0,Nr.parse)(r,Nr.STR|Nr.OBJ|Nr.ARR);if(a&&typeof a=="object")return{payload:a,complete:o}}catch{}return{payload:null,complete:o}},rl=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>ol&&!kv&&(kv=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ol}.`)),t.slice(0,ol)},jT=e=>rl(e)[0]??null,zT=(e,t)=>rl(e)[t]??null,Ov=(e,t)=>{let o=t.styles;o&&(o.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",o.sheetBackground),o.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",o.sheetBorder),o.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",o.sheetShadow),o.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",o.pillBackground),o.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",o.pillBackgroundSelected),o.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",o.pillTextColor),o.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",o.pillTextColorSelected),o.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",o.pillBorderRadius),o.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",o.customInputBackground))},Dv=(e,t,o)=>{if(e!=="rows")return null;let n=I("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let r=I("span","persona-ask-row-check");n.appendChild(r)}else{let r=I("span","persona-ask-row-badge");r.textContent=String(o+1),n.appendChild(r)}return n},VT=(e,t,o,n)=>{let a=I("button",o==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",n?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),o==="rows"){let i=I("span","persona-ask-row-content"),d=I("span","persona-ask-row-label");if(d.textContent=e.label,i.appendChild(d),e.description){let c=I("span","persona-ask-row-description");c.textContent=e.description,i.appendChild(c)}a.appendChild(i);let u=Dv(o,n,t);u&&a.appendChild(u)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},KT=e=>{let o=I("span",e==="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 o.setAttribute("aria-hidden","true"),o},GT=(e,t,o,n)=>{let a=I("div",n==="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");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let i=!!e?.multiSelect,u=(Array.isArray(e?.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(u.length===0&&!o){for(let p=0;p<UT;p++)a.appendChild(KT(n));return a}if(u.forEach((p,m)=>{a.appendChild(VT(p,m,n,i))}),e?.allowFreeText!==!1){let p=n==="rows"?BT:OT;if(n==="rows"){let m=I("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(u.length)),m.setAttribute("data-ask-other-row","true");let y=I("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=t.freeTextPlaceholder??Iv,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??p),y.appendChild(h),m.appendChild(y);let S=Dv(n,i,u.length);S&&m.appendChild(S),a.appendChild(m)}else{let m=I("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=t.freeTextLabel??p,a.appendChild(m)}}return a},_v=(e,t)=>{let n=I("div",t==="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");n.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=e.freeTextPlaceholder??Iv,r.setAttribute("data-ask-free-text-input","true"),n.appendChild(r),t!=="rows"){let a=I("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??Hv,a.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(a)}return n},XT=e=>{let t=I("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let o=I("button","persona-ask-multi-submit persona-pointer-events-auto");return o.type="button",o.textContent=e.submitLabel??Hv,o.setAttribute("data-ask-user-action","submit-multi"),o.disabled=!0,t.appendChild(o),t},QT=(e,t,o)=>{let n=I("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let r=I("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=o.backLabel??_T,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,n.appendChild(r);let a=I("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=I("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=o.skipLabel??FT,i.setAttribute("data-ask-user-action","skip"),a.appendChild(i);let d=I("button","persona-ask-nav-next persona-pointer-events-auto");d.type="button";let u=e===t-1;return d.textContent=u?o.submitAllLabel??NT:o.nextLabel??DT,d.setAttribute("data-ask-user-action",u?"submit-all":"next"),d.disabled=!0,a.appendChild(d),n.appendChild(a),n},Ws=e=>{let t=e.getAttribute(Rv);if(!t)return{};try{let o=JSON.parse(t);return o&&typeof o=="object"?o:{}}catch{return{}}},Nv=(e,t)=>{e.setAttribute(Rv,JSON.stringify(t))},sn=e=>{let t=Number(e.getAttribute(Wf)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},YT=(e,t)=>{e.setAttribute(Wf,String(Math.max(0,Math.floor(t))))},Ia=e=>{let t=Number(e.getAttribute(Bf)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Fr=e=>e.getAttribute(Of)==="true",JT=(e,t)=>{let o=e.agentMetadata?.askUserQuestionAnswers;if(!o||typeof o!="object")return{};let n={};return t.forEach((r,a)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(o,i)){let d=o[i];(typeof d=="string"||Array.isArray(d))&&(n[a]=d)}}),n},ZT=(e,t)=>{let o=e.agentMetadata?.askUserQuestionIndex;return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(t-1,Math.floor(o)))},mc=(e,t)=>{let{payload:o}=dr(t),n=rl(o),r=Ws(e),a={},i=new Set;return n.forEach((d,u)=>{let c=typeof d?.question=="string"?d.question:"";c&&(i.has(c)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),i.add(c),Object.prototype.hasOwnProperty.call(r,u)&&(a[c]=r[u]))}),a},Fv=e=>{let t=Ws(e),o=sn(e),n=t[o],r=new Set;typeof n=="string"?r.add(n):Array.isArray(n)&&n.forEach(u=>r.add(u));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(u=>{let c=u.getAttribute("data-option-label")??"",p=r.has(c);u.setAttribute("aria-pressed",p?"true":"false"),u.classList.toggle("persona-ask-pill-selected",p)});let i=new Set(Array.from(a).map(u=>u.getAttribute("data-option-label")??"")),d=e.querySelector('[data-ask-free-text-input="true"]');d&&(typeof n=="string"&&n.length>0&&!i.has(n)?(d.value=n,d.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):d.value="")},Uv=e=>{if(!Fr(e))return;let t=Ws(e),o=sn(e),n=t[o],r=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let d=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=d.length===0}},Df=(e,t,o)=>{let n=fc(o),r=$T(e),{payload:a,complete:i}=dr(t),d=Fr(e),u=sn(e),c=Ia(e),p=d?zT(a,u):jT(a),m=!!p?.multiSelect,y=e.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=d?`${u+1}/${c}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let S=e.querySelector('[data-ask-question="true"]');if(S){let P=typeof p?.question=="string"?p.question:"";S.textContent=P,S.classList.toggle("persona-ask-question-skeleton",!P&&!i)}let A=e.querySelector('[data-ask-pill-list="true"]');if(A){let P=GT(p,n,i,r);A.replaceWith(P)}if(r!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(_v(n,r))}let T=e.querySelector('[data-ask-multi-actions="true"]');!d&&m&&!T?e.appendChild(XT(n)):(!m||d)&&T&&T.remove(),e.setAttribute("data-multi-select",m?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(d){let P=QT(u,c,n);k?k.replaceWith(P):e.appendChild(P)}else k&&k.remove();Fv(e),Uv(e)},eE=(e,t,o)=>{let n=fc(t),r=qT(n),a=e.toolCall.id,i=rl(o),d=Math.max(1,i.length),u=d>1,c=JT(e,i),p=u?ZT(e,d):0,m=I("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(ka,a),m.setAttribute("data-tool-call-id",a),m.setAttribute("data-message-id",e.id),m.setAttribute(Bf,String(d)),m.setAttribute(Wf,String(p)),m.setAttribute(Of,u?"true":"false"),m.setAttribute(Wv,r),Nv(m,c),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),Ov(m,n);let y=I("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=I("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",y.appendChild(h);let S=I("span","persona-ask-sheet-step-inline");S.setAttribute("data-ask-step-inline","true"),S.textContent="",y.appendChild(S),m.appendChild(y);let T=I("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 T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),m.appendChild(T),r!=="rows"&&m.appendChild(_v(n,r)),Df(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},tE=(e,t,o)=>{let{payload:n}=dr(t),r=Math.max(1,rl(n).length);r>Ia(e)&&(e.setAttribute(Bf,String(r)),r>1&&!Fr(e)&&e.setAttribute(Of,"true")),Df(e,t,o)},qv=(e,t)=>{let o=I("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.setAttribute("data-bubble-type","ask-user-question");let n=fc(t);Ov(o,n);let r=I("span","persona-ask-stub-label"),{complete:a}=dr(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",o.appendChild(r),o},Ha=(e,t,o)=>{if(!o||!lr(e)||fc(t).enabled===!1)return;let r=e.toolCall.id;o.querySelectorAll(`[${ka}]`).forEach(c=>{c.getAttribute(ka)!==r&&c.remove()});let i=o.querySelector(`[${ka}="${Bv(r)}"]`);if(i){tE(i,e,t);return}let{payload:d}=dr(e),u=eE(e,t,d);o.appendChild(u)},Ur=(e,t)=>{if(!e)return;let o=t?`[${ka}="${Bv(t)}"]`:`[${ka}]`;e.querySelectorAll(o).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(a)?a:180)})},_f=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),qr=(e,t)=>{let o=Ws(e),n=sn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete o[n]:o[n]=t,Nv(e,o),Fv(e),Uv(e)},gc=(e,t,o,n)=>{let r=Ia(e),a=Math.max(0,Math.min(r-1,n));YT(e,a),Df(e,t,o)};var Nn="suggest_replies";var Nf={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},hc={name:Nn,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:Nf,origin:"sdk",annotations:{readOnlyHint:!0}},jv=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Bs=e=>e.variant==="tool"&&e.toolCall?.name===Nn,Ff=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let o=t?.suggestions;if(!Array.isArray(o))return[];let n=o.flatMap(r=>{if(typeof r=="string"){let d=r.trim();return d?[d]:[]}if(!r||typeof r!="object")return[];let a=r;if(typeof a.label!="string"||!a.label.trim())return[];let i={label:a.label.trim()};return typeof a.prompt=="string"&&a.prompt.trim()&&(i.prompt=a.prompt.trim()),typeof a.description=="string"&&a.description.trim()&&(i.description=a.description.trim()),[i]});return n.length>4?(console.warn(`[persona] suggest_replies: ${n.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),n.slice(0,4)):n},yc=e=>{for(let t=e.length-1;t>=0;t--){let o=e[t];if(o.role==="user")return null;if(!Bs(o))continue;let n=Ff(o.toolCall?.args);return n.length>0?n:null}return null},$v=new Set,oE=(e,t,o)=>{let n=`${e}:${t}:${o}`;$v.has(n)||($v.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},$r=e=>{let t=e?.suggestions?.followUps,o=e?.features?.suggestReplies,n=i=>{let d=t?.[i],u=o?.[i];d===void 0||u===void 0||d!==u&&oE(i,u,d)};e&&(n("enabled"),n("expose"));let r=t?.enabled??o?.enabled??!0,a=r?t?.expose??o?.expose??!1:!1;return{enabled:r,expose:a}};var Uf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ol,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},qf={name:nl,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:Uf,origin:"sdk",annotations:{readOnlyHint:!0}},Ra=e=>{let t=[],o=e?.features?.askUserQuestion;return o?.expose===!0&&o.enabled!==!1&&t.push(qf),$r(e).expose&&t.push(hc),t};var cr=Zt(pc(),1),bc=e=>e.replace(/\\n/g,`
5
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),vc=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},nE=e=>{let t=e.completedAt??Date.now(),o=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},zv=e=>e.status==="complete"?nE(e):e.status==="pending"?"Waiting":"",rE=e=>{let o=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var Vv=e=>e.status==="complete"?rE(e):"Using tool...",xc=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},al=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return xc(t)},Cc=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return xc(t)},$f=(e,t,o)=>{if(!t)return o;let n=e.name?.trim()||"tool",r=al(e);return t.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,r)},Sc=(e,t)=>{let o=e.replace(/\{toolName\}/g,t),n=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,i;for(;(i=r.exec(o))!==null;)i.index>a&&sl(n,o.slice(a,i.index),[]),i[1]!==void 0?sl(n,i[1],["bold"]):i[2]!==void 0?sl(n,i[2],["italic"]):i[3]!==void 0&&sl(n,i[3],["dim"]),a=i.index+i[0].length;return a<o.length&&sl(n,o.slice(a),[]),n},sl=(e,t,o)=>{let n=t.split("{duration}");for(let r=0;r<n.length;r++)n[r]&&e.push({text:n[r],styles:o}),r<n.length-1&&e.push({text:"{duration}",styles:o,isDuration:!0})},sE=()=>{let e=null,t=0,o=n=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=n.match(r);if(a&&a[1])try{return a[1].replace(/\\n/g,`
1
+ "use strict";var AgentWidget=(()=>{var uT=Object.create;var sc=Object.defineProperty;var pT=Object.getOwnPropertyDescriptor;var fT=Object.getOwnPropertyNames;var mT=Object.getPrototypeOf,gT=Object.prototype.hasOwnProperty;var ho=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var av=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),hT=(e,t)=>{for(var o in t)sc(e,o,{get:t[o],enumerable:!0})},iv=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of fT(t))!gT.call(e,r)&&r!==o&&sc(e,r,{get:()=>t[r],enumerable:!(n=pT(t,r))||n.enumerable});return e};var Zt=(e,t,o)=>(o=e!=null?uT(mT(e)):{},iv(t||!e||!e.__esModule?sc(o,"default",{value:e,enumerable:!0}):o,e)),yT=e=>iv(sc({},"__esModule",{value:!0}),e);var Bf=av(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.Allow=be.ALL=be.COLLECTION=be.ATOM=be.SPECIAL=be.INF=be._INFINITY=be.INFINITY=be.NAN=be.BOOL=be.NULL=be.OBJ=be.ARR=be.NUM=be.STR=void 0;be.STR=1;be.NUM=2;be.ARR=4;be.OBJ=8;be.NULL=16;be.BOOL=32;be.NAN=64;be.INFINITY=128;be._INFINITY=256;be.INF=be.INFINITY|be._INFINITY;be.SPECIAL=be.NULL|be.BOOL|be.INF|be.NAN;be.ATOM=be.STR|be.NUM|be.SPECIAL;be.COLLECTION=be.ARR|be.OBJ;be.ALL=be.ATOM|be.COLLECTION;be.Allow={STR:be.STR,NUM:be.NUM,ARR:be.ARR,OBJ:be.OBJ,NULL:be.NULL,BOOL:be.BOOL,NAN:be.NAN,INFINITY:be.INFINITY,_INFINITY:be._INFINITY,INF:be.INF,SPECIAL:be.SPECIAL,ATOM:be.ATOM,COLLECTION:be.COLLECTION,ALL:be.ALL};be.default=be.Allow});var pc=av(ro=>{"use strict";var WT=ro&&ro.__createBinding||(Object.create?(function(e,t,o,n){n===void 0&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}):(function(e,t,o,n){n===void 0&&(n=o),e[n]=t[o]})),BT=ro&&ro.__exportStar||function(e,t){for(var o in e)o!=="default"&&!Object.prototype.hasOwnProperty.call(t,o)&&WT(t,e,o)};Object.defineProperty(ro,"__esModule",{value:!0});ro.Allow=ro.MalformedJSON=ro.PartialJSON=ro.parseJSON=ro.parse=void 0;var yo=Bf();Object.defineProperty(ro,"Allow",{enumerable:!0,get:function(){return yo.Allow}});BT(Bf(),ro);var cc=class extends Error{};ro.PartialJSON=cc;var uc=class extends Error{};ro.MalformedJSON=uc;function Hv(e,t=yo.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return OT(e.trim(),t)}ro.parseJSON=Hv;var OT=(e,t)=>{let o=e.length,n=0,r=h=>{throw new cc(`${h} at position ${n}`)},a=h=>{throw new uc(`${h} at position ${n}`)},i=()=>(m(),n>=o&&r("Unexpected end of input"),e[n]==='"'?d():e[n]==="{"?c():e[n]==="["?u():e.substring(n,n+4)==="null"||yo.Allow.NULL&t&&o-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||yo.Allow.BOOL&t&&o-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||yo.Allow.BOOL&t&&o-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||yo.Allow.INFINITY&t&&o-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||yo.Allow._INFINITY&t&&1<o-n&&o-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||yo.Allow.NAN&t&&o-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):p()),d=()=>{let h=n,y=!1;for(n++;n<o&&(e[n]!=='"'||y&&e[n-1]==="\\");)y=e[n]==="\\"?!y:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(h,++n-Number(y)))}catch(x){a(String(x))}else if(yo.Allow.STR&t)try{return JSON.parse(e.substring(h,n-Number(y))+'"')}catch{return JSON.parse(e.substring(h,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{n++,m();let h={};try{for(;e[n]!=="}";){if(m(),n>=o&&yo.Allow.OBJ&t)return h;let y=d();m(),n++;try{let x=i();h[y]=x}catch(x){if(yo.Allow.OBJ&t)return h;throw x}m(),e[n]===","&&n++}}catch{if(yo.Allow.OBJ&t)return h;r("Expected '}' at end of object")}return n++,h},u=()=>{n++;let h=[];try{for(;e[n]!=="]";)h.push(i()),m(),e[n]===","&&n++}catch{if(yo.Allow.ARR&t)return h;r("Expected ']' at end of array")}return n++,h},p=()=>{if(n===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(y){if(yo.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(y))}}let h=n;for(e[n]==="-"&&n++;e[n]&&",]}".indexOf(e[n])===-1;)n++;n==o&&!(yo.Allow.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(h,n))}catch{e.substring(h,n)==="-"&&r("Not sure what '-' is");try{return JSON.parse(e.substring(h,e.lastIndexOf("e")))}catch(x){a(String(x))}}},m=()=>{for(;n<o&&`
2
+ \r `.includes(e[n]);)n++};return i()},DT=Hv;ro.parse=DT});var E0={};hT(E0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Vf,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>$f,ASK_USER_QUESTION_TOOL_NAME:()=>nl,AgentWidgetClient:()=>Os,AgentWidgetSession:()=>_a,AttachmentManager:()=>Fs,BrowserSpeechEngine:()=>Ds,DEFAULT_COMPONENTS:()=>dg,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Vc,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>zo,DEFAULT_PALETTE:()=>ig,DEFAULT_SEMANTIC:()=>lg,DEFAULT_WIDGET_CONFIG:()=>rt,HistoryProviderError:()=>ln,PRESETS:()=>Sh,PRESET_FULLSCREEN:()=>Ch,PRESET_MINIMAL:()=>xh,PRESET_SHOP:()=>vh,ReadAloudController:()=>Da,SUGGEST_REPLIES_CLIENT_TOOL:()=>hc,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Uf,SUGGEST_REPLIES_TOOL_NAME:()=>Fn,THEME_ZONES:()=>NC,VERSION:()=>Un,WEBMCP_TOOL_PREFIX:()=>el,applyFeaturePreferences:()=>th,applyThemeVariables:()=>Us,attachHeaderToContainer:()=>Vs,buildComposer:()=>Ks,buildDefaultHeader:()=>Tg,buildHeader:()=>mr,buildHeaderWithLayout:()=>Ya,buildMinimalHeader:()=>Eg,builtInClientToolsForDispatch:()=>Wa,canonicalArtifactDisplayMode:()=>Ro,collectEnrichedPageContext:()=>qw,componentRegistry:()=>Cn,createActionManager:()=>ql,createAgentExperience:()=>Vu,createAskUserQuestionBubble:()=>zv,createBubbleWithLayout:()=>SS,createCSATFeedback:()=>Uu,createComboButton:()=>bu,createComponentMiddleware:()=>Cw,createComponentStreamParser:()=>_u,createDefaultSanitizer:()=>kf,createDirectivePostprocessor:()=>pv,createDropdownMenu:()=>js,createFlexibleJsonStreamParser:()=>Yv,createIconButton:()=>zs,createImagePart:()=>Pc,createJsonStreamParser:()=>Mc,createLabelButton:()=>Mg,createLocalStorageAdapter:()=>Ou,createMarkdownProcessor:()=>Ji,createMarkdownProcessorFromConfig:()=>Zi,createMessageActions:()=>Hg,createNPSFeedback:()=>qu,createPlainTextParser:()=>wc,createRegexJsonParser:()=>Ac,createSplitButton:()=>mS,createStandardBubble:()=>Ja,createTextPart:()=>an,createTheme:()=>wl,createThemeObserver:()=>Ka,createToggleGroup:()=>fS,createTypingIndicator:()=>Gs,createWidgetHostLayout:()=>Vl,createXmlParser:()=>Tc,defaultActionHandlers:()=>Ys,defaultJsonActionParser:()=>Ul,defaultParseRules:()=>yh,detectColorScheme:()=>Al,directivePostprocessor:()=>fv,ensureAskUserQuestionSheet:()=>Ha,escapeHtml:()=>dr,extractComponentDirectiveFromMessage:()=>Fu,fileToImagePart:()=>tx,formatEnrichedContext:()=>$w,generateAssistantMessageId:()=>Fr,generateMessageId:()=>Iv,generateStableSelector:()=>bh,generateUserMessageId:()=>La,getActiveTheme:()=>Kr,getColorScheme:()=>lu,getDisplayText:()=>Ec,getHeaderLayout:()=>Pg,getImageParts:()=>ex,getPreset:()=>jw,hasComponentDirective:()=>$l,hasImages:()=>Oa,headerLayouts:()=>vu,initAgentWidget:()=>Iw,isAskUserQuestionMessage:()=>cr,isComponentDirectiveType:()=>xw,isDockedMountMode:()=>St,isHistoryProviderError:()=>wx,isSuggestRepliesMessage:()=>Bs,isWebMcpToolName:()=>_r,isWelcomeVisible:()=>Yr,latestAgentSuggestions:()=>yc,listRegisteredStreamAnimations:()=>bg,loadMarkdownParsers:()=>ic,markdownPostprocessor:()=>Pf,mergeWithDefaults:()=>ja,normalizeContent:()=>Zv,normalizeMediaType:()=>Nr,onMarkdownParsersReady:()=>ka,parseAskUserQuestionPayload:()=>ur,parseSuggestRepliesPayload:()=>qf,parseWidgetPreferenceSlice:()=>eh,pickBestVoice:()=>cl,pluginRegistry:()=>Fl,registerIcons:()=>Bx,registerStreamAnimationPlugin:()=>Ga,removeAskUserQuestionSheet:()=>$r,renderComponentDirective:()=>Nu,renderLoadingIndicatorWithFallback:()=>Rg,renderLucideIcon:()=>ce,resolveArtifactDisplay:()=>Wf,resolveArtifactDisplayMode:()=>Nn,resolveConfigPreferences:()=>Nl,resolveDockConfig:()=>Wo,resolveSanitizer:()=>lc,resolveTokens:()=>au,resolveWelcomeConfig:()=>xn,stripWebMcpPrefix:()=>Hf,themeToCssVariables:()=>iu,unregisterStreamAnimationPlugin:()=>yg,validateImageFile:()=>ox,validateTheme:()=>cg});var mt=e=>{let{fallbackImport:t,resetOnSetLoader:o=!1}=e,n=null,r=null,a=null;return{setLoader:p=>{n=p,o&&(r=null,a=null)},load:()=>r?Promise.resolve(r):a||(a=(n??t)().then(m=>(r=m,m)).catch(m=>{throw a=null,m}),a),provide:p=>{r=p},getSync:()=>r}};var{setLoader:bT,load:vT,provide:O0,getSync:Ef}=mt({fallbackImport:()=>import("./markdown-parsers-entry")}),ac=new Set,xT=()=>{let e=[...ac];ac.clear();for(let t of e)try{t()}catch{}},lv=bT,ic=()=>{let e=Ef();return e?Promise.resolve(e):vT().then(t=>(xT(),t))},ka=e=>Ef()?()=>{}:(ac.add(e),()=>{ac.delete(e)});var _n=Ef;var CT=e=>{if(!e)return;let t={},o=e;if(o.heading){let n=o.heading;t.heading=(r,a,i)=>n({type:"heading",raw:i,depth:a,text:r,tokens:[]})}if(o.code){let n=o.code;t.code=(r,a,i)=>n({type:"code",raw:"",text:r,lang:a,escaped:i})}if(o.blockquote){let n=o.blockquote;t.blockquote=r=>n({type:"blockquote",raw:"",text:r,tokens:[]})}if(o.table){let n=o.table;t.table=(r,a)=>n({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:a})}if(o.link){let n=o.link;t.link=(r,a,i)=>n({type:"link",raw:"",href:r,title:a??null,text:i,tokens:[]})}if(o.image){let n=o.image;t.image=(r,a,i)=>n({type:"image",raw:"",href:r,title:a??null,text:i})}if(o.list){let n=o.list;t.list=(r,a,i)=>n({type:"list",raw:"",ordered:a,start:i,loose:!1,items:[],itemsHtml:r})}if(o.listitem){let n=o.listitem;t.listitem=(r,a,i)=>n({type:"list_item",raw:"",task:a,checked:i,loose:!1,text:r,tokens:[]})}if(o.paragraph){let n=o.paragraph;t.paragraph=r=>n({type:"paragraph",raw:"",text:r,tokens:[]})}if(o.codespan){let n=o.codespan;t.codespan=r=>n({type:"codespan",raw:"",text:r})}if(o.strong){let n=o.strong;t.strong=r=>n({type:"strong",raw:"",text:r,tokens:[]})}if(o.em){let n=o.em;t.em=r=>n({type:"em",raw:"",text:r,tokens:[]})}if(o.del){let n=o.del;t.del=r=>n({type:"del",raw:"",text:r,tokens:[]})}if(o.html){let n=o.html;t.html=r=>n({type:"html",raw:r,text:r})}if(o.text){let n=o.text;t.text=r=>n({type:"text",raw:r,text:r})}if(o.checkbox){let n=o.checkbox;t.checkbox=r=>n({checked:r})}return o.hr&&(t.hr=o.hr),o.br&&(t.br=o.br),t},Ji=e=>{let t=null;return o=>{let n=_n();if(!n)return dr(o);if(!t){let{Marked:r}=n,a=e?.markedOptions;t=new r({gfm:a?.gfm??!0,breaks:a?.breaks??!0,pedantic:a?.pedantic,silent:a?.silent});let i=CT(e?.renderer);i&&t.use({renderer:i})}return t.parse(o)}},Zi=e=>e?Ji({markedOptions:e.options,renderer:e.renderer}):Ji(),ST=Ji(),Pf=e=>ST(e),dr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),cv=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),dv=e=>`%%FORM_PLACEHOLDER_${e}%%`,uv=(e,t)=>{let o=e;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,r)=>{try{let a=JSON.parse(r.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let i=dv(t.length);return t.push({token:i,type:String(a.type)}),i}}catch{return n}return n}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,r)=>{let a=dv(t.length);return t.push({token:a,type:r}),a}),o},pv=e=>{let t=Zi(e);return o=>{let n=[],r=uv(o,n),a=t(r);return n.forEach(({token:i,type:d})=>{let c=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${cv(d)}"></div>`;a=a.replace(c,p)}),a}},fv=e=>{let t=[],o=uv(e,t),n=Pf(o);return t.forEach(({token:r,type:a})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${cv(a)}"></div>`;n=n.replace(i,c)}),n};var wT={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"]},AT=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,kf=()=>{let e=null;return t=>{let o=_n();if(!o)return dr(t);if(!e){let{DOMPurify:n}=o;e=n(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,a)=>{if(a.attrName==="src"||a.attrName==="href"){let i=a.attrValue;i.toLowerCase().startsWith("data:")&&!AT.test(i)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,wT)}},lc=e=>e===!1?null:typeof e=="function"?e:kf();var mv=/^\s*\|?[\s:|-]*-[\s:|-]*$/,gv=e=>e.includes("|"),hv=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(o=>o.trim())},MT=e=>`| ${e.join(" | ")} |`,TT=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,ET=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),yv=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
3
+ `),o=!1;for(let n=0;n<t.length-1;n++){let r=t[n],a=t[n+1];if(!gv(r)||mv.test(r)||!mv.test(a))continue;let i=hv(r).length;if(i<1)continue;let d=TT(i);t[n+1]!==d&&(t[n+1]=d,o=!0);let c=n+2;for(;c<t.length;c++){let u=t[c];if(u.trim()===""||!gv(u))break;let p=MT(ET(hv(u),i));t[c]!==p&&(t[c]=p,o=!0)}n=c-1}return o?t.join(`
4
+ `):e};var bv="var(--persona-md-table-scroll-fade, 24px)",vv=new WeakSet;function Cv(e){e.querySelectorAll("table").forEach(o=>{if(o.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",o.replaceWith(r),r.appendChild(o)})}function xv(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let n=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty("--persona-fade-l",n<=1?"0px":bv),e.style.setProperty("--persona-fade-r",r<=1?"0px":bv)}function Lf(e){vv.has(e)||(vv.add(e),e.addEventListener("scroll",t=>{let o=t.target;o?.classList?.contains("persona-table-scroll")&&xv(o)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(xv)}var el="webmcp:",If=new Map,wv=e=>{If.clear();for(let t of e){let o=t.title?.trim();o&&If.set(t.name,o)}},dc=e=>If.get(Hf(e)),Rf=null,Av=e=>{Rf=e};function Mv(e){if(e.length===0)return"0:empty";let t=e.map(o=>[o.name,o.description??"",o.parametersSchema?JSON.stringify(o.parametersSchema):"",o.origin??"",o.annotations?JSON.stringify(o.annotations):""].join("")).sort();return`${e.length}:${PT(t.join(""))}`}function Sv(e,t){let o=3735928559^t,n=1103547991^t;for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);o=Math.imul(o^a,2654435761),n=Math.imul(n^a,1597334677)}return o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),4294967296*(2097151&n)+(o>>>0)}function PT(e){let t=Sv(e,0).toString(36),o=Sv(e,2654435761).toString(36);return`${t}.${o}`}var Hf=e=>e.startsWith(el)?e.slice(el.length):e,_r=e=>e.startsWith(el),Tv=()=>Rf?Rf():import("@mcp-b/webmcp-polyfill");var{setLoader:kT,load:LT}=mt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),Ev=kT,Pv=LT;function Ro(e){return e==="card"?"collapsed":e}function Nr(e){return e.split(";",1)[0].trim().toLowerCase()}function IT(e,t){if(!e)return;let o=Object.entries(e);for(let[r,a]of o)if(Nr(r)===t)return{mode:Ro(a),selector:Nr(r)};let n=`${t.split("/",1)[0]}/*`;for(let[r,a]of o)if(Nr(r)===n)return{mode:Ro(a),selector:n}}function Wf(e,t){let o=e?.display,n=typeof o=="string"?{default:o}:o??{};if(t.file&&n.files){if(typeof n.files=="string")return{mode:Ro(n.files),matchedBy:{type:"files"}};let d=t.file.mimeType?Nr(t.file.mimeType):void 0,c=d?IT(n.files.byMediaType,d):void 0;if(d&&c)return{mode:c.mode,matchedBy:{type:"mediaType",mediaType:d,selector:c.selector}};if(n.files.default)return{mode:Ro(n.files.default),matchedBy:{type:"files"}}}let r=n.byKind?.[t.artifactType];if(r)return{mode:Ro(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=n.byType?.[t.artifactType];if(a)return{mode:Ro(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:Ro(i),matchedBy:{type:"preferredMode"}}:n.default?{mode:Ro(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Nn(e,t){return Wf(e,t).mode}function tl(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var RT="agent_",HT="flow_";function kv(e){return e.startsWith(RT)?{kind:"agentId",agentId:e}:e.startsWith(HT)?{kind:"flowId",flowId:e}:null}function Lv(e,t){let o=e.trim();if(!o)throw new Error("[Persona] `target` is empty.");let n=o.indexOf(":");if(n>0){let i=o.slice(0,n),d=o.slice(n+1);if(i==="runtype"){let u=kv(d);if(u)return u;throw new Error(`[Persona] target "runtype:${d}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(d).payload}}let r=kv(o);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(o).payload};throw new Error(`[Persona] target "${o}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${o}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Iv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function La(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Fr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Rv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}var Ur=Zt(pc(),1);var I=(e,t)=>{let o=document.createElement(e);return t&&(o.className=t),o};var Y=(e,t={},...o)=>{let n=document.createElement(e);if(t.className&&(n.className=t.className),t.text!==void 0&&(n.textContent=t.text),t.attrs)for(let[a,i]of Object.entries(t.attrs))n.setAttribute(a,i);if(t.style){let a=n.style,i=t.style;for(let d of Object.keys(i)){let c=i[d];c!=null&&(a[d]=c)}}let r=o.filter(a=>a!=null);return r.length>0&&n.append(...r),n},bo=(...e)=>e.filter(Boolean).join(" ");var nl="ask_user_question",ol=8,Ia="data-persona-ask-sheet-for",_T="Other",NT="Other\u2026",Bv="Type your own answer here",Ov="Send",FT="Next",UT="Back",qT="Submit all",$T="Skip",VT=3,Of="data-ask-current-index",Df="data-ask-question-count",Dv="data-ask-answers",_f="data-ask-grouped",_v="data-ask-layout",jT=e=>e.layout==="pills"?"pills":"rows",zT=e=>e.getAttribute(_v)==="pills"?"pills":"rows",Wv=!1,Nv=e=>e.replace(/["\\]/g,"\\$&"),cr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===nl,fc=e=>e?.features?.askUserQuestion??{},ur=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let o=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:o};let n=t.chunks;if(!n||n.length===0)return{payload:null,complete:o};try{let r=n.join(""),a=(0,Ur.parse)(r,Ur.STR|Ur.OBJ|Ur.ARR);if(a&&typeof a=="object")return{payload:a,complete:o}}catch{}return{payload:null,complete:o}},rl=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>ol&&!Wv&&(Wv=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ol}.`)),t.slice(0,ol)},KT=e=>rl(e)[0]??null,GT=(e,t)=>rl(e)[t]??null,Fv=(e,t)=>{let o=t.styles;o&&(o.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",o.sheetBackground),o.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",o.sheetBorder),o.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",o.sheetShadow),o.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",o.pillBackground),o.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",o.pillBackgroundSelected),o.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",o.pillTextColor),o.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",o.pillTextColorSelected),o.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",o.pillBorderRadius),o.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",o.customInputBackground))},Uv=(e,t,o)=>{if(e!=="rows")return null;let n=I("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let r=I("span","persona-ask-row-check");n.appendChild(r)}else{let r=I("span","persona-ask-row-badge");r.textContent=String(o+1),n.appendChild(r)}return n},XT=(e,t,o,n)=>{let a=I("button",o==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",n?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),o==="rows"){let i=I("span","persona-ask-row-content"),d=I("span","persona-ask-row-label");if(d.textContent=e.label,i.appendChild(d),e.description){let u=I("span","persona-ask-row-description");u.textContent=e.description,i.appendChild(u)}a.appendChild(i);let c=Uv(o,n,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},QT=e=>{let o=I("span",e==="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 o.setAttribute("aria-hidden","true"),o},YT=(e,t,o,n)=>{let a=I("div",n==="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");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let i=!!e?.multiSelect,c=(Array.isArray(e?.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(c.length===0&&!o){for(let p=0;p<VT;p++)a.appendChild(QT(n));return a}if(c.forEach((p,m)=>{a.appendChild(XT(p,m,n,i))}),e?.allowFreeText!==!1){let p=n==="rows"?_T:NT;if(n==="rows"){let m=I("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 h=I("span","persona-ask-row-content"),y=document.createElement("input");y.type="text",y.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",y.placeholder=t.freeTextPlaceholder??Bv,y.setAttribute("data-ask-free-text-input","true"),y.setAttribute("aria-label",t.freeTextLabel??p),h.appendChild(y),m.appendChild(h);let x=Uv(n,i,c.length);x&&m.appendChild(x),a.appendChild(m)}else{let m=I("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=t.freeTextLabel??p,a.appendChild(m)}}return a},qv=(e,t)=>{let n=I("div",t==="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");n.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=e.freeTextPlaceholder??Bv,r.setAttribute("data-ask-free-text-input","true"),n.appendChild(r),t!=="rows"){let a=I("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??Ov,a.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(a)}return n},JT=e=>{let t=I("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let o=I("button","persona-ask-multi-submit persona-pointer-events-auto");return o.type="button",o.textContent=e.submitLabel??Ov,o.setAttribute("data-ask-user-action","submit-multi"),o.disabled=!0,t.appendChild(o),t},ZT=(e,t,o)=>{let n=I("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let r=I("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=o.backLabel??UT,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,n.appendChild(r);let a=I("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=I("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=o.skipLabel??$T,i.setAttribute("data-ask-user-action","skip"),a.appendChild(i);let d=I("button","persona-ask-nav-next persona-pointer-events-auto");d.type="button";let c=e===t-1;return d.textContent=c?o.submitAllLabel??qT:o.nextLabel??FT,d.setAttribute("data-ask-user-action",c?"submit-all":"next"),d.disabled=!0,a.appendChild(d),n.appendChild(a),n},Ws=e=>{let t=e.getAttribute(Dv);if(!t)return{};try{let o=JSON.parse(t);return o&&typeof o=="object"?o:{}}catch{return{}}},$v=(e,t)=>{e.setAttribute(Dv,JSON.stringify(t))},sn=e=>{let t=Number(e.getAttribute(Of)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},eE=(e,t)=>{e.setAttribute(Of,String(Math.max(0,Math.floor(t))))},Ra=e=>{let t=Number(e.getAttribute(Df)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},qr=e=>e.getAttribute(_f)==="true",tE=(e,t)=>{let o=e.agentMetadata?.askUserQuestionAnswers;if(!o||typeof o!="object")return{};let n={};return t.forEach((r,a)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(o,i)){let d=o[i];(typeof d=="string"||Array.isArray(d))&&(n[a]=d)}}),n},oE=(e,t)=>{let o=e.agentMetadata?.askUserQuestionIndex;return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(t-1,Math.floor(o)))},mc=(e,t)=>{let{payload:o}=ur(t),n=rl(o),r=Ws(e),a={},i=new Set;return n.forEach((d,c)=>{let u=typeof d?.question=="string"?d.question:"";u&&(i.has(u)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${u}"; later answer wins.`),i.add(u),Object.prototype.hasOwnProperty.call(r,c)&&(a[u]=r[c]))}),a},Vv=e=>{let t=Ws(e),o=sn(e),n=t[o],r=new Set;typeof n=="string"?r.add(n):Array.isArray(n)&&n.forEach(c=>r.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{let u=c.getAttribute("data-option-label")??"",p=r.has(u);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let i=new Set(Array.from(a).map(c=>c.getAttribute("data-option-label")??"")),d=e.querySelector('[data-ask-free-text-input="true"]');d&&(typeof n=="string"&&n.length>0&&!i.has(n)?(d.value=n,d.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):d.value="")},jv=e=>{if(!qr(e))return;let t=Ws(e),o=sn(e),n=t[o],r=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let d=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=d.length===0}},Nf=(e,t,o)=>{let n=fc(o),r=zT(e),{payload:a,complete:i}=ur(t),d=qr(e),c=sn(e),u=Ra(e),p=d?GT(a,c):KT(a),m=!!p?.multiSelect,h=e.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=d?`${c+1}/${u}`:"");let y=e.querySelector('[data-ask-stepper="true"]');y&&y.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let P=typeof p?.question=="string"?p.question:"";x.textContent=P,x.classList.toggle("persona-ask-question-skeleton",!P&&!i)}let T=e.querySelector('[data-ask-pill-list="true"]');if(T){let P=YT(p,n,i,r);T.replaceWith(P)}if(r!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(qv(n,r))}let w=e.querySelector('[data-ask-multi-actions="true"]');!d&&m&&!w?e.appendChild(JT(n)):(!m||d)&&w&&w.remove(),e.setAttribute("data-multi-select",m?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(d){let P=ZT(c,u,n);k?k.replaceWith(P):e.appendChild(P)}else k&&k.remove();Vv(e),jv(e)},nE=(e,t,o)=>{let n=fc(t),r=jT(n),a=e.toolCall.id,i=rl(o),d=Math.max(1,i.length),c=d>1,u=tE(e,i),p=c?oE(e,d):0,m=I("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Ia,a),m.setAttribute("data-tool-call-id",a),m.setAttribute("data-message-id",e.id),m.setAttribute(Df,String(d)),m.setAttribute(Of,String(p)),m.setAttribute(_f,c?"true":"false"),m.setAttribute(_v,r),$v(m,u),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),Fv(m,n);let h=I("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),y=I("div","persona-ask-sheet-question persona-flex-1");y.setAttribute("data-ask-question","true"),y.textContent="",h.appendChild(y);let x=I("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",h.appendChild(x),m.appendChild(h);let w=I("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 w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),m.appendChild(w),r!=="rows"&&m.appendChild(qv(n,r)),Nf(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},rE=(e,t,o)=>{let{payload:n}=ur(t),r=Math.max(1,rl(n).length);r>Ra(e)&&(e.setAttribute(Df,String(r)),r>1&&!qr(e)&&e.setAttribute(_f,"true")),Nf(e,t,o)},zv=(e,t)=>{let o=I("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.setAttribute("data-bubble-type","ask-user-question");let n=fc(t);Fv(o,n);let r=I("span","persona-ask-stub-label"),{complete:a}=ur(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",o.appendChild(r),o},Ha=(e,t,o)=>{if(!o||!cr(e)||fc(t).enabled===!1)return;let r=e.toolCall.id;o.querySelectorAll(`[${Ia}]`).forEach(u=>{u.getAttribute(Ia)!==r&&u.remove()});let i=o.querySelector(`[${Ia}="${Nv(r)}"]`);if(i){rE(i,e,t);return}let{payload:d}=ur(e),c=nE(e,t,d);o.appendChild(c)},$r=(e,t)=>{if(!e)return;let o=t?`[${Ia}="${Nv(t)}"]`:`[${Ia}]`;e.querySelectorAll(o).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(a)?a:180)})},Ff=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Vr=(e,t)=>{let o=Ws(e),n=sn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete o[n]:o[n]=t,$v(e,o),Vv(e),jv(e)},gc=(e,t,o,n)=>{let r=Ra(e),a=Math.max(0,Math.min(r-1,n));eE(e,a),Nf(e,t,o)};var Fn="suggest_replies";var Uf={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},hc={name:Fn,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:Uf,origin:"sdk",annotations:{readOnlyHint:!0}},Gv=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Bs=e=>e.variant==="tool"&&e.toolCall?.name===Fn,qf=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let o=t?.suggestions;if(!Array.isArray(o))return[];let n=o.flatMap(r=>{if(typeof r=="string"){let d=r.trim();return d?[d]:[]}if(!r||typeof r!="object")return[];let a=r;if(typeof a.label!="string"||!a.label.trim())return[];let i={label:a.label.trim()};return typeof a.prompt=="string"&&a.prompt.trim()&&(i.prompt=a.prompt.trim()),typeof a.description=="string"&&a.description.trim()&&(i.description=a.description.trim()),[i]});return n.length>4?(console.warn(`[persona] suggest_replies: ${n.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),n.slice(0,4)):n},yc=e=>{for(let t=e.length-1;t>=0;t--){let o=e[t];if(o.role==="user")return null;if(!Bs(o))continue;let n=qf(o.toolCall?.args);return n.length>0?n:null}return null},Kv=new Set,sE=(e,t,o)=>{let n=`${e}:${t}:${o}`;Kv.has(n)||(Kv.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},jr=e=>{let t=e?.suggestions?.followUps,o=e?.features?.suggestReplies,n=i=>{let d=t?.[i],c=o?.[i];d===void 0||c===void 0||d!==c&&sE(i,c,d)};e&&(n("enabled"),n("expose"));let r=t?.enabled??o?.enabled??!0,a=r?t?.expose??o?.expose??!1:!1;return{enabled:r,expose:a}};var $f={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ol,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},Vf={name:nl,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:$f,origin:"sdk",annotations:{readOnlyHint:!0}},Wa=e=>{let t=[],o=e?.features?.askUserQuestion;return o?.expose===!0&&o.enabled!==!1&&t.push(Vf),jr(e).expose&&t.push(hc),t};var pr=Zt(pc(),1),bc=e=>e.replace(/\\n/g,`
5
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),vc=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},aE=e=>{let t=e.completedAt??Date.now(),o=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Xv=e=>e.status==="complete"?aE(e):e.status==="pending"?"Waiting":"",iE=e=>{let o=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var Qv=e=>e.status==="complete"?iE(e):"Using tool...",xc=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},al=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return xc(t)},Cc=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return xc(t)},jf=(e,t,o)=>{if(!t)return o;let n=e.name?.trim()||"tool",r=al(e);return t.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,r)},Sc=(e,t)=>{let o=e.replace(/\{toolName\}/g,t),n=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,i;for(;(i=r.exec(o))!==null;)i.index>a&&sl(n,o.slice(a,i.index),[]),i[1]!==void 0?sl(n,i[1],["bold"]):i[2]!==void 0?sl(n,i[2],["italic"]):i[3]!==void 0&&sl(n,i[3],["dim"]),a=i.index+i[0].length;return a<o.length&&sl(n,o.slice(a),[]),n},sl=(e,t,o)=>{let n=t.split("{duration}");for(let r=0;r<n.length;r++)n[r]&&e.push({text:n[r],styles:o}),r<n.length-1&&e.push({text:"{duration}",styles:o,isDuration:!0})},lE=()=>{let e=null,t=0,o=n=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=n.match(r);if(a&&a[1])try{return a[1].replace(/\\n/g,`
6
6
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,d=n.match(i);if(d&&d[1])try{return d[1].replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return d[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=t)return e!==null?{text:e,raw:n}:null;let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let a=o(n);return a!==null&&(e=a),t=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},il=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},wc=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ac=()=>{let e=sE();return{processChunk:async t=>{let o=t.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Mc=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,cr.parse)(o,cr.STR|cr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?bc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=bc(r.text)))}catch{}return t=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Kv=e=>{let t=null,o=0,r=e||(a=>{if(!a||typeof a!="object")return null;let i=d=>typeof d=="string"?bc(d):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?bc(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return i(a.on_load_text)||i(a.text)||null;case"message":case"message_and_click":case"checkout":return i(a.text)||null;default:return i(a.text)||i(a.display_text)||i(a.message)||null}return i(a.text)||i(a.display_text)||i(a.message)||i(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let i=a.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(a.length<=o)return t!==null?{text:t,raw:a}:null;try{let d=(0,cr.parse)(a,cr.STR|cr.OBJ),u=r(d);u!==null&&(t=u)}catch{}return o=a.length,{text:t||"",raw:a}},close:()=>{}}},Tc=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Gv="4.19.0";var jr=Gv;var Wa="[Image]";function Xv(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ec(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ba(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Qv(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function an(e){return{type:"text",text:e}}function Pc(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Yv(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},n.onerror=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function Jv(e,t=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Zv=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],iE=["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=[...Zv,...iE];function lE(e){return Zv.includes(e)||e.startsWith("image/")}function Lc(e){return lE(e.type)}function ex(e,t,o){return{type:"file",data:e,mimeType:t,filename:o}}async function tx(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;Lc(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},n.onerror=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function ox(e,t=ur,o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function dE(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function nx(e,t){let o=dE(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||o||"FILE"}var cE=["user","assistant","system"],uE=0;function rx(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function kc(e){return typeof e=="string"?e:void 0}function pE(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?an(t.text):null;case"image":return typeof t.image=="string"?Pc(t.image,{mimeType:kc(t.mimeType),alt:kc(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?ex(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...kc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...kc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function fE(e,t){let o=rx(t),n=e.map(i=>rx(i.timestamp)),r=new Array(e.length),a=0;for(;a<n.length;){let i=n[a];if(i!==null){r[a]=i,a+=1;continue}let d=a;for(;d+1<n.length&&n[d+1]===null;)d+=1;let u=d-a+1,c=a>0?r[a-1]:null,p=d+1<n.length?n[d+1]:null,m=p!==null&&o!==null?Math.min(p,o):p??o;for(let y=0;y<u;y+=1)r[a+y]=m!==null?m-(u-y):c!==null?c+y+1:uE+y;a=d+1}return r.map(i=>new Date(i).toISOString())}function sx(e,t){let o=fE(e,t?.beforeCreatedAt),n=[];return e.forEach((r,a)=>{if(typeof r?.id!="string"||r.id===""||!cE.includes(r.role))return;let i=r.role,d=o[a];if(r.displayAvailable===!1){let u={historyDisplayUnavailable:!0};n.push({id:r.id,role:i,content:"",createdAt:d,agentMetadata:u});return}if(typeof r.displayContent=="string"){n.push({id:r.id,role:i,content:r.displayContent,createdAt:d});return}if(typeof r.content=="string"){n.push({id:r.id,role:i,content:r.content,createdAt:d});return}if(Array.isArray(r.content)){let u=r.content.map(pE).filter(p=>p!==null),c=Ec(u);n.push({id:r.id,role:i,content:c||(Ba(u)?Wa:""),createdAt:d,...u.length>0&&{contentParts:u}});return}n.push({id:r.id,role:i,content:"",createdAt:d})}),n}function ll(e){let t=e.content;if(typeof t!="string"||t==="")return;let o=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof o=="string"&&o===t))return t}function dl(e,t){let o=new Map;for(let n of e)o.set(n.id,n);for(let n of t)o.set(n.id,n);return[...o.values()].sort((n,r)=>{let a=new Date(n.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(a)&&!Number.isNaN(i)&&a!==i)return a-i;let d=n.sequence??0,u=r.sequence??0;return d!==u?d-u:n.id.localeCompare(r.id)})}var mE="https://api.runtype.com/v1/dispatch",ax="https://api.runtype.com",qe=class extends Error{constructor(t,o,n){super(o),this.name="HistoryClientError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}},ix=32768,jf=49152,lx=e=>{let t=e??{},o=typeof t.targetId=="string"?t.targetId:typeof t.flowId=="string"?t.flowId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:o,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},dx=e=>"reason"in e?e.reason:void 0,cx="The identity proof was not admitted; account history is unavailable",ux="The identity proof was rejected",px="The request carried no visitor credential",fx="The stored visitor belongs to a different signed-in user",mx=(e,t)=>e instanceof qe&&e.code===t;function gE(e){let t=e.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(n)return`attachment.${n}`;let r=t.indexOf("/");if(r>0){let a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var zf=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function hE(e){switch(e){case"json":return Mc;case"regex-json":return Ac;case"xml":return Tc;default:return wc}}var gx=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function yE(e,t){if(!e)return t;let o=e.trim(),n=t.trim();if(o.length===0)return t;if(n.length===0)return e;let r=gx(o);if(!gx(n))return e;if(!r||n===o||n.startsWith(o))return t;let i=il(e);return il(t)!==null&&i===null?t:e}var Os=class{constructor(t={},o={}){this.config=t;this.historyInternals=o;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(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??mE,this.headers={"Content-Type":"application/json","X-Persona-Version":jr,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??hE(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,t.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(t.webmcp))}createWebMcpBridge(t){return Av().then(o=>{let n=new o.WebMcpBridge(t,{recordToolDisplayTitles:vv,getToolDisplayTitle:dc,loadPolyfill:Sv});return this.pendingWebMcpConfirmHandler!==void 0&&n.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=n,n}).catch(o=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",o),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(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.pendingWebMcpConfirmHandler=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,o,n){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(t,o,n):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:o,target:n,targetProviders:r}=this.config;if(!n)return{agentId:t,flowId:o};let a=Tv(n,r);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ax}getClientApiUrl(t){return`${this.clientApiBase()}/v1/client/${t}`}getClientSession(){return this.clientSession}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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.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 t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}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 t=this.historyIdentityStatus;return t?.state==="browser_only"?t: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(t){let o=this.getHistoryIdentityStatus(),n=o.state===t.state&&dx(o)===dx(t);if(this.historyIdentityStatus=t,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let o=this.isHistoryCapable()&&!t.omitVisitorFields,n=null;o&&(await this.historyInternals.historyBootstrapReady,n=await this.readVisitorToken());let r=this.routing(),a=r.agentId??r.flowId,i=o?t.conversationId:void 0,d={token:this.config.clientToken,...a&&{flowId:a},...o&&{visitorHistory:!0},...o&&n?{visitorToken:n}:{},...o&&t.identityProof?{identityProof:t.identityProof}:{},...i?{conversationId:i}:t.storedSessionId?{sessionId:t.storedSessionId}:{}},u=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":jr},body:JSON.stringify(d)});if(!u.ok){let p=await u.json().catch(()=>({error:"Session initialization failed"}));if(o&&u.status===403&&p.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),i)throw new qe("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw o&&u.status===401&&p.error==="visitor_required"?new qe("visitor_required","Visitor credential no longer resolves"):i&&u.status===404?new qe("not_found","Conversation not found"):u.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):u.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let c=await u.json();return c.visitor?.token&&await this.historyInternals.visitorStore?.set(c.visitor.token),{sessionId:c.sessionId,expiresAt:new Date(c.expiresAt),flow:c.flow,...c.conversationId?{conversationId:c.conversationId}:{},...c.targetId??c.flow?.id?{targetId:c.targetId??c.flow?.id}:{},...c.conversationRevision?{conversationRevision:c.conversationRevision}:{},...c.visitor?{visitor:c.visitor}:{},config:{welcomeMessage:c.config.welcomeMessage,placeholder:c.config.placeholder,theme:c.config.theme}}}async _doInitSession(){if(!this.isHistoryCapable()){let n=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n});return this.config.setStoredSessionId?.(r.sessionId),r}await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,o=await this.readVisitorToken();if(t&&o)try{let n=await this.createClientSession({conversationId:t});return this.finishInit(n,t,!1)}catch(n){if(!mx(n,"not_found")&&!mx(n,"visitor_required"))throw n;return this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,o){let n=this.historyInternals.visitorStore;return n&&this.isHistoryCapable()&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.doOrdinaryInit(t,o)):this.doOrdinaryInit(t,o)}async doOrdinaryInit(t,o){let n=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),a=await this.claimFirstConversation(r);return this.finishInit(a,t,o)}async reinitWithProof(t){let o=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:o,identityProof:t}),a=this.finishInit(r,n,!1);return this.clientSession=a,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),a}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable())return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,o,n){let r=t.conversationId;return r&&o&&(n||r!==o)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:o,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let o=!1;return{session:t,commit:()=>{o||(o=!0,this.clientSession=t,this.resetClientToolsFingerprint())},discard:()=>{o=!0}}}async prepareConversationSession(t,o){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new qe("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let n=o?.proof??null;if(!await this.readVisitorToken()&&!n)throw new qe("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let a=await this.createClientSession({conversationId:t,identityProof:n});return this.prepared(a)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}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(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":jr},body:JSON.stringify(r)});if(!a.ok){let i=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:t,type:o})}async submitCSATFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:t,comment:o})}async submitNPSFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:t,comment:o})}historyUrl(t,o){let n=new URLSearchParams;for(let[a,i]of Object.entries(o))i===void 0||i===""||n.set(a,String(i));let r=n.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let o=this.config.features?.history?.scope;return o||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,o){let n=this.config.getIdentityProof;if(!n)return o&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;o&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await n()??null}catch{throw o&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new qe("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new qe("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return o&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,o,n){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(o);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new qe("proof_not_admitted",cx);return r}async readErrorCode(t){let o=await t.json().catch(()=>({}));return typeof o.error=="string"?o.error:typeof o.message=="string"?o.message:""}async recoverFromUnauthorized(t,o,n){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new qe("invalid_identity_proof",ux);if(r.includes("visitor token required"))throw new qe("visitor_token_missing",px);if(r.includes("visitor_identity_mismatch")){if(!o)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new qe("visitor_identity_mismatch",fx);return this.reinitWithProof(o)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new qe("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,o){let n=await this.readErrorCode(t);if(t.status===404)return new qe("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new qe("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&n.includes("identity_proof_not_admitted"))return o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new qe("proof_not_admitted",cx);if(t.status===401){let r=n.toLowerCase();return r.includes("invalid_identity_proof")?(o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new qe("invalid_identity_proof",ux)):r.includes("visitor token required")?new qe("visitor_token_missing",px):r.includes("visitor_identity_mismatch")?new qe("visitor_identity_mismatch",fx):new qe("unauthorized",n||"History request was not authorized")}return new qe("request_failed",n||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,o,n){let r=t?.toLowerCase()??null;if(o){if(r==="admitted"){n&&this.setHistoryIdentityStatus({state:"verified"});return}throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new qe("identity_contract_violation","Server reported an ignored identity proof on a success response"):new qe("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new qe("identity_contract_violation","Server admitted an identity proof that was never sent");n&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,o){this.assertHistoryUsable();let n=o.trackIdentity!==!1,r=await this.initSession(),a=null;this.resolveHistoryScope(o.scope)==="verified-user"&&(a=await this.resolveIdentityProof(r,n),a&&(r=await this.bindIdentity(r,a,n)));let i=this.historyInternals.visitorStore,d=!1;for(;;){let u=i?.revision()??0,c=await this.readVisitorToken();if(!c&&!o.visitorTokenOptional)throw new qe("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(this.historyUrl(t,{...o.query,sessionId:r.sessionId}),{method:o.method,headers:{"X-Persona-Version":jr,...c?{"X-Visitor-Token":c}:{},...a?{"X-Identity-Proof":a}:{},...o.body!==void 0?{"Content-Type":"application/json"}:{}},...o.body!==void 0?{body:JSON.stringify(o.body)}:{},...o.keepalive?{keepalive:!0}:{}});if(p.status===401&&!d){d=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(p),a,n);continue}if(!p.ok)throw await this.historyErrorFor(p,n);let m=p.headers.get("X-History-Identity-Status"),y=await p.json().catch(()=>{});if(i&&i.revision()!==u)throw new qe("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,a!==null,n),y}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new qe("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let o=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(o?.data)?o.data:[]).map(lx),nextCursor:typeof o?.nextCursor=="string"?o.nextCursor:null}}async getConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...o?.messageCursor?{messageCursor:o.messageCursor}:{}},...o?.scope?{scope:o.scope}:{}}),r=n&&typeof n.conversation=="object"&&n.conversation!==null?n.conversation:n;return{summary:lx(r),messages:Array.isArray(n?.messages)?n.messages:[],nextMessageCursor:typeof n?.nextMessageCursor=="string"?n.nextMessageCursor:null,conversationRevision:typeof n?.conversationRevision=="string"?n.conversationRevision:null}}async finalizeDisplayProjections(t,o){this.assertHistoryUsable();let n=0;for(let u of o){let c=u.displayContent.length;if(c>ix)throw new qe("payload_too_large",`displayContent exceeds the ${ix} character limit`);n+=c}if(n>jf)throw new qe("payload_too_large",`Display projection batch exceeds the ${jf} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,a=r?.revision()??0,i=await this.historyFetch(`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:o},scope:"browser",keepalive:n<=jf,trackIdentity:!1}),d=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return d&&this.clientSession?.conversationId===t&&(r?.revision()??0)===a&&this.historyInternals.setStoredConversationRevision?.(d),{conversationRevision:d}}async deleteConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...o?.scope?{scope:o.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async deleteAllConversations(t){let o=await this.historyFetch("conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.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(t,o){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,o):this.isAgentMode()?this.dispatchAgent(t,o):this.dispatchProxy(t,o)}async dispatchClientToken(t,o){let n=Pv();this.currentClientTurnId=n;let r=()=>this.currentClientTurnId===n,a=i=>{r()&&o(i)};o({type:"status",status:"connecting"});try{let i=await this.initSession();if(new Date>=new Date(i.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let h=new Error("Session expired. Please refresh to continue.");throw a({type:"error",error:h}),h}let d=await this.buildPayload(t.messages),u=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([h])=>h!=="sessionId"&&h!=="session_id")):void 0,c=this.isHistoryCapable(),p={sessionId:i.sessionId,messages:t.messages.filter(zf).map(h=>{let S=c?ll(h):void 0;return{id:h.id,role:h.role,content:h.contentParts??h.llmContent??h.rawContent??h.content,...S!==void 0&&{displayContent:S}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:n,...t.interrupt&&{submitMode:"interrupt"}},{response:m,commit:y}=await this.sendWithClientToolsDiff(i.sessionId,d.clientTools,h=>{let S={...p,...h};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":jr},body:JSON.stringify(S),signal:t.signal})});if(!m.ok){let h=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let A=new Error("Session expired. Please refresh to continue.");throw a({type:"error",error:A}),A}if(m.status===429){let A=new Error(h.hint||"Message limit reached for this session.");throw a({type:"error",error:A}),A}if(m.status===410&&h.error==="conversation_deleted"){let A=new qe("conversation_deleted","This conversation was deleted");throw a({type:"error",error:A}),A}let S=new Error(h.error||"Failed to send message");throw a({type:"error",error:S}),S}if(!m.body){let h=new Error("No response body received");throw a({type:"error",error:h}),h}y(),a({type:"status",status:"connected"});try{await this.streamResponse(m.body,a,t.assistantMessageId)}finally{a({type:"status",status:"idle"})}}catch(i){let d=i instanceof Error?i:new Error(String(i));throw!(d instanceof qe)&&!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&a({type:"error",error:d}),d}}async dispatchProxy(t,o){o({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o)}finally{o({type:"status",status:"idle"})}}async dispatchAgent(t,o){o({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o,t.assistantMessageId)}finally{o({type:"status",status:"idle"})}}async processStream(t,o,n,r){o({type:"status",status:"connected"});try{await this.streamResponse(t,o,n,r)}finally{o({type:"status",status:"idle"})}}async resolveApproval(t,o){let n=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(n,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:o,streamResponse:!0})})}async sendWithClientToolsDiff(t,o,n,r){let a=!!(o&&o.length>0),i=a?Cv(o):void 0,d=this.clientToolsFingerprintSessionId===t,u=a&&d&&this.lastSentClientToolsFingerprint===i,c=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,m;for(let y=0;;y++){if(m=await n({...a&&(p||!u)&&o?{clientTools:o}:{},...c?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),m.status===409&&y===0&&a&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:c&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,o,n){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||ax}/resume`,i;r&&(i=(await this.initSession()).sessionId);let d={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(d,await this.getHeaders());let u={executionId:t,toolOutputs:o,streamResponse:n?.streamResponse??!0};if(i&&(u.sessionId=i),r&&i){let c=[...Ra(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:p,commit:m}=await this.sendWithClientToolsDiff(i,c,y=>{let h={...u,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",h),fetch(a,{method:"POST",headers:d,body:JSON.stringify(h),signal:n?.signal})},{emptyMeansReplace:!0});return p.ok&&m(),p}return fetch(a,{method:"POST",headers:d,body:JSON.stringify(u),signal:n?.signal})}latestMentionContext(t){for(let o=t.length-1;o>=0;o--){let n=t[o];if(n.role==="user")return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async buildContextAggregate(t){let o={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let a=await r({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));let n=this.latestMentionContext(t);return n&&Object.assign(o,n),Object.keys(o).length?o:null}normalizeComposerOptions(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o:void 0}applyInlineAgentModel(t,o){let n=o?.selectedModelId;return!n||!("model"in t)?t:this.config.composer?.models?.some(a=>a.id===n)?{...t,model:n}:t}async buildAgentPayload(t,o){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(zf).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let m=new Date(c.createdAt).getTime(),y=new Date(p.createdAt).getTime();return m-y}).map(c=>({role:c.role,content:c.contentParts??c.llmContent??c.rawContent??c.content,createdAt:c.createdAt})),a=this.normalizeComposerOptions(o),i={agent:this.applyInlineAgentModel(this.config.agent??{agentId:n},a),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};a&&(i.composerOptions=a);let d=[...Ra(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];d.length>0&&(i.clientTools=d);let u=await this.buildContextAggregate(t);return u&&(i.context=u),i}async buildPayload(t,o){let n=t.slice().filter(zf).sort((c,p)=>{let m=new Date(c.createdAt).getTime(),y=new Date(p.createdAt).getTime();return m-y}).map(c=>({role:c.role,content:c.contentParts??c.llmContent??c.rawContent??c.content,createdAt:c.createdAt})),r=this.routing(),a={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[c,p]of Object.entries(r.targetPayload))c!=="messages"&&(a[c]=p);let i=[...Ra(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];i.length>0&&(a.clientTools=i);let d=await this.buildContextAggregate(t);d&&(a.context=d);let u=this.normalizeComposerOptions(o);if(u&&(a.composerOptions=u),this.requestMiddleware)try{let c=await this.requestMiddleware({payload:{...a},config:this.config});if(c&&typeof c=="object"){let p=c;return a.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=a.clientTools),p}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",c)}return a}async handleCustomSSEEvent(t,o,n,r,a,i){if(!this.parseSSEEvent)return!1;try{let d=await this.parseSSEEvent(t);if(d===null)return!1;let u=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return n.current=m,r(m),m},c=p=>n.current?n.current:u(p);if(d.text!==void 0){d.partId!==void 0&&i.current!==null&&d.partId!==i.current&&(n.current&&(n.current.streaming=!1,r(n.current)),u(d.partId)),d.partId!==void 0&&(i.current=d.partId);let p=c(d.partId);d.partId!==void 0&&!p.partId&&(p.partId=d.partId),p.content+=d.text,r(p)}return d.done&&(n.current&&(n.current.streaming=!1,r(n.current)),i.current=null,o({type:"status",status:"idle"})),d.error&&(i.current=null,o({type:"error",error:new Error(d.error)})),!0}catch(d){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",d),!1}}async streamResponse(t,o,n,r){let a=t.getReader(),i=new TextDecoder,d="",u=Date.now(),c=0,p=()=>u+c++,m=B=>{let te=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,C=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,U=B.tools?B.tools.map(q=>({...q,chunks:q.chunks?[...q.chunks]:void 0})):void 0;return{...B,reasoning:te,toolCall:C,tools:U}},y=B=>{if(B.role!=="assistant"||B.variant)return!0;let te=Array.isArray(B.contentParts)&&B.contentParts.length>0,C=typeof B.rawContent=="string"&&B.rawContent.trim()!=="";return typeof B.content=="string"&&B.content.trim()!==""||te||C||!!B.stopReason},h=B=>{y(B)&&o({type:"message",message:m(B)})},S=null,A=null,T={current:null},k={current:null},P=null,R="",b=new Map,w=new Map,x=new Map,L=new Map,F=new Map,X={lastId:null,byStep:new Map},G={lastId:null,byCall:new Map},E=B=>{if(B==null)return null;try{return String(B)}catch{return null}},_=B=>E(B.stepId??B.step_id??B.step??B.parentId??B.flowStepId??B.flow_step_id),O=B=>E(B.callId??B.call_id??B.requestId??B.request_id??B.toolCallId??B.tool_call_id??B.stepId??B.step_id),W=n,oe=!1,Q=()=>{if(S)return S;let B,te="",C=P;return!oe&&W?(B=W,oe=!0,te=r??""):W&&C?B=`${W}_${C}`:B=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,S={id:B,role:"assistant",content:te,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},h(S),S},de=(B,te)=>{X.lastId=te,B&&X.byStep.set(B,te)},pe=(B,te)=>{let C=B.reasoningId??B.id,U=_(B);if(C){let $=String(C);return de(U,$),$}if(U){let $=X.byStep.get(U);if($)return X.lastId=$,$}if(X.lastId&&!te)return X.lastId;if(!te)return null;let q=`reason-${p()}`;return de(U,q),q},xe=B=>{let te=L.get(B);if(te)return te;let C={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:B,status:"streaming",chunks:[]}};return L.set(B,C),h(C),C},Pe=(B,te)=>{G.lastId=te,B&&G.byCall.set(B,te)},ge=new Set,Ke=new Map,Bt=new Set,ke=new Map,z=B=>{if(!B)return!1;let te=B.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},Ue=(B,te)=>{let C=B.toolId??B.id,U=O(B);if(C){let $=String(C);return Pe(U,$),$}if(U){let $=G.byCall.get(U);if($)return G.lastId=$,$}if(G.lastId&&!te)return G.lastId;if(!te)return null;let q=`tool-${p()}`;return Pe(U,q),q},Ge=B=>{let te=F.get(B);if(te)return te;let C={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:B,status:"pending"}};return F.set(B,C),h(C),C},Ae=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let te=Number(B);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let C=Date.parse(B);if(!Number.isNaN(C))return C}return Date.now()},De=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},he=new Map,gt=new Map,dn=new Map,Js=(B,te,C)=>{let U=dn.get(B);U||(U=[],dn.set(B,U));let q=0,$=U.length;for(;q<$;){let ne=q+$>>>1;U[ne].seq<te?q=ne+1:$=ne}U[q]?.seq===te?U[q]={seq:te,text:C}:U.splice(q,0,{seq:te,text:C});let ee="";for(let ne=0;ne<U.length;ne++)ee+=U[ne].text;return ee},oo=(B,te)=>{let C=De(te),U=gt.get(B.id),q=yE(U,C);B.rawContent=q;let $=he.get(B.id),ee=$e=>{let Rt=B.content??"";$e.trim()!==""&&(Rt.trim().length===0||$e.startsWith(Rt)||$e.trimStart().startsWith(Rt.trim()))&&(B.content=$e)},ne=()=>{if($){let $e=$.close?.();$e instanceof Promise&&$e.catch(()=>{})}he.delete(B.id),gt.delete(B.id),B.streaming=!1,h(B)};if(!$){ee(C),ne();return}let ie=il(q);if(ie!==null&&ie.trim()!==""){ee(ie),ne();return}let Se=$e=>{let Rt=typeof $e=="string"?$e:$e?.text??null;if(Rt!==null&&Rt.trim()!=="")return Rt;let wt=$.getExtractedText();return wt!==null&&wt.trim()!==""?wt:C},ht;try{ht=$.processChunk(q)}catch{ee(C),ne();return}if(ht instanceof Promise){ht.then($e=>{ee(Se($e)),ne()}).catch(()=>{ee(C),ne()});return}ee(Se(ht)),ne()},Xo=null,jn=(B,te,C,U)=>{B.rawContent=te,he.has(B.id)||he.set(B.id,this.createStreamParser());let q=he.get(B.id),$=te.trim().startsWith("{")||te.trim().startsWith("[");if($&&gt.set(B.id,te),q.__isPlainTextParser===!0){B.content=U!==void 0?te:B.content+C,gt.delete(B.id),he.delete(B.id),B.rawContent=void 0,h(B);return}let ne=q.processChunk(te);if(ne instanceof Promise)ne.then(ie=>{let Se=typeof ie=="string"?ie:ie?.text??null;Se!==null&&Se.trim()!==""?(B.content=Se,h(B)):!$&&!te.trim().startsWith("<")&&(B.content=U!==void 0?te:B.content+C,gt.delete(B.id),he.delete(B.id),B.rawContent=void 0,h(B))}).catch(()=>{B.content=U!==void 0?te:B.content+C,gt.delete(B.id),he.delete(B.id),B.rawContent=void 0,h(B)});else{let ie=typeof ne=="string"?ne:ne?.text??null;ie!==null&&ie.trim()!==""?(B.content=ie,h(B)):!$&&!te.trim().startsWith("<")&&(B.content=U!==void 0?te:B.content+C,gt.delete(B.id),he.delete(B.id),B.rawContent=void 0,h(B))}},Ht=(B,te)=>{let C=te??B.content;if(C==null||C===""){B.streaming=!1,h(B);return}let q=gt.get(B.id)??De(C);B.rawContent=q;let $=he.get(B.id),ee=null,ne=!1;if($&&(ee=$.getExtractedText(),ee===null&&(ee=il(q)),ee===null)){let ie=$.processChunk(q);ie instanceof Promise?(ne=!0,ie.then(Se=>{let ht=typeof Se=="string"?Se:Se?.text??null;ht!==null&&(B.content=ht,B.streaming=!1,he.delete(B.id),gt.delete(B.id),h(B))}).catch(()=>{})):ee=typeof ie=="string"?ie:ie?.text??null}if(!ne){ee!==null&&ee.trim()!==""?B.content=ee:gt.has(B.id)||(B.content=De(C));let ie=he.get(B.id);if(ie){let Se=ie.close?.();Se instanceof Promise&&Se.catch(()=>{}),he.delete(B.id)}gt.delete(B.id),B.streaming=!1,h(B)}},Yr=(B,te,C)=>{let U=w.get(B);if(U)return U;let q={id:`nested-${te}-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...C?{variant:C}:{},...C==="reasoning"?{reasoning:{id:B,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return w.set(B,q),h(q),q},Ao=[],Sn,li=new Map,Jr=0,po="agent",di=!1,Tt=null,ut=null,cn=new Map,zl=this.config.iterationDisplay??"separate";for(Sn=()=>{for(let B=0;B<Ao.length;B++){let te=Ao[B].payloadType,C=Ao[B].payload;if(!di&&po!=="flow"&&typeof C.stepType=="string"&&(po="flow"),te==="reasoning_start"){let U=typeof C.id=="string"?C.id:null,q=typeof C.parentToolCallId=="string"&&C.parentToolCallId?C.parentToolCallId:null;if(U&&q){b.set(U,q),Yr(U,q,"reasoning");continue}let $=pe(C,!0)??`reason-${p()}`,ee=xe($);ee.reasoning=ee.reasoning??{id:$,status:"streaming",chunks:[]},ee.reasoning.startedAt=ee.reasoning.startedAt??Ae(C.startedAt??C.timestamp),ee.reasoning.completedAt=void 0,ee.reasoning.durationMs=void 0,(C.scope==="loop"||C.scope==="turn")&&(ee.reasoning.scope=C.scope),ee.streaming=!0,ee.reasoning.status="streaming",h(ee)}else if(te==="reasoning_delta"){let U=typeof C.id=="string"?C.id:null;if(U&&b.has(U)&&w.has(U)){let ne=w.get(U),ie=C.reasoningText??C.text??C.delta??"";ie&&C.hidden!==!0&&ne.reasoning&&(ne.reasoning.chunks.push(String(ie)),h(ne));continue}let q=pe(C,!1)??pe(C,!0)??`reason-${p()}`,$=xe(q);$.reasoning=$.reasoning??{id:q,status:"streaming",chunks:[]},$.reasoning.startedAt=$.reasoning.startedAt??Ae(C.startedAt??C.timestamp);let ee=C.reasoningText??C.text??C.delta??"";if(ee&&C.hidden!==!0){let ne=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(ne!==void 0){let ie=Js(q,ne,String(ee));$.reasoning.chunks=[ie]}else $.reasoning.chunks.push(String(ee))}if($.reasoning.status=C.done?"complete":"streaming",C.done){$.reasoning.completedAt=Ae(C.completedAt??C.timestamp);let ne=$.reasoning.startedAt??Date.now();$.reasoning.durationMs=Math.max(0,($.reasoning.completedAt??Date.now())-ne)}$.streaming=$.reasoning.status!=="complete",h($)}else if(te==="reasoning_complete"){let U=typeof C.id=="string"?C.id:null;if(U&&b.has(U)&&w.has(U)){let ie=w.get(U);if(ie.reasoning){let Se=typeof C.text=="string"?C.text:"";Se&&ie.reasoning.chunks.length===0&&ie.reasoning.chunks.push(Se),ie.reasoning.status="complete",ie.streaming=!1,h(ie)}b.delete(U),w.delete(U);continue}let q=pe(C,!1)??pe(C,!0)??`reason-${p()}`,$=typeof C.text=="string"?C.text:"";!L.get(q)&&($||C.scope==="loop")&&xe(q);let ee=L.get(q);if(ee?.reasoning){(C.scope==="loop"||C.scope==="turn")&&(ee.reasoning.scope=C.scope),$&&ee.reasoning.chunks.length===0&&ee.reasoning.chunks.push($),ee.reasoning.status="complete",ee.reasoning.completedAt=Ae(C.completedAt??C.timestamp);let ie=ee.reasoning.startedAt??Date.now();ee.reasoning.durationMs=Math.max(0,(ee.reasoning.completedAt??Date.now())-ie),ee.streaming=!1,h(ee)}let ne=_(C);ne&&X.byStep.delete(ne)}else if(te==="tool_start"){S&&(S.streaming=!1,h(S),S=null),typeof C.iteration=="number"&&(Jr=C.iteration);let U=(typeof C.toolCallId=="string"?C.toolCallId:void 0)??Ue(C,!0)??`tool-${p()}`,q=C.toolName??C.name;if(z(q)){ge.add(U);continue}Pe(O(C),U);let $=Ge(U),ee=$.toolCall??{id:U,status:"pending"};ee.name=q??ee.name,ee.status="running",C.parameters!==void 0?ee.args=C.parameters:C.args!==void 0&&(ee.args=C.args),ee.startedAt=ee.startedAt??Ae(C.startedAt??C.timestamp),ee.completedAt=void 0,ee.durationMs=void 0,$.toolCall=ee,$.streaming=!0,C.executionId&&($.agentMetadata={executionId:C.executionId,iteration:C.iteration}),h($)}else if(te==="tool_output_delta"){let U=Ue(C,!1)??Ue(C,!0)??`tool-${p()}`;if(ge.has(U))continue;let q=Ge(U),$=q.toolCall??{id:U,status:"running"};$.startedAt=$.startedAt??Ae(C.startedAt??C.timestamp);let ee=C.text??C.delta??C.message??"";ee&&($.chunks=$.chunks??[],$.chunks.push(String(ee))),$.status="running",q.toolCall=$,q.streaming=!0;let ne=C.agentContext;(ne||C.executionId)&&(q.agentMetadata=q.agentMetadata??{executionId:ne?.executionId??C.executionId,iteration:ne?.iteration??C.iteration}),h(q)}else if(te==="tool_complete"){let U=Ue(C,!1)??Ue(C,!0)??`tool-${p()}`;if(ge.has(U)){ge.delete(U);continue}let q=Ge(U),$=q.toolCall??{id:U,status:"running"};$.status="complete",C.result!==void 0&&($.result=C.result),typeof C.duration=="number"&&($.duration=C.duration),$.completedAt=Ae(C.completedAt??C.timestamp);let ee=C.duration??C.executionTime;if(typeof ee=="number")$.durationMs=ee;else{let Se=$.startedAt??Date.now();$.durationMs=Math.max(0,($.completedAt??Date.now())-Se)}q.toolCall=$,q.streaming=!1;let ne=C.agentContext;(ne||C.executionId)&&(q.agentMetadata=q.agentMetadata??{executionId:ne?.executionId??C.executionId,iteration:ne?.iteration??C.iteration}),h(q);let ie=O(C);ie&&G.byCall.delete(ie)}else if(te==="await"&&C.toolName){let U=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,q=U??C.toolId??`local-${p()}`,$=Ge(q),ee=C.toolName,ne=C.origin==="webmcp"&&!Or(ee)?`webmcp:${ee}`:ee,ie=Or(ne),Se=$.toolCall??{id:q,status:"pending"};Se.name=ne,Se.args=C.parameters,Se.status=ie?"running":"complete",Se.chunks=Se.chunks??[],Se.startedAt=Se.startedAt??Ae(C.startedAt??C.timestamp??C.awaitedAt),ie?(Se.completedAt=void 0,Se.duration=void 0,Se.durationMs=void 0):Se.completedAt=Se.completedAt??Se.startedAt,$.toolCall=Se,$.streaming=!1,$.agentMetadata={...$.agentMetadata,executionId:C.executionId??$.agentMetadata?.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},h($)}else if(te==="text_start"){let U=typeof C.id=="string"?C.id:null,q=typeof C.parentToolCallId=="string"&&C.parentToolCallId?C.parentToolCallId:null;if(U&&q){b.set(U,q);continue}let $=S;$&&(po==="flow"?(Ht($),Xo=$):($.streaming=!1,h($)),S=null),P=typeof C.id=="string"?C.id:P,R=""}else if(te==="text_delta"){let U=typeof C.id=="string"?C.id:null,q=U?b.get(U):void 0;if(U&&q){let ee=typeof C.delta=="string"?C.delta:"",ne=(x.get(U)??"")+ee;if(x.set(U,ne),ne.trim()==="")continue;let ie=Yr(U,q);ie.agentMetadata={...ie.agentMetadata,executionId:C.executionId,parentToolId:q},jn(ie,ne,ee,void 0);continue}if(P=typeof C.id=="string"?C.id:P,po==="flow"){let ee=typeof C.delta=="string"?C.delta:"";if(R+=ee,R.trim()==="")continue;let ne=Q();ne.agentMetadata={executionId:C.executionId,iteration:C.iteration},jn(ne,R,ee,void 0),A=ne;continue}let $=Q();$.content+=C.delta??"",$.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:Tt??void 0,agentName:ut?.agentName},A=$,h($)}else if(te==="text_complete"){let U=typeof C.id=="string"?C.id:null;if(U&&b.has(U)){let $=w.get(U);$&&Ht($),b.delete(U),x.delete(U),w.delete(U);continue}let q=S;q&&(po==="flow"?(Ht(q),Xo=q):((q.content??"")===""&&typeof C.text=="string"&&(q.content=C.text),q.streaming=!1,h(q)),S=null),P=null,R=""}else if(te==="step_complete"){let U=C.stepType,q=C.executionType;if(U==="tool"||q==="context")continue;if(C.success===!1){let $=C.error,ee=typeof $=="string"&&$!==""?$:$!=null&&typeof $=="object"&&Reflect.has($,"message")?String($.message??"Step failed"):"Step failed";o({type:"error",error:new Error(ee)});let ne=S;ne&&ne.streaming&&(ne.streaming=!1,h(ne)),o({type:"status",status:"idle"});continue}{let $=Xo;Xo=null;let ee=C.stopReason,ne=C.result?.response;if($)ee&&($.stopReason=ee),ne!=null?oo($,ne):$.streaming!==!1&&(he.delete($.id),gt.delete($.id),$.streaming=!1,h($));else{let ie=ne!=null&&ne!=="";if(ie||ee){let Se=Q();ee&&(Se.stopReason=ee),ie?Ht(Se,ne):(Se.streaming=!1,h(Se))}}continue}}else if(te==="execution_start")po=C.kind==="flow"?"flow":"agent",di=!0,po==="agent"&&(ut={executionId:C.executionId,agentId:C.agentId??"virtual",agentName:C.agentName??"",status:"running",currentIteration:0,maxTurns:C.maxTurns??1,startedAt:Ae(C.startedAt)});else if(te==="turn_start"){let U=typeof C.iteration=="number"?C.iteration:Jr;if(U!==Jr){if(ut&&(ut.currentIteration=U),zl==="separate"&&U>1){let q=S;q&&(q.streaming=!1,h(q),cn.set(U-1,q),S=null)}Jr=U}Tt=typeof C.id=="string"?C.id:null,A=null}else if(te==="tool_input_delta"){let U=C.toolCallId??G.lastId;if(U){let q=F.get(U);q?.toolCall&&(q.toolCall.chunks=q.toolCall.chunks??[],q.toolCall.chunks.push(C.delta??""),h(q))}}else{if(te==="tool_input_complete")continue;if(te==="turn_complete"){let U=C.stopReason,q=S??A;if(U&&q!==null){let $=C.id;(!$||q.agentMetadata?.turnId===$)&&(q.stopReason=U,h(q))}Tt===C.id&&(Tt=null)}else if(te==="media_start"){let U=String(C.id);li.set(U,{mediaType:typeof C.mediaType=="string"?C.mediaType:void 0,role:typeof C.role=="string"?C.role:void 0,toolCallId:C.toolCallId,parts:[]})}else if(te==="media_delta"){let U=li.get(String(C.id));U&&typeof C.delta=="string"&&U.parts.push(C.delta)}else if(te==="media_complete"){let U=String(C.id),q=li.get(U);li.delete(U);let $=(typeof C.mediaType=="string"?C.mediaType:void 0)??q?.mediaType??"application/octet-stream",ee=typeof C.data=="string"?C.data:void 0,ne=typeof C.url=="string"?C.url:q&&q.parts.length>0?q.parts.join(""):void 0,ie=null;if(ee)ie={type:"media",data:ee,mediaType:$};else if(ne){let Rt=$.toLowerCase();ie={type:Rt==="image"||Rt.startsWith("image/")?"image-url":"file-url",url:ne,mediaType:$}}let Se=C.toolCallId??q?.toolCallId,ht=ie?[ie]:[],$e=[];for(let Rt of ht){if(!Rt||typeof Rt!="object")continue;let wt=Rt,Zr=typeof wt.type=="string"?wt.type:void 0,Bo=typeof wt.mediaType=="string"?wt.mediaType.toLowerCase():"",qt=null,fo="";if(Zr==="media"){let ao=typeof wt.data=="string"?wt.data:void 0;if(!ao)continue;fo=Bo.length>0?Bo:"application/octet-stream",qt=`data:${fo};base64,${ao}`}else if(Zr==="image-url"){let ao=typeof wt.url=="string"?wt.url:void 0;if(!ao)continue;fo=Bo,qt=ao}else if(Zr==="file-url"){let ao=typeof wt.url=="string"?wt.url:void 0;if(!ao)continue;fo=Bo,qt=ao}else continue;if(qt)if(Zr==="image-url"||fo.startsWith("image/"))$e.push({type:"image",image:qt,...fo.includes("/")?{mimeType:fo}:{}});else if(fo.startsWith("audio/"))$e.push({type:"audio",audio:qt,mimeType:fo});else if(fo.startsWith("video/"))$e.push({type:"video",video:qt,mimeType:fo});else{let ao=fo||"application/octet-stream";$e.push({type:"file",data:qt,mimeType:ao,filename:gE(ao)})}}if($e.length>0){let Rt=p(),wt=Se,Bo={id:`agent-media-${typeof wt=="string"&&wt.length>0?`${wt}-${Rt}`:String(Rt)}`,role:"assistant",content:"",contentParts:$e,createdAt:new Date().toISOString(),streaming:!1,sequence:Rt,agentMetadata:{executionId:C.executionId,iteration:typeof C.iteration=="number"?C.iteration:Jr}};h(Bo);let qt=S;qt&&(qt.streaming=!1,h(qt)),S=null,T.current=null}}else if(te==="execution_complete"){let U=C.kind??po;U==="agent"&&ut&&(ut.status=C.success?"complete":"error",ut.completedAt=Ae(C.completedAt),ut.stopReason=C.stopReason);let q=S;q&&(U==="flow"&&q.streaming!==!1?Ht(q):(q.streaming=!1,h(q)),S=null),P=null,R="",Xo=null,o({type:"status",status:"idle",terminal:!0})}else if(te==="execution_error"){let U=typeof C.error=="string"?C.error:C.error?.message??"Execution error";o({type:"error",error:new Error(U)})}else if(te!=="ping"){if(te==="approval_start"){let U=C.approvalId??`approval-${p()}`,q={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:U,status:"pending",agentId:ut?.agentId??"virtual",executionId:C.executionId??ut?.executionId??"",toolName:C.toolName??"",toolType:C.toolType,description:C.description??`Execute ${C.toolName??"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};h(q)}else if(te==="step_await"&&C.awaitReason==="approval_required"){let U=C.approvalId??`approval-${p()}`,q={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:U,status:"pending",agentId:ut?.agentId??"virtual",executionId:C.executionId??ut?.executionId??"",toolName:C.toolName??"",toolType:C.toolType,description:C.description??`Execute ${C.toolName??"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};h(q)}else if(te==="approval_complete"){let U=C.approvalId;if(U){let $={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:U,status:C.decision??"approved",agentId:ut?.agentId??"virtual",executionId:C.executionId??ut?.executionId??"",toolName:C.toolName??"",description:C.description??"",resolvedAt:Date.now()}};h($)}}else if(te==="artifact_start"||te==="artifact_delta"||te==="artifact_update"||te==="artifact_complete"){if(te==="artifact_start"){let U=C.artifactType,q=String(C.id),$=typeof C.title=="string"?C.title:void 0,ee=C.file,ne;ee&&typeof ee=="object"&&!Array.isArray(ee)&&typeof ee.path=="string"&&typeof ee.mimeType=="string"&&(ne={path:ee.path,mimeType:ee.mimeType,...typeof ee.language=="string"?{language:ee.language}:{}}),o({type:"artifact_start",id:q,artifactType:U,title:$,component:typeof C.component=="string"?C.component:void 0,...ne?{file:ne}:{}});let ie=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?{...C.props}:void 0;if(ke.set(q,{markdown:"",title:$,file:ne,...ie?{props:ie}:{}}),!Bt.has(q)){Bt.add(q);let Se=_n(this.config.features?.artifacts,{artifactType:U,...ne?{file:ne}:{}}),ht=typeof C.component=="string"?C.component:void 0,$e={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:tl(Se,{artifactId:q,title:$,artifactType:U,status:"streaming",...ne?{file:ne}:{},...ht?{component:ht}:{}})};Ke.set(q,$e),h($e)}}else if(te==="artifact_delta"){let U=String(C.id),q=typeof C.delta=="string"?C.delta:String(C.delta??"");o({type:"artifact_delta",id:U,artDelta:q});let $=ke.get(U);$&&($.markdown+=q)}else if(te==="artifact_update"){let U=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};o({type:"artifact_update",id:String(C.id),props:U,component:typeof C.component=="string"?C.component:void 0});let q=ke.get(String(C.id));q&&(q.props={...q.props??{},...U})}else if(te==="artifact_complete"){let U=String(C.id);o({type:"artifact_complete",id:U});let q=Ke.get(U);if(q){q.streaming=!1;try{let $=JSON.parse(q.rawContent??"{}");if($.props){$.props.status="complete";let ee=ke.get(U);ee?.markdown&&($.props.markdown=ee.markdown),ee?.file&&($.props.file=ee.file),$.component==="PersonaArtifactInline"&&ee?.props&&Object.keys(ee.props).length>0&&($.props.componentProps=ee.props)}q.rawContent=JSON.stringify($)}catch{}ke.delete(U),h(q),Ke.delete(U)}}}else if(te==="transcript_insert"){let U=C.message;if(!U||typeof U!="object")continue;let q=String(U.id??`msg-${p()}`),$=U.role,ne={id:q,role:$==="user"?"user":$==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:p()};if(h(ne),ne.rawContent)try{let Se=JSON.parse(ne.rawContent)?.props?.artifactId;typeof Se=="string"&&Bt.add(Se)}catch{}S=null,T.current=null,he.delete(q),gt.delete(q)}else if(te==="error"){if(C.recoverable===!1&&C.error!=null&&C.error!==""){let U=typeof C.error=="string"?C.error:C.error?.message!=null?String(C.error.message):"Execution error";o({type:"error",error:new Error(U)});let q=S;q&&q.streaming&&(q.streaming=!1,h(q)),o({type:"status",status:"idle"})}}else if(te==="step_error"||te==="dispatch_error"||te==="flow_error"){let U=null;if(C.error instanceof Error)U=C.error;else if(te==="dispatch_error"){let q=C.message??C.error;q!=null&&q!==""&&(U=new Error(String(q)))}else{let q=C.error;typeof q=="string"&&q!==""?U=new Error(q):q!=null&&typeof q=="object"&&Reflect.has(q,"message")&&(U=new Error(String(q.message??q)))}if(U){o({type:"error",error:U});let q=S;q&&q.streaming&&(q.streaming=!1,h(q)),o({type:"status",status:"idle"})}}}}}Ao.length=0};;){let{done:B,value:te}=await a.read();if(B)break;d+=i.decode(te,{stream:!0});let C=d.split(`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return d[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=t)return e!==null?{text:e,raw:n}:null;let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let a=o(n);return a!==null&&(e=a),t=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},il=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},wc=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ac=()=>{let e=lE();return{processChunk:async t=>{let o=t.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Mc=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,pr.parse)(o,pr.STR|pr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?bc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=bc(r.text)))}catch{}return t=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Yv=e=>{let t=null,o=0,r=e||(a=>{if(!a||typeof a!="object")return null;let i=d=>typeof d=="string"?bc(d):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?bc(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return i(a.on_load_text)||i(a.text)||null;case"message":case"message_and_click":case"checkout":return i(a.text)||null;default:return i(a.text)||i(a.display_text)||i(a.message)||null}return i(a.text)||i(a.display_text)||i(a.message)||i(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let i=a.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(a.length<=o)return t!==null?{text:t,raw:a}:null;try{let d=(0,pr.parse)(a,pr.STR|pr.OBJ),c=r(d);c!==null&&(t=c)}catch{}return o=a.length,{text:t||"",raw:a}},close:()=>{}}},Tc=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Jv="4.21.0";var Un=Jv;var Ba="[Image]";function Zv(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ec(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Oa(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function ex(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function an(e){return{type:"text",text:e}}function Pc(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function tx(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},n.onerror=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function ox(e,t=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var nx=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],cE=["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"],fr=[...nx,...cE];function uE(e){return nx.includes(e)||e.startsWith("image/")}function kc(e){return uE(e.type)}function rx(e,t,o){return{type:"file",data:e,mimeType:t,filename:o}}async function sx(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;kc(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},n.onerror=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function ax(e,t=fr,o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function pE(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function ix(e,t){let o=pE(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||o||"FILE"}var fE=["user","assistant","system"],mE=0;function lx(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Lc(e){return typeof e=="string"?e:void 0}function gE(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?an(t.text):null;case"image":return typeof t.image=="string"?Pc(t.image,{mimeType:Lc(t.mimeType),alt:Lc(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?rx(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...Lc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...Lc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function hE(e,t){let o=lx(t),n=e.map(i=>lx(i.timestamp)),r=new Array(e.length),a=0;for(;a<n.length;){let i=n[a];if(i!==null){r[a]=i,a+=1;continue}let d=a;for(;d+1<n.length&&n[d+1]===null;)d+=1;let c=d-a+1,u=a>0?r[a-1]:null,p=d+1<n.length?n[d+1]:null,m=p!==null&&o!==null?Math.min(p,o):p??o;for(let h=0;h<c;h+=1)r[a+h]=m!==null?m-(c-h):u!==null?u+h+1:mE+h;a=d+1}return r.map(i=>new Date(i).toISOString())}function dx(e,t){let o=hE(e,t?.beforeCreatedAt),n=[];return e.forEach((r,a)=>{if(typeof r?.id!="string"||r.id===""||!fE.includes(r.role))return;let i=r.role,d=o[a];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};n.push({id:r.id,role:i,content:"",createdAt:d,agentMetadata:c});return}if(typeof r.displayContent=="string"){n.push({id:r.id,role:i,content:r.displayContent,createdAt:d});return}if(typeof r.content=="string"){n.push({id:r.id,role:i,content:r.content,createdAt:d});return}if(Array.isArray(r.content)){let c=r.content.map(gE).filter(p=>p!==null),u=Ec(c);n.push({id:r.id,role:i,content:u||(Oa(c)?Ba:""),createdAt:d,...c.length>0&&{contentParts:c}});return}n.push({id:r.id,role:i,content:"",createdAt:d})}),n}function ll(e){let t=e.content;if(typeof t!="string"||t==="")return;let o=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof o=="string"&&o===t))return t}function dl(e,t){let o=new Map;for(let n of e)o.set(n.id,n);for(let n of t)o.set(n.id,n);return[...o.values()].sort((n,r)=>{let a=new Date(n.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(a)&&!Number.isNaN(i)&&a!==i)return a-i;let d=n.sequence??0,c=r.sequence??0;return d!==c?d-c:n.id.localeCompare(r.id)})}var yE="https://api.runtype.com/v1/dispatch",cx="https://api.runtype.com",Fe=class extends Error{constructor(t,o,n){super(o),this.name="HistoryClientError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}},ux=32768,zf=49152,px=e=>{let t=e??{},o=typeof t.targetId=="string"?t.targetId:typeof t.flowId=="string"?t.flowId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:o,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},fx=e=>"reason"in e?e.reason:void 0,mx="The identity proof was not admitted; account history is unavailable",gx="The identity proof was rejected",hx="The request carried no visitor credential",yx="The stored visitor belongs to a different signed-in user",Kf=(e,t)=>e instanceof Fe&&e.code===t;function bE(e){let t=e.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(n)return`attachment.${n}`;let r=t.indexOf("/");if(r>0){let a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var Gf=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function vE(e){switch(e){case"json":return Mc;case"regex-json":return Ac;case"xml":return Tc;default:return wc}}var bx=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function xE(e,t){if(!e)return t;let o=e.trim(),n=t.trim();if(o.length===0)return t;if(n.length===0)return e;let r=bx(o);if(!bx(n))return e;if(!r||n===o||n.startsWith(o))return t;let i=il(e);return il(t)!==null&&i===null?t:e}var Os=class{constructor(t={},o={}){this.config=t;this.historyInternals=o;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(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??yE,this.headers={"Content-Type":"application/json","X-Persona-Version":Un,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??vE(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,t.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(t.webmcp))}createWebMcpBridge(t){return Pv().then(o=>{let n=new o.WebMcpBridge(t,{recordToolDisplayTitles:wv,getToolDisplayTitle:dc,loadPolyfill:Tv});return this.pendingWebMcpConfirmHandler!==void 0&&n.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=n,n}).catch(o=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",o),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(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.pendingWebMcpConfirmHandler=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,o,n){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(t,o,n):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:o,target:n,targetProviders:r}=this.config;if(!n)return{agentId:t,flowId:o};let a=Lv(n,r);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||cx}getClientApiUrl(t){return`${this.clientApiBase()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let o=await this.initSession(),n=!1;for(;;){let r=o.conversationId,a=await this.readVisitorToken();if(o.durableRecovery?.enabled!==!0||!r||!a)throw new Fe("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,d=new URLSearchParams({sessionId:o.sessionId,after:t.after}),c=await fetch(`${i}?${d}`,{method:"GET",headers:{"X-Persona-Version":Un,"X-Visitor-Token":a},signal:t.signal});if(c.status===401&&!n){n=!0,o=await this.recoverFromUnauthorized(await this.readErrorCode(c),null,!0);continue}if(!c.ok)throw await this.historyErrorFor(c,!0);return c}}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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.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 t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}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 t=this.historyIdentityStatus;return t?.state==="browser_only"?t: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(t){let o=this.getHistoryIdentityStatus(),n=o.state===t.state&&fx(o)===fx(t);if(this.historyIdentityStatus=t,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let o=this.isHistoryCapable()&&!t.omitVisitorFields,n=!t.omitVisitorFields,r=null;(o||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let a=this.routing(),i=a.agentId??a.flowId,d=o||t.durableResume?t.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...o&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(o||n)&&r?{visitorToken:r}:{},...o&&t.identityProof?{identityProof:t.identityProof}:{},...d?{conversationId:d}:t.storedSessionId?{sessionId:t.storedSessionId}:{}},u=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Un},body:JSON.stringify(c)});if(u.status===400&&n){let m={...c};delete m.durableRecovery,u=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Un},body:JSON.stringify(m)})}if(!u.ok){let m=await u.json().catch(()=>({error:"Session initialization failed"}));if(o&&u.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),d)throw new Fe("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw u.status===403&&m.error==="durable_recovery_disabled"?new Fe("history_disabled","Durable recovery is disabled for this surface"):(o||t.durableResume)&&u.status===401&&m.error==="visitor_required"?new Fe("visitor_required","Visitor credential no longer resolves"):d&&u.status===404?new Fe("not_found","Conversation not found"):u.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):u.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let p=await u.json();return p.visitor?.token&&await this.historyInternals.visitorStore?.set(p.visitor.token),{sessionId:p.sessionId,expiresAt:new Date(p.expiresAt),flow:p.flow,...p.conversationId?{conversationId:p.conversationId}:{},...p.targetId??p.flow?.id?{targetId:p.targetId??p.flow?.id}:{},...p.conversationRevision?{conversationRevision:p.conversationRevision}:{},...p.durableRecovery?{durableRecovery:p.durableRecovery}:{},...p.visitor?{visitor:p.visitor}:{},config:{welcomeMessage:p.config.welcomeMessage,placeholder:p.config.placeholder,theme:p.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,o=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!o)return this.ordinaryInit(t,!1);let n=await this.readVisitorToken();if(t&&n)try{let r=await this.createClientSession({conversationId:t,durableResume:o});return o&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,t,!1)}catch(r){if(!Kf(r,"not_found")&&!Kf(r,"visitor_required")&&!Kf(r,"history_disabled"))throw r;return o&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,o){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.doOrdinaryInit(t,o)):this.doOrdinaryInit(t,o)}async doOrdinaryInit(t,o){let n=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),a=await this.claimFirstConversation(r);return this.finishInit(a,t,o)}async reinitWithProof(t){let o=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:o,identityProof:t}),a=this.finishInit(r,n,!1);return this.clientSession=a,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),a}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&t.durableRecovery?.enabled!==!0)return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,o,n){let r=t.conversationId;return r&&o&&(n||r!==o)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:o,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let o=!1;return{session:t,commit:()=>{o||(o=!0,this.clientSession=t,this.resetClientToolsFingerprint())},discard:()=>{o=!0}}}async prepareConversationSession(t,o){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new Fe("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let n=o?.proof??null;if(!await this.readVisitorToken()&&!n)throw new Fe("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let a=await this.createClientSession({conversationId:t,identityProof:n});return this.prepared(a)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}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(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Un},body:JSON.stringify(r)});if(!a.ok){let i=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:t,type:o})}async submitCSATFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:t,comment:o})}async submitNPSFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:t,comment:o})}historyUrl(t,o){let n=new URLSearchParams;for(let[a,i]of Object.entries(o))i===void 0||i===""||n.set(a,String(i));let r=n.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let o=this.config.features?.history?.scope;return o||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,o){let n=this.config.getIdentityProof;if(!n)return o&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;o&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await n()??null}catch{throw o&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new Fe("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Fe("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return o&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,o,n){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(o);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Fe("proof_not_admitted",mx);return r}async readErrorCode(t){let o=await t.json().catch(()=>({}));return typeof o.error=="string"?o.error:typeof o.message=="string"?o.message:""}async recoverFromUnauthorized(t,o,n){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Fe("invalid_identity_proof",gx);if(r.includes("visitor token required"))throw new Fe("visitor_token_missing",hx);if(r.includes("visitor_identity_mismatch")){if(!o)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Fe("visitor_identity_mismatch",yx);return this.reinitWithProof(o)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new Fe("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,o){let n=await this.readErrorCode(t);if(t.status===404)return new Fe("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new Fe("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&n.includes("identity_proof_not_admitted"))return o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Fe("proof_not_admitted",mx);if(t.status===401){let r=n.toLowerCase();return r.includes("invalid_identity_proof")?(o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Fe("invalid_identity_proof",gx)):r.includes("visitor token required")?new Fe("visitor_token_missing",hx):r.includes("visitor_identity_mismatch")?new Fe("visitor_identity_mismatch",yx):new Fe("unauthorized",n||"History request was not authorized")}return new Fe("request_failed",n||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,o,n){let r=t?.toLowerCase()??null;if(o){if(r==="admitted"){n&&this.setHistoryIdentityStatus({state:"verified"});return}throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new Fe("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Fe("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new Fe("identity_contract_violation","Server admitted an identity proof that was never sent");n&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,o){this.assertHistoryUsable();let n=o.trackIdentity!==!1,r=await this.initSession(),a=null;this.resolveHistoryScope(o.scope)==="verified-user"&&(a=await this.resolveIdentityProof(r,n),a&&(r=await this.bindIdentity(r,a,n)));let i=this.historyInternals.visitorStore,d=!1;for(;;){let c=i?.revision()??0,u=await this.readVisitorToken();if(!u&&!o.visitorTokenOptional)throw new Fe("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(this.historyUrl(t,{...o.query,sessionId:r.sessionId}),{method:o.method,headers:{"X-Persona-Version":Un,...u?{"X-Visitor-Token":u}:{},...a?{"X-Identity-Proof":a}:{},...o.body!==void 0?{"Content-Type":"application/json"}:{}},...o.body!==void 0?{body:JSON.stringify(o.body)}:{},...o.keepalive?{keepalive:!0}:{}});if(p.status===401&&!d){d=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(p),a,n);continue}if(!p.ok)throw await this.historyErrorFor(p,n);let m=p.headers.get("X-History-Identity-Status"),h=await p.json().catch(()=>{});if(i&&i.revision()!==c)throw new Fe("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,a!==null,n),h}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new Fe("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let o=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(o?.data)?o.data:[]).map(px),nextCursor:typeof o?.nextCursor=="string"?o.nextCursor:null}}async getConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...o?.messageCursor?{messageCursor:o.messageCursor}:{}},...o?.scope?{scope:o.scope}:{}}),r=n&&typeof n.conversation=="object"&&n.conversation!==null?n.conversation:n;return{summary:px(r),messages:Array.isArray(n?.messages)?n.messages:[],nextMessageCursor:typeof n?.nextMessageCursor=="string"?n.nextMessageCursor:null,conversationRevision:typeof n?.conversationRevision=="string"?n.conversationRevision:null}}async finalizeDisplayProjections(t,o){this.assertHistoryUsable();let n=0;for(let c of o){let u=c.displayContent.length;if(u>ux)throw new Fe("payload_too_large",`displayContent exceeds the ${ux} character limit`);n+=u}if(n>zf)throw new Fe("payload_too_large",`Display projection batch exceeds the ${zf} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,a=r?.revision()??0,i=await this.historyFetch(`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:o},scope:"browser",keepalive:n<=zf,trackIdentity:!1}),d=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return d&&this.clientSession?.conversationId===t&&(r?.revision()??0)===a&&this.historyInternals.setStoredConversationRevision?.(d),{conversationRevision:d}}async deleteConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...o?.scope?{scope:o.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async deleteAllConversations(t){let o=await this.historyFetch("conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.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(t,o){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,o):this.isAgentMode()?this.dispatchAgent(t,o):this.dispatchProxy(t,o)}async dispatchClientToken(t,o){let n=Rv();this.currentClientTurnId=n;let r=()=>this.currentClientTurnId===n,a=i=>{r()&&o(i)};o({type:"status",status:"connecting"});try{let i=await this.initSession();if(new Date>=new Date(i.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let x=new Error("Session expired. Please refresh to continue.");throw a({type:"error",error:x}),x}let d=await this.buildPayload(t.messages),c=i.durableRecovery?.enabled===!0?await this.readVisitorToken():null,u=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([x])=>x!=="sessionId"&&x!=="session_id")):void 0,p=this.isHistoryCapable(),m={sessionId:i.sessionId,messages:t.messages.filter(Gf).map(x=>{let T=p?ll(x):void 0;return{id:x.id,role:x.role,content:x.contentParts??x.llmContent??x.rawContent??x.content,...T!==void 0&&{displayContent:T}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:n,...t.interrupt&&{submitMode:"interrupt"}},{response:h,commit:y}=await this.sendWithClientToolsDiff(i.sessionId,d.clientTools,x=>{let T={...m,...x};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",T),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Un,...c?{"X-Visitor-Token":c}:{}},body:JSON.stringify(T),signal:t.signal})});if(!h.ok){let x=await h.json().catch(()=>({error:"Chat request failed"}));if(h.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let w=new Error("Session expired. Please refresh to continue.");throw a({type:"error",error:w}),w}if(h.status===429){let w=new Error(x.hint||"Message limit reached for this session.");throw a({type:"error",error:w}),w}if(h.status===410&&x.error==="conversation_deleted"){let w=new Fe("conversation_deleted","This conversation was deleted");throw a({type:"error",error:w}),w}let T=new Error(x.error||"Failed to send message");throw a({type:"error",error:T}),T}if(!h.body){let x=new Error("No response body received");throw a({type:"error",error:x}),x}y(),a({type:"status",status:"connected"});try{await this.streamResponse(h.body,a,t.assistantMessageId)}finally{a({type:"status",status:"idle"})}}catch(i){let d=i instanceof Error?i:new Error(String(i));throw!(d instanceof Fe)&&!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&a({type:"error",error:d}),d}}async dispatchProxy(t,o){o({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o)}finally{o({type:"status",status:"idle"})}}async dispatchAgent(t,o){o({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o,t.assistantMessageId)}finally{o({type:"status",status:"idle"})}}async processStream(t,o,n,r){o({type:"status",status:"connected"});try{await this.streamResponse(t,o,n,r)}finally{o({type:"status",status:"idle"})}}async resolveApproval(t,o){let n=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(n,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:o,streamResponse:!0})})}async sendWithClientToolsDiff(t,o,n,r){let a=!!(o&&o.length>0),i=a?Mv(o):void 0,d=this.clientToolsFingerprintSessionId===t,c=a&&d&&this.lastSentClientToolsFingerprint===i,u=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,m;for(let h=0;;h++){if(m=await n({...a&&(p||!c)&&o?{clientTools:o}:{},...u?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),m.status===409&&h===0&&a&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:u&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,o,n){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||cx}/resume`,i,d=null;if(r){let p=await this.initSession();i=p.sessionId,p.durableRecovery?.enabled===!0&&(d=await this.readVisitorToken())}let c={"Content-Type":"application/json",...d?{"X-Visitor-Token":d}:{},...this.headers};this.getHeaders&&Object.assign(c,await this.getHeaders());let u={executionId:t,toolOutputs:o,streamResponse:n?.streamResponse??!0,...n?.after?{after:n.after}:{}};if(i&&(u.sessionId=i),r&&i){let p=[...Wa(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:h}=await this.sendWithClientToolsDiff(i,p,y=>{let x={...u,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",x),fetch(a,{method:"POST",headers:c,body:JSON.stringify(x),signal:n?.signal})},{emptyMeansReplace:!0});return m.ok&&h(),m}return fetch(a,{method:"POST",headers:c,body:JSON.stringify(u),signal:n?.signal})}latestMentionContext(t){for(let o=t.length-1;o>=0;o--){let n=t[o];if(n.role==="user")return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async buildContextAggregate(t){let o={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let a=await r({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));let n=this.latestMentionContext(t);return n&&Object.assign(o,n),Object.keys(o).length?o:null}normalizeComposerOptions(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o:void 0}applyInlineAgentModel(t,o){let n=o?.selectedModelId;return!n||!("model"in t)?t:this.config.composer?.models?.some(a=>a.id===n)?{...t,model:n}:t}async buildAgentPayload(t,o){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Gf).filter(u=>u.role==="user"||u.role==="assistant"||u.role==="system").filter(u=>!u.variant||u.variant==="assistant").sort((u,p)=>{let m=new Date(u.createdAt).getTime(),h=new Date(p.createdAt).getTime();return m-h}).map(u=>({role:u.role,content:u.contentParts??u.llmContent??u.rawContent??u.content,createdAt:u.createdAt})),a=this.normalizeComposerOptions(o),i={agent:this.applyInlineAgentModel(this.config.agent??{agentId:n},a),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};a&&(i.composerOptions=a);let d=[...Wa(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];d.length>0&&(i.clientTools=d);let c=await this.buildContextAggregate(t);return c&&(i.context=c),i}async buildPayload(t,o){let n=t.slice().filter(Gf).sort((u,p)=>{let m=new Date(u.createdAt).getTime(),h=new Date(p.createdAt).getTime();return m-h}).map(u=>({role:u.role,content:u.contentParts??u.llmContent??u.rawContent??u.content,createdAt:u.createdAt})),r=this.routing(),a={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[u,p]of Object.entries(r.targetPayload))u!=="messages"&&(a[u]=p);let i=[...Wa(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];i.length>0&&(a.clientTools=i);let d=await this.buildContextAggregate(t);d&&(a.context=d);let c=this.normalizeComposerOptions(o);if(c&&(a.composerOptions=c),this.requestMiddleware)try{let u=await this.requestMiddleware({payload:{...a},config:this.config});if(u&&typeof u=="object"){let p=u;return a.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=a.clientTools),p}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",u)}return a}async handleCustomSSEEvent(t,o,n,r,a,i){if(!this.parseSSEEvent)return!1;try{let d=await this.parseSSEEvent(t);if(d===null)return!1;let c=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return n.current=m,r(m),m},u=p=>n.current?n.current:c(p);if(d.text!==void 0){d.partId!==void 0&&i.current!==null&&d.partId!==i.current&&(n.current&&(n.current.streaming=!1,r(n.current)),c(d.partId)),d.partId!==void 0&&(i.current=d.partId);let p=u(d.partId);d.partId!==void 0&&!p.partId&&(p.partId=d.partId),p.content+=d.text,r(p)}return d.done&&(n.current&&(n.current.streaming=!1,r(n.current)),i.current=null,o({type:"status",status:"idle"})),d.error&&(i.current=null,o({type:"error",error:new Error(d.error)})),!0}catch(d){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",d),!1}}async streamResponse(t,o,n,r){let a=t.getReader(),i=new TextDecoder,d="",c=Date.now(),u=0,p=()=>c+u++,m=B=>{let ee=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,S=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,U=B.tools?B.tools.map(q=>({...q,chunks:q.chunks?[...q.chunks]:void 0})):void 0;return{...B,reasoning:ee,toolCall:S,tools:U}},h=B=>{if(B.role!=="assistant"||B.variant)return!0;let ee=Array.isArray(B.contentParts)&&B.contentParts.length>0,S=typeof B.rawContent=="string"&&B.rawContent.trim()!=="";return typeof B.content=="string"&&B.content.trim()!==""||ee||S||!!B.stopReason},y=B=>{h(B)&&o({type:"message",message:m(B)})},x=null,T=null,w={current:null},k={current:null},P=null,R="",b=new Map,A=new Map,C=new Map,L=new Map,F=new Map,X={lastId:null,byStep:new Map},G={lastId:null,byCall:new Map},E=B=>{if(B==null)return null;try{return String(B)}catch{return null}},O=B=>E(B.stepId??B.step_id??B.step??B.parentId??B.flowStepId??B.flow_step_id),D=B=>E(B.callId??B.call_id??B.requestId??B.request_id??B.toolCallId??B.tool_call_id??B.stepId??B.step_id),W=n,te=!1,Q=()=>{if(x)return x;let B,ee="",S=P;return!te&&W?(B=W,te=!0,ee=r??""):W&&S?B=`${W}_${S}`:B=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:B,role:"assistant",content:ee,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},y(x),x},de=(B,ee)=>{X.lastId=ee,B&&X.byStep.set(B,ee)},pe=(B,ee)=>{let S=B.reasoningId??B.id,U=O(B);if(S){let $=String(S);return de(U,$),$}if(U){let $=X.byStep.get(U);if($)return X.lastId=$,$}if(X.lastId&&!ee)return X.lastId;if(!ee)return null;let q=`reason-${p()}`;return de(U,q),q},Ce=B=>{let ee=L.get(B);if(ee)return ee;let S={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:B,status:"streaming",chunks:[]}};return L.set(B,S),y(S),S},Ee=(B,ee)=>{G.lastId=ee,B&&G.byCall.set(B,ee)},ge=new Set,Ke=new Map,Bt=new Set,Le=new Map,j=B=>{if(!B)return!1;let ee=B.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},qe=(B,ee)=>{let S=B.toolId??B.id,U=D(B);if(S){let $=String(S);return Ee(U,$),$}if(U){let $=G.byCall.get(U);if($)return G.lastId=$,$}if(G.lastId&&!ee)return G.lastId;if(!ee)return null;let q=`tool-${p()}`;return Ee(U,q),q},Ge=B=>{let ee=F.get(B);if(ee)return ee;let S={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:B,status:"pending"}};return F.set(B,S),y(S),S},Ae=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let ee=Number(B);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let S=Date.parse(B);if(!Number.isNaN(S))return S}return Date.now()},De=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},he=new Map,gt=new Map,dn=new Map,Js=(B,ee,S)=>{let U=dn.get(B);U||(U=[],dn.set(B,U));let q=0,$=U.length;for(;q<$;){let ne=q+$>>>1;U[ne].seq<ee?q=ne+1:$=ne}U[q]?.seq===ee?U[q]={seq:ee,text:S}:U.splice(q,0,{seq:ee,text:S});let oe="";for(let ne=0;ne<U.length;ne++)oe+=U[ne].text;return oe},oo=(B,ee)=>{let S=De(ee),U=gt.get(B.id),q=xE(U,S);B.rawContent=q;let $=he.get(B.id),oe=$e=>{let Ht=B.content??"";$e.trim()!==""&&(Ht.trim().length===0||$e.startsWith(Ht)||$e.trimStart().startsWith(Ht.trim()))&&(B.content=$e)},ne=()=>{if($){let $e=$.close?.();$e instanceof Promise&&$e.catch(()=>{})}he.delete(B.id),gt.delete(B.id),B.streaming=!1,y(B)};if(!$){oe(S),ne();return}let ie=il(q);if(ie!==null&&ie.trim()!==""){oe(ie),ne();return}let xe=$e=>{let Ht=typeof $e=="string"?$e:$e?.text??null;if(Ht!==null&&Ht.trim()!=="")return Ht;let wt=$.getExtractedText();return wt!==null&&wt.trim()!==""?wt:S},ht;try{ht=$.processChunk(q)}catch{oe(S),ne();return}if(ht instanceof Promise){ht.then($e=>{oe(xe($e)),ne()}).catch(()=>{oe(S),ne()});return}oe(xe(ht)),ne()},Xo=null,Sn=(B,ee,S,U)=>{B.rawContent=ee,he.has(B.id)||he.set(B.id,this.createStreamParser());let q=he.get(B.id),$=ee.trim().startsWith("{")||ee.trim().startsWith("[");if($&&gt.set(B.id,ee),q.__isPlainTextParser===!0){B.content=U!==void 0?ee:B.content+S,gt.delete(B.id),he.delete(B.id),B.rawContent=void 0,y(B);return}let ne=q.processChunk(ee);if(ne instanceof Promise)ne.then(ie=>{let xe=typeof ie=="string"?ie:ie?.text??null;xe!==null&&xe.trim()!==""?(B.content=xe,y(B)):!$&&!ee.trim().startsWith("<")&&(B.content=U!==void 0?ee:B.content+S,gt.delete(B.id),he.delete(B.id),B.rawContent=void 0,y(B))}).catch(()=>{B.content=U!==void 0?ee:B.content+S,gt.delete(B.id),he.delete(B.id),B.rawContent=void 0,y(B)});else{let ie=typeof ne=="string"?ne:ne?.text??null;ie!==null&&ie.trim()!==""?(B.content=ie,y(B)):!$&&!ee.trim().startsWith("<")&&(B.content=U!==void 0?ee:B.content+S,gt.delete(B.id),he.delete(B.id),B.rawContent=void 0,y(B))}},Rt=(B,ee)=>{let S=ee??B.content;if(S==null||S===""){B.streaming=!1,y(B);return}let q=gt.get(B.id)??De(S);B.rawContent=q;let $=he.get(B.id),oe=null,ne=!1;if($&&(oe=$.getExtractedText(),oe===null&&(oe=il(q)),oe===null)){let ie=$.processChunk(q);ie instanceof Promise?(ne=!0,ie.then(xe=>{let ht=typeof xe=="string"?xe:xe?.text??null;ht!==null&&(B.content=ht,B.streaming=!1,he.delete(B.id),gt.delete(B.id),y(B))}).catch(()=>{})):oe=typeof ie=="string"?ie:ie?.text??null}if(!ne){oe!==null&&oe.trim()!==""?B.content=oe:gt.has(B.id)||(B.content=De(S));let ie=he.get(B.id);if(ie){let xe=ie.close?.();xe instanceof Promise&&xe.catch(()=>{}),he.delete(B.id)}gt.delete(B.id),B.streaming=!1,y(B)}},Jr=(B,ee,S)=>{let U=A.get(B);if(U)return U;let q={id:`nested-${ee}-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...S?{variant:S}:{},...S==="reasoning"?{reasoning:{id:B,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return A.set(B,q),y(q),q},Ao=[],wn,di=new Map,Zr=0,po="agent",ci=!1,Tt=null,ut=null,cn=new Map,jl=this.config.iterationDisplay??"separate";for(wn=()=>{for(let B=0;B<Ao.length;B++){let ee=Ao[B].payloadType,S=Ao[B].payload;if(!ci&&po!=="flow"&&typeof S.stepType=="string"&&(po="flow"),ee==="reasoning_start"){let U=typeof S.id=="string"?S.id:null,q=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(U&&q){b.set(U,q),Jr(U,q,"reasoning");continue}let $=pe(S,!0)??`reason-${p()}`,oe=Ce($);oe.reasoning=oe.reasoning??{id:$,status:"streaming",chunks:[]},oe.reasoning.startedAt=oe.reasoning.startedAt??Ae(S.startedAt??S.timestamp),oe.reasoning.completedAt=void 0,oe.reasoning.durationMs=void 0,(S.scope==="loop"||S.scope==="turn")&&(oe.reasoning.scope=S.scope),oe.streaming=!0,oe.reasoning.status="streaming",y(oe)}else if(ee==="reasoning_delta"){let U=typeof S.id=="string"?S.id:null;if(U&&b.has(U)&&A.has(U)){let ne=A.get(U),ie=S.reasoningText??S.text??S.delta??"";ie&&S.hidden!==!0&&ne.reasoning&&(ne.reasoning.chunks.push(String(ie)),y(ne));continue}let q=pe(S,!1)??pe(S,!0)??`reason-${p()}`,$=Ce(q);$.reasoning=$.reasoning??{id:q,status:"streaming",chunks:[]},$.reasoning.startedAt=$.reasoning.startedAt??Ae(S.startedAt??S.timestamp);let oe=S.reasoningText??S.text??S.delta??"";if(oe&&S.hidden!==!0){let ne=typeof S.sequenceIndex=="number"?S.sequenceIndex:void 0;if(ne!==void 0){let ie=Js(q,ne,String(oe));$.reasoning.chunks=[ie]}else $.reasoning.chunks.push(String(oe))}if($.reasoning.status=S.done?"complete":"streaming",S.done){$.reasoning.completedAt=Ae(S.completedAt??S.timestamp);let ne=$.reasoning.startedAt??Date.now();$.reasoning.durationMs=Math.max(0,($.reasoning.completedAt??Date.now())-ne)}$.streaming=$.reasoning.status!=="complete",y($)}else if(ee==="reasoning_complete"){let U=typeof S.id=="string"?S.id:null;if(U&&b.has(U)&&A.has(U)){let ie=A.get(U);if(ie.reasoning){let xe=typeof S.text=="string"?S.text:"";xe&&ie.reasoning.chunks.length===0&&ie.reasoning.chunks.push(xe),ie.reasoning.status="complete",ie.streaming=!1,y(ie)}b.delete(U),A.delete(U);continue}let q=pe(S,!1)??pe(S,!0)??`reason-${p()}`,$=typeof S.text=="string"?S.text:"";!L.get(q)&&($||S.scope==="loop")&&Ce(q);let oe=L.get(q);if(oe?.reasoning){(S.scope==="loop"||S.scope==="turn")&&(oe.reasoning.scope=S.scope),$&&oe.reasoning.chunks.length===0&&oe.reasoning.chunks.push($),oe.reasoning.status="complete",oe.reasoning.completedAt=Ae(S.completedAt??S.timestamp);let ie=oe.reasoning.startedAt??Date.now();oe.reasoning.durationMs=Math.max(0,(oe.reasoning.completedAt??Date.now())-ie),oe.streaming=!1,y(oe)}let ne=O(S);ne&&X.byStep.delete(ne)}else if(ee==="tool_start"){x&&(x.streaming=!1,y(x),x=null),typeof S.iteration=="number"&&(Zr=S.iteration);let U=(typeof S.toolCallId=="string"?S.toolCallId:void 0)??qe(S,!0)??`tool-${p()}`,q=S.toolName??S.name;if(j(q)){ge.add(U);continue}Ee(D(S),U);let $=Ge(U),oe=$.toolCall??{id:U,status:"pending"};oe.name=q??oe.name,oe.status="running",S.parameters!==void 0?oe.args=S.parameters:S.args!==void 0&&(oe.args=S.args),oe.startedAt=oe.startedAt??Ae(S.startedAt??S.timestamp),oe.completedAt=void 0,oe.durationMs=void 0,$.toolCall=oe,$.streaming=!0,S.executionId&&($.agentMetadata={executionId:S.executionId,iteration:S.iteration}),y($)}else if(ee==="tool_output_delta"){let U=qe(S,!1)??qe(S,!0)??`tool-${p()}`;if(ge.has(U))continue;let q=Ge(U),$=q.toolCall??{id:U,status:"running"};$.startedAt=$.startedAt??Ae(S.startedAt??S.timestamp);let oe=S.text??S.delta??S.message??"";oe&&($.chunks=$.chunks??[],$.chunks.push(String(oe))),$.status="running",q.toolCall=$,q.streaming=!0;let ne=S.agentContext;(ne||S.executionId)&&(q.agentMetadata=q.agentMetadata??{executionId:ne?.executionId??S.executionId,iteration:ne?.iteration??S.iteration}),y(q)}else if(ee==="tool_complete"){let U=qe(S,!1)??qe(S,!0)??`tool-${p()}`;if(ge.has(U)){ge.delete(U);continue}let q=Ge(U),$=q.toolCall??{id:U,status:"running"};$.status="complete",S.result!==void 0&&($.result=S.result),typeof S.duration=="number"&&($.duration=S.duration),$.completedAt=Ae(S.completedAt??S.timestamp);let oe=S.duration??S.executionTime;if(typeof oe=="number")$.durationMs=oe;else{let xe=$.startedAt??Date.now();$.durationMs=Math.max(0,($.completedAt??Date.now())-xe)}q.toolCall=$,q.streaming=!1;let ne=S.agentContext;(ne||S.executionId)&&(q.agentMetadata=q.agentMetadata??{executionId:ne?.executionId??S.executionId,iteration:ne?.iteration??S.iteration}),y(q);let ie=D(S);ie&&G.byCall.delete(ie)}else if(ee==="await"&&S.toolName){let U=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:void 0,q=U??S.toolId??`local-${p()}`,$=Ge(q),oe=S.toolName,ne=S.origin==="webmcp"&&!_r(oe)?`webmcp:${oe}`:oe,ie=_r(ne),xe=$.toolCall??{id:q,status:"pending"};xe.name=ne,xe.args=S.parameters,xe.status=ie?"running":"complete",xe.chunks=xe.chunks??[],xe.startedAt=xe.startedAt??Ae(S.startedAt??S.timestamp??S.awaitedAt),ie?(xe.completedAt=void 0,xe.duration=void 0,xe.durationMs=void 0):xe.completedAt=xe.completedAt??xe.startedAt,$.toolCall=xe,$.streaming=!1,$.agentMetadata={...$.agentMetadata,executionId:S.executionId??$.agentMetadata?.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},y($)}else if(ee==="text_start"){let U=typeof S.id=="string"?S.id:null,q=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(U&&q){b.set(U,q);continue}let $=x;$&&(po==="flow"?(Rt($),Xo=$):($.streaming=!1,y($)),x=null),P=typeof S.id=="string"?S.id:P,R=""}else if(ee==="text_delta"){let U=typeof S.id=="string"?S.id:null,q=U?b.get(U):void 0;if(U&&q){let ne=typeof S.delta=="string"?S.delta:"",ie=(C.get(U)??"")+ne;if(C.set(U,ie),ie.trim()==="")continue;let xe=Jr(U,q);xe.agentMetadata={...xe.agentMetadata,executionId:S.executionId,parentToolId:q},Sn(xe,ie,ne,void 0);continue}if(P=typeof S.id=="string"?S.id:P,po==="flow"){let ne=typeof S.delta=="string"?S.delta:"";if(R+=ne,R.trim()==="")continue;let ie=Q();ie.agentMetadata={executionId:S.executionId,iteration:S.iteration},Sn(ie,R,ne,void 0),T=ie;continue}let $=typeof S.delta=="string"?S.delta:"";R+=$;let oe=Q();oe.agentMetadata={executionId:S.executionId,iteration:S.iteration,turnId:Tt??void 0,agentName:ut?.agentName},Sn(oe,R,$,void 0),T=oe}else if(ee==="text_complete"){let U=typeof S.id=="string"?S.id:null;if(U&&b.has(U)){let $=A.get(U);$&&Rt($),b.delete(U),C.delete(U),A.delete(U);continue}let q=x;q&&(po==="flow"?(Rt(q),Xo=q):((q.content??"")===""&&typeof S.text=="string"&&(q.content=S.text),q.streaming=!1,y(q)),x=null),P=null,R=""}else if(ee==="step_complete"){let U=S.stepType,q=S.executionType;if(U==="tool"||q==="context")continue;if(S.success===!1){let $=S.error,oe=typeof $=="string"&&$!==""?$:$!=null&&typeof $=="object"&&Reflect.has($,"message")?String($.message??"Step failed"):"Step failed";o({type:"error",error:new Error(oe)});let ne=x;ne&&ne.streaming&&(ne.streaming=!1,y(ne)),o({type:"status",status:"idle"});continue}{let $=Xo;Xo=null;let oe=S.stopReason,ne=S.result?.response;if($)oe&&($.stopReason=oe),ne!=null?oo($,ne):$.streaming!==!1&&(he.delete($.id),gt.delete($.id),$.streaming=!1,y($));else{let ie=ne!=null&&ne!=="";if(ie||oe){let xe=Q();oe&&(xe.stopReason=oe),ie?Rt(xe,ne):(xe.streaming=!1,y(xe))}}continue}}else if(ee==="execution_start")po=S.kind==="flow"?"flow":"agent",ci=!0,po==="agent"&&(ut={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??"",status:"running",currentIteration:0,maxTurns:S.maxTurns??1,startedAt:Ae(S.startedAt)});else if(ee==="turn_start"){let U=typeof S.iteration=="number"?S.iteration:Zr;if(U!==Zr){if(ut&&(ut.currentIteration=U),jl==="separate"&&U>1){let q=x;q&&(q.streaming=!1,y(q),cn.set(U-1,q),x=null)}Zr=U}Tt=typeof S.id=="string"?S.id:null,T=null}else if(ee==="tool_input_delta"){let U=S.toolCallId??G.lastId;if(U){let q=F.get(U);q?.toolCall&&(q.toolCall.chunks=q.toolCall.chunks??[],q.toolCall.chunks.push(S.delta??""),y(q))}}else{if(ee==="tool_input_complete")continue;if(ee==="turn_complete"){let U=S.stopReason,q=x??T;if(U&&q!==null){let $=S.id;(!$||q.agentMetadata?.turnId===$)&&(q.stopReason=U,y(q))}Tt===S.id&&(Tt=null)}else if(ee==="media_start"){let U=String(S.id);di.set(U,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,role:typeof S.role=="string"?S.role:void 0,toolCallId:S.toolCallId,parts:[]})}else if(ee==="media_delta"){let U=di.get(String(S.id));U&&typeof S.delta=="string"&&U.parts.push(S.delta)}else if(ee==="media_complete"){let U=String(S.id),q=di.get(U);di.delete(U);let $=(typeof S.mediaType=="string"?S.mediaType:void 0)??q?.mediaType??"application/octet-stream",oe=typeof S.data=="string"?S.data:void 0,ne=typeof S.url=="string"?S.url:q&&q.parts.length>0?q.parts.join(""):void 0,ie=null;if(oe)ie={type:"media",data:oe,mediaType:$};else if(ne){let Ht=$.toLowerCase();ie={type:Ht==="image"||Ht.startsWith("image/")?"image-url":"file-url",url:ne,mediaType:$}}let xe=S.toolCallId??q?.toolCallId,ht=ie?[ie]:[],$e=[];for(let Ht of ht){if(!Ht||typeof Ht!="object")continue;let wt=Ht,es=typeof wt.type=="string"?wt.type:void 0,Bo=typeof wt.mediaType=="string"?wt.mediaType.toLowerCase():"",qt=null,fo="";if(es==="media"){let ao=typeof wt.data=="string"?wt.data:void 0;if(!ao)continue;fo=Bo.length>0?Bo:"application/octet-stream",qt=`data:${fo};base64,${ao}`}else if(es==="image-url"){let ao=typeof wt.url=="string"?wt.url:void 0;if(!ao)continue;fo=Bo,qt=ao}else if(es==="file-url"){let ao=typeof wt.url=="string"?wt.url:void 0;if(!ao)continue;fo=Bo,qt=ao}else continue;if(qt)if(es==="image-url"||fo.startsWith("image/"))$e.push({type:"image",image:qt,...fo.includes("/")?{mimeType:fo}:{}});else if(fo.startsWith("audio/"))$e.push({type:"audio",audio:qt,mimeType:fo});else if(fo.startsWith("video/"))$e.push({type:"video",video:qt,mimeType:fo});else{let ao=fo||"application/octet-stream";$e.push({type:"file",data:qt,mimeType:ao,filename:bE(ao)})}}if($e.length>0){let Ht=p(),wt=xe,Bo={id:`agent-media-${typeof wt=="string"&&wt.length>0?`${wt}-${Ht}`:String(Ht)}`,role:"assistant",content:"",contentParts:$e,createdAt:new Date().toISOString(),streaming:!1,sequence:Ht,agentMetadata:{executionId:S.executionId,iteration:typeof S.iteration=="number"?S.iteration:Zr}};y(Bo);let qt=x;qt&&(qt.streaming=!1,y(qt)),x=null,w.current=null}}else if(ee==="execution_complete"){let U=S.kind??po;U==="agent"&&ut&&(ut.status=S.success?"complete":"error",ut.completedAt=Ae(S.completedAt),ut.stopReason=S.stopReason);let q=x;q&&(U==="flow"&&q.streaming!==!1?Rt(q):(q.streaming=!1,y(q)),x=null),P=null,R="",Xo=null,o({type:"status",status:"idle",terminal:!0})}else if(ee==="execution_error"){let U=typeof S.error=="string"?S.error:S.error?.message??"Execution error";o({type:"error",error:new Error(U)})}else if(ee!=="ping"){if(ee==="approval_start"){let U=S.approvalId??`approval-${p()}`,q={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:U,status:"pending",agentId:ut?.agentId??"virtual",executionId:S.executionId??ut?.executionId??"",toolName:S.toolName??"",toolType:S.toolType,description:S.description??`Execute ${S.toolName??"tool"}`,...typeof S.reason=="string"&&S.reason?{reason:S.reason}:{},parameters:S.parameters}};y(q)}else if(ee==="step_await"&&S.awaitReason==="approval_required"){let U=S.approvalId??`approval-${p()}`,q={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:U,status:"pending",agentId:ut?.agentId??"virtual",executionId:S.executionId??ut?.executionId??"",toolName:S.toolName??"",toolType:S.toolType,description:S.description??`Execute ${S.toolName??"tool"}`,...typeof S.reason=="string"&&S.reason?{reason:S.reason}:{},parameters:S.parameters}};y(q)}else if(ee==="approval_complete"){let U=S.approvalId;if(U){let $={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:U,status:S.decision??"approved",agentId:ut?.agentId??"virtual",executionId:S.executionId??ut?.executionId??"",toolName:S.toolName??"",description:S.description??"",resolvedAt:Date.now()}};y($)}}else if(ee==="artifact_start"||ee==="artifact_delta"||ee==="artifact_update"||ee==="artifact_complete"){if(ee==="artifact_start"){let U=S.artifactType,q=String(S.id),$=typeof S.title=="string"?S.title:void 0,oe=S.file,ne;oe&&typeof oe=="object"&&!Array.isArray(oe)&&typeof oe.path=="string"&&typeof oe.mimeType=="string"&&(ne={path:oe.path,mimeType:oe.mimeType,...typeof oe.language=="string"?{language:oe.language}:{}}),o({type:"artifact_start",id:q,artifactType:U,title:$,component:typeof S.component=="string"?S.component:void 0,...ne?{file:ne}:{}});let ie=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?{...S.props}:void 0;if(Le.set(q,{markdown:"",title:$,file:ne,...ie?{props:ie}:{}}),!Bt.has(q)){Bt.add(q);let xe=Nn(this.config.features?.artifacts,{artifactType:U,...ne?{file:ne}:{}}),ht=typeof S.component=="string"?S.component:void 0,$e={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:tl(xe,{artifactId:q,title:$,artifactType:U,status:"streaming",...ne?{file:ne}:{},...ht?{component:ht}:{}})};Ke.set(q,$e),y($e)}}else if(ee==="artifact_delta"){let U=String(S.id),q=typeof S.delta=="string"?S.delta:String(S.delta??"");o({type:"artifact_delta",id:U,artDelta:q});let $=Le.get(U);$&&($.markdown+=q)}else if(ee==="artifact_update"){let U=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?S.props:{};o({type:"artifact_update",id:String(S.id),props:U,component:typeof S.component=="string"?S.component:void 0});let q=Le.get(String(S.id));q&&(q.props={...q.props??{},...U})}else if(ee==="artifact_complete"){let U=String(S.id);o({type:"artifact_complete",id:U});let q=Ke.get(U);if(q){q.streaming=!1;try{let $=JSON.parse(q.rawContent??"{}");if($.props){$.props.status="complete";let oe=Le.get(U);oe?.markdown&&($.props.markdown=oe.markdown),oe?.file&&($.props.file=oe.file),$.component==="PersonaArtifactInline"&&oe?.props&&Object.keys(oe.props).length>0&&($.props.componentProps=oe.props)}q.rawContent=JSON.stringify($)}catch{}Le.delete(U),y(q),Ke.delete(U)}}}else if(ee==="transcript_insert"){let U=S.message;if(!U||typeof U!="object")continue;let q=String(U.id??`msg-${p()}`),$=U.role,ne={id:q,role:$==="user"?"user":$==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:p()};if(y(ne),ne.rawContent)try{let xe=JSON.parse(ne.rawContent)?.props?.artifactId;typeof xe=="string"&&Bt.add(xe)}catch{}x=null,w.current=null,he.delete(q),gt.delete(q)}else if(ee==="error"){if(S.recoverable===!1&&S.error!=null&&S.error!==""){let U=typeof S.error=="string"?S.error:S.error?.message!=null?String(S.error.message):"Execution error";o({type:"error",error:new Error(U)});let q=x;q&&q.streaming&&(q.streaming=!1,y(q)),o({type:"status",status:"idle"})}}else if(ee==="step_error"||ee==="dispatch_error"||ee==="flow_error"){let U=null;if(S.error instanceof Error)U=S.error;else if(ee==="dispatch_error"){let q=S.message??S.error;q!=null&&q!==""&&(U=new Error(String(q)))}else{let q=S.error;typeof q=="string"&&q!==""?U=new Error(q):q!=null&&typeof q=="object"&&Reflect.has(q,"message")&&(U=new Error(String(q.message??q)))}if(U){o({type:"error",error:U});let q=x;q&&q.streaming&&(q.streaming=!1,y(q)),o({type:"status",status:"idle"})}}}}}Ao.length=0};;){let{done:B,value:ee}=await a.read();if(B)break;d+=i.decode(ee,{stream:!0});let S=d.split(`
8
8
 
9
- `);d=C.pop()??"";for(let U of C){let q=U.split(`
10
- `),$="message",ee="",ne=null;for(let $e of q)$e.startsWith("event:")?$=$e.replace("event:","").trim():$e.startsWith("data:")?ee+=$e.replace("data:","").trim():$e.startsWith("id:")&&(ne=$e.slice(3).trim());let ie=()=>{ne!==null&&ne!==""&&o({type:"cursor",id:ne})};if(!ee){ie();continue}let Se;try{Se=JSON.parse(ee)}catch($e){o({type:"error",error:$e instanceof Error?$e:new Error("Failed to parse chat stream payload")});continue}let ht=$!=="message"?$:Se.type??"message";if(this.onSSEEvent?.(ht,Se),this.parseSSEEvent){T.current=S;let $e=await this.handleCustomSSEEvent(Se,o,T,h,p,k);if(T.current&&T.current!==S&&(S=T.current),$e){ie();continue}}Ao.push({payloadType:ht,payload:Se}),Sn(),ie()}}Sn()}};function bE(e){let t=0;for(let o of e.split(`
11
- `)){let n=/^ {0,3}(`+)/.exec(o);n&&n[1].length>t&&(t=n[1].length)}return t}function hx(e,t){let o="`".repeat(Math.max(3,bE(t)+1));return`${o}${e}
9
+ `);d=S.pop()??"";for(let U of S){let q=U.split(`
10
+ `),$="message",oe="",ne=null;for(let $e of q)$e.startsWith("event:")?$=$e.replace("event:","").trim():$e.startsWith("data:")?oe+=$e.replace("data:","").trim():$e.startsWith("id:")&&(ne=$e.slice(3).trim());let ie=()=>{ne!==null&&ne!==""&&o({type:"cursor",id:ne})};if(!oe){ie();continue}let xe;try{xe=JSON.parse(oe)}catch($e){o({type:"error",error:$e instanceof Error?$e:new Error("Failed to parse chat stream payload")});continue}let ht=$!=="message"?$:xe.type??"message";if(this.onSSEEvent?.(ht,xe),this.parseSSEEvent){w.current=x;let $e=await this.handleCustomSSEEvent(xe,o,w,y,p,k);if(w.current&&w.current!==x&&(x=w.current),$e){ie();continue}}Ao.push({payloadType:ht,payload:xe}),wn(),ie()}}wn()}};function CE(e){let t=0;for(let o of e.split(`
11
+ `)){let n=/^ {0,3}(`+)/.exec(o);n&&n[1].length>t&&(t=n[1].length)}return t}function vx(e,t){let o="`".repeat(Math.max(3,CE(t)+1));return`${o}${e}
12
12
  ${t}
13
- ${o}`}var vE=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function xE(e){let t=e?.text?.trim()??"";return t?hx(vE(e),t):""}function yx(e){let t=xE(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[an(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
13
+ ${o}`}var SE=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function wE(e){let t=e?.text?.trim()??"";return t?vx(SE(e),t):""}function xx(e){let t=wE(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[an(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
14
14
 
15
- `)}:{}}function Ic(e,t=140){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,t-1)}\u2026`}function bx(e,t){let o=e.findIndex(r=>r.id===t);if(o===-1||e[o].role!=="user")return null;let n=o+1;for(;n<e.length&&e[n].role!=="user";)n+=1;return{start:o,end:n}}function Vf(e,t){let o=e.findIndex(n=>n.id===t);if(o<=0)return null;for(let n=o-1;n>=0;n-=1)if(e[n].role==="user")return e[n].id;return null}function vx(e){for(let t=e.length-1;t>=0;t-=1){let o=e[t];if(o.role==="user"||o.streaming)return null;if(!(o.role!=="assistant"||o.variant))return Vf(e,o.id)?o.id:null}return null}function Kf(e){return e.role!=="user"||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content=="string"&&e.content.length>0}var ln=class extends Error{constructor(t,o,n){super(o),this.name="HistoryProviderError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};function xx(e){return e instanceof ln}function cl(e){let t=["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 o of t){let n=e.find(r=>r.name===o);if(n)return n}return e.find(o=>o.lang.startsWith("en"))??e[0]}var Ds=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,o){if(!e.isSupported()){o.onError?.(new Error("Web Speech API is unavailable"));return}let n=window.speechSynthesis;n.cancel();let r=new SpeechSynthesisUtterance(t.text),a=n.getVoices();if(t.voice){let i=a.find(d=>d.name===t.voice);i&&(r.voice=i)}else a.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(a):cl(a));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>o.onEnd?.(),r.onerror=i=>{let d=i.error;d==="canceled"||d==="interrupted"?o.onEnd?.():o.onError?.(new Error(d||"Speech synthesis failed"))},setTimeout(()=>{n.speak(r),o.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Oa=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,o){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,o)}async play(t,o){let n=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(n!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(o,{onStart:()=>{n===this.generation&&this.set(t,"playing")},onEnd:()=>{n===this.generation&&this.set(null,"idle")},onError:()=>{n===this.generation&&this.set(null,"idle")}})}catch{n===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(t,o){this.activeId=o==="idle"?null:t,this.state=o;for(let n of this.listeners)n(this.activeId,this.state)}};var CE=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Cx(e){try{if(e?.type==="custom"&&e.custom){let t=e.custom,o=typeof t=="function"?t():t;return!!o&&typeof o.startListening=="function"}return e?.type==="runtype"&&e.runtype?!0:CE()}catch{return!1}}var{setLoader:SE,load:wE}=mt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),Sx=SE,Gf=wE;function Xf(e){if(!e)return"";let t=AE(e);return wx(t!==null?t:e)}function AE(e){let t=e.trim(),o=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(o&&(t=o[1].trim()),!t.startsWith("{"))return null;try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{}return null}function wx(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
15
+ `)}:{}}function Ic(e,t=140){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,t-1)}\u2026`}function Cx(e,t){let o=e.findIndex(r=>r.id===t);if(o===-1||e[o].role!=="user")return null;let n=o+1;for(;n<e.length&&e[n].role!=="user";)n+=1;return{start:o,end:n}}function Xf(e,t){let o=e.findIndex(n=>n.id===t);if(o<=0)return null;for(let n=o-1;n>=0;n-=1)if(e[n].role==="user")return e[n].id;return null}function Sx(e){for(let t=e.length-1;t>=0;t-=1){let o=e[t];if(o.role==="user"||o.streaming)return null;if(!(o.role!=="assistant"||o.variant))return Xf(e,o.id)?o.id:null}return null}function Qf(e){return e.role!=="user"||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content=="string"&&e.content.length>0}var ln=class extends Error{constructor(t,o,n){super(o),this.name="HistoryProviderError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};function wx(e){return e instanceof ln}function cl(e){let t=["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 o of t){let n=e.find(r=>r.name===o);if(n)return n}return e.find(o=>o.lang.startsWith("en"))??e[0]}var Ds=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,o){if(!e.isSupported()){o.onError?.(new Error("Web Speech API is unavailable"));return}let n=window.speechSynthesis;n.cancel();let r=new SpeechSynthesisUtterance(t.text),a=n.getVoices();if(t.voice){let i=a.find(d=>d.name===t.voice);i&&(r.voice=i)}else a.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(a):cl(a));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>o.onEnd?.(),r.onerror=i=>{let d=i.error;d==="canceled"||d==="interrupted"?o.onEnd?.():o.onError?.(new Error(d||"Speech synthesis failed"))},setTimeout(()=>{n.speak(r),o.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Da=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,o){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,o)}async play(t,o){let n=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(n!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(o,{onStart:()=>{n===this.generation&&this.set(t,"playing")},onEnd:()=>{n===this.generation&&this.set(null,"idle")},onError:()=>{n===this.generation&&this.set(null,"idle")}})}catch{n===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(t,o){this.activeId=o==="idle"?null:t,this.state=o;for(let n of this.listeners)n(this.activeId,this.state)}};var AE=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Ax(e){try{if(e?.type==="custom"&&e.custom){let t=e.custom,o=typeof t=="function"?t():t;return!!o&&typeof o.startListening=="function"}return e?.type==="runtype"&&e.runtype?!0:AE()}catch{return!1}}var{setLoader:ME,load:TE}=mt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),Mx=ME,Yf=TE;function Jf(e){if(!e)return"";let t=EE(e);return Tx(t!==null?t:e)}function EE(e){let t=e.trim(),o=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(o&&(t=o[1].trim()),!t.startsWith("{"))return null;try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{}return null}function Tx(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
16
16
  `),t=t.replace(/\n{2,}/g,`
17
- `),t.trim()}var Qf=null,Ax=e=>{Qf=e},Yf=()=>Qf?Qf():import("./runtype-tts-entry");var{setLoader:ME,load:TE}=mt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),Mx=ME,Tx=TE;var EE=["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 PE(e,t){return EE.some(o=>e[o]!==t[o])}var Fn=class extends Error{constructor(t,o){super(o),this.name="SessionHistoryError",this.code=t}};function Jf(e,t){let o=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(o);let n="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return o.message?`${n}
17
+ `),t.trim()}var Zf=null,Ex=e=>{Zf=e},em=()=>Zf?Zf():import("./runtype-tts-entry");var{setLoader:PE,load:kE}=mt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),Px=PE,kx=kE;var LE=["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 IE(e,t){return LE.some(o=>e[o]!==t[o])}var qn=class extends Error{constructor(t,o){super(o),this.name="SessionHistoryError",this.code=t}};function tm(e,t){let o=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(o);let n="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return o.message?`${n}
18
18
 
19
- _Details: ${o.message}_`:n}var Zf=e=>({isError:!0,content:[{type:"text",text:e}]}),LE=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ex=e=>Or(e)||e===Nn,Da=class e{constructor(t={},o,n={}){this.config=t;this.callbacks=o;this.historyInternals=n;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.ttsSpokenMessageIds=new Set;this.readAloud=new Oa(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let o=t.message.toolCall,n=!!o?.name&&(Or(o.name)||o.name===Nn&&$r(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&n&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.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?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.historyInternals=this.composeHistoryInternals(n),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Os(t,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.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&&Gf().catch(()=>{})}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let o=t.host??this.config.apiUrl,n=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!o||!n||!this.config.clientToken||Yf().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Cx(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.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let o=Ds.isSupported()?new Ds({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let n=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,a=this.config.clientToken,i=t.browserFallback!==!1;if(n&&r&&a)return Yf().then(({RuntypeSpeechEngine:d,FallbackSpeechEngine:u})=>{let c=new d({host:n,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&o?new u(c,o,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):c});if(i&&o)return a&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),o}return o}setupVoice(t){try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");let n=++this.voiceSetupGeneration;this.voiceSetupPromise=Gf().then(r=>{n===this.voiceSetupGeneration&&this.wireVoiceProvider(r.createVoiceProvider(o))}).catch(r=>{console.error("Failed to setup voice:",r)}).finally(()=>{n===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(o){console.error("Failed to setup voice:",o)}}wireVoiceProvider(t){try{this.voiceProvider=t;let n=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(r=>{r.provider!=="runtype"&&r.text&&r.text.trim()&&this.sendMessage(r.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((r,a,i)=>{if(r==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let d=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=d.id}if(i){this.pendingVoiceUserMessageId=null;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let d=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=d.id}i&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(r=>{this.voiceLevel=Number.isFinite(r)?Math.max(0,Math.min(1,r)):0}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(r=>{this.config.voiceRecognition?.onMetrics?.(r)}),this.voiceProvider.onError(r=>{console.error("Voice error:",r),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:n,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(r=>{this.voiceStatus=r,this.voiceActive=r==="listening",this.callbacks.onVoiceStatusChanged?.(r)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}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(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.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 t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){this.clientSession=t,this.injectWelcomeMessage(t)}injectWelcomeMessage(t){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||this.messages.length!==0)return;let o={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,o){return this.client.submitMessageFeedback(t,o)}async submitCSATFeedback(t,o){return this.client.submitCSATFeedback(t,o)}async submitNPSFeedback(t,o){return this.client.submitNPSFeedback(t,o)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let o=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:n=>{this.handleHistoryContinuityChanged(n),o?.(n)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new Fn("history_unavailable","No conversation history provider is installed");return t}historyContext(t){let o=this.requireHistoryProvider(),n=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",a=n??(o.capabilities.scopes.includes(r)?r:o.capabilities.scopes[0]??r);if(!o.capabilities.scopes.includes(a))throw new ln("unsupported_scope","This history scope is not supported.");return{scope:a}}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(t,o){this.callbacks.onHistoryNotice?.({code:t,message:o})}async awaitHistorySettled(){let t=this.historyGate;t&&await t.catch(()=>{});let o=this.projectionFinalizationPromise;o&&await o.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Fn("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.requireHistoryProvider().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.historyContext(t?.scope)})}async openConversation(t,o){let n=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(o?.scope);await this.awaitHistorySettled();let a=++this.historyOpenEpoch,i=await n.getPage(t,{context:r});if(a!==this.historyOpenEpoch)throw new Fn("superseded","A later selection won");let d=await n.prepareOpen(t,{context:r});if(a!==this.historyOpenEpoch)throw d.discard(),new Fn("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(d)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=d.conversationId||t,this.activeConversationRevision=d.conversationRevision||i.conversationRevision||null,this.historyNextMessageCursor=i.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let u of i.messages)this.acknowledgedProjections.set(u.id,u.content);return this.persistConversationMetadata(),this.hydrateMessages(i.messages),this.emitHistoryState(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,o,n){let r=this.requireHistoryProvider(),a=this.historyContext(n?.scope),i=o??this.historyNextMessageCursor;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let d=`${t} ${i}`,u=this.olderPageRequests.get(d);if(u)return u;let c=this.fetchOlderPage(r,t,i,a).finally(()=>{this.olderPageRequests.delete(d)});return this.olderPageRequests.set(d,c),c}async fetchOlderPage(t,o,n,r){let a=this.messages[0]?.createdAt,i=await t.getPage(o,{cursor:n,...a?{beforeCreatedAt:a}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==o)return{messages:[],nextMessageCursor:i.nextCursor};let d=dl(this.messages,i.messages);this.messages=this.sortMessages(d.map(u=>this.ensureSequence(u))),this.historyNextMessageCursor=i.nextCursor;for(let u of i.messages)this.acknowledgedProjections.set(u.id,u.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,a=await o.prepareStartNew({context:n});if(r!==this.historyOpenEpoch)throw a.discard(),new Fn("superseded","A later action won");await this.installFreshConversation(a)}async installFreshConversation(t){this.discardConversationState(),await this.commitActivation(t),this.activeConversationId=t.conversationId||null,this.activeConversationRevision=t.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(t,o){let n=this.requireHistoryProvider(),r=this.historyContext(o?.scope);await this.awaitHistorySettled(),await n.delete(t,{context:r}),t===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(t,o,n){let r=this.requireHistoryProvider();if(!r.update)throw new Fn("history_unavailable","This history provider cannot update conversations");let a=this.historyContext(n?.scope);return await this.awaitHistorySettled(),r.update(t,o,{context:a})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=await o.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:n});return await this.recoverFromDestroyedConversation(n),r}async resetHistoryDevice(){let t=this.requireHistoryProvider();if(!t.resetDevice)throw new Fn("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await t.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(t){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(t)}async prepareReplacementConversation(t){let o=this.historyProvider;if(!o){this.historySendBlocked=!1,this.emitHistoryState();return}try{let n=await o.prepareStartNew({context:t});await this.installFreshConversation(n)}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 Fn("new_conversation_required","A new conversation is required before sending")}async commitActivation(t){await t.commit();let o=this.client.getClientSession();o&&o.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(o)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.activeConversationId=t.conversationId,this.activeConversationRevision=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(t)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){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(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.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 t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(o=>this.handleExternalCredentialChange(o))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let o=this.messages.length>0;o||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(),o&&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(t){let o=this.historyProvider,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!o||!n)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let a=this.runBootReconciliation(o,n,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===a&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=a,a}async runBootReconciliation(t,o,n){this.activeConversationId=o;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,a=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&a&&r===a){this.activeConversationRevision=r;return}let i=await t.getPage(o,{context:n}),d=new Set(i.messages.map(m=>m.id)),u=this.messages.some(m=>d.has(m.id)),c=i.messages[0]?.createdAt,p;if(!u)p=i.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,y=this.messages.filter(h=>d.has(h.id)||h.id===m?!0:c!==void 0&&h.createdAt<c);p=dl(y,i.messages).map(h=>this.ensureSequence(h))}this.historyNextMessageCursor=i.nextCursor,this.activeConversationRevision=i.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of i.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(p),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let o of t){let n=ll(o);n!==void 0&&this.acknowledgedProjections.set(o.id,n)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let t=this.activeConversationId;if(!t)return;let o=[];for(let n of this.messages){if(n.role!=="assistant"||n.streaming)continue;let r=ll(n);r!==void 0&&this.acknowledgedProjections.get(n.id)!==r&&o.push({id:n.id,displayContent:r})}o.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:o.map(n=>n.id)}),this.enqueueProjectionFinalization(t,o))}enqueueProjectionFinalization(t,o){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,o,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,o,n){if(this.activeConversationId!==t)return;let r=o.filter(a=>this.acknowledgedProjections.get(a.id)!==a.displayContent);if(r.length===0){this.clearFinalizedMarker(t,o);return}try{let{conversationRevision:a}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.acknowledgedProjections.set(i.id,i.displayContent);this.activeConversationId===t&&a&&(this.activeConversationRevision=a),this.clearFinalizedMarker(t,o)}catch(a){if(!n&&this.isTransientProjectionError(a)){await this.finalizeProjections(t,r,!0);return}if(a instanceof qe&&(a.code==="not_found"||a.code==="conversation_deleted")){this.clearFinalizedMarker(t,o);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof qe?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,o){let n=this.readPendingProjections();if(!n||n.conversationId!==t)return;let r=new Set(o.map(i=>i.id)),a=n.messageIds.filter(i=>!r.has(i));this.setPendingProjections(a.length?{conversationId:t,messageIds:a}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let o=[];for(let n of t.messageIds){let r=this.messages.find(a=>a.id===n);!r||typeof r.content!="string"||o.push({id:n,displayContent:r.content})}if(o.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,o),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(t){return t instanceof qe&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,o,n,r,a){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions,interrupt:a?.interrupt},this.handleEvent);return}catch(i){if(!e.isConversationDeleted(i))throw i;let d=await this.recoverFromDeletedConversation(r);if(!d)throw i;this.recordDispatchedProjections([d]),await this.client.dispatch({messages:[d],signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(t){let o=this.messages.find(r=>r.id===t);if(!o)return null;let n={...o};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 a=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(a)}else{this.client.clearClientSession();let a=await this.client.initSession();this.bindActivatedSession(a)}}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(n),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===n.id)??n}updateConfig(t){let o=this.config.features?.artifacts?.display,n={...this.config,...t},r=JSON.stringify(o)!==JSON.stringify(n.features?.artifacts?.display);if(!PE(this.config,n)){this.config=n,this.client.updateConfig(n),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let a=this.client.getSSEEventCallback();this.config=n,this.client=new Os(this.config,this.historyInternals),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),a&&this.client.setSSEEventCallback(a)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:o,content:n,llmContent:r,contentParts:a,id:i,createdAt:d,sequence:u,streaming:c=!1,voiceProcessing:p,rawContent:m}=t,h={id:i??(o==="user"?La():o==="assistant"?_r():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:o,content:n,createdAt:d??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:c,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let o=[];for(let n of t){let{role:r,content:a,llmContent:i,contentParts:d,id:u,createdAt:c,sequence:p,streaming:m=!1,voiceProcessing:y,rawContent:h}=n,A={id:u??(r==="user"?La():r==="assistant"?_r():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:c??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:m,...i!==void 0&&{llmContent:i},...d!==void 0&&{contentParts:d},...y!==void 0&&{voiceProcessing:y},...h!==void 0&&{rawContent:h}};o.push(A)}return this.messages=this.sortMessages([...this.messages,...o]),this.callbacks.onMessagesChanged([...this.messages]),o}injectComponentDirective(t){let{component:o,props:n={},text:r="",llmContent:a,id:i,createdAt:d,sequence:u}=t,c={text:r,component:o,props:n};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(c),...a!==void 0&&{llmContent:a},...i!==void 0&&{id:i},...d!==void 0&&{createdAt:d},...u!==void 0&&{sequence:u}})}async applyMentionBundle(t,o,n){let r;try{r=await n()}catch{return}let a=r.blocks.join(`
19
+ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]}),RE=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Lx=e=>_r(e)||e===Fn,_a=class e{constructor(t={},o,n={}){this.config=t;this.callbacks=o;this.historyInternals=n;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.ttsSpokenMessageIds=new Set;this.readAloud=new Da(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let o=t.message.toolCall,n=!!o?.name&&(_r(o.name)||o.name===Fn&&jr(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&n&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.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?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.historyInternals=this.composeHistoryInternals(n),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Os(t,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.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&&Yf().catch(()=>{})}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let o=t.host??this.config.apiUrl,n=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!o||!n||!this.config.clientToken||em().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Ax(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.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let o=Ds.isSupported()?new Ds({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let n=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,a=this.config.clientToken,i=t.browserFallback!==!1;if(n&&r&&a)return em().then(({RuntypeSpeechEngine:d,FallbackSpeechEngine:c})=>{let u=new d({host:n,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&o?new c(u,o,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):u});if(i&&o)return a&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),o}return o}setupVoice(t){try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");let n=++this.voiceSetupGeneration;this.voiceSetupPromise=Yf().then(r=>{n===this.voiceSetupGeneration&&this.wireVoiceProvider(r.createVoiceProvider(o))}).catch(r=>{console.error("Failed to setup voice:",r)}).finally(()=>{n===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(o){console.error("Failed to setup voice:",o)}}wireVoiceProvider(t){try{this.voiceProvider=t;let n=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(r=>{r.provider!=="runtype"&&r.text&&r.text.trim()&&this.sendMessage(r.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((r,a,i)=>{if(r==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let d=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=d.id}if(i){this.pendingVoiceUserMessageId=null;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let d=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=d.id}i&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(r=>{this.voiceLevel=Number.isFinite(r)?Math.max(0,Math.min(1,r)):0}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(r=>{this.config.voiceRecognition?.onMetrics?.(r)}),this.voiceProvider.onError(r=>{console.error("Voice error:",r),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:n,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(r=>{this.voiceStatus=r,this.voiceActive=r==="listening",this.callbacks.onVoiceStatusChanged?.(r)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}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(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.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 t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){this.clientSession=t,this.injectWelcomeMessage(t)}injectWelcomeMessage(t){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||this.messages.length!==0)return;let o={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,o){return this.client.submitMessageFeedback(t,o)}async submitCSATFeedback(t,o){return this.client.submitCSATFeedback(t,o)}async submitNPSFeedback(t,o){return this.client.submitNPSFeedback(t,o)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let o=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:n=>{this.handleHistoryContinuityChanged(n),o?.(n)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new qn("history_unavailable","No conversation history provider is installed");return t}historyContext(t){let o=this.requireHistoryProvider(),n=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",a=n??(o.capabilities.scopes.includes(r)?r:o.capabilities.scopes[0]??r);if(!o.capabilities.scopes.includes(a))throw new ln("unsupported_scope","This history scope is not supported.");return{scope:a}}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(t,o){this.callbacks.onHistoryNotice?.({code:t,message:o})}async awaitHistorySettled(){let t=this.historyGate;t&&await t.catch(()=>{});let o=this.projectionFinalizationPromise;o&&await o.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new qn("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.requireHistoryProvider().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.historyContext(t?.scope)})}async openConversation(t,o){let n=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(o?.scope);await this.awaitHistorySettled();let a=++this.historyOpenEpoch,i=await n.getPage(t,{context:r});if(a!==this.historyOpenEpoch)throw new qn("superseded","A later selection won");let d=await n.prepareOpen(t,{context:r});if(a!==this.historyOpenEpoch)throw d.discard(),new qn("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(d)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=d.conversationId||t,this.activeConversationRevision=d.conversationRevision||i.conversationRevision||null,this.historyNextMessageCursor=i.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let c of i.messages)this.acknowledgedProjections.set(c.id,c.content);return this.persistConversationMetadata(),this.hydrateMessages(i.messages),this.emitHistoryState(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,o,n){let r=this.requireHistoryProvider(),a=this.historyContext(n?.scope),i=o??this.historyNextMessageCursor;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let d=`${t} ${i}`,c=this.olderPageRequests.get(d);if(c)return c;let u=this.fetchOlderPage(r,t,i,a).finally(()=>{this.olderPageRequests.delete(d)});return this.olderPageRequests.set(d,u),u}async fetchOlderPage(t,o,n,r){let a=this.messages[0]?.createdAt,i=await t.getPage(o,{cursor:n,...a?{beforeCreatedAt:a}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==o)return{messages:[],nextMessageCursor:i.nextCursor};let d=dl(this.messages,i.messages);this.messages=this.sortMessages(d.map(c=>this.ensureSequence(c))),this.historyNextMessageCursor=i.nextCursor;for(let c of i.messages)this.acknowledgedProjections.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,a=await o.prepareStartNew({context:n});if(r!==this.historyOpenEpoch)throw a.discard(),new qn("superseded","A later action won");await this.installFreshConversation(a)}async installFreshConversation(t){this.discardConversationState(),await this.commitActivation(t),this.activeConversationId=t.conversationId||null,this.activeConversationRevision=t.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(t,o){let n=this.requireHistoryProvider(),r=this.historyContext(o?.scope);await this.awaitHistorySettled(),await n.delete(t,{context:r}),t===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(t,o,n){let r=this.requireHistoryProvider();if(!r.update)throw new qn("history_unavailable","This history provider cannot update conversations");let a=this.historyContext(n?.scope);return await this.awaitHistorySettled(),r.update(t,o,{context:a})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=await o.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:n});return await this.recoverFromDestroyedConversation(n),r}async resetHistoryDevice(){let t=this.requireHistoryProvider();if(!t.resetDevice)throw new qn("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await t.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(t){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(t)}async prepareReplacementConversation(t){let o=this.historyProvider;if(!o){this.historySendBlocked=!1,this.emitHistoryState();return}try{let n=await o.prepareStartNew({context:t});await this.installFreshConversation(n)}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 qn("new_conversation_required","A new conversation is required before sending")}async commitActivation(t){await t.commit();let o=this.client.getClientSession();o&&o.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(o)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.activeConversationId=t.conversationId,this.activeConversationRevision=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(t)}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(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.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 t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(o=>this.handleExternalCredentialChange(o))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let o=this.messages.length>0;o||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(),o&&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(t){let o=this.historyProvider,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!o||!n)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let a=this.runBootReconciliation(o,n,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===a&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=a,a}async runBootReconciliation(t,o,n){this.activeConversationId=o;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,a=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&a&&r===a){this.activeConversationRevision=r;return}let i=await t.getPage(o,{context:n}),d=new Set(i.messages.map(m=>m.id)),c=this.messages.some(m=>d.has(m.id)),u=i.messages[0]?.createdAt,p;if(!c)p=i.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,h=this.messages.filter(y=>d.has(y.id)||y.id===m?!0:u!==void 0&&y.createdAt<u);p=dl(h,i.messages).map(y=>this.ensureSequence(y))}this.historyNextMessageCursor=i.nextCursor,this.activeConversationRevision=i.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of i.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(p),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let o of t){let n=ll(o);n!==void 0&&this.acknowledgedProjections.set(o.id,n)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let t=this.activeConversationId;if(!t)return;let o=[];for(let n of this.messages){if(n.role!=="assistant"||n.streaming)continue;let r=ll(n);r!==void 0&&this.acknowledgedProjections.get(n.id)!==r&&o.push({id:n.id,displayContent:r})}o.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:o.map(n=>n.id)}),this.enqueueProjectionFinalization(t,o))}enqueueProjectionFinalization(t,o){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,o,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,o,n){if(this.activeConversationId!==t)return;let r=o.filter(a=>this.acknowledgedProjections.get(a.id)!==a.displayContent);if(r.length===0){this.clearFinalizedMarker(t,o);return}try{let{conversationRevision:a}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.acknowledgedProjections.set(i.id,i.displayContent);this.activeConversationId===t&&a&&(this.activeConversationRevision=a),this.clearFinalizedMarker(t,o)}catch(a){if(!n&&this.isTransientProjectionError(a)){await this.finalizeProjections(t,r,!0);return}if(a instanceof Fe&&(a.code==="not_found"||a.code==="conversation_deleted")){this.clearFinalizedMarker(t,o);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof Fe?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,o){let n=this.readPendingProjections();if(!n||n.conversationId!==t)return;let r=new Set(o.map(i=>i.id)),a=n.messageIds.filter(i=>!r.has(i));this.setPendingProjections(a.length?{conversationId:t,messageIds:a}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let o=[];for(let n of t.messageIds){let r=this.messages.find(a=>a.id===n);!r||typeof r.content!="string"||o.push({id:n,displayContent:r.content})}if(o.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,o),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(t){return t instanceof Fe&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,o,n,r,a){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions,interrupt:a?.interrupt},this.handleEvent);return}catch(i){if(!e.isConversationDeleted(i))throw i;let d=await this.recoverFromDeletedConversation(r);if(!d)throw i;this.recordDispatchedProjections([d]),await this.client.dispatch({messages:[d],signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(t){let o=this.messages.find(r=>r.id===t);if(!o)return null;let n={...o};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 a=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(a)}else{this.client.clearClientSession();let a=await this.client.initSession();this.bindActivatedSession(a)}}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(n),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===n.id)??n}updateConfig(t){let o=this.config.features?.artifacts?.display,n={...this.config,...t},r=JSON.stringify(o)!==JSON.stringify(n.features?.artifacts?.display);if(!IE(this.config,n)){this.config=n,this.client.updateConfig(n),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let a=this.client.getSSEEventCallback();this.config=n,this.client=new Os(this.config,this.historyInternals),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),a&&this.client.setSSEEventCallback(a)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:o,content:n,llmContent:r,contentParts:a,id:i,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:p,rawContent:m}=t,y={id:i??(o==="user"?La():o==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:o,content:n,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let o=[];for(let n of t){let{role:r,content:a,llmContent:i,contentParts:d,id:c,createdAt:u,sequence:p,streaming:m=!1,voiceProcessing:h,rawContent:y}=n,T={id:c??(r==="user"?La():r==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:u??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:m,...i!==void 0&&{llmContent:i},...d!==void 0&&{contentParts:d},...h!==void 0&&{voiceProcessing:h},...y!==void 0&&{rawContent:y}};o.push(T)}return this.messages=this.sortMessages([...this.messages,...o]),this.callbacks.onMessagesChanged([...this.messages]),o}injectComponentDirective(t){let{component:o,props:n={},text:r="",llmContent:a,id:i,createdAt:d,sequence:c}=t,u={text:r,component:o,props:n};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(u),...a!==void 0&&{llmContent:a},...i!==void 0&&{id:i},...d!==void 0&&{createdAt:d},...c!==void 0&&{sequence:c}})}async applyMentionBundle(t,o,n){let r;try{r=await n()}catch{return}let a=r.blocks.join(`
20
20
 
21
21
  `),i=[a,o].filter(Boolean).join(`
22
22
 
23
- `),d=Array.isArray(t.contentParts)&&t.contentParts.length>0,u=r.contentParts.length>0;if(d){let c=[];a&&c.push(an(a)),c.push(...r.contentParts),c.push(...t.contentParts),t.contentParts=c}else if(u){let c=[];i&&c.push(an(i)),c.push(...r.contentParts),t.contentParts=c}else a&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,o){let n=t.trim(),r=!!o?.replayFields&&(o.replayFields.llmContent!==void 0||o.replayFields.rawContent!==void 0||(o.replayFields.contextMentions?.length??0)>0);if(!n&&(!o?.contentParts||o.contentParts.length===0)&&(!o?.mentions||o.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 a=La(),i=_r();this.activeAssistantMessageId=null;let d=o?.contentParts&&Ba(o.contentParts)?Wa:"",u={id:a,role:"user",content:n||d,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:o?.viaVoice||!1,...o?.contentParts&&o.contentParts.length>0&&{contentParts:o.contentParts},...o?.mentions&&o.mentions.refs.length>0&&{contextMentions:o.mentions.refs},...o?.contentSegments&&o.contentSegments.length>0&&{contentSegments:o.contentSegments},...o?.composerOptions&&{composerOptions:o.composerOptions},...o?.replayFields??{}};this.appendMessage(u),this.setStreaming(!0);let c=new AbortController;if(this.abortController=c,o?.mentions){let m=this.messages.find(y=>y.id===a)??u;if(await this.applyMentionBundle(m,n,o.mentions.finalize),c.signal.aborted||this.abortController!==c)return;this.callbacks.onMessagesChanged([...this.messages])}if(o?.quote&&!o.replayFields){let m=this.messages.find(h=>h.id===a)??u,y=yx({quote:o.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={...o.quote},this.callbacks.onMessagesChanged([...this.messages]))}let p=[...this.messages];try{await this.dispatchWithDeletedRecovery(p,c,i,a,{composerOptions:o?.composerOptions,interrupt:o?.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 h=Jf(m,this.config.errorMessage);if(h){let S={id:i,role:"assistant",createdAt:new Date().toISOString(),content:h,sequence:this.nextSequence()};this.appendMessage(S)}}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(t,o){let n=bx(this.messages,t);if(!n)return!1;let r=this.messages[n.start],a=o.replacement,i=a?a.text:r.content,d=a?a.contentParts:r.contentParts;if(!(!!i?.trim()||(d?.length??0)>0||!a&&(r.llmContent?.trim()?.length??0)>0))return!1;let c=a?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}},p=a?this.toComposerOptionsPayload(a.options):r.composerOptions,m=a?a.contentSegments:r.contentSegments,y=a?a.options?.quote:void 0,h=a?a.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(i??"",{...d?.length?{contentParts:[...d]}:{},...m?.length?{contentSegments:[...m]}:{},...p?{composerOptions:p}:{},...y?{quote:y}:{},...c&&Object.keys(c).length>0?{replayFields:c}:{},viaVoice:h===!0}),!0}toComposerOptionsPayload(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o: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 t=_r();this.activeAssistantMessageId=null,this.setStreaming(!0);let o=new AbortController;this.abortController=o;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:o.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let a=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!a){let i=Jf(r,this.config.errorMessage);if(i){let d={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.nextSequence()};this.appendMessage(d)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,a||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,o){if(this.streaming&&!o?.allowReentry)return;o?.allowReentry||this.abortController?.abort(),o?.preserveAssistantId&&o.assistantMessageId&&(this.activeAssistantMessageId=o.assistantMessageId);let n=o?.preserveAssistantId?o.assistantMessageId:void 0,r=!1;for(let a of this.messages)a.streaming&&a.id!==n&&(a.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,o?.assistantMessageId,o?.seedContent)}catch(a){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(a instanceof Error?a:new Error(String(a)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(o=>this.requestWebMcpApproval(o))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let o={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},n=`approval-${o.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o}),new Promise(r=>{this.webMcpApprovalResolvers.set(n,r)})}resolveWebMcpApproval(t,o){let n=this.webMcpApprovalResolvers.get(t);if(!n)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(a=>a.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:o,resolvedAt:Date.now()}}),n(o==="approved")}async resolveApproval(t,o,n){let r=`approval-${t.id}`,a={...t,status:o,resolvedAt:Date.now()},i=this.messages.find(p=>p.id===r),d={id:r,role:"assistant",content:"",createdAt:i?.createdAt??new Date().toISOString(),...i?.sequence!==void 0?{sequence:i.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(d),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let u=this.config.approval,c=u&&typeof u=="object"?u.onDecision:void 0;try{let p;if(c?p=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},o,n):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},o),p){let m=null;if(p instanceof Response){if(!p.ok){let y=await p.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);m?await this.connectStream(m,{allowReentry:!0}):(o==="denied"&&this.appendMessage({id:`denial-${t.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(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:o.answers,askUserQuestionIndex:o.currentIndex}})}markAskUserQuestionResolved(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...o?{askUserQuestionAnswers:o}:{}}})}async resolveAskUserQuestion(t,o){if(this.messages.find(p=>p.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,a=t.toolCall?.name;if(!r||!a){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof o=="string"?void 0:o;if(i===void 0&&typeof o=="string"){let p=t.toolCall?.args,m=Array.isArray(p?.questions)?p.questions:[];if(m.length===1){let y=typeof m[0]?.question=="string"?m[0].question:"";y&&(i={[y]:o})}}this.markAskUserQuestionResolved(t,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=t.toolCall.id,u=t.toolCall?.args,c=Array.isArray(u?.questions)?u.questions:[];if(c.length===0){let p=typeof o=="string"?o:Object.entries(o).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | ");this.appendMessage({id:`ask-user-answer-${d}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let p=i??{};c.forEach((m,y)=>{let h=typeof m?.question=="string"?m.question:"";if(!h)return;let S=p[h],A=Array.isArray(S)?S.join(", "):typeof S=="string"?S:"";this.appendMessage({id:`ask-user-q-${d}-${y}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${d}-${y}`,role:"user",content:A||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let p=await this.client.resumeFlow(r,{[a]:o});if(!p.ok){let m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}p.body?await this.connectStream(p.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}enqueueWebMcpAwait(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.id;if(!o||!n){let a=this.webMcpEpoch;queueMicrotask(()=>{a===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(o);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(o,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let o of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(o)})}flushWebMcpAwaitBatch(t){let o=this.webMcpAwaitBatches.get(t);if(!o)return;this.webMcpAwaitBatches.delete(t);let{snapshots:n}=o;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(t,n)}resolveWebMcpToolStartedAt(t){let n=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of n)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Nn?!1:(this.messages.find(n=>n.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let o=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:o,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),o}markWebMcpToolComplete(t,o,n,r=Date.now(),a){this.messages.some(i=>i.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:o,startedAt:n,completedAt:r,duration:void 0,durationMs:Math.max(0,r-n)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,o){let n=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let a=await Promise.all(o.map(async d=>{let u=d.toolCall?.name,c=d.toolCall?.id;if(!u||!c)return null;let p=`${t}:${c}`;if(this.webMcpInflightKeys.has(p)||this.webMcpResolvedKeys.has(p)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(p),n.push(p);let m=this.markWebMcpToolRunning(d),y=d.agentMetadata?.webMcpToolCallId??u;if(u===Nn)return{dedupeKey:p,resumeKey:y,output:jv(),toolMessage:d,startedAt:m,completedAt:Date.now()};let h=this.client.executeWebMcpToolCall(u,d.toolCall?.args,r.signal),S;if(!h)S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{S=await h}catch(A){let T=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));return T||this.callbacks.onError?.(A instanceof Error?A:new Error(String(A))),this.markWebMcpToolComplete(d,Zf(T?"Aborted by cancel()":LE(A)),m),this.webMcpInflightKeys.delete(p),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,Zf("Aborted by cancel()"),m),this.webMcpInflightKeys.delete(p),null):{dedupeKey:p,resumeKey:y,output:S,toolMessage:d,startedAt:m,completedAt:Date.now()}})),i=[];try{if(i=a.filter(c=>c!==null),i.length===0)return;let d={};for(let c of i)d[c.resumeKey]=c.output;let u=await this.client.resumeFlow(t,d,{signal:r.signal});if(!u.ok){let c=await u.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${u.status}`)}for(let c of i)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Nn?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.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 c of i)this.markWebMcpToolComplete(c.toolMessage,Zf("Aborted by cancel()"),c.startedAt)}finally{for(let d of n)this.webMcpInflightKeys.delete(d);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.name,r=t.toolCall?.id;if(!o){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!n)return;if(!r){let i=`${o}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(i)||this.webMcpResolvedKeys.has(i))return;this.webMcpInflightKeys.add(i);try{await this.resumeWithToolOutput(o,n,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(i)}catch(d){this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}finally{this.webMcpInflightKeys.delete(i)}return}let a=`${o}:${r}`;if(!(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t)))return this.resolveWebMcpToolCallBatch(o,[t])}async resumeWithToolOutput(t,o,n,r){let a=await this.client.resumeFlow(t,{[o]:n},{signal:r?.signal});if(!a.ok){let i=await a.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${a.status}`)}r?.onHttpOk?.(),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"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(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let o=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=t.artifactType==="markdown"?{id:o,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:o,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(o,n),this.selectedArtifactId=o,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(n),n}injectArtifactRefBlock(t){let o=`artifact-ref-${t.id}`,n=_n(this.config.features?.artifacts,t),r=tl(n,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),a=this.messages.find(i=>i.id===o);if(a){a.rawContent=r,a.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:o,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let o of this.artifacts.values()){let n=this.messages.find(i=>i.id===`artifact-ref-${o.id}`);if(!n)continue;let r=_n(this.config.features?.artifacts,o),a=tl(r,{artifactId:o.id,title:o.title,artifactType:o.artifactType,status:o.status,...o.file?{file:o.file}:{},...o.presentation?{presentation:o.presentation}:{},...o.component?{component:o.component}:{},...o.props?{componentProps:o.props}:{},...o.markdown!==void 0?{markdown:o.markdown}:{}});n.rawContent!==a&&(n.rawContent=a,n.streaming=o.status==="streaming",t=!0)}t&&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(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);o?.artifactType==="markdown"&&(o.markdown=(o.markdown??"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);o?.artifactType==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>({...o,streaming:!1,sequence:o.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,o=null){this.artifacts.clear();for(let n of t)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=o,this.emitArtifactsState()}trackCursor(t){let o=this.agentExecution?.executionId;if(!o||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let n=this.resumable===null;this.resumable={executionId:o,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(n)}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(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.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(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Tx().then(({createReconnectController:t})=>{let o=t(this.buildReconnectHost());return this.reconnectController=o,o}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:o=>t.setStatus(o),setStreaming:o=>t.setStreaming(o),setReconnecting:o=>{t.reconnecting=o},setAbortController:o=>{t.abortController=o},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(o,n,r)=>t.connectStream(o,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:o=>t.appendMessage(o),nextSequence:()=>t.nextSequence(),emitReconnect:o=>t.callbacks.onReconnect?.(o),buildErrorContent:o=>Jf(new Error(o),t.config.errorMessage),onError:o=>t.callbacks.onError?.(o)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let o=this.reopenTrailingAssistant();o||(o=_r(),this.appendMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=o,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:o,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let o=this.messages[t];if(o.role==="assistant"&&!o.variant)return o.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),o.id;if(o.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let o=this.config.onExecutionState;if(o){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),o(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let o=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),o&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let n=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=Xf(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return cl(t)}toggleReadAloud(t){let o=this.messages.find(a=>a.id===t);if(!o||o.role!=="assistant")return;let n=Xf(o.content||"");if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let o=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let o=this.ensureSequence(t),n=this.messages.findIndex(r=>r.id===o.id);if(n===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,a)=>{if(a!==n)return r;let i={...r,...o};if(r.agentMetadata?.askUserQuestionAnswered===!0&&o.agentMetadata&&(i.agentMetadata={...o.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&o.agentMetadata&&(i.agentMetadata={...i.agentMetadata??o.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&o.approval&&r.approval.id===o.approval.id){let p=r.approval,m=o.approval;i.approval={...p,...m,executionId:m.executionId||p.executionId,toolName:m.toolName||p.toolName,description:m.description||p.description,toolType:m.toolType??p.toolType,reason:m.reason??p.reason,parameters:m.parameters??p.parameters}}let d=o.toolCall?.name,u=o.agentMetadata?.executionId,c=o.toolCall?.id;if(d&&Ex(d)&&u&&c&&o.agentMetadata?.awaitingLocalTool===!0){let p=`${u}:${c}`,m=this.webMcpInflightKeys.has(p),y=this.webMcpResolvedKeys.has(p),h=r.toolCall?.name,S=r.agentMetadata?.executionId===u&&r.toolCall?.id===c&&h!==void 0&&Ex(h)&&r.toolCall?.status==="complete";(m||y||S)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((o,n)=>{let r=new Date(o.createdAt).getTime(),a=new Date(n.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(a)&&r!==a)return r-a;let i=o.sequence??0,d=n.sequence??0;return i!==d?i-d:o.id.localeCompare(n.id)})}};var _a=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var em=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var tm=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var ul=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var om=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var nm=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var rm=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var sm=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Na=[["path",{d:"M20 6 9 17l-5-5"}]];var pl=[["path",{d:"m6 9 6 6 6-6"}]];var am=[["path",{d:"m15 18-6-6 6-6"}]];var im=[["path",{d:"m9 18 6-6-6-6"}]];var _s=[["path",{d:"m18 15-6-6-6 6"}]];var lm=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var dm=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var Hc=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Fa=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var cm=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Rc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Wc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var um=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var pm=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var fl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var ml=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Ns=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var gl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var fm=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var mm=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Bc=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var gm=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var hm=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var ym=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var hl=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var bm=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var vm=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var xm=[["path",{d:"M5 12h14"}]];var Oc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M9 3v18"}]];var Cm=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Sm=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var wm=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Am=[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}]];var Mm=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var Tm=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Em=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Pm=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Lm=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var Dc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var km=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Im=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Hm=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Rm=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var Wm=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Bm=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Om=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Dm=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var yl=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Ft=(e,t=24,o="currentColor",n=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(n)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let i=a[0],d=a[1];if(!d)return;let u=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(d).forEach(([c,p])=>{c!=="stroke"&&u.setAttribute(c,String(p))}),r.appendChild(u)}),r};var{setLoader:kE,load:IE}=mt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),Px=kE,_c=IE;var HE={activity:_a,"arrow-down":em,"arrow-up":nm,"arrow-up-right":om,bot:sm,"chevron-down":pl,"chevron-up":_s,"chevron-right":im,"chevron-left":am,check:Na,clipboard:dm,"clipboard-copy":lm,"code-xml":Hc,copy:Fa,file:gl,"file-code":fl,"file-spreadsheet":ml,"file-text":Ns,"image-plus":mm,loader:gm,"loader-circle":Bc,mic:bm,paperclip:Cm,quote:Am,"refresh-cw":Mm,search:Tm,send:Em,"shield-alert":Pm,"shield-check":Lm,"shield-x":Dc,square:km,"thumbs-down":Hm,"thumbs-up":Rm,upload:Om,"volume-2":Dm,x:yl,"at-sign":rm,"arrow-left":tm,"arrow-right":ul,"external-link":um,ellipsis:Wc,"ellipsis-vertical":Rc,menu:ym,"panel-left":Oc,plus:wm,minus:xm,pencil:Sm,trash:Bm,"trash-2":Wm,download:cm,maximize:hm,minimize:vm,"message-square":hl,star:Im,eye:pm,history:fm},RE=["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"],bl=new Map(Object.entries(HE)),Ua=new Set,Nc=!1,Fc=new Set,Lx=e=>{let t=[...Fc];e&&Fc.clear();for(let o of t)try{o()}catch{}},kx=e=>Nc?()=>{}:(Fc.add(e),()=>{Fc.delete(e)}),Ix=()=>{let e=0;for(let t of[...Ua]){let o=bl.get(t.name);if(!o)continue;Ua.delete(t),e++;let n=Ft(o,t.size,t.color,t.strokeWidth);if(n)for(t.el.removeAttribute("data-persona-icon-pending");n.firstChild;)t.el.appendChild(n.firstChild)}return e},Hx=e=>{for(let[t,o]of Object.entries(e))bl.set(t,o);Ix()>0&&!Nc&&Lx(!1)};var _m=!1,WE=()=>{_c().then(e=>{if(!Nc){for(let[t,o]of Object.entries(e.EXTRA_LUCIDE_ICONS))bl.has(t)||bl.set(t,o);Nc=!0,Ix(),Lx(!0)}}).catch(e=>{_m=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},BE=(e,t,o)=>{let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",t),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("data-persona-icon-pending","true"),n},ce=(e,t=24,o="currentColor",n=2)=>{let r=bl.get(e);if(r)return Ft(r,t,o,n);if(RE.includes(e)){_m&&(_m=!1);let a=BE(t,o,n);if(Ua.size>=500){let i=Ua.values().next().value;i&&Ua.delete(i)}return Ua.add({el:a,name:e,size:t,color:o,strokeWidth:n}),WE(),a}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null};var OE={add:e=>tx(e)},DE=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Uc={allowedTypes:ur,maxFileSize:10*1024*1024,maxFiles:4};function _E(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function NE(e){return e==="application/pdf"?Ns:e.startsWith("text/")?Ns:e.includes("word")?Ns:e.includes("excel")||e.includes("spreadsheet")?ml:e==="application/json"?fl:gl}var Fs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??Uc.allowedTypes,maxFileSize:t.maxFileSize??Uc.maxFileSize,maxFiles:t.maxFiles??Uc.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:OE}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let o of this.attachments)this.renderPreview(o)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Uc.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.destroyed)return;let o=[];for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let r=ox(n,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,i);continue}let a={id:_E(),file:n,previewUrl:Lc(n)?URL.createObjectURL(n):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(a),this.renderPreview(a),o.push(a)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(o.map(n=>this.runAdd(n)))}async runAdd(t){let o=new AbortController;this.pendingAdds.set(t.id,o);let n=()=>this.destroyed||o.signal.aborted||this.pendingAdds.get(t.id)!==o||!this.attachments.includes(t);try{let r=await this.adapter().add(t.file,{signal:o.signal,onProgress:a=>{n()||t.status!=="uploading"||(t.progress=DE(a),this.updatePreview(t),this.notify())}});if(n())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(n())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(t.id)===o&&this.pendingAdds.delete(t.id)}this.updatePreview(t),this.notify()}retryAttachment(t){let o=this.attachments.find(n=>n.id===t);!o||o.status!=="error"||this.destroyed||(o.status=this.hasCustomAdapter()?"uploading":"processing",o.progress=this.hasCustomAdapter()?0:void 0,o.error=void 0,this.updatePreview(o),this.notify(),this.runAdd(o))}abortAdd(t){let o=this.pendingAdds.get(t);o&&(this.pendingAdds.delete(t),o.abort())}removeAttachment(t){let o=this.attachments.findIndex(a=>a.id===t);if(o===-1)return;let n=this.attachments[o];this.abortAdd(t),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(o,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),n.status==="ready"&&n.contentPart&&this.releasePart(n.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(t){let o=this.config.adapter?.remove;if(o)try{let n=o(t,{signal:new AbortController().signal});n&&typeof n.catch=="function"&&n.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(n){console.error("[AttachmentManager] adapter.remove failed:",n)}}clearAttachments(){for(let t of this.attachments)this.abortAdd(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let t of this.pendingAdds.values())t.abort();this.pendingAdds.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let o=Lc(t.file),n=I("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",t.id),n.style.width="48px",n.style.height="48px",o&&t.previewUrl){let p=I("img");p.src=t.previewUrl,p.alt=t.file.name,p.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",p.style.width="48px",p.style.height="48px",p.style.objectFit="cover",p.style.borderRadius="8px",n.appendChild(p)}else{let p=I("div");p.style.width="48px",p.style.height="48px",p.style.borderRadius="8px",p.style.backgroundColor="var(--persona-container, #f3f4f6)",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.display="flex",p.style.flexDirection="column",p.style.alignItems="center",p.style.justifyContent="center",p.style.gap="2px",p.style.overflow="hidden";let m=NE(t.file.type),y=Ft(m,20,"var(--persona-muted, #6b7280)",1.5);y&&p.appendChild(y);let h=I("span");h.textContent=nx(t.file.type,t.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",p.appendChild(h),n.appendChild(p)}let r=Y("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),a=I("div","persona-attachment-progress");a.appendChild(I("div","persona-attachment-progress__bar"));let i=Y("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),d=ce("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);d?i.appendChild(d):i.textContent="\u21BB",i.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.retryAttachment(t.id)}),r.append(a,i),n.appendChild(r);let u=I("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");u.type="button",u.setAttribute("aria-label","Remove attachment"),u.style.position="absolute",u.style.top="-4px",u.style.insetInlineEnd="-4px",u.style.width="18px",u.style.height="18px",u.style.borderRadius="50%",u.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",u.style.border="none",u.style.cursor="pointer",u.style.display="flex",u.style.alignItems="center",u.style.justifyContent="center",u.style.padding="0";let c=Ft(yl,10,"var(--persona-text-inverse, #ffffff)",2);c?u.appendChild(c):(u.textContent="\xD7",u.style.color="var(--persona-text-inverse, #ffffff)",u.style.fontSize="14px",u.style.lineHeight="1"),u.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.removeAttachment(t.id)}),n.appendChild(u),this.previewsContainer.appendChild(n),this.applyPreviewState(n,t)}updatePreview(t){let o=this.previewsContainer?.querySelector(`[data-attachment-id="${t.id}"]`);o&&this.applyPreviewState(o,t)}applyPreviewState(t,o){t.dataset.status=o.status;let n=o.status!=="ready"&&o.status!=="error";t.setAttribute("aria-busy",n?"true":"false"),t.title=o.status==="error"?`${o.file.name}: ${o.error??"Upload failed"}`:o.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let a=o.progress;r.style.width=typeof a=="number"?`${Math.round(a*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,o){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:o,adapter:t?.adapter})}};var Rx=(e,t)=>e.length===t.length&&e.every((o,n)=>o===t[n]),FE=(e,t)=>e.length===t.length&&e.every((o,n)=>{let r=t[n];return o.id===r.id&&o.name===r.name&&o.mimeType===r.mimeType&&o.size===r.size&&o.status===r.status&&o.progress===r.progress&&o.error===r.error});function Wx(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,o=null,n=!1,r=!1,a=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",i=()=>{let p=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:p,inputDisabled:e.inputDisabled,sendDisabled:p!=="idle"||e.sendDisabled||e.inputDisabled})},d=()=>(o||(o=i()),o),u=()=>{if(n=!1,r||t.size===0)return;let p=d();for(let m of[...t])try{m(p)}catch(y){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",y)}},c=()=>{o=null,!(r||n)&&(n=!0,queueMicrotask(u))};return{getState:d,subscribe:p=>(t.add(p),()=>t.delete(p)),setText:p=>{e.text!==p&&(e.text=p,c())},setAttachments:p=>{FE(e.attachments,p)||(e.attachments=[...p],c())},setMentionRefs:p=>{Rx(e.mentionRefs,p)||(e.mentionRefs=[...p],c())},setSelectedModelId:p=>{e.selectedModelId!==p&&(e.selectedModelId=p,c())},setActiveModeIds:p=>{Rx(e.activeModeIds,p)||(e.activeModeIds=[...p],c())},setQuote:p=>{let m=e.quote;m?.text===p?.text&&m?.messageId===p?.messageId&&m?.sourceLabel===p?.sourceLabel||(e.quote=p?{...p}:void 0,c())},setPendingSubmission:p=>{e.pendingSubmission!==p&&(e.pendingSubmission=p,c())},setPreparing:p=>{e.preparing!==p&&(e.preparing=p,c())},setStreaming:p=>{e.streaming!==p&&(e.streaming=p,c())},setInputDisabled:p=>{e.inputDisabled!==p&&(e.inputDisabled=p,c())},setSendDisabled:p=>{e.sendDisabled!==p&&(e.sendDisabled=p,c())},flush:()=>{n&&u()},destroy:()=>{r=!0,n=!1,t.clear()}}}var Ro=(e,...t)=>{for(let o of t){let n=e.querySelector(o);if(n)return n}return null},Bx=(e,t)=>{let o=I("div",e);return o.setAttribute(t,""),o.setAttribute("data-persona-composer-synthesized",""),o.style.display="contents",o};function Ox(e,t={}){let o=Ro(e,"[data-persona-composer-form]"),n=Ro(e,"[data-persona-composer-input]");if(!o||!n){let k=`[Persona] composer surface is missing required element(s): ${[!o&&"form",!n&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(o||n))throw new Error(k);return typeof console<"u"&&console.warn(k),null}let r={header:Ro(e,"[data-persona-composer-header]"),body:Ro(e,"[data-persona-composer-body]"),actionsStart:Ro(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Ro(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Ro(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Ro(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Ro(e,"[data-persona-composer-status]")},a=new Set,i=r.header;i||(a.add("header"),i=Bx("persona-widget-composer__header","data-persona-composer-header"),o.parentNode?o.parentNode.insertBefore(i,o):e.appendChild(i));let d=r.body??n.parentElement??o,u=(T,k,P,R,b)=>{if(k)return k;a.add(T);let w=Bx(P,R);return b.appendChild(w),w},c=u("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",o),p=u("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",o),m=u("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),y=u("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[],S=(T,k)=>T.target===k.target&&T.type===k.type&&T.handler===k.handler,A=Ro(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:o,input:n,header:i,body:d,actionsStart:c,actionsEnd:p,suggestions:m,status:y,attachmentInput:A,attachmentPreviews:Ro(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Ro(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Ro(e,"[data-persona-composer-submit]")??void 0,micButton:Ro(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:r,addListener:(T,k,P,R)=>{T.addEventListener(k,P,R),h.push({target:T,type:k,handler:P,options:R})},removeListener:(T,k,P,R)=>{T.removeEventListener(k,P,R),h=h.filter(b=>!S(b,{target:T,type:k,handler:P}))},destroy:()=>{for(let T of h)T.target.removeEventListener(T.type,T.handler,T.options);h=[]}}}var Ut={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},so=1e5,qa=so+1;var UE=8,qE=8,Nm=10,Dx=200,_x=300,Nx=0,$c=e=>Math.max(0,e);function Fx(e){e.delayMs!==void 0&&(Dx=$c(e.delayMs)),e.skipDelayMs!==void 0&&(_x=$c(e.skipDelayMs))}var $E=()=>Date.now()<Nx,jE=e=>{Nx=e>0?Date.now()+e:0},qc=new WeakMap,Um="data-persona-tooltip-suppressed",zE=e=>typeof e.closest=="function"&&e.closest(`[${Um}]`)!==null;function Ux(e){qc.get(e)?.hide()}var qx=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,VE=e=>{let t=e.getRootNode?.();return qx(t)?t:e.ownerDocument.body},Fm=(e,t,o)=>Math.min(Math.max(e,t),Math.max(t,o)),KE=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"];function eo(e){qc.get(e.anchor)?.destroy();let{anchor:t,trigger:o=t,text:n,hint:r,enabled:a=!0,gap:i=UE,viewportPadding:d=qE}=e,u=()=>t.ownerDocument,c=()=>u().defaultView??window,p=null,m=null,y=null,h=null,S,A=!1,T=!1,k=!1,P=()=>(typeof n=="function"?n():n).trim(),R=()=>(typeof r=="function"?r():r??"").trim(),b=()=>$c(e.delayMs??Dx),w=()=>$c(e.skipDelayMs??_x),x=()=>{S!==void 0&&(c().clearTimeout(S),S=void 0)},L=()=>{x();let xe=p!==null;h?.(),h=null,p?.remove(),p=null,m=null,y=null,xe&&jE(w())},F=()=>{if(!p)return;let xe=u(),Pe=c(),ge=t.getBoundingClientRect(),Ke=p.getBoundingClientRect(),Bt=xe.documentElement.clientWidth||Pe.innerWidth,ke=xe.documentElement.clientHeight||Pe.innerHeight,z=Bt-d-Ke.width,Ue=ge.left+ge.width/2-Ke.width/2,Ge=Fm(Ue,d,z),Ae=ge.top-d,De=ke-d-ge.bottom,he=Ke.height+i,gt=Ae>=he||Ae>=De?"top":"bottom",dn=gt==="top"?ge.top-i-Ke.height:ge.bottom+i,Js=ke-d-Ke.height,oo=Fm(dn,d,Js),Xo=ge.left+ge.width/2,jn=Math.max(Nm,Ke.width-Nm),Ht=Fm(Xo-Ge,Nm,jn);p.dataset.placement=gt,p.style.left=`${Ge}px`,p.style.top=`${oo}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${Ht}px`)},X=()=>{if(k||!a||p||!t.isConnected||zE(t))return;let xe=P(),Pe=VE(t);if(!xe||!Pe)return;let ge=u(),Ke=c();p=ge.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(qa);let Bt=Ke.getComputedStyle?.(t);if(Bt){for(let he of KE){let gt=Bt.getPropertyValue(he).trim();gt&&p.style.setProperty(he,gt)}Bt.fontFamily&&(p.style.fontFamily=Bt.fontFamily)}m=ge.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=xe,p.appendChild(m);let ke=R();ke&&(y=ge.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=ke,p.appendChild(y));let z=ge.createElement("span");z.className="persona-control-tooltip__arrow",p.appendChild(z),Pe.appendChild(p),F(),p.dataset.state="open";let Ue=()=>{if(!t.isConnected){L();return}m&&(m.textContent=P()),y&&(y.textContent=R()),F()};Ke.addEventListener("scroll",Ue,!0),Ke.addEventListener("resize",Ue);let Ge=t.getRootNode(),Ae=qx(Ge)?Ge:ge.documentElement,De=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||L()});De?.observe(Ae,{childList:!0,subtree:!0}),h=()=>{Ke.removeEventListener("scroll",Ue,!0),Ke.removeEventListener("resize",Ue),De?.disconnect()}},G=xe=>{if(!(k||p)){if(x(),xe||b()<=0||$E()){X();return}S=c().setTimeout(()=>{S=void 0,X()},b())}},E=()=>{A||T?G(T):L()},_=()=>{let xe=c();(!xe.matchMedia||!xe.matchMedia("(hover: none)").matches)&&(A=!0,E())},O=()=>{A=!1,E()},W=()=>{try{T=t.matches(":focus-visible")}catch{T=!0}E()},oe=()=>{T=!1,E()},Q=()=>{A=!1,T=!1,L()},de=xe=>{xe.key==="Escape"&&Q()};o.addEventListener("mouseenter",_),o.addEventListener("mouseleave",O),t.addEventListener("focus",W),t.addEventListener("blur",oe),t.addEventListener("keydown",de),t.addEventListener("click",Q);let pe={get isOpen(){return p!==null},show:X,hide:L,reposition:F,destroy:()=>{k||(k=!0,L(),o.removeEventListener("mouseenter",_),o.removeEventListener("mouseleave",O),t.removeEventListener("focus",W),t.removeEventListener("blur",oe),t.removeEventListener("keydown",de),t.removeEventListener("click",Q),qc.delete(t))}};return qc.set(t,pe),pe}var $x=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function $a(e,t){if(!e)return t;if(!t)return e;let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];$x(a)&&$x(r)?o[n]=$a(a,r):o[n]=r}return o}var Vo="min(440px, calc(100vw - 24px))",jc="440px",qm="How can I help...",GE={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:Vo,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)"},rt={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:GE,copy:{inputPlaceholder:qm,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 jx(e,t){if(!(!e&&!t))return e?t?$a(e,t):e:t}function ja(e){return e?{...rt,...e,theme:jx(rt.theme,e.theme),darkTheme:jx(rt.darkTheme,e.darkTheme),launcher:{...rt.launcher,...e.launcher,dock:{...rt.launcher?.dock,...e.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...rt.tooltip,...e.tooltip},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=rt.features?.artifacts,o=e.features?.artifacts,n=rt.features?.scrollToBottom,r=e.features?.scrollToBottom,a=rt.features?.scrollBehavior,i=e.features?.scrollBehavior,d=rt.features?.streamAnimation,u=e.features?.streamAnimation,c=rt.features?.askUserQuestion,p=e.features?.askUserQuestion,m=rt.features?.history,y=e.features?.history,h=t===void 0&&o===void 0?void 0:{...t,...o,layout:{...t?.layout,...o?.layout}},S=n===void 0&&r===void 0?void 0:{...n,...r},A=a===void 0&&i===void 0?void 0:{...a,...i},T=d===void 0&&u===void 0?void 0:{...d,...u},k=c===void 0&&p===void 0?void 0:{...c,...p,styles:{...c?.styles,...p?.styles}},P=m===void 0&&y===void 0?void 0:{...m,...y,copy:{...m?.copy,...y?.copy}};return{...rt.features,...e.features,...S!==void 0?{scrollToBottom:S}:{},...A!==void 0?{scrollBehavior:A}:{},...h!==void 0?{artifacts:h}:{},...T!==void 0?{streamAnimation:T}:{},...k!==void 0?{askUserQuestion:k}:{},...P!==void 0?{history:P}:{}}})(),suggestionChips:e.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...rt.layout?.header,...e.layout?.header},messages:{...rt.layout?.messages,...e.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...e.layout?.slots}},markdown:{...rt.markdown,...e.markdown,options:{...rt.markdown?.options,...e.markdown?.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}function $m(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let o=t.getComputedStyle(e).lineHeight;if(!o||!o.trim().endsWith("px"))return 20;let n=parseFloat(o);return Number.isFinite(n)&&n>0?n:20}function zc(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function zx(e,t){e.style.maxHeight=`${t*$m(e)}px`,e.style.overflowY="auto"}function Cl(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function Vx(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Kx(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let o=e.metaKey===!0||e.ctrlKey===!0,n=t.submitKey??"enter";return n==="none"?!1:n==="mod-enter"?o:o||!Vx(t)}function XE(e){return(e.submitKey??"enter")!=="enter"||Vx(e)?"enter":"send"}function Vc(e,t){e.setAttribute("enterkeyhint",XE(t))}function Kc(e,t){let o=t?.autocomplete;e.setAttribute("autocomplete",typeof o=="string"&&o?o:"off");let n=(r,a)=>{a===void 0?e.removeAttribute(r):e.setAttribute(r,a)};n("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),n("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),n("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),n("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function jm(e){return e===!0?{disabled:!0}:!e||typeof e!="object"?{disabled:!1}:{disabled:!0,reason:typeof e.reason=="string"&&e.reason?e.reason:void 0}}var Ko="persona-composer-control",vn="persona-composer-control--glyph",Vm=40,vo=24,Gc=(e,t)=>{let o=I("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=e?.copy?.inputPlaceholder??qm,o.dir="auto",Vc(o,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Cl(o)}),Kc(o,e?.composer?.inputAttributes),o.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",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=zc(e?.composer?.maxLines,t?.defaultMaxLines??3),r=`${n*20}px`;o.style.maxHeight=r,o.style.overflowY="auto";let a=()=>{let d=o.style.maxHeight;if(d!==r){let c=parseFloat(d);if(Number.isFinite(c)&&c>0)return c}let u=n*$m(o);return r=`${u}px`,o.style.maxHeight=r,u},i=()=>{o.addEventListener("input",()=>{o.style.height="auto";let d=Math.min(o.scrollHeight,a());o.style.height=`${d}px`})};return o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"}),{textarea:o,attachAutoResize:i}},YE="[data-persona-glyph-stack]",Km=(e,t,o="send")=>{let n=Y("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":o,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),n.append(e,t),n},Xc=e=>{let t=e?.sendButton??{},o=t.useIcon??!1,n=t.iconText??"\u2191",r=t.iconName,a=t.stopIconName??"square",i=t.tooltipText??"Send message",d=t.stopTooltipText??"Stop generating",u=e?.copy?.sendButtonLabel??"Send",c=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,m=t.size,y=parseFloat(m??"")||Vm,h=t.backgroundColor,S=t.textColor,A=I("div","persona-send-button-wrapper"),T=Y("button",{className:bo("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",o?`persona-flex persona-items-center persona-justify-center ${Ko}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",o&&!h&&"persona-bg-persona-primary",!o&&!S&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:o?m:void 0,height:o?m:void 0,minWidth:o?m:void 0,minHeight:o?m:void 0,fontSize:o?"18px":void 0,lineHeight:o?"1":void 0,color:o?S||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":S||void 0,backgroundColor:o&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:o?"0":t.paddingX||void 0,paddingRight:o?"0":t.paddingX||void 0,paddingTop:o?"0":t.paddingY||void 0,paddingBottom:o?"0":t.paddingY||void 0}}),k=null,P=null,R=null;if(o){let x=parseFloat(t.iconSize??"")||Math.round(y*.5),L=t.iconStrokeWidth??2,F=S?.trim()||"currentColor";r&&(k=ce(r,x,F,L)),P=ce(a,x,F,L),k&&P?(R=Km(k,P),T.appendChild(R)):k?T.appendChild(k):(T.textContent=n,P=null)}else T.textContent=u;T.setAttribute("aria-label",i),A.appendChild(T),eo({anchor:T,trigger:A,text:()=>T.getAttribute("aria-label")??"",enabled:p});let b="send";return{button:T,wrapper:A,setMode:x=>{if(x===b)return;b=x;let L=x==="stop"?d:i;T.setAttribute("aria-label",L),T.setAttribute("data-persona-send-mode",x),o?(T.querySelector(YE)??R)?.setAttribute("data-mode",x):T.textContent=x==="stop"?c:u},glyphStack:R}},za=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let n=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",a=t.provider?.type==="custom";if(!(n||r||a))return null;let d=t.iconName??"mic",u=t.iconSize,c=parseFloat(u??"")||vo,p=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,y=I("div","persona-send-button-wrapper"),h=Y("button",{className:bo("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ko,!u&&vn),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:u,height:u,minWidth:u,minHeight:u,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),A=ce(d,c,m||"currentColor",1.5);A?h.appendChild(A):h.textContent="\u{1F3A4}",y.appendChild(h);let T=t.tooltipText??"Start voice recognition",k=t.showTooltip??!1;return eo({anchor:h,trigger:y,text:()=>h.getAttribute("aria-label")??T,enabled:k}),{button:h,wrapper:y}},Qc=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let o=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=I("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??ur).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",a=I("div","persona-send-button-wrapper"),i=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Ko} ${vn}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),d=ce(r,vo,"currentColor",1.5);d?i.appendChild(d):i.textContent="\u{1F4CE}",i.addEventListener("click",c=>{c.preventDefault(),n.click()}),a.appendChild(i);let u=t.buttonTooltipText??"Attach file";return eo({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??u}),{button:i,wrapper:a,input:n,previewsContainer:o}},Yc=e=>{let t=e?.statusIndicator??{},o=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",n=I("div",`persona-mt-2 ${o} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let r=t.visible??!0;n.style.display=r?"":"none";let a=t.idleText??"Online";if(t.idleLink){let i=I("a");i.href=t.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=a,i.style.color="inherit",i.style.textDecoration="none",n.appendChild(i)}else n.textContent=a;return n},Jc=()=>Y("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function JE(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Zc(e){let{anchor:t,content:o,placement:n="bottom-start",offset:r=6,matchAnchorWidth:a=!1,horizontalOffset:i,verticalOffset:d,zIndex:u=2147483e3,onOpen:c,onDismiss:p}=e,m=e.container??JE(t),y=!1,h=null,S=()=>{if(!y)return;let k=t.getBoundingClientRect();o.style.position="fixed",a&&(o.style.minWidth=`${k.width}px`),i&&(o.style.maxWidth=`${k.width}px`);let P=o.getBoundingClientRect(),R=d?.()??null,b=R!=null?k.top+R:k.top,w=n==="top-start"||n==="top-end"?b-r-P.height:k.bottom+r,L=n==="bottom-end"||n==="top-end"?k.right-P.width:k.left,F=i?.()??null;if(F!=null){let X=Math.max(k.left,k.right-P.width);L=Math.min(Math.max(k.left+F,k.left),X)}o.style.top=`${w}px`,o.style.left=`${L}px`},A=()=>{y&&(y=!1,h&&(h(),h=null),o.remove())},T=()=>{if(y)return;y=!0,u!=null&&(o.style.zIndex=String(u)),m.appendChild(o),S();let k=(t.ownerDocument??document).defaultView??window,P=t.ownerDocument??document,R=()=>{if(!t.isConnected){A(),p?.("anchor-removed");return}S()},b=x=>{let L=typeof x.composedPath=="function"?x.composedPath():[];L.includes(o)||L.includes(t)||(A(),p?.("outside"))},w=k.setTimeout(()=>{P.addEventListener("pointerdown",b,!0)},0);k.addEventListener("scroll",R,!0),k.addEventListener("resize",R),h=()=>{k.clearTimeout(w),P.removeEventListener("pointerdown",b,!0),k.removeEventListener("scroll",R,!0),k.removeEventListener("resize",R)},c?.()};return{get isOpen(){return y},open:T,close:A,toggle:()=>y?A():T(),reposition:S,destroy:A}}var ZE='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',Gm="data-persona-menu-focus",eP=new Set(["ArrowDown","ArrowUp","Home","End"]);function Gx(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(ZE)??e}var tP=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function Xx(e){let t=e.label,o=!1,n=I("div","persona-send-button-wrapper"),r=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Ko} ${vn}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});n.appendChild(r);let a=Y("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let W=e.getButtonSize?.()??"";r.style.width=W,r.style.height=W,r.style.minWidth=W,r.style.minHeight=W,r.style.lineHeight="1",r.replaceChildren();let oe=ce("plus",vo,"currentColor",1.5);oe?r.appendChild(oe):r.textContent="+"},d=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),a.setAttribute("aria-label",t)};d(),i();let u=[],c=-1,p=!1,m=()=>{let oe=a.getRootNode().activeElement;return oe instanceof HTMLElement?oe:null},y=()=>{let W=m();for(let oe of u){let Q=!!W&&Gx(oe)===W;oe.toggleAttribute(Gm,Q&&p)}},h=()=>u.filter(W=>W.isConnected||a.contains(W)).map(Gx).filter(W=>!tP(W)),S=(W,oe)=>{W.forEach((Q,de)=>{Q.setAttribute("tabindex",de===oe?"0":"-1")})},A=W=>{let oe=h();if(oe.length===0)return;let Q=(W%oe.length+oe.length)%oe.length;c=Q,S(oe,Q),oe[Q].focus(),y()},T=()=>n.ownerDocument??document,k=null,P=null,R=null,b=()=>{k&&(T().removeEventListener("focusin",k,!0),k=null)},w=()=>{P&&(a.removeEventListener("focusin",P),P=null),R&&(a.removeEventListener("pointerdown",R,!0),R=null)},x=null,L=()=>(x||(x=Zc({anchor:r,content:a,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),b()}})),x),F=()=>x?.isOpen===!0,X=(W=!1)=>{if(F()){x?.close(),r.setAttribute("aria-expanded","false"),b(),w(),c=-1,p=!1;for(let oe of u)oe.removeAttribute(Gm);W&&r.focus()}},G=(W=0,oe=!1)=>{if(o||F())return;p=oe,L().open(),r.setAttribute("aria-expanded","true");let Q=h();S(Q,-1),A(W<0?Q.length-1:W),k=de=>{let pe=typeof de.composedPath=="function"?de.composedPath():[];pe.includes(a)||pe.includes(n)||X()},T().addEventListener("focusin",k,!0),P=()=>y(),a.addEventListener("focusin",P),R=()=>{p=!1},a.addEventListener("pointerdown",R,!0)},E=W=>{W.preventDefault(),W.stopPropagation(),F()?X(!0):G(0)},_=W=>{if(W.key==="ArrowDown"||W.key==="Enter"||W.key===" "){W.preventDefault(),p=!0,F()?A(0):G(0,!0);return}W.key==="ArrowUp"&&(W.preventDefault(),p=!0,F()?A(-1):G(-1,!0))},O=W=>{switch(eP.has(W.key)&&(p=!0),W.key){case"ArrowDown":W.preventDefault(),A(c+1);return;case"ArrowUp":W.preventDefault(),A(c-1);return;case"Home":W.preventDefault(),A(0);return;case"End":W.preventDefault(),A(h().length-1);return;case"Escape":W.preventDefault(),W.stopPropagation(),X(!0);return;case"Tab":X(!0);return;default:}};return r.addEventListener("click",E),r.addEventListener("keydown",_),a.addEventListener("keydown",O),{trigger:n,triggerButton:r,panel:a,setItems:W=>{for(let Q of u)W.includes(Q)||Q.removeAttribute(Gm);if(u=[...W],!F())return;let oe=h();S(oe,Math.min(c,oe.length-1)),y()},isOpen:F,open:()=>G(0),close:X,setLabel:W=>{W!==t&&(t=W,d())},applyButtonSize:i,destroy:()=>{o=!0,b(),w(),r.removeEventListener("click",E),r.removeEventListener("keydown",_),a.removeEventListener("keydown",O),x?.destroy(),x=null,n.remove(),a.remove(),u=[]}}}var Un={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Qx="data-persona-composer-action",Xm="data-persona-composer-disable-when-streaming",oP="core:overflow",nP=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function rP(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let o=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(o))return o;let n=I("div");n.style.position="absolute",n.style.visibility="hidden",n.style.pointerEvents="none",n.style.height="0",n.style.width=e,t.appendChild(n);let r=n.getBoundingClientRect().width;return n.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(o)?o:null}function Qm(e){let t=e.clientWidth;if(!t)return 0;let o=e.ownerDocument?.defaultView;if(!o?.getComputedStyle)return t;let n=o.getComputedStyle(e),r=(Number.parseFloat(n.paddingLeft)||0)+(Number.parseFloat(n.paddingRight)||0);return Math.max(0,t-r)}var Yx=(e,t)=>{!e||typeof console>"u"||console.warn(t)},sP=(e,t)=>t.includes(":")?t:`${e}:${t}`;function aP(e){let{debug:t}=e,o=[],n=new Map,r=0,a=d=>{let u=n.get(d.id);if(u){Yx(t,`[Persona] composer action "${d.id}" is already contributed by ${Jx(u)}; the ${Jx(d)} copy is ignored.`);return}n.set(d.id,d),o.push(d)};for(let d of e.builtIns)a({id:d.id,placement:d.placement,presentation:"bar",order:d.order,sequence:r++,source:"core",builtIn:d});let i=(d,u,c)=>{let p=c?sP(c,d.id):d.id,m=d.order??Un.custom;d.placement==="end"&&m>=Un.send&&(Yx(t,`[Persona] composer action "${p}" ordered at ${m} would render after send; clamped to ${Un.send-1}.`),m=Un.send-1),a({id:p,placement:d.placement,presentation:d.presentation??"bar",order:m,sequence:r++,source:u,pluginId:c,action:d})};for(let d of e.configActions??[])i(d,"config");for(let d of e.plugins){if(!d.contributeComposerActions)continue;let u;try{u=d.contributeComposerActions(e.contributionContext)}catch(c){typeof console<"u"&&console.error(`[Persona] plugin "${d.id}" contributeComposerActions failed:`,c);continue}for(let c of u??[])i(c,"plugin",d.id)}return o.sort((d,u)=>d.order===u.order?d.sequence-u.sequence:d.order-u.order)}var Jx=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",Zx=(e,t,o)=>e===void 0?o:typeof e=="function"?e(t)===!0:e===!0,zr=e=>e.kind==="custom",Ym=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,iP=e=>{let t=Ym(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},lP='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function dP(e){let t="",o=n=>{if(n.nodeType===Node.TEXT_NODE){t+=n.nodeValue??"";return}if(n.nodeType!==Node.ELEMENT_NODE)return;let r=n;typeof r.matches=="function"&&r.matches(lP)||n.childNodes.forEach(o)};return o(e),t.trim()}var cP=e=>dP(e).length===0;function eC(e){let t=new Map,o=[],n=!1,r=()=>e.getButtonSize?.(),a=(E,_)=>{let O=E.button;if(!O)return;O.setAttribute("role","menuitem"),O.setAttribute("tabindex","-1"),O.className="persona-composer-overflow-menu__item";for(let Q of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])O.style[Q]="";O.style.lineHeight="1",_.tooltipText?O.setAttribute("title",_.tooltipText):O.removeAttribute("title"),O.replaceChildren();let W=I("span","persona-composer-overflow-menu__icon");if(_.iconName){let Q=ce(_.iconName,16,"currentColor",1.5);Q&&W.appendChild(Q)}let oe=I("span","persona-composer-overflow-menu__label");oe.textContent=_.shortLabel??_.label,O.append(W,oe)},i=(E,_)=>{let O=E.button;if(!O)return;if(O.setAttribute("aria-label",_.label),_.pressed===void 0?O.removeAttribute("aria-pressed"):O.setAttribute("aria-pressed",_.pressed?"true":"false"),O.toggleAttribute(Xm,_.disableWhenStreaming===!0),E.mode==="menu"){E.tooltip?.destroy(),E.tooltip=void 0,a(E,_);return}O.removeAttribute("role"),O.removeAttribute("tabindex"),O.removeAttribute("title");let W=r(),oe=!!_.shortLabel;if(O.className=bo("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Ko,vn,oe&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),O.style.width=W&&!oe?W:"",O.style.height=W??"",O.style.minWidth=W&&!oe?W:"",O.style.minHeight=W??"",O.style.fontSize=oe?"":"18px",O.style.lineHeight="1",O.style.color=_.iconColor??"",O.style.backgroundColor=_.backgroundColor??"",O.replaceChildren(),_.iconName){let Q=ce(_.iconName,vo,"currentColor",1.5);Q&&O.appendChild(Q)}if(oe){let Q=I("span","persona-composer-action-button__label");Q.textContent=_.shortLabel,O.appendChild(Q)}else O.firstChild||(O.textContent=_.label);E.tooltip?.destroy(),E.tooltip=eo({anchor:O,trigger:E.element,text:()=>_.tooltipText??_.label,enabled:!!_.tooltipText})},d=(E,_)=>{let O=E.action,W=Y("button",{attrs:{type:"button"}}),oe=W;if(_==="bar"){let pe=I("div","persona-send-button-wrapper");pe.appendChild(W),oe=pe}oe.setAttribute(Qx,E.id);let Q={resolved:E,element:oe,button:W,owned:!0,managed:!0,busy:!1,visible:!0,mode:_},de=pe=>{if(pe.preventDefault(),pe.stopPropagation(),Q.busy||W.disabled)return;let xe=Q.resolved.action;Q.mode==="menu"&&h?.close(!0);let Pe;try{Pe=xe.onSelect(e.actionContext,pe)}catch(ge){e.reportError(ge,{actionId:Q.resolved.id});return}!Pe||typeof Pe.then!="function"||(Q.busy=!0,W.setAttribute("aria-busy","true"),Pe.catch(ge=>{e.reportError(ge,{actionId:Q.resolved.id})}).finally(()=>{Q.busy=!1,W.removeAttribute("aria-busy")}))};return W.addEventListener("click",de),Q.detach=()=>W.removeEventListener("click",de),i(Q,O),Q},u=E=>{let _=E.action,O;try{O=_.render({...e.actionContext,id:E.id,action:_})}catch(W){return e.reportError(W,{actionId:E.id}),null}return O?.element?(O.element.setAttribute(Qx,E.id),O.element.toggleAttribute(Xm,_.disableWhenStreaming===!0),{resolved:E,element:O.element,owned:!0,managed:!0,destroy:O.destroy,busy:!1,visible:!0,mode:"bar"}):null},c=(E,_)=>{if(E.builtIn){let W=E.builtIn.element;return W?{resolved:E,element:W,owned:!1,managed:E.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let O=E.action;return O?zr(O)?u(E):d(E,_):null},p=E=>{if(E.detach?.(),E.tooltip?.destroy(),E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0,E.owned){try{E.destroy?.()}catch(_){e.reportError(_,{actionId:E.resolved.id})}E.element.remove()}},m=(E,_)=>{for(let O=0;O<_.length;O++){let W=_[O];if(!W.managed)continue;let oe=null;for(let Q=O+1;Q<_.length;Q++){let de=_[Q];if(!de.managed&&de.element.parentElement===E){oe=de.element;break}}oe?(W.element.parentElement!==E||W.element.nextSibling!==oe)&&E.insertBefore(W.element,oe):E.lastChild!==W.element&&E.appendChild(W.element)}},y=(E,_)=>{if(E.button){E.button.disabled=_;return}if(!E.owned)return;let O=E.element;O.toggleAttribute("data-disabled",_),O.setAttribute("aria-disabled",_?"true":"false");let W=O instanceof HTMLButtonElement||O instanceof HTMLSelectElement||O instanceof HTMLInputElement||O instanceof HTMLTextAreaElement?O:O.querySelector("button, select, input, textarea");W&&(W.disabled=_)},h=null,S=null,A=null,T=0,k=()=>{let E=e.getOverflow?.();return E?.enabled===!0?E:void 0},P=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=Xx({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),R=E=>{S!==E&&(A?.disconnect(),S=E,T=Qm(E),!(typeof ResizeObserver>"u")&&(A=new ResizeObserver(_=>{let W=_[_.length-1]?.contentRect?.width??Qm(E);W!==T&&(T=W,X())}),A.observe(E)))},b=(E,_)=>{let O=rP(E.collapseAutoActionsBelow,_);if(O===null)return!1;let W=T||Qm(_);return W>0&&W<O},w=(E,_,O)=>{if(!_)return"bar";if(E.resolved.builtIn){let oe=nP(E.resolved.id);return oe&&_.includeBuiltIns?.includes(oe)?"menu":"bar"}let W=E.resolved.presentation;return W==="overflow"||W==="auto"&&O?"menu":"bar"},x=E=>{let _=E.menuSlot;if(!_)return;if(!cP(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let O=iP(E.element);if(!O){E.menuLabel?.remove(),E.menuLabel=void 0;return}E.menuLabel||(E.menuLabel=I("span","persona-composer-overflow-menu__label")),E.menuLabel.textContent!==O&&(E.menuLabel.textContent=O),E.menuLabel.parentElement!==_&&_.appendChild(E.menuLabel)},L=(E,_)=>{if(E.mode===_)return E;let O=E.resolved.action;if(O&&!zr(O)){p(E),t.delete(E.resolved.id);let W=d(E.resolved,_);return t.set(E.resolved.id,W),W}if(_==="menu"){let W=Y("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Um]:""}});W.appendChild(E.element),Ux(Ym(E.element)),E.menuSlot=W;let oe=Q=>{let de=Ym(E.element);if(de.disabled)return;let pe=Q.target===de||de.contains(Q.target);h?.close(!0),pe||de.click()};W.addEventListener("click",oe,!0),E.detachMenuSlot=()=>W.removeEventListener("click",oe,!0),E.managed=!0,x(E)}else E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0;return E.mode=_,E},F=(E,_)=>{let O=_.map(W=>W.menuSlot??W.element);for(O.forEach((W,oe)=>{let Q=E.children[oe];Q!==W&&(Q?E.insertBefore(W,Q):E.appendChild(W))});E.children.length>O.length;)E.lastElementChild?.remove()},X=()=>{if(n)return;let E=e.getBindings();if(!E)return;let _=e.getState(),O=_.phase==="streaming",W=k();W&&R(E.footer);let oe=W?b(W,E.footer):!1,Q={start:[],end:[]},de=[];for(let pe of o){let xe=t.get(pe.id);if(!xe)continue;let Pe=pe.action,ge=Pe?Zx(Pe.visible,_,!0):!0;if(xe.visible!==ge&&(xe.visible=ge,!ge&&xe.managed&&(xe.menuSlot??xe.element).remove()),!!ge){if(xe=L(xe,w(xe,W,oe)),Pe){let Ke=Zx(Pe.disabled,_,!1)||Pe.disableWhenStreaming===!0&&O;y(xe,Ke),!zr(Pe)&&Pe.pressed!==void 0&&xe.button?.setAttribute("aria-pressed",Pe.pressed?"true":"false")}xe.mode==="menu"?(x(xe),de.push(xe)):Q[pe.placement].push(xe)}}if(de.length>0){let pe=P();F(pe.panel,de),pe.setItems(de.map(Ke=>Ke.menuSlot??Ke.element)),pe.applyButtonSize();let xe=Number.isFinite(W?.order)?W?.order:Un.overflow,Pe=Q.start.findIndex(Ke=>Ke.resolved.order>xe),ge={resolved:{id:oP,placement:"start",presentation:"bar",order:xe,sequence:-1,source:"core"},element:pe.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};Q.start.splice(Pe<0?Q.start.length:Pe,0,ge)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));m(E.actionsStart,Q.start),m(E.actionsEnd,Q.end)};return{resolve:()=>{if(n)return;let E=aP(e.collect()),_=new Set(E.map(O=>O.id));for(let[O,W]of t)_.has(O)||(p(W),t.delete(O));for(let O of E){let W=t.get(O.id);if(!W){let pe=c(O,"bar");pe&&t.set(O.id,pe);continue}let oe=W.resolved.action,Q=O.action;if(!!oe!=!!Q||oe&&Q&&zr(oe)!==zr(Q)||oe&&Q&&zr(oe)&&zr(Q)&&oe.render!==Q.render){p(W),t.delete(O.id);let pe=c(O,W.mode);pe&&t.set(O.id,pe);continue}W.resolved=O,O.builtIn?(W.managed=O.builtIn.managed===!0||W.mode==="menu",O.builtIn.element&&W.mode==="bar"&&(W.element=O.builtIn.element)):Q&&!zr(Q)?i(W,Q):Q&&W.element.toggleAttribute(Xm,Q.disableWhenStreaming===!0)}o=E,X()},sync:X,getResolved:()=>o,getOverflowMenu:()=>h,destroy:()=>{if(!n){n=!0,A?.disconnect(),A=null,S=null;for(let E of t.values())p(E);t.clear(),h?.destroy(),h=null,o=[]}}}}var uP="core:model",pP=700,tC=16,fP=["--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"],mP=(e,t)=>{let o=e.ownerDocument?.defaultView;if(!o)return;let n=o.getComputedStyle(e);for(let r of fP){let a=n.getPropertyValue(r).trim();a&&t.style.setProperty(r,a)}},oC=()=>{let e=Y("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Y("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function nC(e){let t=e.label??"Model",o=e.presentation??"native",n=null,r=u=>{let c=e.getSelectedModelId();return u.find(p=>p.id===c)??u[0]},a=()=>{let u=Y("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),c="",p=()=>{let A=e.getModels(),T=A.map(k=>`${k.id}:${k.label}`).join("|");T!==c&&(c=T,u.replaceChildren(...A.map(k=>{let P=Y("option",{attrs:{value:k.id}});return P.textContent=k.label,P}))),u.value=r(A)?.id??""};p(),n=p;let m=()=>{u.value&&e.onSelect(u.value)};u.addEventListener("change",m);let y=A=>A.stopPropagation();u.addEventListener("click",y);let{wrapper:h,chevron:S}=oC();return h.append(u,S),{element:h,destroy:()=>{n===p&&(n=null),u.removeEventListener("change",m),u.removeEventListener("click",y)}}},i=()=>{let u=Y("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"}}),c=I("span","persona-composer-model-picker-label"),p=I("span","persona-composer-model-picker-suffix");u.append(c,p);let m=Y("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),y=new Map,h="",S=null,A=()=>S?.isOpen===!0,T=(_=!1)=>{A()&&(S?.close(),u.setAttribute("aria-expanded","false"),_&&u.focus())},k=_=>{let O=[...y.values()];if(O.length===0)return;let W=(_%O.length+O.length)%O.length;O[W].focus()},P=_=>{if(A())return;S||(S=Zc({anchor:u,content:m,placement:"top-start",offset:6,onDismiss:()=>u.setAttribute("aria-expanded","false")})),mP(u,m),S.open(),u.setAttribute("aria-expanded","true");let W=[...y.keys()].indexOf(r(e.getModels())?.id??"");k(_??(W>=0?W:0))},R=_=>{T(!0),e.onSelect(_)},b=_=>{_.preventDefault(),_.stopPropagation();let O=_.currentTarget.getAttribute("data-persona-model-option");O&&R(O)},w=_=>{let O=Y("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":_.id}});if(_.icon){let pe=ce(_.icon,tC,"currentColor",1.5);if(pe){let xe=I("span","persona-composer-model-option-icon");xe.appendChild(pe),O.appendChild(xe)}}let W=I("span","persona-composer-model-option-body"),oe=I("span","persona-composer-model-option-label");if(oe.textContent=_.label,W.appendChild(oe),_.description){let pe=I("span","persona-composer-model-option-description");pe.textContent=_.description,W.appendChild(pe)}O.appendChild(W);let Q=I("span","persona-composer-model-option-check");Q.setAttribute("aria-hidden","true");let de=ce("check",tC,"currentColor",2);return de&&Q.appendChild(de),O.appendChild(Q),O.addEventListener("click",b),O},x=()=>{let _=e.getModels(),O=_.map(Q=>`${Q.id}:${Q.label}:${Q.icon??""}:${Q.description??""}`).join("|");if(O!==h){h=O;for(let Q of y.values())Q.removeEventListener("click",b);y.clear(),m.replaceChildren(..._.map(Q=>{let de=w(Q);return y.set(Q.id,de),de}))}let W=r(_);for(let[Q,de]of y)de.setAttribute("aria-selected",String(Q===W?.id));c.textContent=W?.label??"";let oe=e.getSuffix?.()??"";p.textContent=oe,u.setAttribute("aria-label",[t,[W?.label,oe].filter(Boolean).join(" ")].filter(Boolean).join(": "))};x(),n=x;let L=_=>{_.preventDefault(),_.stopPropagation(),A()?T(!0):P()},F=_=>{if(_.key==="ArrowDown"){_.preventDefault(),A()?k(0):P(0);return}_.key==="ArrowUp"&&(_.preventDefault(),A()?k(-1):P(-1))},X=_=>{let O=[...y.values()],W=O.indexOf(_.target?.closest?.(".persona-composer-model-option"));switch(_.key){case"ArrowDown":_.preventDefault(),k(W+1);return;case"ArrowUp":_.preventDefault(),k(W-1);return;case"Home":_.preventDefault(),k(0);return;case"End":_.preventDefault(),k(O.length-1);return;case"Escape":_.preventDefault(),_.stopPropagation(),T(!0);return;case"Tab":T(!0);return;default:}};u.addEventListener("click",L),u.addEventListener("keydown",F),m.addEventListener("keydown",X);let{wrapper:G,chevron:E}=oC();return G.append(u,E),{element:G,destroy:()=>{n===x&&(n=null),u.removeEventListener("click",L),u.removeEventListener("keydown",F),m.removeEventListener("keydown",X);for(let _ of y.values())_.removeEventListener("click",b);y.clear(),S?.destroy(),S=null,m.remove()}}};return{action:{id:uP,kind:"custom",placement:"end",order:pP,presentation:o==="popover"?"bar":"auto",label:t,render:()=>o==="popover"?i():a()},repaint:()=>n?.()}}var Jm="[data-persona-composer-chip-row]";function eu(e){e.style.display=e.childElementCount>0?"flex":"none"}function Zm(e){let t=e.querySelector(Jm);if(t)return t;let o=Y("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});o.style.display="none";let n=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return n?.parentElement===e?e.insertBefore(o,n):e.appendChild(o),o}var gP=":scope > [data-persona-composer-mode]";function rC(e){let t=e.row,o="",n=!1,r=new Set(e.initialIds??[]),a=c=>{let p=Y("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":c.id}});if(c.iconName){let S=I("span","persona-mention-chip-icon"),A=ce(c.iconName,12,"currentColor",1.5);A&&S.appendChild(A),p.appendChild(S)}let m=I("span","persona-mention-chip-label");m.textContent=c.shortLabel??c.label,p.appendChild(m);let y=Y("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${c.label}`}}),h=ce("x",12,"currentColor",2);return h?y.appendChild(h):y.textContent="\xD7",y.addEventListener("click",S=>{S.preventDefault(),S.stopPropagation(),e.onRemove(c.id)}),p.appendChild(y),p},i=()=>Array.from(t.querySelectorAll(gP)),d=c=>{c.setAttribute("data-persona-chip-exit",""),c.setAttribute("aria-hidden","true"),c.style.pointerEvents="none";let p=()=>{c.remove(),eu(t)},m=t.ownerDocument.defaultView,y=typeof m?.getComputedStyle=="function"?m.getComputedStyle(c).animationName:"";if(!y||y==="none"){p();return}c.addEventListener("animationend",p,{once:!0}),c.addEventListener("animationcancel",p,{once:!0})},u=()=>{for(let c of i())c.remove()};return{element:t,render:(c,p)=>{if(n)return;let m=p.filter(A=>c.includes(A.id)),y=m.map(A=>`${A.id}:${A.shortLabel??A.label}`).join("|");if(y===o)return;o=y;let h=new Map;for(let A of i()){let T=A.getAttribute("data-persona-composer-mode");T&&m.some(P=>P.id===T)&&!A.hasAttribute("data-persona-chip-exit")?h.set(T,A):A.hasAttribute("data-persona-chip-exit")||d(A)}let S=t.firstChild;for(let A of m){let T=h.get(A.id);T||(T=a(A),r.has(A.id)||(T.setAttribute("data-persona-chip-enter",""),T.addEventListener("animationend",()=>T?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(A.id),T!==S&&t.insertBefore(T,S),S=T.nextSibling}eu(t)},destroy:()=>{n=!0,u(),eu(t)}}}var sC=e=>`core:mode:${e}`;var eg=e=>Math.min(300+e,499),aC=e=>`core:mode-group:${e}`;function tu(e,t){return e?t?.find(o=>o.id===e)?.presentation==="segmented":!1}function iC(e,t){return e?.length?e.filter(o=>!tu(o.groupId,t)):[]}var hP=(e,t)=>e.groupId?t?.find(o=>o.id===e.groupId)?.selection??null:null;function lC(e,t,o,n){let r=o.find(d=>d.id===t);if(!r)return[...e];let a=e.includes(t),i=new Set(e);if(a)i.delete(t);else{if(hP(r,n)==="single"){let d=o.filter(u=>u.groupId===r.groupId).map(u=>u.id);i=new Set([...i].filter(u=>!d.includes(u)))}i.add(t)}return o.filter(d=>i.has(d.id)).map(d=>d.id)}function ou(e,t){return t?.length?t.filter(o=>e.includes(o.id)).map(o=>o.id):[]}function dC(e,t){return t?.length?t.filter(o=>e.includes(o.id)&&(o.persistence??"sticky")!=="once").map(o=>o.id):[]}function cC(e,t){if(!(!t?.length||e.length===0))return t.find(o=>e.includes(o.id)&&o.placeholder)?.placeholder}var yP=16;function uC(e){let t=null;return{action:{id:aC(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let n=Y("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,a="",i=c=>{c.preventDefault(),c.stopPropagation();let m=c.currentTarget.getAttribute("data-persona-composer-mode");!m||e.getActiveIds().includes(m)&&e.getGroup()?.selection==="single"||e.onSelect(m)},d=c=>{let p=Y("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":c.id,"aria-label":c.label}});if(c.iconName){let y=ce(c.iconName,yP,"currentColor",1.5);y&&p.appendChild(y)}let m=I("span","persona-composer-segmented-label");return m.textContent=c.shortLabel??c.label,p.appendChild(m),p.addEventListener("click",i),p},u=()=>{let c=e.getGroup();c?.label?(n.setAttribute("role","group"),n.setAttribute("aria-label",c.label)):(n.removeAttribute("role"),n.removeAttribute("aria-label"));let p=e.getModes(),m=p.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(m!==a){a=m;for(let S of r.values())S.removeEventListener("click",i);r.clear();let h=p.map(S=>{let A=d(S);return r.set(S.id,A),A});n.replaceChildren(...h)}let y=e.getActiveIds();for(let[h,S]of r)S.setAttribute("aria-pressed",String(y.includes(h)))};return u(),t=u,{element:n,destroy:()=>{t===u&&(t=null);for(let c of r.values())c.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}function pC(e){let t=Y("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let o="",n=!1,r=a=>{let i=I("span","persona-composer-quote-bar"),d=I("div","persona-composer-quote-content");if(a.sourceLabel){let m=I("div","persona-composer-quote-source");m.textContent=a.sourceLabel,d.appendChild(m)}let u=Y("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});u.textContent=Ic(a.text),d.appendChild(u);let c=Y("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),p=ce("x",12,"currentColor",2);p?c.appendChild(p):c.textContent="\xD7",c.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,d,c)};return{element:t,render:a=>{if(n)return;let i=a?`${a.sourceLabel??""}\0${a.text}`:"";if(i!==o){if(o=i,!a){t.replaceChildren(),t.style.display="none";return}r(a),t.style.display="flex"}},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function fC(e){let t=Y("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let o,n=!1,r=(i,d,u,c)=>{let p=Y("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":d,[u]:""}}),m=ce(i,12,"currentColor",2);return m?p.appendChild(m):p.textContent=d,p.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),c()}),p},a=i=>{let d=Ic(i.text??"",90);if(d)return d;let u=i.contentParts?.length??0;return u>0?u===1?"1 attachment":`${u} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(p=>p.label).join(", "):"Queued message"};return{element:t,render:i=>{if(n||i===o)return;if(o=i,!i){t.replaceChildren(),t.style.display="none";return}let d=I("span","persona-composer-pending-badge");d.textContent=e.label??"Sends next";let u=Y("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});u.textContent=a(i),t.replaceChildren(d,u,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function mC(e){let t=Y("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),o=Y("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});o.value=e.initialText;let n=()=>{o.style.height="auto",o.style.height=`${o.scrollHeight}px`};o.addEventListener("input",n);let r=I("div","persona-message-edit-actions"),a=(d,u,c,p)=>{let m=Y("button",{className:`persona-message-edit-button ${u}`,attrs:{type:"button",[c]:""},text:d});return m.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),p()}),m},i=()=>{let d=o.value.trim();d&&e.onSave(d)};return r.append(a(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),a(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",i)),o.addEventListener("keydown",d=>{if(d.key==="Escape"){d.preventDefault(),d.stopPropagation(),e.onCancel();return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),i())}),t.append(o,r),{element:t,getValue:()=>o.value,focus:()=>{o.focus();let d=o.value.length;o.setSelectionRange(d,d),n()},destroy:()=>{t.replaceChildren(),t.remove()}}}function gC(e){let t=e.text??"";if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function hC(e,t){if(!e||typeof e.text!="string")return;let o=new Set(t.mentionSourceIds),n=(e.mentionRefs??[]).filter(u=>o.has(u.sourceId)),r=n.length===(e.mentionRefs?.length??0)&&n.length>0,a=new Set(t.modes.map(u=>u.id)),i=(e.activeModeIds??[]).filter(u=>a.has(u)),d=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:n}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...d?{selectedModelId:d}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function yC(e){let t=e.delay??500,o=null,n=!1,r=()=>{o!==null&&(clearTimeout(o),o=null)};return{schedule:()=>{n||(r(),o=setTimeout(()=>{o=null,e.write()},t))},flush:()=>{n||o===null||(r(),e.write())},cancel:r,destroy:()=>{n=!0,r()}}}function bC(e){return e.wrapped||e.text.includes(`
24
- `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission||e.dictationActive)}function vC(){let e=!1;return{observe:(t,o)=>o?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function xC(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let o=t.getComputedStyle(e),n=Number.parseFloat(o.lineHeight),r=Number.parseFloat(o.fontSize),a=Number.isFinite(n)&&n>0?n:Number.isFinite(r)&&r>0?r*1.4:0;if(!a)return!1;let i=(Number.parseFloat(o.paddingTop)||0)+(Number.parseFloat(o.paddingBottom)||0);return e.scrollHeight-i>a*1.5}function CC(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function tg(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function wC(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var bP=e=>typeof e?.then=="function";function SC(e,t){return t===!1?{status:"canceled"}:!t||typeof t!="object"?{status:"proceed"}:(typeof t.text=="string"&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"})}function AC(e,t,o){let n;try{n=e(tg(t),{signal:o})}catch(r){return{status:"error",error:r}}return bP(n)?Promise.resolve(n).then(r=>o.aborted?{status:"aborted"}:SC(t,r),r=>o.aborted?{status:"aborted"}:{status:"error",error:r}):SC(t,n)}var MC=/\s/;function vP(e,t,o){if(o==="input-start")return t===0;let n=t>0?e[t-1]:"";return o==="line-start"?n===""||n===`
25
- `:n===""||MC.test(n)}function xP(e,t,o="@",n="anywhere",r=!1){if(!o||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let i=e[a];if(i===o)return vP(e,a,n)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(i===`
26
- `||i==="\uFFFC"||!r&&MC.test(i))return null;a--}return null}function TC(e,t,o){for(let n of o){let r=xP(e,t,n.trigger,n.position??"anywhere",n.allowSpaces??!1);if(r)return{channel:n,match:r}}return null}function EC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function PC(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},o=(e.triggers??[]).map(n=>({trigger:n.trigger,position:n.triggerPosition??"anywhere",allowSpaces:n.allowSpaces??!1,sources:Array.isArray(n.sources)?n.sources:[],searchPlaceholder:n.searchPlaceholder,showButton:n.showButton===!0,buttonIconName:n.buttonIconName,buttonTooltipText:n.buttonTooltipText}));return[t,...o]}function LC(e){let{config:t,onOpen:o}=e,n=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",a=I("div","persona-send-button-wrapper"),i=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Ko} ${vn}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),d=ce(n,vo,"currentColor",1.5);return d?i.appendChild(d):i.textContent="+",i.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),o()}),a.appendChild(i),eo({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:a}}var{setLoader:CP,load:SP}=mt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),kC=CP,og=SP;var{setLoader:wP,load:AP}=mt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),IC=wP,HC=AP;function Sl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let o=Y("span",{className:bo("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&o.style.setProperty("--persona-mention-token-accent",e.color);let n=ce(e.iconName??"at-sign",13,"currentColor",2);if(n){let r=I("span","persona-mention-token-icon");r.appendChild(n),o.appendChild(r)}return o.appendChild(Y("span",{className:"persona-mention-token-label",text:`@${e.label}`})),o}function RC(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let o=PC(t).filter(b=>b.sources.length>0);if(o.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let n=o.filter(b=>b.sources.some(w=>typeof w.matchCommand=="function")),r=b=>n.some(w=>w.trigger?w.position==="line-start"?b.split(`
27
- `).some(L=>L.startsWith(w.trigger)):(w.position==="anywhere"?b:b.split(`
28
- `)[0]).startsWith(w.trigger):!1),a=(b,w)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${b}`,{detail:w}))}catch{}},i=!e.chipRow,d=e.chipRow??Y("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),u=null,c=null,p=e.textarea,m=null,y=null,h=null,S=null,A=()=>{if(u)return Promise.resolve(u);if(c)return c;let b=og().then(w=>(w.setMentionIconRenderer(ce),u=w.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:R,emit:a}),u)).catch(w=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",w),c===b&&(c=null),null));return c=b,b},T=()=>{HC().then(b=>{let w=b.mountInlineComposer({textarea:e.textarea,renderToken:L=>Sl(L,{render:t.renderMentionToken}),onMentionRemoved:L=>u?.untrackMention(L)});m=w.input,y=w.destroy;let x=p;x.replaceWith(w.element),p=w.element,S={next:w.element,prev:x},h?.(w.element,x),u?u.rebindComposer(w.input):c&&c.then(L=>L?.rebindComposer(w.input))}).catch(b=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",b)})};t.display==="inline"&&T();let k=[],P=new Map;for(let b of o){if(!b.showButton)continue;let w=LC({config:{...t,buttonIconName:b.buttonIconName,buttonTooltipText:b.buttonTooltipText},onOpen:()=>{A().then(x=>x?.openMenu(b.trigger))}});k.push(w),P.set(b.trigger,w.button)}let R=(b,w,x)=>{let L=P.get(w);L&&(L.setAttribute("aria-expanded",b?"true":"false"),b?L.setAttribute("aria-controls",x):L.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(b=>b.wrapper),contextRow:d,handleInput:b=>{if(u){u.handleInput();return}if(!EC(b))return;let w=p,x=w.selectionStart??0;TC(w.value,x,o)&&A().then(L=>L?.handleInput())},handleKeydown:b=>{if(u?.isMenuOpen())return u.handleKeydown(b);if(b.key==="Backspace"&&u?.hasMentions()&&!S){let w=p,x=w.selectionStart===0&&w.selectionEnd===0;if((w.value.length===0||x)&&u.removeLastChip())return b.preventDefault(),!0}return!1},isMenuOpen:()=>u?.isMenuOpen()??!1,hasMentions:()=>u?.hasMentions()??!1,getMentionRefs:()=>u?.getMentionRefs()??[],collectForSubmit:()=>u?.collectForSubmit()??null,takeInlineCommand:async b=>r(b)?(u??await A())?.dispatchInlineCommand(b)??null:null,clear:()=>u?.clear(),prefetch:()=>{og().catch(()=>{})},onComposerSwap:b=>{h=b,S&&b(S.next,S.prev)},destroy:()=>{u?.destroy(),y?.();for(let b of k)b.wrapper.remove();i&&d.remove()}}}var nu="16px",ru="transparent",MP=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?"0px":`${t/4}rem`;return e})(),rg={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"}},spacing:MP,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"}},sg={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"}},ag={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:Vo,maxWidth:jc,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:nu,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"}},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 xo(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let o=t.split("."),n=e;for(let r of o){if(n==null)return;n=n[r]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?xo(e,n):n}function su(e){let t={};function o(n,r){for(let[a,i]of Object.entries(n)){let d=`${r}.${a}`;if(typeof i=="string"){let u=xo(e,i);u!==void 0&&(t[d]={path:d,value:u,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&o(i,d)}}return o(e.palette,"palette"),o(e.semantic,"semantic"),o(e.components,"components"),t}function ig(e){let t=[],o=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||o.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||o.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:o}}function BC(e,t){let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];a&&typeof a=="object"&&!Array.isArray(a)&&r&&typeof r=="object"&&!Array.isArray(r)?o[n]=BC(a,r):o[n]=r}return o}function TP(e,t){return t?BC(e,t):e}function wl(e,t={}){let o={palette:rg,semantic:sg,components:ag},n={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:TP(o.components,e?.components)};if(t.validate!==!1){let r=ig(n);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(a=>a.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)n=r.transform(n);return n}var ng=e=>e.trim()==="0"?"0px":e,WC="--persona-",EP=e=>{if(!e)return;let t=e.trim().toLowerCase(),o;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?o=[0,1,2].map(d=>parseInt(i[d]+i[d],16)):(i.length===6||i.length===8)&&(o=[0,2,4].map(d=>parseInt(i.slice(d,d+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let d=i[1].split(/[,/\s]+/).filter(Boolean);d.length>=3&&(o=d.slice(0,3).map(u=>{let c=u.endsWith("%"),p=parseFloat(c?u.slice(0,-1):u);return c?p/100*255:p}))}}if(!o||o.some(i=>!Number.isFinite(i)))return;let[n,r,a]=o.map(i=>{let d=Math.max(0,Math.min(255,i))/255;return d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)});return .2126*n+.7152*r+.0722*a},PP=.179,to=(e,t)=>{for(let[o,...n]of t){let r;for(let a of n)if(r=a.charCodeAt(0)===61?a.slice(1):e[WC+a],r!==void 0)break;r!==void 0&&(e[WC+o]=r)}};function au(e){let t=su(e),o={};for(let[z,Ue]of Object.entries(t)){let Ge=z.replace(/\./g,"-");o[`--persona-${Ge}`]=Ue.value}to(o,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let n=o["--persona-components-launcher-foreground"];o["--persona-launcher-fg-muted"]=n&&n!==o["--persona-primary"]?`color-mix(in srgb, ${n} 70%, transparent)`:o["--persona-muted"],to(o,[["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"]]),to(o,[["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"]]),o["--persona-panel-border"]=o["--persona-components-panel-border"]??`1px solid ${o["--persona-border"]}`,to(o,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),o["--persona-panel-inset"]=o["--persona-components-panel-inset"]??nu,o["--persona-panel-canvas-bg"]=o["--persona-components-panel-canvasBackground"]??ru,to(o,[["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"]]),to(o,[["header-bg","components-header-background","surface"]]);let r=o["--persona-header-bg"],a=o["--persona-components-header-foreground"],i=a?`color-mix(in srgb, ${a} 72%, ${r})`:void 0;o["--persona-header-border"]=o["--persona-components-header-border"]??(a?`color-mix(in srgb, ${a} 14%, ${r})`:void 0)??o["--persona-divider"],to(o,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),o["--persona-header-title-fg"]=o["--persona-components-header-title-color"]??o["--persona-components-header-titleForeground"]??a??o["--persona-primary"],o["--persona-header-subtitle-fg"]=o["--persona-components-header-subtitle-color"]??o["--persona-components-header-subtitleForeground"]??i??o["--persona-text-muted"],o["--persona-header-action-icon-fg"]=o["--persona-components-header-actionIconForeground"]??i??o["--persona-muted"],to(o,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let d=e.components?.header;d?.shadow&&(o["--persona-header-shadow"]=d.shadow),d?.borderBottom&&(o["--persona-header-border-bottom"]=d.borderBottom),d?.minHeight&&(o["--persona-header-min-height"]=d.minHeight);let u=o["--persona-components-history-railHeader-background"];u&&(o["--persona-history-rail-header-bg"]=u);let c=o["--persona-components-history-railHeader-border"];c&&(o["--persona-history-rail-header-border"]=c);let p=o["--persona-components-history-railHeader-minHeight"];p&&(o["--persona-history-rail-header-min-height"]=p);for(let[z,Ue]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ge=o[`--persona-components-history-overlay-${z}`];Ge&&(o[`--persona-history-overlay-${Ue}`]=Ge)}for(let[z,Ue]of[["background","bg"],["borderRadius","radius"]]){let Ge=o[`--persona-components-history-menu-${z}`];Ge&&(o[`--persona-history-menu-${Ue}`]=Ge)}let m=e.components?.history?.motion;if(m){let z=Ae=>{if(Ae===void 0)return;let De=String(Ae).trim();return/^\d+(\.\d+)?$/.test(De)?`${De}ms`:De},Ue=z(m.enterDurationMs);Ue!==void 0&&(o["--persona-history-enter-ms"]=Ue);let Ge=z(m.exitDurationMs);Ge!==void 0&&(o["--persona-history-exit-ms"]=Ge),m.enterEasing&&(o["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(o["--persona-history-exit-easing"]=m.exitEasing)}let y=o["--persona-components-history-dangerForeground"];y&&(o["--persona-history-danger-fg"]=y),o["--persona-danger"]=o["--persona-components-history-confirm-dangerBackground"]??o["--persona-palette-colors-error-700"]??"#b42318",o["--persona-danger-fg"]=o["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let z of["scrim","shadow"]){let Ue=o[`--persona-components-history-confirm-${z}`];Ue&&(o[`--persona-history-confirm-${z}`]=Ue)}for(let[z,Ue]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ge=o[`--persona-components-tooltip-${z}`];Ge&&(o[`--persona-tooltip-${Ue}`]=Ge)}e.components?.tooltip?.arrow===!1&&(o["--persona-tooltip-arrow-display"]="none");for(let[z,Ue]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ge=o[`--persona-components-messageActions-${z}`];Ge&&(o[`--persona-message-action-${Ue}`]=Ge)}to(o,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=o["--persona-components-introCard-background"],S=o["--persona-components-introCard-shadow"],A=(!h||h==="transparent"||h==="none")&&(!S||S==="none"),T=o["--persona-components-introCard-padding"]??"1.5rem";o["--persona-intro-card-padding"]=A&&T==="1.5rem"?"1.5rem 0":T,to(o,[["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"],["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"]]),to(o,[["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 k=o["--persona-components-markdown-heading-h1-fontSize"];k&&(o["--persona-md-h1-size"]=k);let P=o["--persona-components-markdown-heading-h1-fontWeight"];P&&(o["--persona-md-h1-weight"]=P);let R=o["--persona-components-markdown-heading-h2-fontSize"];R&&(o["--persona-md-h2-size"]=R);let b=o["--persona-components-markdown-heading-h2-fontWeight"];b&&(o["--persona-md-h2-weight"]=b);let w=o["--persona-components-markdown-prose-fontFamily"];w&&w!=="inherit"&&(o["--persona-md-prose-font-family"]=w),to(o,[["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"]]),to(o,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),to(o,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),to(o,[["md-hr-color","components-markdown-hr-color","divider"]]),to(o,[["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"]]),o["--cw-container"]=o["--persona-components-collapsibleWidget-container"]??o["--persona-surface"],o["--cw-surface"]=o["--persona-components-collapsibleWidget-surface"]??o["--persona-surface"],o["--cw-border"]=o["--persona-components-collapsibleWidget-border"]??o["--persona-border"],to(o,[["message-border","components-message-border","border"]]),to(o,[["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 x=e.components,L=x?.iconButton;L&&(L.background&&(o["--persona-icon-btn-bg"]=L.background),L.border&&(o["--persona-icon-btn-border"]=L.border),L.color&&(o["--persona-icon-btn-color"]=L.color),L.padding&&(o["--persona-icon-btn-padding"]=L.padding),L.borderRadius&&(o["--persona-icon-btn-radius"]=L.borderRadius),L.hoverBackground&&(o["--persona-icon-btn-hover-bg"]=L.hoverBackground),L.hoverColor&&(o["--persona-icon-btn-hover-color"]=L.hoverColor),L.activeBackground&&(o["--persona-icon-btn-active-bg"]=L.activeBackground),L.activeBorder&&(o["--persona-icon-btn-active-border"]=L.activeBorder));let F=x?.labelButton;F&&(F.background&&(o["--persona-label-btn-bg"]=F.background),F.border&&(o["--persona-label-btn-border"]=F.border),F.color&&(o["--persona-label-btn-color"]=F.color),F.padding&&(o["--persona-label-btn-padding"]=F.padding),F.borderRadius&&(o["--persona-label-btn-radius"]=F.borderRadius),F.hoverBackground&&(o["--persona-label-btn-hover-bg"]=F.hoverBackground),F.fontSize&&(o["--persona-label-btn-font-size"]=F.fontSize),F.gap&&(o["--persona-label-btn-gap"]=F.gap));let X=x?.toggleGroup;X&&(X.gap&&(o["--persona-toggle-group-gap"]=X.gap),X.borderRadius&&(o["--persona-toggle-group-radius"]=X.borderRadius));let G=x?.artifact;if(G?.toolbar){let z=G.toolbar;z.iconHoverColor&&(o["--persona-artifact-toolbar-icon-hover-color"]=z.iconHoverColor),z.iconHoverBackground&&(o["--persona-artifact-toolbar-icon-hover-bg"]=z.iconHoverBackground),z.iconPadding&&(o["--persona-artifact-toolbar-icon-padding"]=z.iconPadding),z.iconBorderRadius&&(o["--persona-artifact-toolbar-icon-radius"]=z.iconBorderRadius),z.iconBorder&&(o["--persona-artifact-toolbar-icon-border"]=z.iconBorder),z.toggleGroupGap&&(o["--persona-artifact-toolbar-toggle-group-gap"]=ng(z.toggleGroupGap)),z.toggleBorderRadius&&(o["--persona-artifact-toolbar-toggle-radius"]=z.toggleBorderRadius),z.toggleGroupPadding&&(o["--persona-artifact-toolbar-toggle-group-padding"]=ng(z.toggleGroupPadding)),z.toggleGroupBorder&&(o["--persona-artifact-toolbar-toggle-group-border"]=z.toggleGroupBorder),z.toggleGroupBorderRadius&&(o["--persona-artifact-toolbar-toggle-group-radius"]=z.toggleGroupBorderRadius),z.toggleGroupBackground&&(o["--persona-artifact-toolbar-toggle-group-bg"]=xo(e,z.toggleGroupBackground)??z.toggleGroupBackground),z.copyBackground&&(o["--persona-artifact-toolbar-copy-bg"]=z.copyBackground),z.copyBorder&&(o["--persona-artifact-toolbar-copy-border"]=z.copyBorder),z.copyColor&&(o["--persona-artifact-toolbar-copy-color"]=z.copyColor),z.copyBorderRadius&&(o["--persona-artifact-toolbar-copy-radius"]=ng(z.copyBorderRadius)),z.copyPadding&&(o["--persona-artifact-toolbar-copy-padding"]=z.copyPadding),z.copyMenuBackground&&(o["--persona-artifact-toolbar-copy-menu-bg"]=z.copyMenuBackground,o["--persona-dropdown-bg"]=o["--persona-dropdown-bg"]??z.copyMenuBackground),z.copyMenuBorder&&(o["--persona-artifact-toolbar-copy-menu-border"]=z.copyMenuBorder,o["--persona-dropdown-border"]=o["--persona-dropdown-border"]??z.copyMenuBorder),z.copyMenuShadow&&(o["--persona-artifact-toolbar-copy-menu-shadow"]=z.copyMenuShadow,o["--persona-dropdown-shadow"]=o["--persona-dropdown-shadow"]??z.copyMenuShadow),z.copyMenuBorderRadius&&(o["--persona-artifact-toolbar-copy-menu-radius"]=z.copyMenuBorderRadius,o["--persona-dropdown-radius"]=o["--persona-dropdown-radius"]??z.copyMenuBorderRadius),z.copyMenuItemHoverBackground&&(o["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=z.copyMenuItemHoverBackground,o["--persona-dropdown-item-hover-bg"]=o["--persona-dropdown-item-hover-bg"]??z.copyMenuItemHoverBackground),z.iconBackground&&(o["--persona-artifact-toolbar-icon-bg"]=z.iconBackground),z.toolbarBorder&&(o["--persona-artifact-toolbar-border"]=z.toolbarBorder)}if(G?.tab){let z=G.tab;z.background&&(o["--persona-artifact-tab-bg"]=z.background),z.activeBackground&&(o["--persona-artifact-tab-active-bg"]=z.activeBackground),z.activeBorder&&(o["--persona-artifact-tab-active-border"]=z.activeBorder),z.borderRadius&&(o["--persona-artifact-tab-radius"]=z.borderRadius),z.textColor&&(o["--persona-artifact-tab-color"]=z.textColor),z.hoverBackground&&(o["--persona-artifact-tab-hover-bg"]=z.hoverBackground),z.listBackground&&(o["--persona-artifact-tab-list-bg"]=z.listBackground),z.listBorderColor&&(o["--persona-artifact-tab-list-border-color"]=z.listBorderColor),z.listPadding&&(o["--persona-artifact-tab-list-padding"]=z.listPadding)}if(G?.pane){let z=G.pane;if(z.toolbarBackground){let Ue=xo(e,z.toolbarBackground)??z.toolbarBackground;o["--persona-artifact-toolbar-bg"]=Ue}}if(G?.card){let z=G.card;z.background&&(o["--persona-artifact-card-bg"]=z.background),z.border&&(o["--persona-artifact-card-border"]=z.border),z.borderRadius&&(o["--persona-artifact-card-radius"]=z.borderRadius),z.hoverBackground&&(o["--persona-artifact-card-hover-bg"]=z.hoverBackground),z.hoverBorderColor&&(o["--persona-artifact-card-hover-border"]=z.hoverBorderColor)}if(G?.inline){let z=G.inline;z.background&&(o["--persona-artifact-inline-bg"]=xo(e,z.background)??z.background),z.border&&(o["--persona-artifact-inline-border"]=z.border),z.borderRadius&&(o["--persona-artifact-inline-radius"]=z.borderRadius),z.chromeBackground&&(o["--persona-artifact-inline-chrome-bg"]=xo(e,z.chromeBackground)??z.chromeBackground),z.chromeBorder&&(o["--persona-artifact-inline-chrome-border"]=xo(e,z.chromeBorder)??z.chromeBorder),z.titleColor&&(o["--persona-artifact-inline-title-color"]=xo(e,z.titleColor)??z.titleColor),z.mutedColor&&(o["--persona-artifact-inline-muted-color"]=xo(e,z.mutedColor)??z.mutedColor),z.frameHeight&&(o["--persona-artifact-inline-frame-height"]=z.frameHeight)}let E=x?.code;E&&(E.keywordColor&&(o["--persona-code-keyword-color"]=E.keywordColor),E.stringColor&&(o["--persona-code-string-color"]=E.stringColor),E.commentColor&&(o["--persona-code-comment-color"]=E.commentColor),E.numberColor&&(o["--persona-code-number-color"]=E.numberColor),E.tagColor&&(o["--persona-code-tag-color"]=E.tagColor),E.attrColor&&(o["--persona-code-attr-color"]=E.attrColor),E.propertyColor&&(o["--persona-code-property-color"]=E.propertyColor),E.lineNumberColor&&(o["--persona-code-line-number-color"]=E.lineNumberColor),E.gutterBorderColor&&(o["--persona-code-gutter-border-color"]=E.gutterBorderColor),E.background&&(o["--persona-code-bg"]=xo(e,E.background)??E.background));let _=o["--persona-surface"],O=o["--persona-container"],W=o["--persona-palette-colors-gray-100"]??"#f3f4f6",oe=o["--persona-palette-colors-gray-200"]??"#e5e7eb",Q=o["--persona-palette-colors-gray-300"]??"#d1d5db",de=!O||O===_,pe=EP(_??o["--persona-background"]),xe=de&&pe!==void 0&&pe<PP,Pe=xe?"rgba(255, 255, 255, 0.08)":W,ge=xe?"rgba(255, 255, 255, 0.12)":oe,Ke=xe?"rgba(255, 255, 255, 0.16)":Q,Bt=de?Pe:O,ke=de?ge:O;return o["--persona-icon-btn-hover-bg"]=o["--persona-icon-btn-hover-bg"]??Bt,o["--persona-icon-btn-active-bg"]=o["--persona-icon-btn-active-bg"]??ke,de&&(o["--persona-icon-btn-active-border"]=o["--persona-icon-btn-active-border"]??Ke),o["--persona-label-btn-hover-bg"]=o["--persona-label-btn-hover-bg"]??Bt,o["--persona-artifact-tab-hover-bg"]=o["--persona-artifact-tab-hover-bg"]??Bt,o["--persona-artifact-card-hover-bg"]=o["--persona-artifact-card-hover-bg"]??Bt,o}var OC={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var LP={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"}}},kP={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},DC=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Al=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",IP=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Al()},iu=e=>IP(e),HP=e=>wl(e),RP=e=>{let t=$a(kP,e??{})??{};return wl({...t,palette:{...t.palette,colors:{...LP.colors,...t.palette?.colors}}},{validate:!1})},Vr=e=>{let t=iu(e),o=DC(e?.theme),n=DC(e?.darkTheme);return t==="dark"?RP($a(o??{},n??{})):HP(o)},WP=e=>au(e),Us=(e,t)=>{let o=Vr(t),n=WP(o);for(let[r,a]of Object.entries(n))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",iu(t))},Va=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let o=new MutationObserver(()=>{e(Al())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>o.disconnect())}if(typeof window<"u"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(Al());o.addEventListener?(o.addEventListener("change",n),t.push(()=>o.removeEventListener("change",n))):o.addListener&&(o.addListener(n),t.push(()=>o.removeListener(n)))}return()=>{t.forEach(o=>o())}};var Kr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var lu="24px",lg=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Ml=e=>{if(typeof e!="string")return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let o=Number(t[1])/100;return o>0&&o<1?o:null},_C=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var NC=null;var dg=()=>{if(NC!==null)return NC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},BP="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",du=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},cu=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),o=t.pop(),n={key:o,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")n.mod=!0;else if(r==="shift")n.shift=!0;else if(r==="alt"||r==="option")n.alt=!0;else return du("unknown modifier in",e),null;return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(o)||!/^([^+\s]|[a-z]{2,12})$/.test(o)?(du("unsupported",e),null):(o==="space"&&(n.key=" "),n)},OP=e=>BP.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),FC=(e,t)=>{let o=cu(e);if(!o)return"";let n=dg(),r=OP(o.key);if(!t&&n)return`${o.alt?"\u2325":""}${o.shift?"\u21E7":""}\u2318${r}`;let a=[t?n?"Meta":"Control":"Ctrl"];return o.alt&&a.push("Alt"),o.shift&&a.push("Shift"),a.push(r),a.join("+")},uu=e=>FC(e,!1),Tl=e=>FC(e,!0),DP=(e,t)=>t.key?.toLowerCase()===e.key&&(dg()?t.metaKey:t.ctrlKey)===e.mod&&!(dg()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,_P=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},UC=e=>{let t=new Map,o=e?.ownerDocument??(typeof document<"u"?document:null),n=(a,i)=>{if((a.scope??"widget")==="page")return!0;if(!e)return!1;let d=i.composedPath?.();return d?.length?d.includes(e):e.contains(i.target)},r=a=>{if(a.isComposing||!t.size)return;let i=a.composedPath?.()[0]??a.target;for(let d of t.values())if(DP(d.parsed,a)&&d.when?.()!==!1&&n(d,a)&&!(!d.allowInInput&&_P(i))){a.preventDefault();try{d.run(a)}catch(u){du(`${d.id} threw on`,d.combo),console.warn(u)}return}};return o?.addEventListener("keydown",r),{register(a){let i=cu(a.combo);if(!i)return()=>{};let d=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,u=t.get(d);return u?(du(`${u.id} already owns`,a.combo),()=>{}):(t.set(d,{...a,parsed:i}),a.element?.setAttribute("aria-keyshortcuts",Tl(a.combo)),()=>{t.get(d)?.id===a.id&&t.delete(d),a.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),o?.removeEventListener("keydown",r)}}};var qC=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:y=>y.getAttribute("im-preserve")==="true",shouldReAppend:y=>y.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function o(y,h,S={}){y=p(y);let A=m(h),T=c(y,A,S),k=r(T,()=>d(T,y,A,P=>P.morphStyle==="innerHTML"?(a(P,y,A),Array.from(y.childNodes)):n(P,y,A)));return T.pantry.remove(),k}function n(y,h,S){let A=m(h);return a(y,A,S,h,h.nextSibling),Array.from(A.childNodes)}function r(y,h){if(!y.config.restoreFocus)return h();let S=document.activeElement;if(!(S instanceof HTMLInputElement||S instanceof HTMLTextAreaElement))return h();let{id:A,selectionStart:T,selectionEnd:k}=S,P=h();return A&&A!==document.activeElement?.getAttribute("id")&&(S=y.target.querySelector(`[id="${A}"]`),S?.focus()),S&&!S.selectionEnd&&k&&S.setSelectionRange(T,k),P}let a=(function(){function y(b,w,x,L=null,F=null){w instanceof HTMLTemplateElement&&x instanceof HTMLTemplateElement&&(w=w.content,x=x.content),L||(L=w.firstChild);for(let X of x.childNodes){if(L&&L!=F){let E=S(b,X,L,F);if(E){E!==L&&T(b,L,E),i(E,X,b),L=E.nextSibling;continue}}if(X instanceof Element){let E=X.getAttribute("id");if(b.persistentIds.has(E)){let _=k(w,E,L,b);i(_,X,b),L=_.nextSibling;continue}}let G=h(w,X,L,b);G&&(L=G.nextSibling)}for(;L&&L!=F;){let X=L;L=L.nextSibling,A(b,X)}}function h(b,w,x,L){if(L.callbacks.beforeNodeAdded(w)===!1)return null;if(L.idMap.has(w)){let F=document.createElement(w.tagName);return b.insertBefore(F,x),i(F,w,L),L.callbacks.afterNodeAdded(F),F}else{let F=document.importNode(w,!0);return b.insertBefore(F,x),L.callbacks.afterNodeAdded(F),F}}let S=(function(){function b(L,F,X,G){let E=null,_=F.nextSibling,O=0,W=X;for(;W&&W!=G;){if(x(W,F)){if(w(L,W,F))return W;E===null&&(L.idMap.has(W)||(E=W))}if(E===null&&_&&x(W,_)&&(O++,_=_.nextSibling,O>=2&&(E=void 0)),L.activeElementAndParents.includes(W))break;W=W.nextSibling}return E||null}function w(L,F,X){let G=L.idMap.get(F),E=L.idMap.get(X);if(!E||!G)return!1;for(let _ of G)if(E.has(_))return!0;return!1}function x(L,F){let X=L,G=F;return X.nodeType===G.nodeType&&X.tagName===G.tagName&&(!X.getAttribute?.("id")||X.getAttribute?.("id")===G.getAttribute?.("id"))}return b})();function A(b,w){if(b.idMap.has(w))R(b.pantry,w,null);else{if(b.callbacks.beforeNodeRemoved(w)===!1)return;w.parentNode?.removeChild(w),b.callbacks.afterNodeRemoved(w)}}function T(b,w,x){let L=w;for(;L&&L!==x;){let F=L;L=L.nextSibling,A(b,F)}return L}function k(b,w,x,L){let F=L.target.getAttribute?.("id")===w&&L.target||L.target.querySelector(`[id="${w}"]`)||L.pantry.querySelector(`[id="${w}"]`);return P(F,L),R(b,F,x),F}function P(b,w){let x=b.getAttribute("id");for(;b=b.parentNode;){let L=w.idMap.get(b);L&&(L.delete(x),L.size||w.idMap.delete(b))}}function R(b,w,x){if(b.moveBefore)try{b.moveBefore(w,x)}catch{b.insertBefore(w,x)}else b.insertBefore(w,x)}return y})(),i=(function(){function y(P,R,b){return b.ignoreActive&&P===document.activeElement?null:(b.callbacks.beforeNodeMorphed(P,R)===!1||(P instanceof HTMLHeadElement&&b.head.ignore||(P instanceof HTMLHeadElement&&b.head.style!=="morph"?u(P,R,b):(h(P,R,b),k(P,b)||a(b,P,R))),b.callbacks.afterNodeMorphed(P,R)),P)}function h(P,R,b){let w=R.nodeType;if(w===1){let x=P,L=R,F=x.attributes,X=L.attributes;for(let G of X)T(G.name,x,"update",b)||x.getAttribute(G.name)!==G.value&&x.setAttribute(G.name,G.value);for(let G=F.length-1;0<=G;G--){let E=F[G];if(E&&!L.hasAttribute(E.name)){if(T(E.name,x,"remove",b))continue;x.removeAttribute(E.name)}}k(x,b)||S(x,L,b)}(w===8||w===3)&&P.nodeValue!==R.nodeValue&&(P.nodeValue=R.nodeValue)}function S(P,R,b){if(P instanceof HTMLInputElement&&R instanceof HTMLInputElement&&R.type!=="file"){let w=R.value,x=P.value;A(P,R,"checked",b),A(P,R,"disabled",b),R.hasAttribute("value")?x!==w&&(T("value",P,"update",b)||(P.setAttribute("value",w),P.value=w)):T("value",P,"remove",b)||(P.value="",P.removeAttribute("value"))}else if(P instanceof HTMLOptionElement&&R instanceof HTMLOptionElement)A(P,R,"selected",b);else if(P instanceof HTMLTextAreaElement&&R instanceof HTMLTextAreaElement){let w=R.value,x=P.value;if(T("value",P,"update",b))return;w!==x&&(P.value=w),P.firstChild&&P.firstChild.nodeValue!==w&&(P.firstChild.nodeValue=w)}}function A(P,R,b,w){let x=R[b],L=P[b];if(x!==L){let F=T(b,P,"update",w);F||(P[b]=R[b]),x?F||P.setAttribute(b,""):T(b,P,"remove",w)||P.removeAttribute(b)}}function T(P,R,b,w){return P==="value"&&w.ignoreActiveValue&&R===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(P,R,b)===!1}function k(P,R){return!!R.ignoreActiveValue&&P===document.activeElement&&P!==document.body}return y})();function d(y,h,S,A){if(y.head.block){let T=h.querySelector("head"),k=S.querySelector("head");if(T&&k){let P=u(T,k,y);return Promise.all(P).then(()=>{let R=Object.assign(y,{head:{block:!1,ignore:!0}});return A(R)})}}return A(y)}function u(y,h,S){let A=[],T=[],k=[],P=[],R=new Map;for(let w of h.children)R.set(w.outerHTML,w);for(let w of y.children){let x=R.has(w.outerHTML),L=S.head.shouldReAppend(w),F=S.head.shouldPreserve(w);x||F?L?T.push(w):(R.delete(w.outerHTML),k.push(w)):S.head.style==="append"?L&&(T.push(w),P.push(w)):S.head.shouldRemove(w)!==!1&&T.push(w)}P.push(...R.values());let b=[];for(let w of P){let x=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(S.callbacks.beforeNodeAdded(x)!==!1){if("href"in x&&x.href||"src"in x&&x.src){let L,F=new Promise(function(X){L=X});x.addEventListener("load",function(){L()}),b.push(F)}y.appendChild(x),S.callbacks.afterNodeAdded(x),A.push(x)}}for(let w of T)S.callbacks.beforeNodeRemoved(w)!==!1&&(y.removeChild(w),S.callbacks.afterNodeRemoved(w));return S.head.afterHeadMorphed(y,{added:A,kept:k,removed:T}),b}let c=(function(){function y(b,w,x){let{persistentIds:L,idMap:F}=P(b,w),X=h(x),G=X.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(G))throw`Do not understand how to morph style ${G}`;return{target:b,newContent:w,config:X,morphStyle:G,ignoreActive:X.ignoreActive,ignoreActiveValue:X.ignoreActiveValue,restoreFocus:X.restoreFocus,idMap:F,persistentIds:L,pantry:S(),activeElementAndParents:A(b),callbacks:X.callbacks,head:X.head}}function h(b){let w=Object.assign({},t);return Object.assign(w,b),w.callbacks=Object.assign({},t.callbacks,b.callbacks),w.head=Object.assign({},t.head,b.head),w}function S(){let b=document.createElement("div");return b.hidden=!0,document.body.insertAdjacentElement("afterend",b),b}function A(b){let w=[],x=document.activeElement;if(x?.tagName!=="BODY"&&b.contains(x))for(;x&&(w.push(x),x!==b);)x=x.parentElement;return w}function T(b){let w=Array.from(b.querySelectorAll("[id]"));return b.getAttribute?.("id")&&w.push(b),w}function k(b,w,x,L){for(let F of L){let X=F.getAttribute("id");if(w.has(X)){let G=F;for(;G;){let E=b.get(G);if(E==null&&(E=new Set,b.set(G,E)),E.add(X),G===x)break;G=G.parentElement}}}}function P(b,w){let x=T(b),L=T(w),F=R(x,L),X=new Map;k(X,F,b,x);let G=w.__idiomorphRoot||w;return k(X,F,G,L),{persistentIds:F,idMap:X}}function R(b,w){let x=new Set,L=new Map;for(let{id:X,tagName:G}of b)L.has(X)?x.add(X):L.set(X,G);let F=new Set;for(let{id:X,tagName:G}of w)F.has(X)?x.add(X):L.get(X)===G&&F.add(X);for(let X of x)F.delete(X);return F}return y})(),{normalizeElement:p,normalizeParent:m}=(function(){let y=new WeakSet;function h(k){return k instanceof Document?k.documentElement:k}function S(k){if(k==null)return document.createElement("div");if(typeof k=="string")return S(T(k));if(y.has(k))return k;if(k instanceof Node){if(k.parentNode)return new A(k);{let P=document.createElement("div");return P.append(k),P}}else{let P=document.createElement("div");for(let R of[...k])P.append(R);return P}}class A{constructor(P){this.originalNode=P,this.realParentNode=P.parentNode,this.previousSibling=P.previousSibling,this.nextSibling=P.nextSibling}get childNodes(){let P=[],R=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;R&&R!=this.nextSibling;)P.push(R),R=R.nextSibling;return P}querySelectorAll(P){return this.childNodes.reduce((R,b)=>{if(b instanceof Element){b.matches(P)&&R.push(b);let w=b.querySelectorAll(P);for(let x=0;x<w.length;x++)R.push(w[x])}return R},[])}insertBefore(P,R){return this.realParentNode.insertBefore(P,R)}moveBefore(P,R){return this.realParentNode.moveBefore(P,R)}get __idiomorphRoot(){return this.originalNode}}function T(k){let P=new DOMParser,R=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(R.match(/<\/html>/)||R.match(/<\/head>/)||R.match(/<\/body>/)){let b=P.parseFromString(k,"text/html");if(R.match(/<\/html>/))return y.add(b),b;{let w=b.firstChild;return w&&y.add(w),w}}else{let w=P.parseFromString("<body><template>"+k+"</template></body>","text/html").body.querySelector("template").content;return y.add(w),w}}return{normalizeElement:h,normalizeParent:S}})();return{morph:o,defaults:t}})();var pu=(e,t,o={})=>{let{preserveTypingAnimation:n=!0}=o;qC.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,a){if(r instanceof HTMLElement&&n){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let i=r.textContent??"",d=a.textContent??"";if(i!==d)return}return!1}}}}})};var $C=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var cg={index:-1,draft:""};function jC(e){let{direction:t,history:o,currentValue:n,atStart:r,state:a}=e,i=a.index!==-1;if(o.length===0)return{handled:!1,state:a};if(t==="up"){if(!i&&!r)return{handled:!1,state:a};if(!i){let d=o.length-1;return{handled:!0,value:o[d],state:{index:d,draft:n}}}if(a.index>0){let d=a.index-1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,state:a}}if(!i)return{handled:!1,state:a};if(a.index<o.length-1){let d=a.index+1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function zC(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function VC(){return new Map}function KC(e,t,o){let n=e.get(t);return n&&n.fingerprint===o?n.wrapper:null}function GC(e,t,o,n){e.set(t,{fingerprint:o,wrapper:n})}function XC(e,t){for(let o of e.keys())t.has(o)||e.delete(o)}function QC(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function YC(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function qn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function qs(e,t){return qn(e)-e.scrollTop<=t}function JC(e){let{following:t,currentScrollTop:o,lastScrollTop:n,nearBottom:r,userScrollThreshold:a,isAutoScrolling:i=!1,pauseOnUpwardScroll:d=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:c=!1}=e,p=o-n;return i||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:o}:!t&&r&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:o}:t&&d&&p<0?{action:"pause",delta:p,nextLastScrollTop:o}:t&&u&&!r?{action:"pause",delta:p,nextLastScrollTop:o}:{action:"none",delta:p,nextLastScrollTop:o}}function ZC(e){let{following:t,deltaY:o,nearBottom:n=!1,resumeWhenNearBottom:r=!1}=e;return t&&o<0?"pause":!t&&r&&o>0&&n?"resume":"none"}function eS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function ug(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),o=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:o}}function tS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var El={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},NP=["pre","code","a","script","style"],fu=e=>({type:e?.type??El.type,placeholder:e?.placeholder??El.placeholder,speed:e?.speed??El.speed,duration:e?.duration??El.duration,buffer:e?.buffer??El.buffer}),nS=[{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"}],Pl=new Map;for(let e of nS)Pl.set(e.name,e);var rS=["wipe","glyph-cycle"],Ka=e=>{Pl.set(e.name,e)},mg=e=>{nS.some(t=>t.name===e)||Pl.delete(e)},gg=()=>Array.from(Pl.keys()),Ll=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Pl.get(e)??null,mu=(e,t,o,n,r)=>{if(!r)return e;if(o?.bufferContent)return o.bufferContent(e,n);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
29
- `);return a<0?"":e.slice(0,a)}return e},FP=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${o}-${n}`,r.style.setProperty("--char-index",String(n)),r.textContent=t,r},UP=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${o}-${n}`,r.style.setProperty("--word-index",String(n)),r.textContent=t,r},pg=/\s/,qP=(e,t)=>{let o=e.parentNode;for(;o;){if(o.nodeType===1){let n=o;if(t.has(n.tagName.toLowerCase()))return!0}o=o.parentNode}return!1},$P=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=0;for(;d<a.length;)if(pg.test(a[d])){let u=d;for(;u<a.length&&pg.test(a[u]);)u+=1;i.appendChild(n.createTextNode(a.slice(d,u))),d=u}else{let u=n.createElement("span");u.className="persona-stream-word-group";let c=d;for(;c<a.length&&!pg.test(a[c]);)u.appendChild(FP(n,a[c],t,o.value)),o.value+=1,c+=1;i.appendChild(u),d=c}r.replaceChild(i,e)},jP=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=a.split(/(\s+)/);for(let u of d)u&&(/^\s+$/.test(u)?i.appendChild(n.createTextNode(u)):(i.appendChild(UP(n,u,t,o.value)),o.value+=1));r.replaceChild(i,e)},kl=(e,t,o,n)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let a=new Set((n?.skipTags??NP).map(m=>m.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),d=[],u=i.nextNode();for(;u;)qP(u,a)||d.push(u),u=i.nextNode();let c={value:n?.startIndex??0},p=t==="char"?$P:jP;for(let m of d)p(m,o,c);return r.innerHTML},gu=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Il=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let o=e.createElement("div");return o.className="persona-stream-skeleton-line",t.appendChild(o),t},oS=new WeakMap,zP=(e,t)=>{if(!e.styles)return;let o=oS.get(t);if(o||(o=new Set,oS.set(t,o)),o.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;o.delete(e.name)}o.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},fg=new WeakMap,VP=(e,t)=>{if(!e.onAttach)return;let o=fg.get(t);if(o||(o=new Map,fg.set(t,o)),o.has(e.name))return;let n=e.onAttach(t);o.set(e.name,n)},sS=e=>{let t=fg.get(e);if(t){for(let o of t.values())typeof o=="function"&&o();t.clear()}},Hl=(e,t)=>{zP(e,t),VP(e,t)};var{setLoader:KP,load:GP}=mt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),aS=KP,iS=GP;function hg(e,t=so){let o=e.style.position,n=e.style.zIndex,r=e.style.isolation,a=getComputedStyle(e),i=a.position==="static"||a.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=o),e.style.zIndex=n,e.style.isolation=r}}var Rl=0,Gr=null;function yg(e=document){if(Rl++,Rl===1){let o=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Gr={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:r},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${r}px`,o.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Rl=Math.max(0,Rl-1),Rl===0&&Gr)){let o=e.body,n=e.defaultView??window;o.style.overflow=Gr.originalOverflow,o.style.position=Gr.originalPosition,o.style.top=Gr.originalTop,o.style.width=Gr.originalWidth,n.scrollTo(0,Gr.scrollY),Gr=null}}}var Wl={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},St=e=>(e?.launcher?.mountMode??"floating")==="docked",Xr=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Wo=e=>{let t=e?.launcher?.dock;return{side:t?.side??Wl.side,width:t?.width??Wl.width,animate:t?.animate??Wl.animate,reveal:t?.reveal??Wl.reveal,maxHeight:t?.maxHeight??Wl.maxHeight}};var bg=e=>e==="followUp"?"follow-up":e,vg=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let o=e.label.trim();if(!o)return null;let n=e.prompt?.trim()||o;return{id:e.id?.trim()||n||`suggestion-${t}`,label:o,prompt:n,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},XP=e=>{switch(e){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'}},lS=new WeakSet,QP=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,YP=e=>{QP()||e.forEach((t,o)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:o*60,easing:"ease-out",fill:"backwards"})})},xg=e=>{var R,b,w;let{item:t,index:o,surface:n,source:r,variant:a,streaming:i,config:d,plugins:u,chipsConfig:c,session:p,getTextarea:m,eventTarget:y,submitPrompt:h}=e,S=n==="followUp",A=t.behavior,T=()=>{if(p.isStreaming())return;let x={suggestion:{...t},surface:n,source:r,behavior:A},L=y.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:x,bubbles:!0,composed:!0,cancelable:!0}));if(S&&y.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!L)return;for(let X of u)if(X.onSuggestionSelect?.({suggestion:{...t},surface:n,source:r,variant:a,config:d})===!1)return;let F=m();if(A==="fill"){F.value=t.prompt,F.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),F.focus();return}if(h){h(t.prompt);return}F.value="",p.sendMessage(t.prompt)},k=()=>{let x=I("button",`persona-suggestion persona-suggestion--${a}`);if(x.type="button",x.disabled=i,x.dataset.suggestionId=t.id,x.dataset.emphasis=t.emphasis,x.dataset.behavior=A,a==="chip"&&(c?.fontFamily&&(x.style.fontFamily=XP(c.fontFamily)),c?.fontWeight&&(x.style.fontWeight=c.fontWeight),c?.paddingX&&(x.style.paddingLeft=c.paddingX,x.style.paddingRight=c.paddingX),c?.paddingY&&(x.style.paddingTop=c.paddingY,x.style.paddingBottom=c.paddingY)),t.icon){let F=ce(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);F&&(F.classList.add("persona-suggestion__icon"),t.iconColor&&(F.style.color=t.iconColor),x.appendChild(F))}let L=I("span","persona-suggestion__copy");if(L.appendChild(Y("span",{className:"persona-suggestion__label",text:t.label})),t.description&&a!=="chip"&&L.appendChild(Y("span",{className:"persona-suggestion__description",text:t.description})),x.appendChild(L),a!=="chip"){let F=Ft(ul,16,"currentColor",1.8);F&&(F.classList.add("persona-suggestion__arrow"),x.appendChild(F))}return x.addEventListener("click",T),x},P=null;for(let x of u)if(x.renderSuggestion&&(P=x.renderSuggestion({suggestion:{...t},index:o,surface:n,source:r,variant:a,streaming:i,config:d,defaultRenderer:k,select:T}),P))break;return P??(P=k()),(R=P.dataset).suggestionId||(R.suggestionId=t.id),(b=P.dataset).behavior||(b.behavior=A),(w=P.dataset).emphasis||(w.emphasis=t.emphasis),P instanceof HTMLButtonElement||P.setAttribute("aria-disabled",i?"true":"false"),P},Bl=e=>{let t=[],o=[],n=null,r=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){a();return}let p=Math.max(0,e.scrollWidth-e.clientWidth);if(p<=1){a();return}let m=getComputedStyle(e).direction==="rtl",y=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),h=4,S=y<=h,A=y>=p-h,T=m?!A:!S,k=m?!S:!A;e.toggleAttribute("data-scroll-left",T),e.toggleAttribute("data-scroll-right",k)},d=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",d,{passive:!0});let u=typeof ResizeObserver=="function"?new ResizeObserver(d):null;return u?.observe(e),{buttons:t,elements:o,destroy:()=>{e.removeEventListener("scroll",d),u?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,m,y,h,S,A)=>{e.replaceChildren(),t.length=0,o.length=0;let T=A?.source??"config",k=A?.surface??(T==="config"?"starter":"followUp"),P=k==="followUp",R=A?.variant??"chip",b=A?.behavior??"send",w=A?.overflow??"wrap",x=A?.config??{},L=A?.plugins??[],F=typeof A?.maxItems=="number"?Math.max(0,Math.floor(A.maxItems)):void 0,X=P?"followUps":"starters";!lS.has(x)&&x.debug===!0&&R!=="chip"&&x.suggestions?.[X]?.overflow!==void 0&&(lS.add(x),console.info(`[persona] suggestions.${X}.overflow applies to the "chip" variant only; the "${R}" variant manages its own stacking.`));let G=Q=>Q.map(vg).filter(de=>de!==null).map(de=>({...de,behavior:de.behavior??b})),E=G(p??[]);L.forEach(Q=>{Q.transformSuggestions&&(E=G(Q.transformSuggestions({suggestions:E.map(de=>({...de})),surface:k,source:T,config:x})))});let _=F===void 0?E:E.slice(0,F);if(!_.length){e.hidden=!0,n=null,a();return}if(!P&&(h??m.getMessages()).some(de=>de.role==="user")){e.hidden=!0,n=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=bg(k),e.dataset.variant=R,e.dataset.overflow=w;let O=document.createDocumentFragment(),W=m.isStreaming();_.forEach((Q,de)=>{let pe=xg({item:Q,index:de,surface:k,source:T,variant:R,streaming:W,config:x,plugins:L,chipsConfig:S,session:m,getTextarea:()=>y,eventTarget:e,submitPrompt:A?.submitPrompt});O.appendChild(pe),o.push(pe),[...pe instanceof HTMLButtonElement?[pe]:[],...Array.from(pe.querySelectorAll("button"))].forEach(Pe=>{t.includes(Pe)||(Pe.disabled=W,t.push(Pe))})}),e.appendChild(O),i(),d();let oe=JSON.stringify({normalized:_,surface:k,variant:R,source:T});oe!==n&&(n=oe,YP(o),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:_.map(Q=>({...Q})),surface:k,source:T,variant:R},bubbles:!0,composed:!0})),P&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:_.map(Q=>Q.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"};var JP="persona-header-control",ZP="persona-header-control--glyph",eL="persona-header-control--sparse",tL=20,oL={x:[1.4,1.05]},dS="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",nL="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",hu=(e,t,o={})=>{let{iconSize:n,iconText:r}=o,[a,i]=oL[t]??[1,1.5],d=!n;e.classList.toggle(ZP,d),e.classList.toggle(eL,d&&a!==1);let u=parseFloat(n??"")||tL,c=ce(t,`${Math.round(u*a)}px`,"currentColor",i);c?(c.style.display="block",d||(c.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(c)):r&&(e.textContent=r)},$s=e=>{let{ariaLabel:t,tooltip:o=!0,tooltipHint:n,iconName:r,iconText:a,wrapperClassName:i=dS,size:d,iconSize:u,color:c,backgroundColor:p,borderWidth:m,borderColor:y,borderRadius:h,paddingX:S,paddingY:A,hidden:T,extraClassName:k,attrs:P}=e,R=I("div",i),b=!!(m||y),w=Y("button",{className:bo(JP,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!b&&"persona-border-none",!h&&"persona-rounded-full",k),attrs:{type:"button","aria-label":t,...P},style:{width:d,height:d,minWidth:d,minHeight:d,display:T?"none":void 0,color:c||Co.actionIconColor,backgroundColor:p,border:b?`${m||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:h,paddingLeft:S,paddingRight:S,paddingTop:A,paddingBottom:A}});return r?hu(w,r,{iconSize:u,iconText:a}):a&&(w.textContent=a),R.appendChild(w),eo({anchor:w,trigger:R,text:()=>w.getAttribute("aria-label")??t,hint:n,enabled:o}),{button:w,wrapper:R}},Ga=(e,t={})=>{let{showClose:o=!0,wrapperClassName:n=dS,buttonSize:r,iconSize:a}=t,i=e?.launcher??{},d=i.closeButtonTooltipText??"Close chat",u=i.closeButtonShowTooltip??!0,{button:c,wrapper:p}=$s({ariaLabel:d,tooltip:u,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:n,size:r??i.closeButtonSize,iconSize:a,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!o});return{button:c,wrapper:p}},Xa=(e,t={})=>{let{wrapperClassName:o=nL,buttonSize:n,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},d=i.tooltipText??"Clear chat",u=i.showTooltip??!0,{button:c,wrapper:p}=$s({ariaLabel:d,tooltip:u,iconName:i.iconName??"refresh-cw",wrapperClassName:o,size:n??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:c,wrapper:p}};var Co={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)"},Cg={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)"},rL={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)"},pr=e=>{let{config:t,showClose:o=!0}=e,n=Y("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:Co.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=t?.launcher??{},a=r.headerIconSize??"48px",i=r.closeButtonPlacement??"inline",d=r.headerIconHidden??!1,u=r.headerIconName,c=Y("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!d)if(u){let w=parseFloat(a)||24,x=ce(u,w*.6,"currentColor",1);x?c.replaceChildren(x):c.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let w=I("img");w.src=t.launcher.iconUrl,w.alt="",w.className="persona-rounded-xl persona-object-cover",w.style.height=a,w.style.width=a,c.replaceChildren(w)}else c.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=I("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Y("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Co.titleColor,...Cg}}),y=Y("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Co.subtitleColor,...rL}});p.append(m,y),d?n.append(p):n.append(c,p);let h=r.clearChat??{},S=h.enabled??!0,A=h.placement??"inline",T=null,k=null;if(S){let x=Xa(t,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=x.button,k=x.wrapper,A==="top-right"&&(k.style.right="48px"),A==="inline"&&n.appendChild(k)}let P=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":S&&A==="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:R,wrapper:b}=Ga(t,{showClose:o,wrapperClassName:P});return i!=="top-right"&&n.appendChild(b),{header:n,iconHolder:c,headerTitle:m,headerSubtitle:y,closeButton:R,closeButtonWrapper:b,clearChatButton:T,clearChatButtonWrapper:k}},js=(e,t,o)=>{let n=o?.launcher??{},r=n.closeButtonPlacement??"inline",a=n.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function zs(e){let{items:t,onSelect:o,anchor:n,position:r="bottom-left",portal:a,onOpenChange:i}=e,d=I("div","persona-dropdown-menu persona-hidden");d.setAttribute("role","menu"),d.setAttribute("data-persona-theme-zone","dropdown"),a?(d.style.position="fixed",d.style.zIndex=String(qa)):(d.style.position="absolute",d.style.top="100%",d.style.marginTop="4px",r==="bottom-right"?d.style.right="0":d.style.left="0");for(let S of t){if(S.dividerBefore){let k=document.createElement("hr");d.appendChild(k)}let A=document.createElement("button");if(A.type="button",A.setAttribute("role","menuitem"),A.setAttribute("data-dropdown-item-id",S.id),S.destructive&&A.setAttribute("data-destructive",""),S.icon){let k=ce(S.icon,16,"currentColor",1.5);k&&A.appendChild(k)}let T=document.createElement("span");T.textContent=S.label,A.appendChild(T),A.addEventListener("click",k=>{k.stopPropagation(),m(),o(S.id)}),d.appendChild(A)}let u=null;function c(){if(!a)return;let S=n.getBoundingClientRect();d.style.top=`${S.bottom+4}px`,r==="bottom-right"?(d.style.right=`${window.innerWidth-S.right}px`,d.style.left="auto"):(d.style.left=`${S.left}px`,d.style.right="auto")}function p(){let S=d.classList.contains("persona-hidden");c(),d.classList.remove("persona-hidden"),S&&i?.(!0),requestAnimationFrame(()=>{let A=T=>{!d.contains(T.target)&&!n.contains(T.target)&&m()};document.addEventListener("click",A,!0),u=()=>document.removeEventListener("click",A,!0)})}function m(){let S=!d.classList.contains("persona-hidden");d.classList.add("persona-hidden"),u?.(),u=null,S&&i?.(!1)}function y(){d.classList.contains("persona-hidden")?p():m()}function h(){m(),d.remove()}return a&&a.appendChild(d),{element:d,show:p,hide:m,toggle:y,destroy:h}}function Vs(e){let{icon:t,label:o,size:n,strokeWidth:r,className:a,chromeless:i,onClick:d,aria:u}=e,c=I("button",bo(!i&&"persona-icon-btn",a));c.type="button",c.setAttribute("aria-label",o),c.title=o;let p=ce(t,n??16,"currentColor",r??2);if(p&&c.appendChild(p),d&&c.addEventListener("click",d),u)for(let[m,y]of Object.entries(u))c.setAttribute(m,y);return c}function Sg(e){let{icon:t,label:o,variant:n="default",size:r="sm",iconSize:a,className:i,onClick:d,aria:u}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+r,i&&(c+=" "+i);let p=I("button",c);if(p.type="button",p.setAttribute("aria-label",o),t){let y=ce(t,a??14,"currentColor",2);y&&p.appendChild(y)}let m=I("span");if(m.textContent=o,p.appendChild(m),d&&p.addEventListener("click",d),u)for(let[y,h]of Object.entries(u))p.setAttribute(y,h);return p}function cS(e){let{items:t,selectedId:o,onSelect:n,className:r}=e,a=I("div","persona-toggle-group"+(r?" "+r:""));a.setAttribute("role","group");let i=o,d=[];function u(){for(let p of d)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let m;p.icon?m=Vs({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,u(),n(p.id)}}):(m=I("button","persona-icon-btn"+(p.className?" "+p.className:"")),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{i=p.id,u(),n(p.id)})),m.setAttribute("aria-pressed",p.id===i?"true":"false"),d.push({id:p.id,btn:m}),a.appendChild(m)}function c(p){i=p,u()}return{element:a,setSelected:c}}function uS(e){let{label:t,icon:o,iconSize:n,iconOnly:r,menuItems:a,onSelect:i,onPrimary:d,position:u="bottom-left",portal:c,chevronLabel:p="More options",chevronIconSize:m,className:y,primaryClassName:h,chevronClassName:S}=e,A=I("div","persona-split-btn"+(y?" "+y:"")),T={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:d},k=r&&o?Vs({...T,icon:o,size:n??14}):Sg({...T,icon:o,iconSize:n??14}),P=Vs({icon:"chevron-down",label:p,size:m??14,className:"persona-split-btn-chevron"+(S?" "+S:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});A.append(k,P);let R=null,b=()=>{if(R)return R;let w=(typeof c=="function"?c():c)??void 0;return R=zs({items:a,onSelect:i,anchor:A,position:u,portal:w,onOpenChange:x=>{P.setAttribute("aria-expanded",x?"true":"false")}}),w||A.appendChild(R.element),R};return A.isConnected?b():requestAnimationFrame(()=>{R||b()}),P.addEventListener("click",w=>{w.stopPropagation(),b().toggle()}),{element:A,primaryButton:k,chevronButton:P,openMenu:()=>b().show(),closeMenu:()=>R?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{R?.destroy(),A.remove()}}}function yu(e){let{label:t,icon:o="chevron-down",menuItems:n,onSelect:r,position:a="bottom-left",portal:i,className:d,hover:u}=e,c=I("div","persona-combo-btn"+(d?" "+d:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let p=I("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let m=ce(o,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",c.appendChild(m)),u&&(c.style.borderRadius=u.borderRadius??"10px",c.style.padding=u.padding??"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{c.style.backgroundColor=u.background??"",c.style.borderColor=u.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let y=zs({items:n,onSelect:S=>{c.setAttribute("aria-expanded","false"),r(S)},anchor:c,position:a,portal:i});i||c.appendChild(y.element);let h=()=>c.getAttribute("data-persona-menu-locked")==="true";return c.addEventListener("click",S=>{if(S.stopPropagation(),h())return;let A=!y.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",A?"false":"true"),y.toggle()}),c.addEventListener("keydown",S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),c.click())}),{element:c,setLabel:S=>{p.textContent=S,c.setAttribute("aria-label",S)},open:()=>{c.setAttribute("aria-expanded","true"),y.show()},close:()=>{c.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let S=!y.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",S?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),c.remove()}}}var wg=e=>{let t=pr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),o=e.layoutHeaderConfig?.onTitleClick;if(o){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>o()),n.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),o())}))}return t};function sL(e,t,o){if(t?.length)for(let n of t){let{button:r,wrapper:a}=$s({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?uu(n.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",n.id),n.shortcut){let i=Tl(n.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(n.menuItems?.length){let i=zs({items:n.menuItems,onSelect:d=>o?.(d),anchor:a,position:"bottom-right"});a.appendChild(i.element),r.addEventListener("click",d=>{d.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>o?.(n.id));e.appendChild(a)}}var Ag=e=>{let{config:t,showClose:o=!0,onClose:n,layoutHeaderConfig:r,onHeaderAction:a}=e,i=t?.launcher??{},d=I("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");d.setAttribute("data-persona-theme-zone","header"),d.style.minHeight=Co.minHeight,d.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",d.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",d.style.boxShadow="var(--persona-header-shadow, none)",d.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let u=r?.titleMenu,c,p;if(u){let b=yu({label:i.title??"Chat Assistant",menuItems:u.menuItems,onSelect:w=>{let x=F=>{F===!1&&b.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:w}}))},L=u.onSelect(w);L instanceof Promise?L.then(x,()=>{}):x(L)},hover:u.hover,className:""});c=b.element,c.style.color=Co.titleColor,p=c.querySelector(".persona-combo-btn-label")??c}else{if(c=I("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=I("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Co.titleColor,Object.assign(p.style,Cg),p.textContent=i.title??"Chat Assistant",c.appendChild(p),r?.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let w=r.onTitleClick;c.addEventListener("click",x=>{x.target.closest("button")||w()}),c.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),w())})}let b=r?.titleRowHover;b&&(c.style.borderRadius=b.borderRadius??"10px",c.style.padding=b.padding??"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{c.style.backgroundColor=b.background??"",c.style.borderColor=b.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}d.appendChild(c);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:y,wrapper:h}=Ga(t,{showClose:o,wrapperClassName:m});n&&y.addEventListener("click",n);let S=I("div","persona-flex persona-items-center persona-gap-1");u||sL(S,r?.trailingActions,r?.onAction??a);let A=i.clearChat??{},T=null,k=null;if(A.enabled??!0){let b=A.placement??"inline",w=Xa(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});T=w.button,k=w.wrapper,b==="top-right"?k.style.right="48px":S.appendChild(k)}S.appendChild(h),d.appendChild(S);let P=I("div");P.style.display="none";let R=I("span");return R.style.display="none",{header:d,iconHolder:P,headerTitle:p,headerSubtitle:R,closeButton:y,closeButtonWrapper:h,clearChatButton:T,clearChatButtonWrapper:k}},bu={default:wg,minimal:Ag},Mg=e=>bu[e]??bu.default,Qa=(e,t,o)=>{if(t?.render){let i=t.render({config:e,onClose:o?.onClose,onClearChat:o?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),d=I("div");d.style.display="none";let u=I("span"),c=I("span"),p=I("button");p.style.display="none";let m=I("div");return m.style.display="none",{header:i,iconHolder:d,headerTitle:u,headerSubtitle:c,closeButton:p,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let n=t?.layout??"default",a=Mg(n)({config:e,showClose:t?.showCloseButton??o?.showClose??!0,onClose:o?.onClose,onClearChat:o?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var Ks=e=>{let{config:t}=e,o=Y("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),n=Jc(),r=Y("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:a,attachAutoResize:i}=Gc(t);i();let d=Xc(t),u=za(t),c=Qc(t),p=Yc(t),m=Y("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),c&&(c.previewsContainer.style.gap="8px",m.append(c.previewsContainer),r.append(c.input)),r.append(a);let y=Y("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=Y("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),S=Y("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return c&&h.append(c.wrapper),u&&S.append(u.wrapper),S.append(d.wrapper),y.append(h,S),r.append(y),r.addEventListener("click",A=>{A.target!==d.button&&A.target!==d.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&A.target!==c?.button&&A.target!==c?.wrapper&&a.focus()}),o.append(n,r,p),{footer:o,suggestions:n,composerForm:r,header:m,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:p,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:y,leftActions:h,rightActions:S,setSendButtonMode:d.setMode}};var pS=()=>{let e=Y("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=I("span","persona-pill-peek__icon"),o=Ft(hl,16,"currentColor",1.5);o&&t.appendChild(o);let n=I("span","persona-pill-peek__text"),r=I("span","persona-pill-peek__caret"),a=Ft(_s,16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,n,r),{root:e,textNode:n}},vu=e=>{let{config:t}=e,o=Y("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=Jc(),r=Yc(t);r.style.display="none";let{textarea:a,attachAutoResize:i}=Gc(t,{defaultMaxLines:5});i();let d=Xc(t),u=za(t),c=Qc(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let p=Y("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=Y("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});c&&m.append(c.wrapper);let y=Y("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});u&&y.append(u.wrapper),y.append(d.wrapper),p.addEventListener("click",A=>{A.target!==d.button&&A.target!==d.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&A.target!==c?.button&&A.target!==c?.wrapper&&a.focus()}),c&&p.append(c.input),p.append(m,a,y);let h=Y("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});o.append(h),c&&h.append(c.previewsContainer),o.append(n,p,r);let S=p;return{footer:o,suggestions:n,composerForm:p,header:h,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:r,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:S,leftActions:m,rightActions:y,setSendButtonMode:d.setMode}};var aL=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},iL=(e,t)=>{if(!e)return null;let o=aL(e);if(o===null)return null;let n=t?.[e],r=n!==void 0?n:o;return r||null},lL=(e,t)=>{let o=I("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return o.setAttribute("data-stop-reason",e),o.setAttribute("role","note"),o.style.opacity="0.75",o.textContent=t,o},dL=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Eg=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Pg=320,yS=320,cL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),uL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),pL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),fL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),mL=e=>{if(!e||e.length===0)return null;let t=Y("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let o of e){let n=Y("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:o.label}}),r=I("span","persona-mention-chip-icon"),a=ce(o.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),n.appendChild(r),n.appendChild(Y("span",{className:"persona-mention-chip-label",text:o.label})),t.appendChild(n)}return t},gL=(e,t)=>{let o=document.createDocumentFragment();for(let n of e){if(n.kind==="text"){o.appendChild(document.createTextNode(n.text));continue}o.appendChild(Sl(n.ref,{readonly:!0,render:t}))}return o},fS="\uE000",mS="\uE001",hL=(e,t,o,n)=>{let r=Math.random().toString(36).slice(2,8),a=y=>`${fS}${r}:${y}${mS}`,i=t.map((y,h)=>y.kind==="text"?y.text:a(h)).join(""),d=o(i);if(!t.every((y,h)=>y.kind==="text"||d.includes(a(h)))){e.replaceChildren(gL(t,n));return}e.innerHTML=d;let c=new RegExp(`${fS}${r}:(\\d+)${mS}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let y=p.nextNode();y;y=p.nextNode())m.push(y);for(let y of m){let h=y;for(let S=c.exec(h.data);S;S=c.exec(h.data)){let A=t[Number(S[1])],T=h.splitText(S.index);T.data=T.data.slice(S[0].length),A?.kind==="mention"&&T.parentNode?.insertBefore(Sl(A.ref,{readonly:!0,render:n}),T),h=T}}},yL=(e,t,o)=>{if(e.length===0)return null;try{let n=I("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let r=0,a=!1,i=()=>{a||(a=!0,n.remove(),o?.())};return e.forEach((d,u)=>{let c=I("img");c.alt=d.alt?.trim()||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Pg}px`,c.style.maxHeight=`${yS}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,c.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),c.remove(),r===0&&i())}),c.addEventListener("load",()=>{p=!0}),dL(d.image)?(c.src=d.image,n.appendChild(c)):(p=!0,r=Math.max(0,r-1),c.remove())}),r===0?(i(),null):n}catch{return o?.(),null}},bL=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let o=0;return e.forEach(n=>{if(!Eg(n.audio))return;let r=I("audio");r.controls=!0,r.preload="metadata",r.src=n.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Pg}px`,t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},vL=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let o=0;return e.forEach(n=>{if(!Eg(n.video))return;let r=I("video");r.controls=!0,r.preload="metadata",r.src=n.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Pg}px`,r.style.maxHeight=`${yS}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},xL=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let o=0;return e.forEach(n=>{if(!Eg(n.data))return;let r=I("a");r.href=n.data,r.download=n.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=n.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",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},Gs=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let 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="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(o),e.appendChild(n),e.appendChild(r),e},Lg=(e,t,o)=>{let n={config:o??{},streaming:!0,location:e,defaultRenderer:Gs};if(t){let r=t(n);if(r!==null)return r}return Gs()},CL=(e,t)=>{let o=I("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=t==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let r=I("img");r.src=n,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",o.appendChild(r)}else o.textContent=n,o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else o.textContent=t==="user"?"U":"A",o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return o},gS=(e,t,o="div")=>{let n=I(o,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Ol=(e,t="bubble")=>{let o=["persona-message-bubble"];switch(t){case"flat":e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):o.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":o.push("persona-text-sm","persona-leading-relaxed"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):o.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:o.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):o.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 o},hS={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"}},SL=(e,t,o="bubble",n)=>{if(!n)return;let r=t==="user"?"user":"assistant",a=hS[o??"bubble"]??hS.bubble;n.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${a.padding})`),n.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${a.fontSize})`),n.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${a.lineHeight})`),n.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},xu="custom:",wL=e=>`${xu}${e}`,bS=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(o=>(o.roles??["assistant"]).includes(t)),kg=(e,t,o,n)=>{let r=t.showCopy??!0,a=t.showUpvote??!0,i=t.showDownvote??!0,d=t.showReadAloud??!1,u=(t.showRegenerate??!1)&&n?.canRegenerate===!0,c=(t.showEdit??!1)&&n?.canEdit===!0,p=(t.showQuote??!1)&&n?.canQuote!==!1,m=bS(t,e.role);if(!r&&!a&&!i&&!d&&!u&&!c&&!p&&m.length===0){let R=I("div");return R.style.display="none",R.id=`actions-${e.id}`,R.setAttribute("data-actions-for",e.id),R}let y=t.visibility??"hover",h=t.align??"right",S=t.layout??"pill-inside",A={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],T={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[S],k=I("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${A} ${T} ${y==="hover"?"persona-message-actions-hover":""}`);k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id);let P=(R,b,w)=>{let x=Vs({icon:R,label:b,size:14,className:"persona-message-action-btn",chromeless:!0});return x.setAttribute("data-action",w),x};r&&k.appendChild(P("copy","Copy message","copy")),d&&k.appendChild(P("volume-2","Read aloud","read-aloud")),a&&k.appendChild(P("thumbs-up","Upvote","upvote")),i&&k.appendChild(P("thumbs-down","Downvote","downvote")),u&&k.appendChild(P("refresh-cw","Regenerate response","regenerate")),c&&k.appendChild(P("pencil","Edit message","edit")),p&&k.appendChild(P("quote","Quote message","quote"));for(let R of m)k.appendChild(P(R.iconName??"ellipsis",R.label,wL(R.id)));return k},Ya=(e,t,o,n,r,a)=>{let i=o??{},d=i.layout??"bubble",u=i.avatar,c=i.timestamp,p=u?.show??!1,m=c?.show??!1,y=u?.position??"left",h=c?.position??"below",S=Ol(e.role,d),A=I("div",S.join(" "));A.id=`bubble-${e.id}`,A.setAttribute("data-message-id",e.id),A.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let T=a?.widgetConfig?.theme?.components?.message;SL(A,e.role,d,e.role==="user"?T?.user:T?.assistant),d==="flat"?(A.style.backgroundColor="transparent",A.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=cL(e),P=e.content?.trim()??"",b=k.length>0&&P===Wa,w=fu(a?.widgetConfig?.features?.streamAnimation),x=a?.widgetConfig?.features?.streamAnimation?.plugins,L=e.role==="assistant"&&w.type!=="none"?Ll(w.type,x):null,F=e.role==="assistant"&&L?.isAnimating?.(e)===!0,X=e.role==="assistant"&&L!==null&&(!!e.streaming||F);X&&L?.bubbleClass&&A.classList.add(L.bubbleClass);let G=document.createElement("div");G.classList.add("persona-message-content"),e.streaming&&G.classList.add("persona-content-streaming"),X&&L&&(L.containerClass&&G.classList.add(L.containerClass),G.style.setProperty("--persona-stream-step",`${w.speed}ms`),G.style.setProperty("--persona-stream-duration",`${w.duration}ms`));let E=X?mu(e.content??"",w.buffer,L,e,!!e.streaming):e.content??"",_=()=>{let ke=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent});return X&&L?.wrap==="char"?kl(ke,"char",e.id,{skipTags:L.skipTags}):X&&L?.wrap==="word"?kl(ke,"word",e.id,{skipTags:L.skipTags}):ke},O=null;if(b?(O=document.createElement("div"),O.innerHTML=_(),O.style.display="none",G.appendChild(O)):e.contentSegments?.length?hL(G,e.contentSegments,ke=>t({text:ke,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):G.innerHTML=_(),X&&L?.useCaret&&!b&&P){let ke=gu(),z=G.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ue=z[z.length-1];if(Ue?.parentNode)Ue.parentNode.insertBefore(ke,Ue.nextSibling);else{let Ge=G.lastElementChild;Ge?Ge.appendChild(ke):G.appendChild(ke)}}if(m&&h==="inline"&&e.createdAt){let ke=gS(e,c,"span");ke.classList.add("persona-timestamp-inline");let z=G.lastElementChild;z?z.appendChild(ke):G.appendChild(ke)}if(k.length>0){let ke=yL(k,!b&&!!P,()=>{b&&O&&(O.style.display="")});ke?A.appendChild(ke):b&&O&&(O.style.display="")}let W=uL(e);if(W.length>0){let ke=bL(W);ke&&A.appendChild(ke)}let oe=pL(e);if(oe.length>0){let ke=vL(oe);ke&&A.appendChild(ke)}let Q=fL(e);if(Q.length>0){let ke=xL(Q);ke&&A.appendChild(ke)}let de=e.contentSegments?.length?null:mL(e.contextMentions);if(de&&A.appendChild(de),A.appendChild(G),m&&h==="below"&&e.createdAt){let ke=gS(e,c);ke.classList.add("persona-mt-1"),A.appendChild(ke)}let pe=e.role==="assistant"?iL(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ke=!!(E&&E.trim()),z=w.placeholder==="skeleton",Ue=z&&w.buffer==="line"&&ke;if(ke)Ue&&A.appendChild(Il());else if(z)A.appendChild(Il());else{let Ge=Lg("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);Ge&&A.appendChild(Ge)}}pe&&e.stopReason&&!e.streaming&&(P||(G.style.display="none"),A.appendChild(lL(e.stopReason,pe)));let xe=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&n?.enabled!==!1,Pe=a?.actionEligibility,ge=e.role==="user"&&!e.streaming&&n?.enabled!==!1&&(n?.showEdit===!0&&Pe?.canEdit===!0||n?.showQuote===!0&&Pe?.canQuote===!0||bS(n,"user").length>0);if((xe||ge)&&n){let ke=kg(e,ge?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,r,Pe);A.appendChild(ke)}if(!p||e.role==="system")return A;let Ke=I("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Bt=CL(u,e.role);return y==="right"||y==="left"&&e.role==="user"?Ke.append(A,Bt):Ke.append(Bt,A),Ke},vS=(e,t,o,n,r,a)=>{let i=o??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ya(e,t,o,n,r,a)};var AL=40,ML=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let o=null;try{o=t()}catch(n){console.warn("[persona] welcome.icon renderer threw",n)}if(!o){e.hidden=!0;return}e.appendChild(o),e.hidden=!1;return}if(t.type==="lucide"){let o=ce(t.name,AL);if(!o){e.hidden=!0;return}e.appendChild(o)}else t.type==="image"?e.appendChild(Y("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Y("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},xS=(e,t,o={})=>{let n=Y("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});n.hidden=!0;let r=I("p","persona-welcome-kicker");r.hidden=!0;let a=I("h2","persona-welcome-title"),i=I("p","persona-welcome-subtitle"),d=Y("div",{className:"persona-welcome-head-text"},r,a),u=Y("div",{className:"persona-welcome-title-row"},n,d);return{host:Y("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:o.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},u,i,t),iconHolder:n,kicker:r,title:a,subtitle:i,starterSuggestions:t}},Ja=(e,t,o)=>{t.hidden=!o,t.style.display=o?"":"none",e.classList.toggle("persona-gap-6",o),e.classList.toggle("persona-gap-3",!o)},Su=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??"",e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",ML(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss),e.host.setAttribute("data-persona-welcome-anchor",t.anchor??"bottom"),t.iconPlacement==="inline"?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},TL="data-persona-welcome-plugin",CS="data-persona-welcome-overlay",Cu="persona-welcome-overlay-active",Ig=new WeakMap,Hg=(e,t,o)=>{o.setAttribute(TL,""),t.appendChild(o),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(CS,""),e.classList.contains(Cu)||(Ig.set(e,e.scrollTop),e.classList.add(Cu),e.scrollTop=0)},Rg=(e,t,o)=>{o&&o!==t&&o.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(CS),e.classList.contains(Cu)&&(e.classList.remove(Cu),e.scrollTop=Ig.get(e)??e.scrollTop,Ig.delete(e))},SS=()=>{let e=Y("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},wu=(e,t,o)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let n=o?.layout?.messages?.layout??"bubble",r=Y("div",{className:Ol("assistant",n).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:n==="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))"}});e.appendChild(Y("div",{className:"persona-flex"},r)),e.hidden=!1},wS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,AS=(e,t)=>{if(wS()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let o=e.getBoundingClientRect(),n=e.parentElement,r=0,a=0,i=0;if(n){let S=getComputedStyle(n);r=parseFloat(S.rowGap)||0;let A=e.previousElementSibling,T=e.nextElementSibling,P=n.getBoundingClientRect().top+(parseFloat(S.borderTopWidth)||0)+(parseFloat(S.paddingTop)||0)-n.scrollTop;a=Math.max(0,A?o.top-A.getBoundingClientRect().bottom-r:o.top-P),i=Math.max(0,T?T.getBoundingClientRect().top-o.bottom-r:0)}let d=e.style.overflow;e.style.overflow="hidden";let u=getComputedStyle(e),c=parseFloat(u.paddingTop)||0,p=parseFloat(u.paddingBottom)||0,m=e.animate([{opacity:"1",transform:"none",height:`${o.height}px`,minHeight:"0px",paddingTop:`${c}px`,paddingBottom:`${p}px`,marginTop:`${a}px`,marginBottom:`${i}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,h=()=>{y||(y=!0,e.style.overflow=d,t(m))};return m.finished.then(h).catch(h),m},MS=(e,t,o)=>{if(t<=1||wS()||typeof e.animate!="function"||!e.isConnected)return null;let n=o==="drop"?-t:t;return e.animate([{transform:`translateY(${n}px)`},{transform:"none"}],{duration:260,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var EL="Hello \u{1F44B}",PL="I can answer questions and help you get things done here.",TS=new WeakSet,So=(e,t)=>!!e&&e[t]!==void 0,LL=(e,t)=>{!e||e.debug!==!0||!t.length||TS.has(e)||(TS.add(e),t.forEach(o=>console.warn(`[persona] ${o}`)))},xn=e=>{let t=e?.welcome,o=e?.copy,n=So(t,"variant")?t.variant:o?.showWelcomeCard===!1?"none":"card",r=n==="hero"?"on-first-message":So(t,"dismiss")?t.dismiss:"never",a=[];So(t,"title")&&So(o,"welcomeTitle")&&a.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),So(t,"subtitle")&&So(o,"welcomeSubtitle")&&a.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),So(t,"variant")&&So(o,"showWelcomeCard")&&a.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),n==="hero"&&So(t,"message")&&a.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),n==="hero"&&So(t,"dismiss")&&t.dismiss!=="on-first-message"&&a.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let i=t?.anchor==="center"?"center":"bottom",d=Ml(t?.anchorComposerTop)!==null;return So(t,"anchorComposerTop")&&!d&&a.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),i!=="center"&&(So(t,"anchorComposerTop")||So(t,"composerGap"))&&a.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),LL(e,a),{title:So(t,"title")?t.title:o?.welcomeTitle??EL,kicker:t?.kicker??"",subtitle:So(t,"subtitle")?t.subtitle:o?.welcomeSubtitle??PL,icon:t?.icon,align:t?.align==="start"||t?.align==="center"?t.align:void 0,iconPlacement:t?.icon&&typeof t.icon!="function"&&t.icon.placement==="inline"?"inline":"above",variant:n,dismiss:r,message:n==="hero"?void 0:t?.message,anchor:i,anchorComposerTop:d?t.anchorComposerTop:"44%",composerGap:t?.composerGap?.trim()||lu}},ES=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Qr=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(o=>o.role==="user");var PS="16px",Bg="10px",Og="14px",LS=e=>{let t=e?.launcher?.enabled??!0,o=St(e);if(Xr(e)){let p=e?.launcher?.composerBar??{},m=I("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=p.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??so);let y=I("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 h=I("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=p.expandedSize??"anchored",h.style.zIndex=String(e?.launcher?.zIndex??so),{wrapper:m,panel:y,pillRoot:h}}if(o){let p=I("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=I("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(m),{wrapper:p,panel:m}}if(!t){let p=I("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=I("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=e?.launcher?.width??"100%";return p.style.width=y,m.style.width="100%",p.appendChild(m),{wrapper:p,panel:m}}let r=e?.launcher??{},a=r.position&&Go[r.position]?Go[r.position]:Go["bottom-right"],i=I("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??so);let d=I("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=e?.launcher?.width??e?.launcherWidth??Vo;return d.style.width=c,d.style.maxWidth=c,i.appendChild(d),{wrapper:i,panel:d}},Dg=e=>{let t=Y("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":bg(e)}});return t.hidden=!0,t},kS=(e,t)=>{let o=Dg("starter"),n=xS(e,o,{flatShadow:St(e)}),r=xn(e);Su(n,r),Ja(t,n.host,Qr(r,e?.initialMessages));let a=SS();return wu(a,r.message,e),{welcome:n,greetingHost:a}},kL=(e,t)=>{let o=I("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");o.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:r}=Ga(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:PS,iconSize:Bg});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let a=e?.launcher?.clearChat?.enabled??!0,i=null,d=null;if(a){let L=Xa(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:PS,iconSize:Og});i=L.button,d=L.wrapper,d.style.position="absolute",d.style.top="8px",d.style.right="32px",d.style.zIndex="10"}let u=Y("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Y("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"}});c.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:m}=kS(e,c),{host:y,title:h,subtitle:S}=p,A=p.starterSuggestions,T=I("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),k=Dg("followUp"),P=Kr(e,!0);P&&(T.style.maxWidth=P,T.style.marginLeft="auto",T.style.marginRight="auto",T.style.width="100%"),c.append(y,m,T,k);let R=Y("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"}}),b=vu({config:e}),{root:w,textNode:x}=pS();return o.append(u,r,c,R),d&&o.appendChild(d),{container:o,body:c,messagesWrapper:T,starterSuggestions:A,transcriptSuggestions:k,composerOverlay:R,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:y,welcomeIconHolder:p.iconHolder,greetingHost:m,introKicker:p.kicker,introTitle:h,introSubtitle:S,closeButton:n,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:d,iconHolder:I("span"),headerTitle:I("span"),headerSubtitle:I("span"),header:u,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:w,peekTextNode:x}},IS=(e,t=!0)=>{if(Xr(e))return kL(e,t);let o=Y("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),n=e?.layout?.header,r=e?.layout?.showHeader!==!1,a=n?Qa(e,n,{showClose:t}):pr({config:e,showClose:t}),i=Y("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"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:u}=kS(e,i),{host:c,title:p,subtitle:m}=d,y=d.starterSuggestions,h=I("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),S=Dg("followUp"),A=Kr(e,!1);A&&(h.style.maxWidth=A,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),i.append(c,u,h,S);let T=Ks({config:e}),k=e?.layout?.showFooter!==!1;r?js(o,a,e):(a.header.style.display="none",js(o,a,e)),o.append(i);let P=Y("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 k||(T.footer.style.display="none"),o.append(T.footer),o.append(P),{container:o,body:i,messagesWrapper:h,starterSuggestions:y,transcriptSuggestions:S,composerOverlay:P,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:c,welcomeIconHolder:d.iconHolder,greetingHost:u,introKicker:d.kicker,introTitle:p,introSubtitle:m,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode}};var _g=(e,t)=>{let o=I("button");o.type="button",o.innerHTML=`
23
+ `),d=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(d){let u=[];a&&u.push(an(a)),u.push(...r.contentParts),u.push(...t.contentParts),t.contentParts=u}else if(c){let u=[];i&&u.push(an(i)),u.push(...r.contentParts),t.contentParts=u}else a&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,o){let n=t.trim(),r=!!o?.replayFields&&(o.replayFields.llmContent!==void 0||o.replayFields.rawContent!==void 0||(o.replayFields.contextMentions?.length??0)>0);if(!n&&(!o?.contentParts||o.contentParts.length===0)&&(!o?.mentions||o.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 a=La(),i=Fr();this.activeAssistantMessageId=null;let d=o?.contentParts&&Oa(o.contentParts)?Ba:"",c={id:a,role:"user",content:n||d,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:o?.viaVoice||!1,...o?.contentParts&&o.contentParts.length>0&&{contentParts:o.contentParts},...o?.mentions&&o.mentions.refs.length>0&&{contextMentions:o.mentions.refs},...o?.contentSegments&&o.contentSegments.length>0&&{contentSegments:o.contentSegments},...o?.composerOptions&&{composerOptions:o.composerOptions},...o?.replayFields??{}};this.appendMessage(c),this.setStreaming(!0);let u=new AbortController;if(this.abortController=u,o?.mentions){let m=this.messages.find(h=>h.id===a)??c;if(await this.applyMentionBundle(m,n,o.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(o?.quote&&!o.replayFields){let m=this.messages.find(y=>y.id===a)??c,h=xx({quote:o.quote,text:m.llmContent??m.content,contentParts:m.contentParts});h.contentParts&&(m.contentParts=h.contentParts),h.llmContent!==void 0&&(m.llmContent=h.llmContent),(h.contentParts||h.llmContent!==void 0)&&(m.quote={...o.quote},this.callbacks.onMessagesChanged([...this.messages]))}let p=[...this.messages];try{await this.dispatchWithDeletedRecovery(p,u,i,a,{composerOptions:o?.composerOptions,interrupt:o?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let h=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!h){let y=tm(m,this.config.errorMessage);if(y){let x={id:i,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(x)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(t,o){let n=Cx(this.messages,t);if(!n)return!1;let r=this.messages[n.start],a=o.replacement,i=a?a.text:r.content,d=a?a.contentParts:r.contentParts;if(!(!!i?.trim()||(d?.length??0)>0||!a&&(r.llmContent?.trim()?.length??0)>0))return!1;let u=a?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}},p=a?this.toComposerOptionsPayload(a.options):r.composerOptions,m=a?a.contentSegments:r.contentSegments,h=a?a.options?.quote:void 0,y=a?a.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(i??"",{...d?.length?{contentParts:[...d]}:{},...m?.length?{contentSegments:[...m]}:{},...p?{composerOptions:p}:{},...h?{quote:h}:{},...u&&Object.keys(u).length>0?{replayFields:u}:{},viaVoice:y===!0}),!0}toComposerOptionsPayload(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o: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 t=Fr();this.activeAssistantMessageId=null,this.setStreaming(!0);let o=new AbortController;this.abortController=o;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:o.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let a=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!a){let i=tm(r,this.config.errorMessage);if(i){let d={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.nextSequence()};this.appendMessage(d)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,a||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,o){if(this.streaming&&!o?.allowReentry)return;o?.allowReentry||this.abortController?.abort(),o?.preserveAssistantId&&o.assistantMessageId&&(this.activeAssistantMessageId=o.assistantMessageId);let n=o?.preserveAssistantId?o.assistantMessageId:void 0,r=!1;for(let a of this.messages)a.streaming&&a.id!==n&&(a.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,o?.assistantMessageId,o?.seedContent)}catch(a){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(a instanceof Error?a:new Error(String(a)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(o=>this.requestWebMcpApproval(o))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let o={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},n=`approval-${o.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o}),new Promise(r=>{this.webMcpApprovalResolvers.set(n,r)})}resolveWebMcpApproval(t,o){let n=this.webMcpApprovalResolvers.get(t);if(!n)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(a=>a.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:o,resolvedAt:Date.now()}}),n(o==="approved")}async resolveApproval(t,o,n){let r=`approval-${t.id}`,a={...t,status:o,resolvedAt:Date.now()},i=this.messages.find(p=>p.id===r),d={id:r,role:"assistant",content:"",createdAt:i?.createdAt??new Date().toISOString(),...i?.sequence!==void 0?{sequence:i.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(d),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,u=c&&typeof c=="object"?c.onDecision:void 0;try{let p;if(u?p=await u({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},o,n):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},o),p){let m=null;if(p instanceof Response){if(!p.ok){let h=await p.json().catch(()=>null);throw new Error(h?.error??`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);m?await this.connectStream(m,{allowReentry:!0}):(o==="denied"&&this.appendMessage({id:`denial-${t.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(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:o.answers,askUserQuestionIndex:o.currentIndex}})}markAskUserQuestionResolved(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...o?{askUserQuestionAnswers:o}:{}}})}async resolveAskUserQuestion(t,o){if(this.messages.find(p=>p.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,a=t.toolCall?.name;if(!r||!a){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof o=="string"?void 0:o;if(i===void 0&&typeof o=="string"){let p=t.toolCall?.args,m=Array.isArray(p?.questions)?p.questions:[];if(m.length===1){let h=typeof m[0]?.question=="string"?m[0].question:"";h&&(i={[h]:o})}}this.markAskUserQuestionResolved(t,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=t.toolCall.id,c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===0){let p=typeof o=="string"?o:Object.entries(o).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | ");this.appendMessage({id:`ask-user-answer-${d}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let p=i??{};u.forEach((m,h)=>{let y=typeof m?.question=="string"?m.question:"";if(!y)return;let x=p[y],T=Array.isArray(x)?x.join(", "):typeof x=="string"?x:"";this.appendMessage({id:`ask-user-q-${d}-${h}`,role:"assistant",content:y,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${d}-${h}`,role:"user",content:T||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let p=await this.client.resumeFlow(r,{[a]:o},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!p.ok){let m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}p.body?await this.connectStream(p.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}enqueueWebMcpAwait(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.id;if(!o||!n){let a=this.webMcpEpoch;queueMicrotask(()=>{a===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(o);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(o,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let o of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(o)})}flushWebMcpAwaitBatch(t){let o=this.webMcpAwaitBatches.get(t);if(!o)return;this.webMcpAwaitBatches.delete(t);let{snapshots:n}=o;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(t,n)}resolveWebMcpToolStartedAt(t){let n=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of n)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Fn?!1:(this.messages.find(n=>n.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let o=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:o,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),o}markWebMcpToolComplete(t,o,n,r=Date.now(),a){this.messages.some(i=>i.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:o,startedAt:n,completedAt:r,duration:void 0,durationMs:Math.max(0,r-n)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,o){let n=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let a=async c=>{let u=c.toolCall?.name,p=c.toolCall?.id;if(!u||!p)return null;let m=`${t}:${p}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(c))return null;this.webMcpInflightKeys.add(m),n.push(m);let h=this.markWebMcpToolRunning(c),y=c.agentMetadata?.webMcpToolCallId??u;if(u===Fn)return{dedupeKey:m,resumeKey:y,output:Gv(),toolMessage:c,startedAt:h,completedAt:Date.now()};let x=this.client.executeWebMcpToolCall(u,c.toolCall?.args,r.signal),T;if(!x)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await x}catch(w){let k=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));return k||this.callbacks.onError?.(w instanceof Error?w:new Error(String(w))),this.markWebMcpToolComplete(c,om(k?"Aborted by cancel()":RE(w)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(c,om("Aborted by cancel()"),h),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:y,output:T,toolMessage:c,startedAt:h,completedAt:Date.now()}},i;if(this.config.webmcp?.execution==="sequential"){i=[];for(let c of o)i.push(await a(c))}else i=await Promise.all(o.map(a));let d=[];try{if(d=i.filter(p=>p!==null),d.length===0)return;let c={};for(let p of d)c[p.resumeKey]=p.output;let u=await this.client.resumeFlow(t,c,{signal:r.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!u.ok){let p=await u.json().catch(()=>null);throw new Error(p?.error??`Resume failed: ${u.status}`)}for(let p of d)this.webMcpResolvedKeys.add(p.dedupeKey),this.markWebMcpToolComplete(p.toolMessage,p.output,p.startedAt,p.completedAt,p.toolMessage.toolCall?.name===Fn?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.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 p of d)this.markWebMcpToolComplete(p.toolMessage,om("Aborted by cancel()"),p.startedAt)}finally{for(let c of n)this.webMcpInflightKeys.delete(c);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.name,r=t.toolCall?.id;if(!o){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!n)return;if(!r){let i=`${o}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(i)||this.webMcpResolvedKeys.has(i))return;this.webMcpInflightKeys.add(i);try{await this.resumeWithToolOutput(o,n,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(i)}catch(d){this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}finally{this.webMcpInflightKeys.delete(i)}return}let a=`${o}:${r}`;if(!(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t)))return this.resolveWebMcpToolCallBatch(o,[t])}async resumeWithToolOutput(t,o,n,r){let a=await this.client.resumeFlow(t,{[o]:n},{signal:r?.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!a.ok){let i=await a.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${a.status}`)}r?.onHttpOk?.(),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"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(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let o=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=t.artifactType==="markdown"?{id:o,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:o,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(o,n),this.selectedArtifactId=o,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(n),n}injectArtifactRefBlock(t){let o=`artifact-ref-${t.id}`,n=Nn(this.config.features?.artifacts,t),r=tl(n,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),a=this.messages.find(i=>i.id===o);if(a){a.rawContent=r,a.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:o,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let o of this.artifacts.values()){let n=this.messages.find(i=>i.id===`artifact-ref-${o.id}`);if(!n)continue;let r=Nn(this.config.features?.artifacts,o),a=tl(r,{artifactId:o.id,title:o.title,artifactType:o.artifactType,status:o.status,...o.file?{file:o.file}:{},...o.presentation?{presentation:o.presentation}:{},...o.component?{component:o.component}:{},...o.props?{componentProps:o.props}:{},...o.markdown!==void 0?{markdown:o.markdown}:{}});n.rawContent!==a&&(n.rawContent=a,n.streaming=o.status==="streaming",t=!0)}t&&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(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);o?.artifactType==="markdown"&&(o.markdown=(o.markdown??"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);o?.artifactType==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>({...o,streaming:!1,sequence:o.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,o=null){this.artifacts.clear();for(let n of t)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=o,this.emitArtifactsState()}trackCursor(t){let o=this.agentExecution?.executionId;if(!o||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let n=this.resumable===null;this.resumable={executionId:o,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(n)}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(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.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(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=kx().then(({createReconnectController:t})=>{let o=t(this.buildReconnectHost());return this.reconnectController=o,o}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:o=>t.setStatus(o),setStreaming:o=>t.setStreaming(o),setReconnecting:o=>{t.reconnecting=o},setAbortController:o=>{t.abortController=o},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(o,n,r)=>t.connectStream(o,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:o=>t.appendMessage(o),nextSequence:()=>t.nextSequence(),emitReconnect:o=>t.callbacks.onReconnect?.(o),buildErrorContent:o=>tm(new Error(o),t.config.errorMessage),onError:o=>t.callbacks.onError?.(o)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let o=this.reopenTrailingAssistant();o||(o=Fr(),this.appendMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=o,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:o,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let o=this.messages[t];if(o.role==="assistant"&&!o.variant)return o.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),o.id;if(o.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let o=this.config.onExecutionState;if(o){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),o(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let o=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),o&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let n=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=Jf(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return cl(t)}toggleReadAloud(t){let o=this.messages.find(a=>a.id===t);if(!o||o.role!=="assistant")return;let n=Jf(o.content||"");if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let o=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let o=this.ensureSequence(t),n=this.messages.findIndex(r=>r.id===o.id);if(n===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,a)=>{if(a!==n)return r;let i={...r,...o};if(r.agentMetadata?.askUserQuestionAnswered===!0&&o.agentMetadata&&(i.agentMetadata={...o.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&o.agentMetadata&&(i.agentMetadata={...i.agentMetadata??o.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&o.approval&&r.approval.id===o.approval.id){let p=r.approval,m=o.approval;i.approval={...p,...m,executionId:m.executionId||p.executionId,toolName:m.toolName||p.toolName,description:m.description||p.description,toolType:m.toolType??p.toolType,reason:m.reason??p.reason,parameters:m.parameters??p.parameters}}let d=o.toolCall?.name,c=o.agentMetadata?.executionId,u=o.toolCall?.id;if(d&&Lx(d)&&c&&u&&o.agentMetadata?.awaitingLocalTool===!0){let p=`${c}:${u}`,m=this.webMcpInflightKeys.has(p),h=this.webMcpResolvedKeys.has(p),y=r.toolCall?.name,x=r.agentMetadata?.executionId===c&&r.toolCall?.id===u&&y!==void 0&&Lx(y)&&r.toolCall?.status==="complete";(m||h||x)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((o,n)=>{let r=new Date(o.createdAt).getTime(),a=new Date(n.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(a)&&r!==a)return r-a;let i=o.sequence??0,d=n.sequence??0;return i!==d?i-d:o.id.localeCompare(n.id)})}};var Na=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var nm=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var rm=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var ul=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var sm=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var am=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var im=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var lm=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Fa=[["path",{d:"M20 6 9 17l-5-5"}]];var pl=[["path",{d:"m6 9 6 6 6-6"}]];var dm=[["path",{d:"m15 18-6-6 6-6"}]];var cm=[["path",{d:"m9 18 6-6-6-6"}]];var _s=[["path",{d:"m18 15-6-6-6 6"}]];var um=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var pm=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var Rc=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Ua=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var fm=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Hc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Wc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var mm=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var gm=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var fl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var ml=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Ns=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var gl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var hm=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var ym=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Bc=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var bm=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var vm=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var xm=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var hl=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var Cm=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Sm=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var wm=[["path",{d:"M5 12h14"}]];var Oc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M9 3v18"}]];var Am=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Mm=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var Tm=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Em=[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}]];var Pm=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var km=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Lm=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Im=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Rm=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var Dc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Hm=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Wm=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Bm=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Om=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var Dm=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var _m=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Nm=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Fm=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var yl=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Ft=(e,t=24,o="currentColor",n=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(n)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let i=a[0],d=a[1];if(!d)return;let c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(d).forEach(([u,p])=>{u!=="stroke"&&c.setAttribute(u,String(p))}),r.appendChild(c)}),r};var{setLoader:HE,load:WE}=mt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),Ix=HE,_c=WE;var BE={activity:Na,"arrow-down":nm,"arrow-up":am,"arrow-up-right":sm,bot:lm,"chevron-down":pl,"chevron-up":_s,"chevron-right":cm,"chevron-left":dm,check:Fa,clipboard:pm,"clipboard-copy":um,"code-xml":Rc,copy:Ua,file:gl,"file-code":fl,"file-spreadsheet":ml,"file-text":Ns,"image-plus":ym,loader:bm,"loader-circle":Bc,mic:Cm,paperclip:Am,quote:Em,"refresh-cw":Pm,search:km,send:Lm,"shield-alert":Im,"shield-check":Rm,"shield-x":Dc,square:Hm,"thumbs-down":Bm,"thumbs-up":Om,upload:Nm,"volume-2":Fm,x:yl,"at-sign":im,"arrow-left":rm,"arrow-right":ul,"external-link":mm,ellipsis:Wc,"ellipsis-vertical":Hc,menu:xm,"panel-left":Oc,plus:Tm,minus:wm,pencil:Mm,trash:_m,"trash-2":Dm,download:fm,maximize:vm,minimize:Sm,"message-square":hl,star:Wm,eye:gm,history:hm},OE=["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"],bl=new Map(Object.entries(BE)),qa=new Set,Nc=!1,Fc=new Set,Rx=e=>{let t=[...Fc];e&&Fc.clear();for(let o of t)try{o()}catch{}},Hx=e=>Nc?()=>{}:(Fc.add(e),()=>{Fc.delete(e)}),Wx=()=>{let e=0;for(let t of[...qa]){let o=bl.get(t.name);if(!o)continue;qa.delete(t),e++;let n=Ft(o,t.size,t.color,t.strokeWidth);if(n)for(t.el.removeAttribute("data-persona-icon-pending");n.firstChild;)t.el.appendChild(n.firstChild)}return e},Bx=e=>{for(let[t,o]of Object.entries(e))bl.set(t,o);Wx()>0&&!Nc&&Rx(!1)};var Um=!1,DE=()=>{_c().then(e=>{if(!Nc){for(let[t,o]of Object.entries(e.EXTRA_LUCIDE_ICONS))bl.has(t)||bl.set(t,o);Nc=!0,Wx(),Rx(!0)}}).catch(e=>{Um=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},_E=(e,t,o)=>{let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",t),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("data-persona-icon-pending","true"),n},ce=(e,t=24,o="currentColor",n=2)=>{let r=bl.get(e);if(r)return Ft(r,t,o,n);if(OE.includes(e)){Um&&(Um=!1);let a=_E(t,o,n);if(qa.size>=500){let i=qa.values().next().value;i&&qa.delete(i)}return qa.add({el:a,name:e,size:t,color:o,strokeWidth:n}),DE(),a}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null};var NE={add:e=>sx(e)},FE=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Uc={allowedTypes:fr,maxFileSize:10*1024*1024,maxFiles:4};function UE(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function qE(e){return e==="application/pdf"?Ns:e.startsWith("text/")?Ns:e.includes("word")?Ns:e.includes("excel")||e.includes("spreadsheet")?ml:e==="application/json"?fl:gl}var Fs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??Uc.allowedTypes,maxFileSize:t.maxFileSize??Uc.maxFileSize,maxFiles:t.maxFiles??Uc.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:NE}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let o of this.attachments)this.renderPreview(o)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Uc.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.destroyed)return;let o=[];for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let r=ax(n,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,i);continue}let a={id:UE(),file:n,previewUrl:kc(n)?URL.createObjectURL(n):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(a),this.renderPreview(a),o.push(a)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(o.map(n=>this.runAdd(n)))}async runAdd(t){let o=new AbortController;this.pendingAdds.set(t.id,o);let n=()=>this.destroyed||o.signal.aborted||this.pendingAdds.get(t.id)!==o||!this.attachments.includes(t);try{let r=await this.adapter().add(t.file,{signal:o.signal,onProgress:a=>{n()||t.status!=="uploading"||(t.progress=FE(a),this.updatePreview(t),this.notify())}});if(n())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(n())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(t.id)===o&&this.pendingAdds.delete(t.id)}this.updatePreview(t),this.notify()}retryAttachment(t){let o=this.attachments.find(n=>n.id===t);!o||o.status!=="error"||this.destroyed||(o.status=this.hasCustomAdapter()?"uploading":"processing",o.progress=this.hasCustomAdapter()?0:void 0,o.error=void 0,this.updatePreview(o),this.notify(),this.runAdd(o))}abortAdd(t){let o=this.pendingAdds.get(t);o&&(this.pendingAdds.delete(t),o.abort())}removeAttachment(t){let o=this.attachments.findIndex(a=>a.id===t);if(o===-1)return;let n=this.attachments[o];this.abortAdd(t),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(o,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),n.status==="ready"&&n.contentPart&&this.releasePart(n.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(t){let o=this.config.adapter?.remove;if(o)try{let n=o(t,{signal:new AbortController().signal});n&&typeof n.catch=="function"&&n.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(n){console.error("[AttachmentManager] adapter.remove failed:",n)}}clearAttachments(){for(let t of this.attachments)this.abortAdd(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let t of this.pendingAdds.values())t.abort();this.pendingAdds.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let o=kc(t.file),n=I("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",t.id),n.style.width="48px",n.style.height="48px",o&&t.previewUrl){let p=I("img");p.src=t.previewUrl,p.alt=t.file.name,p.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",p.style.width="48px",p.style.height="48px",p.style.objectFit="cover",p.style.borderRadius="8px",n.appendChild(p)}else{let p=I("div");p.style.width="48px",p.style.height="48px",p.style.borderRadius="8px",p.style.backgroundColor="var(--persona-container, #f3f4f6)",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.display="flex",p.style.flexDirection="column",p.style.alignItems="center",p.style.justifyContent="center",p.style.gap="2px",p.style.overflow="hidden";let m=qE(t.file.type),h=Ft(m,20,"var(--persona-muted, #6b7280)",1.5);h&&p.appendChild(h);let y=I("span");y.textContent=ix(t.file.type,t.file.name),y.style.fontSize="8px",y.style.fontWeight="600",y.style.color="var(--persona-muted, #6b7280)",y.style.textTransform="uppercase",y.style.lineHeight="1",p.appendChild(y),n.appendChild(p)}let r=Y("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),a=I("div","persona-attachment-progress");a.appendChild(I("div","persona-attachment-progress__bar"));let i=Y("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),d=ce("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);d?i.appendChild(d):i.textContent="\u21BB",i.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.retryAttachment(t.id)}),r.append(a,i),n.appendChild(r);let c=I("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 u=Ft(yl,10,"var(--persona-text-inverse, #ffffff)",2);u?c.appendChild(u):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.removeAttachment(t.id)}),n.appendChild(c),this.previewsContainer.appendChild(n),this.applyPreviewState(n,t)}updatePreview(t){let o=this.previewsContainer?.querySelector(`[data-attachment-id="${t.id}"]`);o&&this.applyPreviewState(o,t)}applyPreviewState(t,o){t.dataset.status=o.status;let n=o.status!=="ready"&&o.status!=="error";t.setAttribute("aria-busy",n?"true":"false"),t.title=o.status==="error"?`${o.file.name}: ${o.error??"Upload failed"}`:o.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let a=o.progress;r.style.width=typeof a=="number"?`${Math.round(a*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,o){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:o,adapter:t?.adapter})}};var Ox=(e,t)=>e.length===t.length&&e.every((o,n)=>o===t[n]),$E=(e,t)=>e.length===t.length&&e.every((o,n)=>{let r=t[n];return o.id===r.id&&o.name===r.name&&o.mimeType===r.mimeType&&o.size===r.size&&o.status===r.status&&o.progress===r.progress&&o.error===r.error});function Dx(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,o=null,n=!1,r=!1,a=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",i=()=>{let p=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:p,inputDisabled:e.inputDisabled,sendDisabled:p!=="idle"||e.sendDisabled||e.inputDisabled})},d=()=>(o||(o=i()),o),c=()=>{if(n=!1,r||t.size===0)return;let p=d();for(let m of[...t])try{m(p)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},u=()=>{o=null,!(r||n)&&(n=!0,queueMicrotask(c))};return{getState:d,subscribe:p=>(t.add(p),()=>t.delete(p)),setText:p=>{e.text!==p&&(e.text=p,u())},setAttachments:p=>{$E(e.attachments,p)||(e.attachments=[...p],u())},setMentionRefs:p=>{Ox(e.mentionRefs,p)||(e.mentionRefs=[...p],u())},setSelectedModelId:p=>{e.selectedModelId!==p&&(e.selectedModelId=p,u())},setActiveModeIds:p=>{Ox(e.activeModeIds,p)||(e.activeModeIds=[...p],u())},setQuote:p=>{let m=e.quote;m?.text===p?.text&&m?.messageId===p?.messageId&&m?.sourceLabel===p?.sourceLabel||(e.quote=p?{...p}:void 0,u())},setPendingSubmission:p=>{e.pendingSubmission!==p&&(e.pendingSubmission=p,u())},setPreparing:p=>{e.preparing!==p&&(e.preparing=p,u())},setStreaming:p=>{e.streaming!==p&&(e.streaming=p,u())},setInputDisabled:p=>{e.inputDisabled!==p&&(e.inputDisabled=p,u())},setSendDisabled:p=>{e.sendDisabled!==p&&(e.sendDisabled=p,u())},flush:()=>{n&&c()},destroy:()=>{r=!0,n=!1,t.clear()}}}var Ho=(e,...t)=>{for(let o of t){let n=e.querySelector(o);if(n)return n}return null},_x=(e,t)=>{let o=I("div",e);return o.setAttribute(t,""),o.setAttribute("data-persona-composer-synthesized",""),o.style.display="contents",o};function Nx(e,t={}){let o=Ho(e,"[data-persona-composer-form]"),n=Ho(e,"[data-persona-composer-input]");if(!o||!n){let k=`[Persona] composer surface is missing required element(s): ${[!o&&"form",!n&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(o||n))throw new Error(k);return typeof console<"u"&&console.warn(k),null}let r={header:Ho(e,"[data-persona-composer-header]"),body:Ho(e,"[data-persona-composer-body]"),actionsStart:Ho(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Ho(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Ho(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Ho(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Ho(e,"[data-persona-composer-status]")},a=new Set,i=r.header;i||(a.add("header"),i=_x("persona-widget-composer__header","data-persona-composer-header"),o.parentNode?o.parentNode.insertBefore(i,o):e.appendChild(i));let d=r.body??n.parentElement??o,c=(w,k,P,R,b)=>{if(k)return k;a.add(w);let A=_x(P,R);return b.appendChild(A),A},u=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",o),p=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",o),m=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),h=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),y=[],x=(w,k)=>w.target===k.target&&w.type===k.type&&w.handler===k.handler,T=Ho(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:o,input:n,header:i,body:d,actionsStart:u,actionsEnd:p,suggestions:m,status:h,attachmentInput:T,attachmentPreviews:Ho(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Ho(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Ho(e,"[data-persona-composer-submit]")??void 0,micButton:Ho(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:r,addListener:(w,k,P,R)=>{w.addEventListener(k,P,R),y.push({target:w,type:k,handler:P,options:R})},removeListener:(w,k,P,R)=>{w.removeEventListener(k,P,R),y=y.filter(b=>!x(b,{target:w,type:k,handler:P}))},destroy:()=>{for(let w of y)w.target.removeEventListener(w.type,w.handler,w.options);y=[]}}}var Ut={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},so=1e5,$a=so+1;var VE=8,jE=8,qm=10,Fx=200,Ux=300,qx=0,$c=e=>Math.max(0,e);function $x(e){e.delayMs!==void 0&&(Fx=$c(e.delayMs)),e.skipDelayMs!==void 0&&(Ux=$c(e.skipDelayMs))}var zE=()=>Date.now()<qx,KE=e=>{qx=e>0?Date.now()+e:0},qc=new WeakMap,Vm="data-persona-tooltip-suppressed",GE=e=>typeof e.closest=="function"&&e.closest(`[${Vm}]`)!==null;function Vx(e){qc.get(e)?.hide()}var jx=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,XE=e=>{let t=e.getRootNode?.();return jx(t)?t:e.ownerDocument.body},$m=(e,t,o)=>Math.min(Math.max(e,t),Math.max(t,o)),QE=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"];function eo(e){qc.get(e.anchor)?.destroy();let{anchor:t,trigger:o=t,text:n,hint:r,enabled:a=!0,gap:i=VE,viewportPadding:d=jE}=e,c=()=>t.ownerDocument,u=()=>c().defaultView??window,p=null,m=null,h=null,y=null,x,T=!1,w=!1,k=!1,P=()=>(typeof n=="function"?n():n).trim(),R=()=>(typeof r=="function"?r():r??"").trim(),b=()=>$c(e.delayMs??Fx),A=()=>$c(e.skipDelayMs??Ux),C=()=>{x!==void 0&&(u().clearTimeout(x),x=void 0)},L=()=>{C();let Ce=p!==null;y?.(),y=null,p?.remove(),p=null,m=null,h=null,Ce&&KE(A())},F=()=>{if(!p)return;let Ce=c(),Ee=u(),ge=t.getBoundingClientRect(),Ke=p.getBoundingClientRect(),Bt=Ce.documentElement.clientWidth||Ee.innerWidth,Le=Ce.documentElement.clientHeight||Ee.innerHeight,j=Bt-d-Ke.width,qe=ge.left+ge.width/2-Ke.width/2,Ge=$m(qe,d,j),Ae=ge.top-d,De=Le-d-ge.bottom,he=Ke.height+i,gt=Ae>=he||Ae>=De?"top":"bottom",dn=gt==="top"?ge.top-i-Ke.height:ge.bottom+i,Js=Le-d-Ke.height,oo=$m(dn,d,Js),Xo=ge.left+ge.width/2,Sn=Math.max(qm,Ke.width-qm),Rt=$m(Xo-Ge,qm,Sn);p.dataset.placement=gt,p.style.left=`${Ge}px`,p.style.top=`${oo}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${Rt}px`)},X=()=>{if(k||!a||p||!t.isConnected||GE(t))return;let Ce=P(),Ee=XE(t);if(!Ce||!Ee)return;let ge=c(),Ke=u();p=ge.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String($a);let Bt=Ke.getComputedStyle?.(t);if(Bt){for(let he of QE){let gt=Bt.getPropertyValue(he).trim();gt&&p.style.setProperty(he,gt)}Bt.fontFamily&&(p.style.fontFamily=Bt.fontFamily)}m=ge.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=Ce,p.appendChild(m);let Le=R();Le&&(h=ge.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=Le,p.appendChild(h));let j=ge.createElement("span");j.className="persona-control-tooltip__arrow",p.appendChild(j),Ee.appendChild(p),F(),p.dataset.state="open";let qe=()=>{if(!t.isConnected){L();return}m&&(m.textContent=P()),h&&(h.textContent=R()),F()};Ke.addEventListener("scroll",qe,!0),Ke.addEventListener("resize",qe);let Ge=t.getRootNode(),Ae=jx(Ge)?Ge:ge.documentElement,De=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||L()});De?.observe(Ae,{childList:!0,subtree:!0}),y=()=>{Ke.removeEventListener("scroll",qe,!0),Ke.removeEventListener("resize",qe),De?.disconnect()}},G=Ce=>{if(!(k||p)){if(C(),Ce||b()<=0||zE()){X();return}x=u().setTimeout(()=>{x=void 0,X()},b())}},E=()=>{T||w?G(w):L()},O=()=>{let Ce=u();(!Ce.matchMedia||!Ce.matchMedia("(hover: none)").matches)&&(T=!0,E())},D=()=>{T=!1,E()},W=()=>{try{w=t.matches(":focus-visible")}catch{w=!0}E()},te=()=>{w=!1,E()},Q=()=>{T=!1,w=!1,L()},de=Ce=>{Ce.key==="Escape"&&Q()};o.addEventListener("mouseenter",O),o.addEventListener("mouseleave",D),t.addEventListener("focus",W),t.addEventListener("blur",te),t.addEventListener("keydown",de),t.addEventListener("click",Q);let pe={get isOpen(){return p!==null},show:X,hide:L,reposition:F,destroy:()=>{k||(k=!0,L(),o.removeEventListener("mouseenter",O),o.removeEventListener("mouseleave",D),t.removeEventListener("focus",W),t.removeEventListener("blur",te),t.removeEventListener("keydown",de),t.removeEventListener("click",Q),qc.delete(t))}};return qc.set(t,pe),pe}var zx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Va(e,t){if(!e)return t;if(!t)return e;let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];zx(a)&&zx(r)?o[n]=Va(a,r):o[n]=r}return o}var zo="min(440px, calc(100vw - 24px))",Vc="440px",jm="How can I help...",YE={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:zo,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)"},rt={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:YE,copy:{inputPlaceholder:jm,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 Kx(e,t){if(!(!e&&!t))return e?t?Va(e,t):e:t}function ja(e){return e?{...rt,...e,theme:Kx(rt.theme,e.theme),darkTheme:Kx(rt.darkTheme,e.darkTheme),launcher:{...rt.launcher,...e.launcher,dock:{...rt.launcher?.dock,...e.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...rt.tooltip,...e.tooltip},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=rt.features?.artifacts,o=e.features?.artifacts,n=rt.features?.scrollToBottom,r=e.features?.scrollToBottom,a=rt.features?.scrollBehavior,i=e.features?.scrollBehavior,d=rt.features?.streamAnimation,c=e.features?.streamAnimation,u=rt.features?.askUserQuestion,p=e.features?.askUserQuestion,m=rt.features?.history,h=e.features?.history,y=t===void 0&&o===void 0?void 0:{...t,...o,layout:{...t?.layout,...o?.layout}},x=n===void 0&&r===void 0?void 0:{...n,...r},T=a===void 0&&i===void 0?void 0:{...a,...i},w=d===void 0&&c===void 0?void 0:{...d,...c},k=u===void 0&&p===void 0?void 0:{...u,...p,styles:{...u?.styles,...p?.styles}},P=m===void 0&&h===void 0?void 0:{...m,...h,copy:{...m?.copy,...h?.copy}};return{...rt.features,...e.features,...x!==void 0?{scrollToBottom:x}:{},...T!==void 0?{scrollBehavior:T}:{},...y!==void 0?{artifacts:y}:{},...w!==void 0?{streamAnimation:w}:{},...k!==void 0?{askUserQuestion:k}:{},...P!==void 0?{history:P}:{}}})(),suggestionChips:e.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...rt.layout?.header,...e.layout?.header},messages:{...rt.layout?.messages,...e.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...e.layout?.slots}},markdown:{...rt.markdown,...e.markdown,options:{...rt.markdown?.options,...e.markdown?.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}function zm(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let o=t.getComputedStyle(e).lineHeight;if(!o||!o.trim().endsWith("px"))return 20;let n=parseFloat(o);return Number.isFinite(n)&&n>0?n:20}function jc(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function Gx(e,t){e.style.maxHeight=`${t*zm(e)}px`,e.style.overflowY="auto"}function Cl(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function Xx(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Qx(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let o=e.metaKey===!0||e.ctrlKey===!0,n=t.submitKey??"enter";return n==="none"?!1:n==="mod-enter"?o:o||!Xx(t)}function JE(e){return(e.submitKey??"enter")!=="enter"||Xx(e)?"enter":"send"}function zc(e,t){e.setAttribute("enterkeyhint",JE(t))}function Kc(e,t){let o=t?.autocomplete;e.setAttribute("autocomplete",typeof o=="string"&&o?o:"off");let n=(r,a)=>{a===void 0?e.removeAttribute(r):e.setAttribute(r,a)};n("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),n("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),n("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),n("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function Km(e){return e===!0?{disabled:!0}:!e||typeof e!="object"?{disabled:!1}:{disabled:!0,reason:typeof e.reason=="string"&&e.reason?e.reason:void 0}}var Ko="persona-composer-control",vn="persona-composer-control--glyph",Xm=40,vo=24,Gc=(e,t,o)=>{let n=e.ownerDocument?.defaultView;if(!n)return;let r=n.getComputedStyle(e);for(let a of o){let i=r.getPropertyValue(a).trim();i?t.style.setProperty(a,i):t.style.removeProperty(a)}},Xc=(e,t)=>{let o=I("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=e?.copy?.inputPlaceholder??jm,o.dir="auto",zc(o,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Cl(o)}),Kc(o,e?.composer?.inputAttributes),o.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",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=jc(e?.composer?.maxLines,t?.defaultMaxLines??3),r=`${n*20}px`;o.style.maxHeight=r,o.style.overflowY="auto";let a=()=>{let d=o.style.maxHeight;if(d!==r){let u=parseFloat(d);if(Number.isFinite(u)&&u>0)return u}let c=n*zm(o);return r=`${c}px`,o.style.maxHeight=r,c},i=()=>{o.addEventListener("input",()=>{o.style.height="auto";let d=Math.min(o.scrollHeight,a());o.style.height=`${d}px`})};return o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"}),{textarea:o,attachAutoResize:i}},eP="[data-persona-glyph-stack]",Qm=(e,t,o="send")=>{let n=Y("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":o,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),n.append(e,t),n},Qc=e=>{let t=e?.sendButton??{},o=t.useIcon??!1,n=t.iconText??"\u2191",r=t.iconName,a=t.stopIconName??"square",i=t.tooltipText??"Send message",d=t.stopTooltipText??"Stop generating",c=e?.copy?.sendButtonLabel??"Send",u=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,m=t.size,h=parseFloat(m??"")||Xm,y=t.backgroundColor,x=t.textColor,T=I("div","persona-send-button-wrapper"),w=Y("button",{className:bo("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",o?`persona-flex persona-items-center persona-justify-center ${Ko}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",o&&!y&&"persona-bg-persona-primary",!o&&!x&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:o?m:void 0,height:o?m:void 0,minWidth:o?m:void 0,minHeight:o?m:void 0,fontSize:o?"18px":void 0,lineHeight:o?"1":void 0,color:o?x||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":x||void 0,backgroundColor:o&&y||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:o?"0":t.paddingX||void 0,paddingRight:o?"0":t.paddingX||void 0,paddingTop:o?"0":t.paddingY||void 0,paddingBottom:o?"0":t.paddingY||void 0}}),k=null,P=null,R=null;if(o){let C=parseFloat(t.iconSize??"")||Math.round(h*.5),L=t.iconStrokeWidth??2,F=x?.trim()||"currentColor";r&&(k=ce(r,C,F,L)),P=ce(a,C,F,L),k&&P?(R=Qm(k,P),w.appendChild(R)):k?w.appendChild(k):(w.textContent=n,P=null)}else w.textContent=c;w.setAttribute("aria-label",i),T.appendChild(w),eo({anchor:w,trigger:T,text:()=>w.getAttribute("aria-label")??"",enabled:p});let b="send";return{button:w,wrapper:T,setMode:C=>{if(C===b)return;b=C;let L=C==="stop"?d:i;w.setAttribute("aria-label",L),w.setAttribute("data-persona-send-mode",C),o?(w.querySelector(eP)??R)?.setAttribute("data-mode",C):w.textContent=C==="stop"?u:c},glyphStack:R}},za=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let n=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",a=t.provider?.type==="custom";if(!(n||r||a))return null;let d=t.iconName??"mic",c=t.iconSize,u=parseFloat(c??"")||vo,p=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,h=I("div","persona-send-button-wrapper"),y=Y("button",{className:bo("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ko,!c&&vn),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),T=ce(d,u,m||"currentColor",1.5);T?y.appendChild(T):y.textContent="\u{1F3A4}",h.appendChild(y);let w=t.tooltipText??"Start voice recognition",k=t.showTooltip??!1;return eo({anchor:y,trigger:h,text:()=>y.getAttribute("aria-label")??w,enabled:k}),{button:y,wrapper:h}},Yc=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let o=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=I("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??fr).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",a=I("div","persona-send-button-wrapper"),i=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Ko} ${vn}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),d=ce(r,vo,"currentColor",1.5);d?i.appendChild(d):i.textContent="\u{1F4CE}",i.addEventListener("click",u=>{u.preventDefault(),n.click()}),a.appendChild(i);let c=t.buttonTooltipText??"Attach file";return eo({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:a,input:n,previewsContainer:o}},Jc=e=>{let t=e?.statusIndicator??{},o=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",n=I("div",`persona-mt-2 ${o} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let r=t.visible??!0;n.style.display=r?"":"none";let a=t.idleText??"Online";if(t.idleLink){let i=I("a");i.href=t.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=a,i.style.color="inherit",i.style.textDecoration="none",n.appendChild(i)}else n.textContent=a;return n},Zc=()=>Y("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function tP(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function eu(e){let{anchor:t,content:o,placement:n="bottom-start",offset:r=6,matchAnchorWidth:a=!1,horizontalOffset:i,verticalOffset:d,zIndex:c=2147483e3,onOpen:u,onDismiss:p}=e,m=e.container??tP(t),h=!1,y=null,x=()=>{if(!h)return;let k=t.getBoundingClientRect();o.style.position="fixed",a&&(o.style.minWidth=`${k.width}px`),i&&(o.style.maxWidth=`${k.width}px`);let P=o.getBoundingClientRect(),R=d?.()??null,b=R!=null?k.top+R:k.top,A=n==="top-start"||n==="top-end"?b-r-P.height:k.bottom+r,L=n==="bottom-end"||n==="top-end"?k.right-P.width:k.left,F=i?.()??null;if(F!=null){let X=Math.max(k.left,k.right-P.width);L=Math.min(Math.max(k.left+F,k.left),X)}o.style.top=`${A}px`,o.style.left=`${L}px`},T=()=>{h&&(h=!1,y&&(y(),y=null),o.remove())},w=()=>{if(h)return;h=!0,c!=null&&(o.style.zIndex=String(c)),m.appendChild(o),x();let k=(t.ownerDocument??document).defaultView??window,P=t.ownerDocument??document,R=()=>{if(!t.isConnected){T(),p?.("anchor-removed");return}x()},b=C=>{let L=typeof C.composedPath=="function"?C.composedPath():[];L.includes(o)||L.includes(t)||(T(),p?.("outside"))},A=k.setTimeout(()=>{P.addEventListener("pointerdown",b,!0)},0);k.addEventListener("scroll",R,!0),k.addEventListener("resize",R),y=()=>{k.clearTimeout(A),P.removeEventListener("pointerdown",b,!0),k.removeEventListener("scroll",R,!0),k.removeEventListener("resize",R)},u?.()};return{get isOpen(){return h},open:w,close:T,toggle:()=>h?T():w(),reposition:x,destroy:T}}var oP='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',nP=["--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"],Ym="data-persona-menu-focus",rP=new Set(["ArrowDown","ArrowUp","Home","End"]);function Yx(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(oP)??e}var sP=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function Jx(e){let t=e.label,o=!1,n=I("div","persona-send-button-wrapper"),r=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Ko} ${vn}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});n.appendChild(r);let a=Y("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let W=e.getButtonSize?.()??"";r.style.width=W,r.style.height=W,r.style.minWidth=W,r.style.minHeight=W,r.style.lineHeight="1",r.replaceChildren();let te=ce("plus",vo,"currentColor",1.5);te?r.appendChild(te):r.textContent="+"},d=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),a.setAttribute("aria-label",t)};d(),i();let c=[],u=-1,p=!1,m=()=>{let te=a.getRootNode().activeElement;return te instanceof HTMLElement?te:null},h=()=>{let W=m();for(let te of c){let Q=!!W&&Yx(te)===W;te.toggleAttribute(Ym,Q&&p)}},y=()=>c.filter(W=>W.isConnected||a.contains(W)).map(Yx).filter(W=>!sP(W)),x=(W,te)=>{W.forEach((Q,de)=>{Q.setAttribute("tabindex",de===te?"0":"-1")})},T=W=>{let te=y();if(te.length===0)return;let Q=(W%te.length+te.length)%te.length;u=Q,x(te,Q),te[Q].focus(),h()},w=()=>n.ownerDocument??document,k=null,P=null,R=null,b=()=>{k&&(w().removeEventListener("focusin",k,!0),k=null)},A=()=>{P&&(a.removeEventListener("focusin",P),P=null),R&&(a.removeEventListener("pointerdown",R,!0),R=null)},C=null,L=()=>(C||(C=eu({anchor:r,content:a,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),b()}})),C),F=()=>C?.isOpen===!0,X=(W=!1)=>{if(F()){C?.close(),r.setAttribute("aria-expanded","false"),b(),A(),u=-1,p=!1;for(let te of c)te.removeAttribute(Ym);W&&r.focus()}},G=(W=0,te=!1)=>{if(o||F())return;p=te,Gc(r,a,nP),L().open(),r.setAttribute("aria-expanded","true");let Q=y();x(Q,-1),T(W<0?Q.length-1:W),k=de=>{let pe=typeof de.composedPath=="function"?de.composedPath():[];pe.includes(a)||pe.includes(n)||X()},w().addEventListener("focusin",k,!0),P=()=>h(),a.addEventListener("focusin",P),R=()=>{p=!1},a.addEventListener("pointerdown",R,!0)},E=W=>{W.preventDefault(),W.stopPropagation(),F()?X(!0):G(0)},O=W=>{if(W.key==="ArrowDown"||W.key==="Enter"||W.key===" "){W.preventDefault(),p=!0,F()?T(0):G(0,!0);return}W.key==="ArrowUp"&&(W.preventDefault(),p=!0,F()?T(-1):G(-1,!0))},D=W=>{switch(rP.has(W.key)&&(p=!0),W.key){case"ArrowDown":W.preventDefault(),T(u+1);return;case"ArrowUp":W.preventDefault(),T(u-1);return;case"Home":W.preventDefault(),T(0);return;case"End":W.preventDefault(),T(y().length-1);return;case"Escape":W.preventDefault(),W.stopPropagation(),X(!0);return;case"Tab":X(!0);return;default:}};return r.addEventListener("click",E),r.addEventListener("keydown",O),a.addEventListener("keydown",D),{trigger:n,triggerButton:r,panel:a,setItems:W=>{for(let Q of c)W.includes(Q)||Q.removeAttribute(Ym);if(c=[...W],!F())return;let te=y();x(te,Math.min(u,te.length-1)),h()},isOpen:F,open:()=>G(0),close:X,setLabel:W=>{W!==t&&(t=W,d())},applyButtonSize:i,destroy:()=>{o=!0,b(),A(),r.removeEventListener("click",E),r.removeEventListener("keydown",O),a.removeEventListener("keydown",D),C?.destroy(),C=null,n.remove(),a.remove(),c=[]}}}var $n={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Zx="data-persona-composer-action",Jm="data-persona-composer-disable-when-streaming",aP="core:overflow",iP=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function lP(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let o=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(o))return o;let n=I("div");n.style.position="absolute",n.style.visibility="hidden",n.style.pointerEvents="none",n.style.height="0",n.style.width=e,t.appendChild(n);let r=n.getBoundingClientRect().width;return n.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(o)?o:null}function Zm(e){let t=e.clientWidth;if(!t)return 0;let o=e.ownerDocument?.defaultView;if(!o?.getComputedStyle)return t;let n=o.getComputedStyle(e),r=(Number.parseFloat(n.paddingLeft)||0)+(Number.parseFloat(n.paddingRight)||0);return Math.max(0,t-r)}var eC=(e,t)=>{!e||typeof console>"u"||console.warn(t)},dP=(e,t)=>t.includes(":")?t:`${e}:${t}`;function cP(e){let{debug:t}=e,o=[],n=new Map,r=0,a=d=>{let c=n.get(d.id);if(c){eC(t,`[Persona] composer action "${d.id}" is already contributed by ${tC(c)}; the ${tC(d)} copy is ignored.`);return}n.set(d.id,d),o.push(d)};for(let d of e.builtIns)a({id:d.id,placement:d.placement,presentation:"bar",order:d.order,sequence:r++,source:"core",builtIn:d});let i=(d,c,u)=>{let p=u?dP(u,d.id):d.id,m=d.order??$n.custom;d.placement==="end"&&m>=$n.send&&(eC(t,`[Persona] composer action "${p}" ordered at ${m} would render after send; clamped to ${$n.send-1}.`),m=$n.send-1),a({id:p,placement:d.placement,presentation:d.presentation??"bar",order:m,sequence:r++,source:c,pluginId:u,action:d})};for(let d of e.configActions??[])i(d,"config");for(let d of e.plugins){if(!d.contributeComposerActions)continue;let c;try{c=d.contributeComposerActions(e.contributionContext)}catch(u){typeof console<"u"&&console.error(`[Persona] plugin "${d.id}" contributeComposerActions failed:`,u);continue}for(let u of c??[])i(u,"plugin",d.id)}return o.sort((d,c)=>d.order===c.order?d.sequence-c.sequence:d.order-c.order)}var tC=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",oC=(e,t,o)=>e===void 0?o:typeof e=="function"?e(t)===!0:e===!0,uP=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function pP(e,t){if(!e||e==="always")return!0;let o=uP(t);return e==="when-text"?o:!o}var zr=e=>e.kind==="custom",eg=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,fP=e=>{let t=eg(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},mP='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function gP(e){let t="",o=n=>{if(n.nodeType===Node.TEXT_NODE){t+=n.nodeValue??"";return}if(n.nodeType!==Node.ELEMENT_NODE)return;let r=n;typeof r.matches=="function"&&r.matches(mP)||n.childNodes.forEach(o)};return o(e),t.trim()}var hP=e=>gP(e).length===0;function nC(e){let t=new Map,o=[],n=!1,r=()=>e.getButtonSize?.(),a=(E,O)=>{let D=E.button;if(!D)return;D.setAttribute("role","menuitem"),D.setAttribute("tabindex","-1"),D.className="persona-composer-overflow-menu__item";for(let Q of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])D.style[Q]="";D.style.lineHeight="1",O.tooltipText?D.setAttribute("title",O.tooltipText):D.removeAttribute("title"),D.replaceChildren();let W=I("span","persona-composer-overflow-menu__icon");if(O.iconName){let Q=ce(O.iconName,16,"currentColor",1.5);Q&&W.appendChild(Q)}let te=I("span","persona-composer-overflow-menu__label");te.textContent=O.shortLabel??O.label,D.append(W,te)},i=(E,O)=>{let D=E.button;if(!D)return;if(D.setAttribute("aria-label",O.label),O.pressed===void 0?D.removeAttribute("aria-pressed"):D.setAttribute("aria-pressed",O.pressed?"true":"false"),D.toggleAttribute(Jm,O.disableWhenStreaming===!0),E.mode==="menu"){E.tooltip?.destroy(),E.tooltip=void 0,a(E,O);return}D.removeAttribute("role"),D.removeAttribute("tabindex"),D.removeAttribute("title");let W=r(),te=!!O.shortLabel;if(D.className=bo("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Ko,vn,te&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),D.style.width=W&&!te?W:"",D.style.height=W??"",D.style.minWidth=W&&!te?W:"",D.style.minHeight=W??"",D.style.fontSize=te?"":"18px",D.style.lineHeight="1",D.style.color=O.iconColor??"",D.style.backgroundColor=O.backgroundColor??"",D.replaceChildren(),O.iconName){let Q=ce(O.iconName,vo,"currentColor",1.5);Q&&D.appendChild(Q)}if(te){let Q=I("span","persona-composer-action-button__label");Q.textContent=O.shortLabel,D.appendChild(Q)}else D.firstChild||(D.textContent=O.label);E.tooltip?.destroy(),E.tooltip=eo({anchor:D,trigger:E.element,text:()=>O.tooltipText??O.label,enabled:!!O.tooltipText})},d=(E,O)=>{let D=E.action,W=Y("button",{attrs:{type:"button"}}),te=W;if(O==="bar"){let pe=I("div","persona-send-button-wrapper");pe.appendChild(W),te=pe}te.setAttribute(Zx,E.id);let Q={resolved:E,element:te,button:W,owned:!0,managed:!0,busy:!1,visible:!0,mode:O},de=pe=>{if(pe.preventDefault(),pe.stopPropagation(),Q.busy||W.disabled)return;let Ce=Q.resolved.action;Q.mode==="menu"&&y?.close(!0);let Ee;try{Ee=Ce.onSelect(e.actionContext,pe)}catch(ge){e.reportError(ge,{actionId:Q.resolved.id});return}!Ee||typeof Ee.then!="function"||(Q.busy=!0,W.setAttribute("aria-busy","true"),Ee.catch(ge=>{e.reportError(ge,{actionId:Q.resolved.id})}).finally(()=>{Q.busy=!1,W.removeAttribute("aria-busy")}))};return W.addEventListener("click",de),Q.detach=()=>W.removeEventListener("click",de),i(Q,D),Q},c=E=>{let O=E.action,D;try{D=O.render({...e.actionContext,id:E.id,action:O})}catch(W){return e.reportError(W,{actionId:E.id}),null}return D?.element?(D.element.setAttribute(Zx,E.id),D.element.toggleAttribute(Jm,O.disableWhenStreaming===!0),{resolved:E,element:D.element,owned:!0,managed:!0,destroy:D.destroy,busy:!1,visible:!0,mode:"bar"}):null},u=(E,O)=>{if(E.builtIn){let W=E.builtIn.element;return W?{resolved:E,element:W,owned:!1,managed:E.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let D=E.action;return D?zr(D)?c(E):d(E,O):null},p=E=>{if(E.detach?.(),E.tooltip?.destroy(),E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0,E.owned){try{E.destroy?.()}catch(O){e.reportError(O,{actionId:E.resolved.id})}E.element.remove()}},m=(E,O)=>{for(let D=0;D<O.length;D++){let W=O[D];if(!W.managed)continue;let te=null;for(let Q=D+1;Q<O.length;Q++){let de=O[Q];if(!de.managed&&de.element.parentElement===E){te=de.element;break}}te?(W.element.parentElement!==E||W.element.nextSibling!==te)&&E.insertBefore(W.element,te):E.lastChild!==W.element&&E.appendChild(W.element)}},h=(E,O)=>{if(E.button){E.button.disabled=O;return}if(!E.owned)return;let D=E.element;D.toggleAttribute("data-disabled",O),D.setAttribute("aria-disabled",O?"true":"false");let W=D instanceof HTMLButtonElement||D instanceof HTMLSelectElement||D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement?D:D.querySelector("button, select, input, textarea");W&&(W.disabled=O)},y=null,x=null,T=null,w=0,k=()=>{let E=e.getOverflow?.();return E?.enabled===!0?E:void 0},P=()=>(y?y.setLabel(e.getOverflowLabel?.()??"More actions"):y=Jx({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),y),R=E=>{x!==E&&(T?.disconnect(),x=E,w=Zm(E),!(typeof ResizeObserver>"u")&&(T=new ResizeObserver(O=>{let W=O[O.length-1]?.contentRect?.width??Zm(E);W!==w&&(w=W,X())}),T.observe(E)))},b=(E,O)=>{let D=lP(E.collapseAutoActionsBelow,O);if(D===null)return!1;let W=w||Zm(O);return W>0&&W<D},A=(E,O,D)=>{if(!O)return"bar";if(E.resolved.builtIn){let te=iP(E.resolved.id);return te&&O.includeBuiltIns?.includes(te)?"menu":"bar"}let W=E.resolved.presentation;return W==="overflow"||W==="auto"&&D?"menu":"bar"},C=E=>{let O=E.menuSlot;if(!O)return;if(!hP(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let D=fP(E.element);if(!D){E.menuLabel?.remove(),E.menuLabel=void 0;return}E.menuLabel||(E.menuLabel=I("span","persona-composer-overflow-menu__label")),E.menuLabel.textContent!==D&&(E.menuLabel.textContent=D),E.menuLabel.parentElement!==O&&O.appendChild(E.menuLabel)},L=(E,O)=>{if(E.mode===O)return E;let D=E.resolved.action;if(D&&!zr(D)){p(E),t.delete(E.resolved.id);let W=d(E.resolved,O);return t.set(E.resolved.id,W),W}if(O==="menu"){let W=Y("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Vm]:""}});W.appendChild(E.element),Vx(eg(E.element)),E.menuSlot=W;let te=Q=>{let de=eg(E.element);if(de.disabled)return;let pe=Q.target===de||de.contains(Q.target);y?.close(!0),pe||de.click()};W.addEventListener("click",te,!0),E.detachMenuSlot=()=>W.removeEventListener("click",te,!0),E.managed=!0,C(E)}else E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0;return E.mode=O,E},F=(E,O)=>{let D=O.map(W=>W.menuSlot??W.element);for(D.forEach((W,te)=>{let Q=E.children[te];Q!==W&&(Q?E.insertBefore(W,Q):E.appendChild(W))});E.children.length>D.length;)E.lastElementChild?.remove()},X=()=>{if(n)return;let E=e.getBindings();if(!E)return;let O=e.getState(),D=O.phase==="streaming",W=k();W&&R(E.footer);let te=W?b(W,E.footer):!1,Q={start:[],end:[]},de=[];for(let pe of o){let Ce=t.get(pe.id);if(!Ce)continue;let Ee=pe.action,ge=Ee?oC(Ee.visible,O,!0)&&pP(Ee.visibility,O):!0;if(Ce.visible!==ge&&(Ce.visible=ge,!ge&&Ce.managed&&(Ce.menuSlot??Ce.element).remove()),!!ge){if(Ce=L(Ce,A(Ce,W,te)),Ee){let Ke=oC(Ee.disabled,O,!1)||Ee.disableWhenStreaming===!0&&D;h(Ce,Ke),!zr(Ee)&&Ee.pressed!==void 0&&Ce.button?.setAttribute("aria-pressed",Ee.pressed?"true":"false")}Ce.mode==="menu"?(C(Ce),de.push(Ce)):Q[pe.placement].push(Ce)}}if(de.length>0){let pe=P();F(pe.panel,de),pe.setItems(de.map(Ke=>Ke.menuSlot??Ke.element)),pe.applyButtonSize();let Ce=Number.isFinite(W?.order)?W?.order:$n.overflow,Ee=Q.start.findIndex(Ke=>Ke.resolved.order>Ce),ge={resolved:{id:aP,placement:"start",presentation:"bar",order:Ce,sequence:-1,source:"core"},element:pe.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};Q.start.splice(Ee<0?Q.start.length:Ee,0,ge)}else y&&(y.close(),y.trigger.remove(),y.setItems([]));m(E.actionsStart,Q.start),m(E.actionsEnd,Q.end)};return{resolve:()=>{if(n)return;let E=cP(e.collect()),O=new Set(E.map(D=>D.id));for(let[D,W]of t)O.has(D)||(p(W),t.delete(D));for(let D of E){let W=t.get(D.id);if(!W){let pe=u(D,"bar");pe&&t.set(D.id,pe);continue}let te=W.resolved.action,Q=D.action;if(!!te!=!!Q||te&&Q&&zr(te)!==zr(Q)||te&&Q&&zr(te)&&zr(Q)&&te.render!==Q.render){p(W),t.delete(D.id);let pe=u(D,W.mode);pe&&t.set(D.id,pe);continue}W.resolved=D,D.builtIn?(W.managed=D.builtIn.managed===!0||W.mode==="menu",D.builtIn.element&&W.mode==="bar"&&(W.element=D.builtIn.element)):Q&&!zr(Q)?i(W,Q):Q&&W.element.toggleAttribute(Jm,Q.disableWhenStreaming===!0)}o=E,X()},sync:X,getResolved:()=>o,getOverflowMenu:()=>y,destroy:()=>{if(!n){n=!0,T?.disconnect(),T=null,x=null;for(let E of t.values())p(E);t.clear(),y?.destroy(),y=null,o=[]}}}}var yP="core:model",bP=700,rC=16,vP=["--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"],sC=()=>{let e=Y("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Y("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function aC(e){let t=e.label??"Model",o=e.presentation??"native",n=null,r=c=>{let u=e.getSelectedModelId();return c.find(p=>p.id===u)??c[0]},a=()=>{let c=Y("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),u="",p=()=>{let T=e.getModels(),w=T.map(k=>`${k.id}:${k.label}`).join("|");w!==u&&(u=w,c.replaceChildren(...T.map(k=>{let P=Y("option",{attrs:{value:k.id}});return P.textContent=k.label,P}))),c.value=r(T)?.id??""};p(),n=p;let m=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",m);let h=T=>T.stopPropagation();c.addEventListener("click",h);let{wrapper:y,chevron:x}=sC();return y.append(c,x),{element:y,destroy:()=>{n===p&&(n=null),c.removeEventListener("change",m),c.removeEventListener("click",h)}}},i=()=>{let c=Y("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"}}),u=I("span","persona-composer-model-picker-label"),p=I("span","persona-composer-model-picker-suffix");c.append(u,p);let m=Y("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),h=new Map,y="",x=null,T=()=>x?.isOpen===!0,w=(O=!1)=>{T()&&(x?.close(),c.setAttribute("aria-expanded","false"),O&&c.focus())},k=O=>{let D=[...h.values()];if(D.length===0)return;let W=(O%D.length+D.length)%D.length;D[W].focus()},P=O=>{if(T())return;x||(x=eu({anchor:c,content:m,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Gc(c,m,vP),x.open(),c.setAttribute("aria-expanded","true");let W=[...h.keys()].indexOf(r(e.getModels())?.id??"");k(O??(W>=0?W:0))},R=O=>{w(!0),e.onSelect(O)},b=O=>{O.preventDefault(),O.stopPropagation();let D=O.currentTarget.getAttribute("data-persona-model-option");D&&R(D)},A=O=>{let D=Y("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":O.id}});if(O.icon){let pe=ce(O.icon,rC,"currentColor",1.5);if(pe){let Ce=I("span","persona-composer-model-option-icon");Ce.appendChild(pe),D.appendChild(Ce)}}let W=I("span","persona-composer-model-option-body"),te=I("span","persona-composer-model-option-label");if(te.textContent=O.label,W.appendChild(te),O.description){let pe=I("span","persona-composer-model-option-description");pe.textContent=O.description,W.appendChild(pe)}D.appendChild(W);let Q=I("span","persona-composer-model-option-check");Q.setAttribute("aria-hidden","true");let de=ce("check",rC,"currentColor",2);return de&&Q.appendChild(de),D.appendChild(Q),D.addEventListener("click",b),D},C=()=>{let O=e.getModels(),D=O.map(Q=>`${Q.id}:${Q.label}:${Q.icon??""}:${Q.description??""}`).join("|");if(D!==y){y=D;for(let Q of h.values())Q.removeEventListener("click",b);h.clear(),m.replaceChildren(...O.map(Q=>{let de=A(Q);return h.set(Q.id,de),de}))}let W=r(O);for(let[Q,de]of h)de.setAttribute("aria-selected",String(Q===W?.id));u.textContent=W?.label??"";let te=e.getSuffix?.()??"";p.textContent=te,c.setAttribute("aria-label",[t,[W?.label,te].filter(Boolean).join(" ")].filter(Boolean).join(": "))};C(),n=C;let L=O=>{O.preventDefault(),O.stopPropagation(),T()?w(!0):P()},F=O=>{if(O.key==="ArrowDown"){O.preventDefault(),T()?k(0):P(0);return}O.key==="ArrowUp"&&(O.preventDefault(),T()?k(-1):P(-1))},X=O=>{let D=[...h.values()],W=D.indexOf(O.target?.closest?.(".persona-composer-model-option"));switch(O.key){case"ArrowDown":O.preventDefault(),k(W+1);return;case"ArrowUp":O.preventDefault(),k(W-1);return;case"Home":O.preventDefault(),k(0);return;case"End":O.preventDefault(),k(D.length-1);return;case"Escape":O.preventDefault(),O.stopPropagation(),w(!0);return;case"Tab":w(!0);return;default:}};c.addEventListener("click",L),c.addEventListener("keydown",F),m.addEventListener("keydown",X);let{wrapper:G,chevron:E}=sC();return G.append(c,E),{element:G,destroy:()=>{n===C&&(n=null),c.removeEventListener("click",L),c.removeEventListener("keydown",F),m.removeEventListener("keydown",X);for(let O of h.values())O.removeEventListener("click",b);h.clear(),x?.destroy(),x=null,m.remove()}}};return{action:{id:yP,kind:"custom",placement:"end",order:bP,presentation:o==="popover"?"bar":"auto",label:t,render:()=>o==="popover"?i():a()},repaint:()=>n?.()}}var tg="[data-persona-composer-chip-row]";function tu(e){e.style.display=e.childElementCount>0?"flex":"none"}function og(e){let t=e.querySelector(tg);if(t)return t;let o=Y("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});o.style.display="none";let n=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return n?.parentElement===e?e.insertBefore(o,n):e.appendChild(o),o}var xP=":scope > [data-persona-composer-mode]";function iC(e){let t=e.row,o="",n=!1,r=new Set(e.initialIds??[]),a=u=>{let p=Y("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":u.id}});if(u.iconName){let x=I("span","persona-mention-chip-icon"),T=ce(u.iconName,12,"currentColor",1.5);T&&x.appendChild(T),p.appendChild(x)}let m=I("span","persona-mention-chip-label");m.textContent=u.shortLabel??u.label,p.appendChild(m);let h=Y("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${u.label}`}}),y=ce("x",12,"currentColor",2);return y?h.appendChild(y):h.textContent="\xD7",h.addEventListener("click",x=>{x.preventDefault(),x.stopPropagation(),e.onRemove(u.id)}),p.appendChild(h),p},i=()=>Array.from(t.querySelectorAll(xP)),d=u=>{u.setAttribute("data-persona-chip-exit",""),u.setAttribute("aria-hidden","true"),u.style.pointerEvents="none";let p=()=>{u.remove(),tu(t)},m=t.ownerDocument.defaultView,h=typeof m?.getComputedStyle=="function"?m.getComputedStyle(u).animationName:"";if(!h||h==="none"){p();return}u.addEventListener("animationend",p,{once:!0}),u.addEventListener("animationcancel",p,{once:!0})},c=()=>{for(let u of i())u.remove()};return{element:t,render:(u,p)=>{if(n)return;let m=p.filter(T=>u.includes(T.id)),h=m.map(T=>`${T.id}:${T.shortLabel??T.label}`).join("|");if(h===o)return;o=h;let y=new Map;for(let T of i()){let w=T.getAttribute("data-persona-composer-mode");w&&m.some(P=>P.id===w)&&!T.hasAttribute("data-persona-chip-exit")?y.set(w,T):T.hasAttribute("data-persona-chip-exit")||d(T)}let x=t.firstChild;for(let T of m){let w=y.get(T.id);w||(w=a(T),r.has(T.id)||(w.setAttribute("data-persona-chip-enter",""),w.addEventListener("animationend",()=>w?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(T.id),w!==x&&t.insertBefore(w,x),x=w.nextSibling}tu(t)},destroy:()=>{n=!0,c(),tu(t)}}}var lC=e=>`core:mode:${e}`;var ng=e=>Math.min(300+e,499),dC=e=>`core:mode-group:${e}`;function ou(e,t){return e?t?.find(o=>o.id===e)?.presentation==="segmented":!1}function CP(e,t){return e?t?.find(o=>o.id===e)?.chipVisibility==="hidden":!1}function cC(e,t){return e?.length?e.filter(o=>!ou(o.groupId,t)&&!CP(o.groupId,t)):[]}var SP=(e,t)=>e.groupId?t?.find(o=>o.id===e.groupId)?.selection??null:null;function uC(e,t,o,n){let r=o.find(d=>d.id===t);if(!r)return[...e];let a=e.includes(t),i=new Set(e);if(a)i.delete(t);else{if(SP(r,n)==="single"){let d=o.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!d.includes(c)))}i.add(t)}return o.filter(d=>i.has(d.id)).map(d=>d.id)}function nu(e,t){return t?.length?t.filter(o=>e.includes(o.id)).map(o=>o.id):[]}function pC(e,t){return t?.length?t.filter(o=>e.includes(o.id)&&(o.persistence??"sticky")!=="once").map(o=>o.id):[]}function fC(e,t){if(!(!t?.length||e.length===0))return t.find(o=>e.includes(o.id)&&o.placeholder)?.placeholder}var wP=16;function mC(e){let t=null;return{action:{id:dC(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let n=Y("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,a="",i=u=>{u.preventDefault(),u.stopPropagation();let m=u.currentTarget.getAttribute("data-persona-composer-mode");!m||e.getActiveIds().includes(m)&&e.getGroup()?.selection==="single"||e.onSelect(m)},d=u=>{let p=Y("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":u.id,"aria-label":u.label}});if(u.iconName){let h=ce(u.iconName,wP,"currentColor",1.5);h&&p.appendChild(h)}let m=I("span","persona-composer-segmented-label");return m.textContent=u.shortLabel??u.label,p.appendChild(m),p.addEventListener("click",i),p},c=()=>{let u=e.getGroup();u?.label?(n.setAttribute("role","group"),n.setAttribute("aria-label",u.label)):(n.removeAttribute("role"),n.removeAttribute("aria-label"));let p=e.getModes(),m=p.map(y=>`${y.id}:${y.shortLabel??y.label}:${y.iconName??""}`).join("|");if(m!==a){a=m;for(let x of r.values())x.removeEventListener("click",i);r.clear();let y=p.map(x=>{let T=d(x);return r.set(x.id,T),T});n.replaceChildren(...y)}let h=e.getActiveIds();for(let[y,x]of r)x.setAttribute("aria-pressed",String(h.includes(y)))};return c(),t=c,{element:n,destroy:()=>{t===c&&(t=null);for(let u of r.values())u.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}function gC(e){let t=Y("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let o="",n=!1,r=a=>{let i=I("span","persona-composer-quote-bar"),d=I("div","persona-composer-quote-content");if(a.sourceLabel){let m=I("div","persona-composer-quote-source");m.textContent=a.sourceLabel,d.appendChild(m)}let c=Y("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Ic(a.text),d.appendChild(c);let u=Y("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),p=ce("x",12,"currentColor",2);p?u.appendChild(p):u.textContent="\xD7",u.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,d,u)};return{element:t,render:a=>{if(n)return;let i=a?`${a.sourceLabel??""}\0${a.text}`:"";if(i!==o){if(o=i,!a){t.replaceChildren(),t.style.display="none";return}r(a),t.style.display="flex"}},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function hC(e){let t=Y("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let o,n=!1,r=(i,d,c,u)=>{let p=Y("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":d,[c]:""}}),m=ce(i,12,"currentColor",2);return m?p.appendChild(m):p.textContent=d,p.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),u()}),p},a=i=>{let d=Ic(i.text??"",90);if(d)return d;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(p=>p.label).join(", "):"Queued message"};return{element:t,render:i=>{if(n||i===o)return;if(o=i,!i){t.replaceChildren(),t.style.display="none";return}let d=I("span","persona-composer-pending-badge");d.textContent=e.label??"Sends next";let c=Y("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=a(i),t.replaceChildren(d,c,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function yC(e){let t=Y("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),o=Y("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});o.value=e.initialText;let n=()=>{o.style.height="auto",o.style.height=`${o.scrollHeight}px`};o.addEventListener("input",n);let r=I("div","persona-message-edit-actions"),a=(d,c,u,p)=>{let m=Y("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[u]:""},text:d});return m.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),m},i=()=>{let d=o.value.trim();d&&e.onSave(d)};return r.append(a(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),a(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",i)),o.addEventListener("keydown",d=>{if(d.key==="Escape"){d.preventDefault(),d.stopPropagation(),e.onCancel();return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),i())}),t.append(o,r),{element:t,getValue:()=>o.value,focus:()=>{o.focus();let d=o.value.length;o.setSelectionRange(d,d),n()},destroy:()=>{t.replaceChildren(),t.remove()}}}function bC(e){let t=e.text??"";if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function vC(e,t){if(!e||typeof e.text!="string")return;let o=new Set(t.mentionSourceIds),n=(e.mentionRefs??[]).filter(c=>o.has(c.sourceId)),r=n.length===(e.mentionRefs?.length??0)&&n.length>0,a=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>a.has(c)),d=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:n}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...d?{selectedModelId:d}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function xC(e){let t=e.delay??500,o=null,n=!1,r=()=>{o!==null&&(clearTimeout(o),o=null)};return{schedule:()=>{n||(r(),o=setTimeout(()=>{o=null,e.write()},t))},flush:()=>{n||o===null||(r(),e.write())},cancel:r,destroy:()=>{n=!0,r()}}}function CC(e){return e.wrapped||e.text.includes(`
24
+ `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission||e.dictationActive)}function SC(){let e=!1;return{observe:(t,o)=>o?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function wC(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let o=t.getComputedStyle(e),n=Number.parseFloat(o.lineHeight),r=Number.parseFloat(o.fontSize),a=Number.isFinite(n)&&n>0?n:Number.isFinite(r)&&r>0?r*1.4:0;if(!a)return!1;let i=(Number.parseFloat(o.paddingTop)||0)+(Number.parseFloat(o.paddingBottom)||0);return e.scrollHeight-i>a*1.5}function AC(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function rg(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function TC(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var AP=e=>typeof e?.then=="function";function MC(e,t){return t===!1?{status:"canceled"}:!t||typeof t!="object"?{status:"proceed"}:(typeof t.text=="string"&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"})}function EC(e,t,o){let n;try{n=e(rg(t),{signal:o})}catch(r){return{status:"error",error:r}}return AP(n)?Promise.resolve(n).then(r=>o.aborted?{status:"aborted"}:MC(t,r),r=>o.aborted?{status:"aborted"}:{status:"error",error:r}):MC(t,n)}var PC=/\s/;function MP(e,t,o){if(o==="input-start")return t===0;let n=t>0?e[t-1]:"";return o==="line-start"?n===""||n===`
25
+ `:n===""||PC.test(n)}function TP(e,t,o="@",n="anywhere",r=!1){if(!o||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let i=e[a];if(i===o)return MP(e,a,n)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(i===`
26
+ `||i==="\uFFFC"||!r&&PC.test(i))return null;a--}return null}function kC(e,t,o){for(let n of o){let r=TP(e,t,n.trigger,n.position??"anywhere",n.allowSpaces??!1);if(r)return{channel:n,match:r}}return null}function LC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function IC(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},o=(e.triggers??[]).map(n=>({trigger:n.trigger,position:n.triggerPosition??"anywhere",allowSpaces:n.allowSpaces??!1,sources:Array.isArray(n.sources)?n.sources:[],searchPlaceholder:n.searchPlaceholder,showButton:n.showButton===!0,buttonIconName:n.buttonIconName,buttonTooltipText:n.buttonTooltipText}));return[t,...o]}function RC(e){let{config:t,onOpen:o}=e,n=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",a=I("div","persona-send-button-wrapper"),i=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Ko} ${vn}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),d=ce(n,vo,"currentColor",1.5);return d?i.appendChild(d):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),o()}),a.appendChild(i),eo({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:a}}var{setLoader:EP,load:PP}=mt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),HC=EP,sg=PP;var{setLoader:kP,load:LP}=mt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),WC=kP,BC=LP;function Sl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let o=Y("span",{className:bo("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&o.style.setProperty("--persona-mention-token-accent",e.color);let n=ce(e.iconName??"at-sign",13,"currentColor",2);if(n){let r=I("span","persona-mention-token-icon");r.appendChild(n),o.appendChild(r)}return o.appendChild(Y("span",{className:"persona-mention-token-label",text:`@${e.label}`})),o}function OC(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let o=IC(t).filter(b=>b.sources.length>0);if(o.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let n=o.filter(b=>b.sources.some(A=>typeof A.matchCommand=="function")),r=b=>n.some(A=>A.trigger?A.position==="line-start"?b.split(`
27
+ `).some(L=>L.startsWith(A.trigger)):(A.position==="anywhere"?b:b.split(`
28
+ `)[0]).startsWith(A.trigger):!1),a=(b,A)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${b}`,{detail:A}))}catch{}},i=!e.chipRow,d=e.chipRow??Y("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),c=null,u=null,p=e.textarea,m=null,h=null,y=null,x=null,T=()=>{if(c)return Promise.resolve(c);if(u)return u;let b=sg().then(A=>(A.setMentionIconRenderer(ce),c=A.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:R,emit:a}),c)).catch(A=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",A),u===b&&(u=null),null));return u=b,b},w=()=>{BC().then(b=>{let A=b.mountInlineComposer({textarea:e.textarea,renderToken:L=>Sl(L,{render:t.renderMentionToken}),onMentionRemoved:L=>c?.untrackMention(L)});m=A.input,h=A.destroy;let C=p;C.replaceWith(A.element),p=A.element,x={next:A.element,prev:C},y?.(A.element,C),c?c.rebindComposer(A.input):u&&u.then(L=>L?.rebindComposer(A.input))}).catch(b=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",b)})};t.display==="inline"&&w();let k=[],P=new Map;for(let b of o){if(!b.showButton)continue;let A=RC({config:{...t,buttonIconName:b.buttonIconName,buttonTooltipText:b.buttonTooltipText},onOpen:()=>{T().then(C=>C?.openMenu(b.trigger))}});k.push(A),P.set(b.trigger,A.button)}let R=(b,A,C)=>{let L=P.get(A);L&&(L.setAttribute("aria-expanded",b?"true":"false"),b?L.setAttribute("aria-controls",C):L.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(b=>b.wrapper),contextRow:d,handleInput:b=>{if(c){c.handleInput();return}if(!LC(b))return;let A=p,C=A.selectionStart??0;kC(A.value,C,o)&&T().then(L=>L?.handleInput())},handleKeydown:b=>{if(c?.isMenuOpen())return c.handleKeydown(b);if(b.key==="Backspace"&&c?.hasMentions()&&!x){let A=p,C=A.selectionStart===0&&A.selectionEnd===0;if((A.value.length===0||C)&&c.removeLastChip())return b.preventDefault(),!0}return!1},isMenuOpen:()=>c?.isMenuOpen()??!1,hasMentions:()=>c?.hasMentions()??!1,getMentionRefs:()=>c?.getMentionRefs()??[],collectForSubmit:()=>c?.collectForSubmit()??null,takeInlineCommand:async b=>r(b)?(c??await T())?.dispatchInlineCommand(b)??null:null,clear:()=>c?.clear(),prefetch:()=>{sg().catch(()=>{})},onComposerSwap:b=>{y=b,x&&b(x.next,x.prev)},destroy:()=>{c?.destroy(),h?.();for(let b of k)b.wrapper.remove();i&&d.remove()}}}var ru="16px",su="transparent",IP=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?"0px":`${t/4}rem`;return e})(),ig={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"}},spacing:IP,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"}},lg={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"}},dg={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:zo,maxWidth:Vc,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ru,canvasBackground:su},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"}},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 xo(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let o=t.split("."),n=e;for(let r of o){if(n==null)return;n=n[r]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?xo(e,n):n}function au(e){let t={};function o(n,r){for(let[a,i]of Object.entries(n)){let d=`${r}.${a}`;if(typeof i=="string"){let c=xo(e,i);c!==void 0&&(t[d]={path:d,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 i=="object"&&i!==null&&o(i,d)}}return o(e.palette,"palette"),o(e.semantic,"semantic"),o(e.components,"components"),t}function cg(e){let t=[],o=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||o.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||o.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:o}}function _C(e,t){let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];a&&typeof a=="object"&&!Array.isArray(a)&&r&&typeof r=="object"&&!Array.isArray(r)?o[n]=_C(a,r):o[n]=r}return o}function RP(e,t){return t?_C(e,t):e}function wl(e,t={}){let o={palette:ig,semantic:lg,components:dg},n={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:RP(o.components,e?.components)};if(t.validate!==!1){let r=cg(n);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(a=>a.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)n=r.transform(n);return n}var ag=e=>e.trim()==="0"?"0px":e,DC="--persona-",HP=e=>{if(!e)return;let t=e.trim().toLowerCase(),o;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?o=[0,1,2].map(d=>parseInt(i[d]+i[d],16)):(i.length===6||i.length===8)&&(o=[0,2,4].map(d=>parseInt(i.slice(d,d+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let d=i[1].split(/[,/\s]+/).filter(Boolean);d.length>=3&&(o=d.slice(0,3).map(c=>{let u=c.endsWith("%"),p=parseFloat(u?c.slice(0,-1):c);return u?p/100*255:p}))}}if(!o||o.some(i=>!Number.isFinite(i)))return;let[n,r,a]=o.map(i=>{let d=Math.max(0,Math.min(255,i))/255;return d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)});return .2126*n+.7152*r+.0722*a},WP=.179,to=(e,t)=>{for(let[o,...n]of t){let r;for(let a of n)if(r=a.charCodeAt(0)===61?a.slice(1):e[DC+a],r!==void 0)break;r!==void 0&&(e[DC+o]=r)}};function iu(e){let t=au(e),o={};for(let[j,qe]of Object.entries(t)){let Ge=j.replace(/\./g,"-");o[`--persona-${Ge}`]=qe.value}to(o,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let n=o["--persona-components-launcher-foreground"];o["--persona-launcher-fg-muted"]=n&&n!==o["--persona-primary"]?`color-mix(in srgb, ${n} 70%, transparent)`:o["--persona-muted"],to(o,[["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"]]),to(o,[["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"]]),o["--persona-panel-border"]=o["--persona-components-panel-border"]??`1px solid ${o["--persona-border"]}`,to(o,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),o["--persona-panel-inset"]=o["--persona-components-panel-inset"]??ru,o["--persona-panel-canvas-bg"]=o["--persona-components-panel-canvasBackground"]??su,to(o,[["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"]]),to(o,[["header-bg","components-header-background","surface"]]);let r=o["--persona-header-bg"],a=o["--persona-components-header-foreground"],i=a?`color-mix(in srgb, ${a} 72%, ${r})`:void 0;o["--persona-header-border"]=o["--persona-components-header-border"]??(a?`color-mix(in srgb, ${a} 14%, ${r})`:void 0)??o["--persona-divider"],to(o,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),o["--persona-header-title-fg"]=o["--persona-components-header-title-color"]??o["--persona-components-header-titleForeground"]??a??o["--persona-primary"],o["--persona-header-subtitle-fg"]=o["--persona-components-header-subtitle-color"]??o["--persona-components-header-subtitleForeground"]??i??o["--persona-text-muted"],o["--persona-header-action-icon-fg"]=o["--persona-components-header-actionIconForeground"]??i??o["--persona-muted"],to(o,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let d=e.components?.header;d?.shadow&&(o["--persona-header-shadow"]=d.shadow),d?.borderBottom&&(o["--persona-header-border-bottom"]=d.borderBottom),d?.minHeight&&(o["--persona-header-min-height"]=d.minHeight);let c=o["--persona-components-history-railHeader-background"];c&&(o["--persona-history-rail-header-bg"]=c);let u=o["--persona-components-history-railHeader-border"];u&&(o["--persona-history-rail-header-border"]=u);let p=o["--persona-components-history-railHeader-minHeight"];p&&(o["--persona-history-rail-header-min-height"]=p);for(let[j,qe]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ge=o[`--persona-components-history-overlay-${j}`];Ge&&(o[`--persona-history-overlay-${qe}`]=Ge)}for(let[j,qe]of[["background","bg"],["borderRadius","radius"]]){let Ge=o[`--persona-components-history-menu-${j}`];Ge&&(o[`--persona-history-menu-${qe}`]=Ge)}let m=e.components?.history?.motion;if(m){let j=Ae=>{if(Ae===void 0)return;let De=String(Ae).trim();return/^\d+(\.\d+)?$/.test(De)?`${De}ms`:De},qe=j(m.enterDurationMs);qe!==void 0&&(o["--persona-history-enter-ms"]=qe);let Ge=j(m.exitDurationMs);Ge!==void 0&&(o["--persona-history-exit-ms"]=Ge),m.enterEasing&&(o["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(o["--persona-history-exit-easing"]=m.exitEasing)}let h=o["--persona-components-history-dangerForeground"];h&&(o["--persona-history-danger-fg"]=h),o["--persona-danger"]=o["--persona-components-history-confirm-dangerBackground"]??o["--persona-palette-colors-error-700"]??"#b42318",o["--persona-danger-fg"]=o["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let j of["scrim","shadow"]){let qe=o[`--persona-components-history-confirm-${j}`];qe&&(o[`--persona-history-confirm-${j}`]=qe)}for(let[j,qe]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ge=o[`--persona-components-tooltip-${j}`];Ge&&(o[`--persona-tooltip-${qe}`]=Ge)}e.components?.tooltip?.arrow===!1&&(o["--persona-tooltip-arrow-display"]="none");for(let[j,qe]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ge=o[`--persona-components-messageActions-${j}`];Ge&&(o[`--persona-message-action-${qe}`]=Ge)}to(o,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let y=o["--persona-components-introCard-background"],x=o["--persona-components-introCard-shadow"],T=(!y||y==="transparent"||y==="none")&&(!x||x==="none"),w=o["--persona-components-introCard-padding"]??"1.5rem";o["--persona-intro-card-padding"]=T&&w==="1.5rem"?"1.5rem 0":w,to(o,[["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"],["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"]]),to(o,[["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 k=o["--persona-components-markdown-heading-h1-fontSize"];k&&(o["--persona-md-h1-size"]=k);let P=o["--persona-components-markdown-heading-h1-fontWeight"];P&&(o["--persona-md-h1-weight"]=P);let R=o["--persona-components-markdown-heading-h2-fontSize"];R&&(o["--persona-md-h2-size"]=R);let b=o["--persona-components-markdown-heading-h2-fontWeight"];b&&(o["--persona-md-h2-weight"]=b);let A=o["--persona-components-markdown-prose-fontFamily"];A&&A!=="inherit"&&(o["--persona-md-prose-font-family"]=A),to(o,[["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"]]),to(o,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),to(o,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),to(o,[["md-hr-color","components-markdown-hr-color","divider"]]),to(o,[["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"]]),o["--cw-container"]=o["--persona-components-collapsibleWidget-container"]??o["--persona-surface"],o["--cw-surface"]=o["--persona-components-collapsibleWidget-surface"]??o["--persona-surface"],o["--cw-border"]=o["--persona-components-collapsibleWidget-border"]??o["--persona-border"],to(o,[["message-border","components-message-border","border"]]),to(o,[["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 C=e.components,L=C?.iconButton;L&&(L.background&&(o["--persona-icon-btn-bg"]=L.background),L.border&&(o["--persona-icon-btn-border"]=L.border),L.color&&(o["--persona-icon-btn-color"]=L.color),L.padding&&(o["--persona-icon-btn-padding"]=L.padding),L.borderRadius&&(o["--persona-icon-btn-radius"]=L.borderRadius),L.hoverBackground&&(o["--persona-icon-btn-hover-bg"]=L.hoverBackground),L.hoverColor&&(o["--persona-icon-btn-hover-color"]=L.hoverColor),L.activeBackground&&(o["--persona-icon-btn-active-bg"]=L.activeBackground),L.activeBorder&&(o["--persona-icon-btn-active-border"]=L.activeBorder));let F=C?.labelButton;F&&(F.background&&(o["--persona-label-btn-bg"]=F.background),F.border&&(o["--persona-label-btn-border"]=F.border),F.color&&(o["--persona-label-btn-color"]=F.color),F.padding&&(o["--persona-label-btn-padding"]=F.padding),F.borderRadius&&(o["--persona-label-btn-radius"]=F.borderRadius),F.hoverBackground&&(o["--persona-label-btn-hover-bg"]=F.hoverBackground),F.fontSize&&(o["--persona-label-btn-font-size"]=F.fontSize),F.gap&&(o["--persona-label-btn-gap"]=F.gap));let X=C?.toggleGroup;X&&(X.gap&&(o["--persona-toggle-group-gap"]=X.gap),X.borderRadius&&(o["--persona-toggle-group-radius"]=X.borderRadius));let G=C?.artifact;if(G?.toolbar){let j=G.toolbar;j.iconHoverColor&&(o["--persona-artifact-toolbar-icon-hover-color"]=j.iconHoverColor),j.iconHoverBackground&&(o["--persona-artifact-toolbar-icon-hover-bg"]=j.iconHoverBackground),j.iconPadding&&(o["--persona-artifact-toolbar-icon-padding"]=j.iconPadding),j.iconBorderRadius&&(o["--persona-artifact-toolbar-icon-radius"]=j.iconBorderRadius),j.iconBorder&&(o["--persona-artifact-toolbar-icon-border"]=j.iconBorder),j.toggleGroupGap&&(o["--persona-artifact-toolbar-toggle-group-gap"]=ag(j.toggleGroupGap)),j.toggleBorderRadius&&(o["--persona-artifact-toolbar-toggle-radius"]=j.toggleBorderRadius),j.toggleGroupPadding&&(o["--persona-artifact-toolbar-toggle-group-padding"]=ag(j.toggleGroupPadding)),j.toggleGroupBorder&&(o["--persona-artifact-toolbar-toggle-group-border"]=j.toggleGroupBorder),j.toggleGroupBorderRadius&&(o["--persona-artifact-toolbar-toggle-group-radius"]=j.toggleGroupBorderRadius),j.toggleGroupBackground&&(o["--persona-artifact-toolbar-toggle-group-bg"]=xo(e,j.toggleGroupBackground)??j.toggleGroupBackground),j.copyBackground&&(o["--persona-artifact-toolbar-copy-bg"]=j.copyBackground),j.copyBorder&&(o["--persona-artifact-toolbar-copy-border"]=j.copyBorder),j.copyColor&&(o["--persona-artifact-toolbar-copy-color"]=j.copyColor),j.copyBorderRadius&&(o["--persona-artifact-toolbar-copy-radius"]=ag(j.copyBorderRadius)),j.copyPadding&&(o["--persona-artifact-toolbar-copy-padding"]=j.copyPadding),j.copyMenuBackground&&(o["--persona-artifact-toolbar-copy-menu-bg"]=j.copyMenuBackground,o["--persona-dropdown-bg"]=o["--persona-dropdown-bg"]??j.copyMenuBackground),j.copyMenuBorder&&(o["--persona-artifact-toolbar-copy-menu-border"]=j.copyMenuBorder,o["--persona-dropdown-border"]=o["--persona-dropdown-border"]??j.copyMenuBorder),j.copyMenuShadow&&(o["--persona-artifact-toolbar-copy-menu-shadow"]=j.copyMenuShadow,o["--persona-dropdown-shadow"]=o["--persona-dropdown-shadow"]??j.copyMenuShadow),j.copyMenuBorderRadius&&(o["--persona-artifact-toolbar-copy-menu-radius"]=j.copyMenuBorderRadius,o["--persona-dropdown-radius"]=o["--persona-dropdown-radius"]??j.copyMenuBorderRadius),j.copyMenuItemHoverBackground&&(o["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=j.copyMenuItemHoverBackground,o["--persona-dropdown-item-hover-bg"]=o["--persona-dropdown-item-hover-bg"]??j.copyMenuItemHoverBackground),j.iconBackground&&(o["--persona-artifact-toolbar-icon-bg"]=j.iconBackground),j.toolbarBorder&&(o["--persona-artifact-toolbar-border"]=j.toolbarBorder)}if(G?.tab){let j=G.tab;j.background&&(o["--persona-artifact-tab-bg"]=j.background),j.activeBackground&&(o["--persona-artifact-tab-active-bg"]=j.activeBackground),j.activeBorder&&(o["--persona-artifact-tab-active-border"]=j.activeBorder),j.borderRadius&&(o["--persona-artifact-tab-radius"]=j.borderRadius),j.textColor&&(o["--persona-artifact-tab-color"]=j.textColor),j.hoverBackground&&(o["--persona-artifact-tab-hover-bg"]=j.hoverBackground),j.listBackground&&(o["--persona-artifact-tab-list-bg"]=j.listBackground),j.listBorderColor&&(o["--persona-artifact-tab-list-border-color"]=j.listBorderColor),j.listPadding&&(o["--persona-artifact-tab-list-padding"]=j.listPadding)}if(G?.pane){let j=G.pane;if(j.toolbarBackground){let qe=xo(e,j.toolbarBackground)??j.toolbarBackground;o["--persona-artifact-toolbar-bg"]=qe}}if(G?.card){let j=G.card;j.background&&(o["--persona-artifact-card-bg"]=j.background),j.border&&(o["--persona-artifact-card-border"]=j.border),j.borderRadius&&(o["--persona-artifact-card-radius"]=j.borderRadius),j.hoverBackground&&(o["--persona-artifact-card-hover-bg"]=j.hoverBackground),j.hoverBorderColor&&(o["--persona-artifact-card-hover-border"]=j.hoverBorderColor)}if(G?.inline){let j=G.inline;j.background&&(o["--persona-artifact-inline-bg"]=xo(e,j.background)??j.background),j.border&&(o["--persona-artifact-inline-border"]=j.border),j.borderRadius&&(o["--persona-artifact-inline-radius"]=j.borderRadius),j.chromeBackground&&(o["--persona-artifact-inline-chrome-bg"]=xo(e,j.chromeBackground)??j.chromeBackground),j.chromeBorder&&(o["--persona-artifact-inline-chrome-border"]=xo(e,j.chromeBorder)??j.chromeBorder),j.titleColor&&(o["--persona-artifact-inline-title-color"]=xo(e,j.titleColor)??j.titleColor),j.mutedColor&&(o["--persona-artifact-inline-muted-color"]=xo(e,j.mutedColor)??j.mutedColor),j.frameHeight&&(o["--persona-artifact-inline-frame-height"]=j.frameHeight)}let E=C?.code;E&&(E.keywordColor&&(o["--persona-code-keyword-color"]=E.keywordColor),E.stringColor&&(o["--persona-code-string-color"]=E.stringColor),E.commentColor&&(o["--persona-code-comment-color"]=E.commentColor),E.numberColor&&(o["--persona-code-number-color"]=E.numberColor),E.tagColor&&(o["--persona-code-tag-color"]=E.tagColor),E.attrColor&&(o["--persona-code-attr-color"]=E.attrColor),E.propertyColor&&(o["--persona-code-property-color"]=E.propertyColor),E.lineNumberColor&&(o["--persona-code-line-number-color"]=E.lineNumberColor),E.gutterBorderColor&&(o["--persona-code-gutter-border-color"]=E.gutterBorderColor),E.background&&(o["--persona-code-bg"]=xo(e,E.background)??E.background));let O=o["--persona-surface"],D=o["--persona-container"],W=o["--persona-palette-colors-gray-100"]??"#f3f4f6",te=o["--persona-palette-colors-gray-200"]??"#e5e7eb",Q=o["--persona-palette-colors-gray-300"]??"#d1d5db",de=!D||D===O,pe=HP(O??o["--persona-background"]),Ce=de&&pe!==void 0&&pe<WP,Ee=Ce?"rgba(255, 255, 255, 0.08)":W,ge=Ce?"rgba(255, 255, 255, 0.12)":te,Ke=Ce?"rgba(255, 255, 255, 0.16)":Q,Bt=de?Ee:D,Le=de?ge:D;return o["--persona-icon-btn-hover-bg"]=o["--persona-icon-btn-hover-bg"]??Bt,o["--persona-icon-btn-active-bg"]=o["--persona-icon-btn-active-bg"]??Le,de&&(o["--persona-icon-btn-active-border"]=o["--persona-icon-btn-active-border"]??Ke),o["--persona-label-btn-hover-bg"]=o["--persona-label-btn-hover-bg"]??Bt,o["--persona-artifact-tab-hover-bg"]=o["--persona-artifact-tab-hover-bg"]??Bt,o["--persona-artifact-card-hover-bg"]=o["--persona-artifact-card-hover-bg"]??Bt,o}var NC={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var BP={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"}}},OP={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},FC=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Al=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",DP=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Al()},lu=e=>DP(e),_P=e=>wl(e),NP=e=>{let t=Va(OP,e??{})??{};return wl({...t,palette:{...t.palette,colors:{...BP.colors,...t.palette?.colors}}},{validate:!1})},Kr=e=>{let t=lu(e),o=FC(e?.theme),n=FC(e?.darkTheme);return t==="dark"?NP(Va(o??{},n??{})):_P(o)},FP=e=>iu(e),Us=(e,t)=>{let o=Kr(t),n=FP(o);for(let[r,a]of Object.entries(n))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",lu(t))},Ka=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let o=new MutationObserver(()=>{e(Al())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>o.disconnect())}if(typeof window<"u"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(Al());o.addEventListener?(o.addEventListener("change",n),t.push(()=>o.removeEventListener("change",n))):o.addListener&&(o.addListener(n),t.push(()=>o.removeListener(n)))}return()=>{t.forEach(o=>o())}};var Gr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var du="24px",ug=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Ml=e=>{if(typeof e!="string")return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let o=Number(t[1])/100;return o>0&&o<1?o:null},UC=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var qC=null;var pg=()=>{if(qC!==null)return qC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},UP="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",cu=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},uu=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),o=t.pop(),n={key:o,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")n.mod=!0;else if(r==="shift")n.shift=!0;else if(r==="alt"||r==="option")n.alt=!0;else return cu("unknown modifier in",e),null;return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(o)||!/^([^+\s]|[a-z]{2,12})$/.test(o)?(cu("unsupported",e),null):(o==="space"&&(n.key=" "),n)},qP=e=>UP.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),$C=(e,t)=>{let o=uu(e);if(!o)return"";let n=pg(),r=qP(o.key);if(!t&&n)return`${o.alt?"\u2325":""}${o.shift?"\u21E7":""}\u2318${r}`;let a=[t?n?"Meta":"Control":"Ctrl"];return o.alt&&a.push("Alt"),o.shift&&a.push("Shift"),a.push(r),a.join("+")},pu=e=>$C(e,!1),Tl=e=>$C(e,!0),$P=(e,t)=>t.key?.toLowerCase()===e.key&&(pg()?t.metaKey:t.ctrlKey)===e.mod&&!(pg()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,VP=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},VC=e=>{let t=new Map,o=e?.ownerDocument??(typeof document<"u"?document:null),n=(a,i)=>{if((a.scope??"widget")==="page")return!0;if(!e)return!1;let d=i.composedPath?.();return d?.length?d.includes(e):e.contains(i.target)},r=a=>{if(a.isComposing||!t.size)return;let i=a.composedPath?.()[0]??a.target;for(let d of t.values())if($P(d.parsed,a)&&d.when?.()!==!1&&n(d,a)&&!(!d.allowInInput&&VP(i))){a.preventDefault();try{d.run(a)}catch(c){cu(`${d.id} threw on`,d.combo),console.warn(c)}return}};return o?.addEventListener("keydown",r),{register(a){let i=uu(a.combo);if(!i)return()=>{};let d=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(d);return c?(cu(`${c.id} already owns`,a.combo),()=>{}):(t.set(d,{...a,parsed:i}),a.element?.setAttribute("aria-keyshortcuts",Tl(a.combo)),()=>{t.get(d)?.id===a.id&&t.delete(d),a.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),o?.removeEventListener("keydown",r)}}};var jC=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:h=>h.getAttribute("im-preserve")==="true",shouldReAppend:h=>h.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function o(h,y,x={}){h=p(h);let T=m(y),w=u(h,T,x),k=r(w,()=>d(w,h,T,P=>P.morphStyle==="innerHTML"?(a(P,h,T),Array.from(h.childNodes)):n(P,h,T)));return w.pantry.remove(),k}function n(h,y,x){let T=m(y);return a(h,T,x,y,y.nextSibling),Array.from(T.childNodes)}function r(h,y){if(!h.config.restoreFocus)return y();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return y();let{id:T,selectionStart:w,selectionEnd:k}=x,P=y();return T&&T!==document.activeElement?.getAttribute("id")&&(x=h.target.querySelector(`[id="${T}"]`),x?.focus()),x&&!x.selectionEnd&&k&&x.setSelectionRange(w,k),P}let a=(function(){function h(b,A,C,L=null,F=null){A instanceof HTMLTemplateElement&&C instanceof HTMLTemplateElement&&(A=A.content,C=C.content),L||(L=A.firstChild);for(let X of C.childNodes){if(L&&L!=F){let E=x(b,X,L,F);if(E){E!==L&&w(b,L,E),i(E,X,b),L=E.nextSibling;continue}}if(X instanceof Element){let E=X.getAttribute("id");if(b.persistentIds.has(E)){let O=k(A,E,L,b);i(O,X,b),L=O.nextSibling;continue}}let G=y(A,X,L,b);G&&(L=G.nextSibling)}for(;L&&L!=F;){let X=L;L=L.nextSibling,T(b,X)}}function y(b,A,C,L){if(L.callbacks.beforeNodeAdded(A)===!1)return null;if(L.idMap.has(A)){let F=document.createElement(A.tagName);return b.insertBefore(F,C),i(F,A,L),L.callbacks.afterNodeAdded(F),F}else{let F=document.importNode(A,!0);return b.insertBefore(F,C),L.callbacks.afterNodeAdded(F),F}}let x=(function(){function b(L,F,X,G){let E=null,O=F.nextSibling,D=0,W=X;for(;W&&W!=G;){if(C(W,F)){if(A(L,W,F))return W;E===null&&(L.idMap.has(W)||(E=W))}if(E===null&&O&&C(W,O)&&(D++,O=O.nextSibling,D>=2&&(E=void 0)),L.activeElementAndParents.includes(W))break;W=W.nextSibling}return E||null}function A(L,F,X){let G=L.idMap.get(F),E=L.idMap.get(X);if(!E||!G)return!1;for(let O of G)if(E.has(O))return!0;return!1}function C(L,F){let X=L,G=F;return X.nodeType===G.nodeType&&X.tagName===G.tagName&&(!X.getAttribute?.("id")||X.getAttribute?.("id")===G.getAttribute?.("id"))}return b})();function T(b,A){if(b.idMap.has(A))R(b.pantry,A,null);else{if(b.callbacks.beforeNodeRemoved(A)===!1)return;A.parentNode?.removeChild(A),b.callbacks.afterNodeRemoved(A)}}function w(b,A,C){let L=A;for(;L&&L!==C;){let F=L;L=L.nextSibling,T(b,F)}return L}function k(b,A,C,L){let F=L.target.getAttribute?.("id")===A&&L.target||L.target.querySelector(`[id="${A}"]`)||L.pantry.querySelector(`[id="${A}"]`);return P(F,L),R(b,F,C),F}function P(b,A){let C=b.getAttribute("id");for(;b=b.parentNode;){let L=A.idMap.get(b);L&&(L.delete(C),L.size||A.idMap.delete(b))}}function R(b,A,C){if(b.moveBefore)try{b.moveBefore(A,C)}catch{b.insertBefore(A,C)}else b.insertBefore(A,C)}return h})(),i=(function(){function h(P,R,b){return b.ignoreActive&&P===document.activeElement?null:(b.callbacks.beforeNodeMorphed(P,R)===!1||(P instanceof HTMLHeadElement&&b.head.ignore||(P instanceof HTMLHeadElement&&b.head.style!=="morph"?c(P,R,b):(y(P,R,b),k(P,b)||a(b,P,R))),b.callbacks.afterNodeMorphed(P,R)),P)}function y(P,R,b){let A=R.nodeType;if(A===1){let C=P,L=R,F=C.attributes,X=L.attributes;for(let G of X)w(G.name,C,"update",b)||C.getAttribute(G.name)!==G.value&&C.setAttribute(G.name,G.value);for(let G=F.length-1;0<=G;G--){let E=F[G];if(E&&!L.hasAttribute(E.name)){if(w(E.name,C,"remove",b))continue;C.removeAttribute(E.name)}}k(C,b)||x(C,L,b)}(A===8||A===3)&&P.nodeValue!==R.nodeValue&&(P.nodeValue=R.nodeValue)}function x(P,R,b){if(P instanceof HTMLInputElement&&R instanceof HTMLInputElement&&R.type!=="file"){let A=R.value,C=P.value;T(P,R,"checked",b),T(P,R,"disabled",b),R.hasAttribute("value")?C!==A&&(w("value",P,"update",b)||(P.setAttribute("value",A),P.value=A)):w("value",P,"remove",b)||(P.value="",P.removeAttribute("value"))}else if(P instanceof HTMLOptionElement&&R instanceof HTMLOptionElement)T(P,R,"selected",b);else if(P instanceof HTMLTextAreaElement&&R instanceof HTMLTextAreaElement){let A=R.value,C=P.value;if(w("value",P,"update",b))return;A!==C&&(P.value=A),P.firstChild&&P.firstChild.nodeValue!==A&&(P.firstChild.nodeValue=A)}}function T(P,R,b,A){let C=R[b],L=P[b];if(C!==L){let F=w(b,P,"update",A);F||(P[b]=R[b]),C?F||P.setAttribute(b,""):w(b,P,"remove",A)||P.removeAttribute(b)}}function w(P,R,b,A){return P==="value"&&A.ignoreActiveValue&&R===document.activeElement?!0:A.callbacks.beforeAttributeUpdated(P,R,b)===!1}function k(P,R){return!!R.ignoreActiveValue&&P===document.activeElement&&P!==document.body}return h})();function d(h,y,x,T){if(h.head.block){let w=y.querySelector("head"),k=x.querySelector("head");if(w&&k){let P=c(w,k,h);return Promise.all(P).then(()=>{let R=Object.assign(h,{head:{block:!1,ignore:!0}});return T(R)})}}return T(h)}function c(h,y,x){let T=[],w=[],k=[],P=[],R=new Map;for(let A of y.children)R.set(A.outerHTML,A);for(let A of h.children){let C=R.has(A.outerHTML),L=x.head.shouldReAppend(A),F=x.head.shouldPreserve(A);C||F?L?w.push(A):(R.delete(A.outerHTML),k.push(A)):x.head.style==="append"?L&&(w.push(A),P.push(A)):x.head.shouldRemove(A)!==!1&&w.push(A)}P.push(...R.values());let b=[];for(let A of P){let C=document.createRange().createContextualFragment(A.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(C)!==!1){if("href"in C&&C.href||"src"in C&&C.src){let L,F=new Promise(function(X){L=X});C.addEventListener("load",function(){L()}),b.push(F)}h.appendChild(C),x.callbacks.afterNodeAdded(C),T.push(C)}}for(let A of w)x.callbacks.beforeNodeRemoved(A)!==!1&&(h.removeChild(A),x.callbacks.afterNodeRemoved(A));return x.head.afterHeadMorphed(h,{added:T,kept:k,removed:w}),b}let u=(function(){function h(b,A,C){let{persistentIds:L,idMap:F}=P(b,A),X=y(C),G=X.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(G))throw`Do not understand how to morph style ${G}`;return{target:b,newContent:A,config:X,morphStyle:G,ignoreActive:X.ignoreActive,ignoreActiveValue:X.ignoreActiveValue,restoreFocus:X.restoreFocus,idMap:F,persistentIds:L,pantry:x(),activeElementAndParents:T(b),callbacks:X.callbacks,head:X.head}}function y(b){let A=Object.assign({},t);return Object.assign(A,b),A.callbacks=Object.assign({},t.callbacks,b.callbacks),A.head=Object.assign({},t.head,b.head),A}function x(){let b=document.createElement("div");return b.hidden=!0,document.body.insertAdjacentElement("afterend",b),b}function T(b){let A=[],C=document.activeElement;if(C?.tagName!=="BODY"&&b.contains(C))for(;C&&(A.push(C),C!==b);)C=C.parentElement;return A}function w(b){let A=Array.from(b.querySelectorAll("[id]"));return b.getAttribute?.("id")&&A.push(b),A}function k(b,A,C,L){for(let F of L){let X=F.getAttribute("id");if(A.has(X)){let G=F;for(;G;){let E=b.get(G);if(E==null&&(E=new Set,b.set(G,E)),E.add(X),G===C)break;G=G.parentElement}}}}function P(b,A){let C=w(b),L=w(A),F=R(C,L),X=new Map;k(X,F,b,C);let G=A.__idiomorphRoot||A;return k(X,F,G,L),{persistentIds:F,idMap:X}}function R(b,A){let C=new Set,L=new Map;for(let{id:X,tagName:G}of b)L.has(X)?C.add(X):L.set(X,G);let F=new Set;for(let{id:X,tagName:G}of A)F.has(X)?C.add(X):L.get(X)===G&&F.add(X);for(let X of C)F.delete(X);return F}return h})(),{normalizeElement:p,normalizeParent:m}=(function(){let h=new WeakSet;function y(k){return k instanceof Document?k.documentElement:k}function x(k){if(k==null)return document.createElement("div");if(typeof k=="string")return x(w(k));if(h.has(k))return k;if(k instanceof Node){if(k.parentNode)return new T(k);{let P=document.createElement("div");return P.append(k),P}}else{let P=document.createElement("div");for(let R of[...k])P.append(R);return P}}class T{constructor(P){this.originalNode=P,this.realParentNode=P.parentNode,this.previousSibling=P.previousSibling,this.nextSibling=P.nextSibling}get childNodes(){let P=[],R=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;R&&R!=this.nextSibling;)P.push(R),R=R.nextSibling;return P}querySelectorAll(P){return this.childNodes.reduce((R,b)=>{if(b instanceof Element){b.matches(P)&&R.push(b);let A=b.querySelectorAll(P);for(let C=0;C<A.length;C++)R.push(A[C])}return R},[])}insertBefore(P,R){return this.realParentNode.insertBefore(P,R)}moveBefore(P,R){return this.realParentNode.moveBefore(P,R)}get __idiomorphRoot(){return this.originalNode}}function w(k){let P=new DOMParser,R=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(R.match(/<\/html>/)||R.match(/<\/head>/)||R.match(/<\/body>/)){let b=P.parseFromString(k,"text/html");if(R.match(/<\/html>/))return h.add(b),b;{let A=b.firstChild;return A&&h.add(A),A}}else{let A=P.parseFromString("<body><template>"+k+"</template></body>","text/html").body.querySelector("template").content;return h.add(A),A}}return{normalizeElement:y,normalizeParent:x}})();return{morph:o,defaults:t}})();var fu=(e,t,o={})=>{let{preserveTypingAnimation:n=!0}=o;jC.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,a){if(r instanceof HTMLElement&&n){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let i=r.textContent??"",d=a.textContent??"";if(i!==d)return}return!1}}}}})};var zC=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var fg={index:-1,draft:""};function KC(e){let{direction:t,history:o,currentValue:n,atStart:r,state:a}=e,i=a.index!==-1;if(o.length===0)return{handled:!1,state:a};if(t==="up"){if(!i&&!r)return{handled:!1,state:a};if(!i){let d=o.length-1;return{handled:!0,value:o[d],state:{index:d,draft:n}}}if(a.index>0){let d=a.index-1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,state:a}}if(!i)return{handled:!1,state:a};if(a.index<o.length-1){let d=a.index+1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function GC(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function XC(){return new Map}function QC(e,t,o){let n=e.get(t);return n&&n.fingerprint===o?n.wrapper:null}function YC(e,t,o,n){e.set(t,{fingerprint:o,wrapper:n})}function JC(e,t){for(let o of e.keys())t.has(o)||e.delete(o)}function ZC(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function eS(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Vn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function qs(e,t){return Vn(e)-e.scrollTop<=t}function tS(e){let{following:t,currentScrollTop:o,lastScrollTop:n,nearBottom:r,userScrollThreshold:a,isAutoScrolling:i=!1,pauseOnUpwardScroll:d=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:u=!1}=e,p=o-n;return i||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:o}:!t&&r&&(!u||p>0)?{action:"resume",delta:p,nextLastScrollTop:o}:t&&d&&p<0?{action:"pause",delta:p,nextLastScrollTop:o}:t&&c&&!r?{action:"pause",delta:p,nextLastScrollTop:o}:{action:"none",delta:p,nextLastScrollTop:o}}function oS(e){let{following:t,deltaY:o,nearBottom:n=!1,resumeWhenNearBottom:r=!1}=e;return t&&o<0?"pause":!t&&r&&o>0&&n?"resume":"none"}function nS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function mg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),o=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:o}}function rS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var El={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},jP=["pre","code","a","script","style"],mu=e=>({type:e?.type??El.type,placeholder:e?.placeholder??El.placeholder,speed:e?.speed??El.speed,duration:e?.duration??El.duration,buffer:e?.buffer??El.buffer}),aS=[{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"}],Pl=new Map;for(let e of aS)Pl.set(e.name,e);var iS=["wipe","glyph-cycle"],Ga=e=>{Pl.set(e.name,e)},yg=e=>{aS.some(t=>t.name===e)||Pl.delete(e)},bg=()=>Array.from(Pl.keys()),kl=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Pl.get(e)??null,gu=(e,t,o,n,r)=>{if(!r)return e;if(o?.bufferContent)return o.bufferContent(e,n);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
29
+ `);return a<0?"":e.slice(0,a)}return e},zP=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${o}-${n}`,r.style.setProperty("--char-index",String(n)),r.textContent=t,r},KP=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${o}-${n}`,r.style.setProperty("--word-index",String(n)),r.textContent=t,r},gg=/\s/,GP=(e,t)=>{let o=e.parentNode;for(;o;){if(o.nodeType===1){let n=o;if(t.has(n.tagName.toLowerCase()))return!0}o=o.parentNode}return!1},XP=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=0;for(;d<a.length;)if(gg.test(a[d])){let c=d;for(;c<a.length&&gg.test(a[c]);)c+=1;i.appendChild(n.createTextNode(a.slice(d,c))),d=c}else{let c=n.createElement("span");c.className="persona-stream-word-group";let u=d;for(;u<a.length&&!gg.test(a[u]);)c.appendChild(zP(n,a[u],t,o.value)),o.value+=1,u+=1;i.appendChild(c),d=u}r.replaceChild(i,e)},QP=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=a.split(/(\s+)/);for(let c of d)c&&(/^\s+$/.test(c)?i.appendChild(n.createTextNode(c)):(i.appendChild(KP(n,c,t,o.value)),o.value+=1));r.replaceChild(i,e)},Ll=(e,t,o,n)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let a=new Set((n?.skipTags??jP).map(m=>m.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),d=[],c=i.nextNode();for(;c;)GP(c,a)||d.push(c),c=i.nextNode();let u={value:n?.startIndex??0},p=t==="char"?XP:QP;for(let m of d)p(m,o,u);return r.innerHTML},hu=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Il=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let o=e.createElement("div");return o.className="persona-stream-skeleton-line",t.appendChild(o),t},sS=new WeakMap,YP=(e,t)=>{if(!e.styles)return;let o=sS.get(t);if(o||(o=new Set,sS.set(t,o)),o.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;o.delete(e.name)}o.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},hg=new WeakMap,JP=(e,t)=>{if(!e.onAttach)return;let o=hg.get(t);if(o||(o=new Map,hg.set(t,o)),o.has(e.name))return;let n=e.onAttach(t);o.set(e.name,n)},lS=e=>{let t=hg.get(e);if(t){for(let o of t.values())typeof o=="function"&&o();t.clear()}},Rl=(e,t)=>{YP(e,t),JP(e,t)};var{setLoader:ZP,load:ek}=mt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),dS=ZP,cS=ek;function vg(e,t=so){let o=e.style.position,n=e.style.zIndex,r=e.style.isolation,a=getComputedStyle(e),i=a.position==="static"||a.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=o),e.style.zIndex=n,e.style.isolation=r}}var Hl=0,Xr=null;function xg(e=document){if(Hl++,Hl===1){let o=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Xr={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:r},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${r}px`,o.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Hl=Math.max(0,Hl-1),Hl===0&&Xr)){let o=e.body,n=e.defaultView??window;o.style.overflow=Xr.originalOverflow,o.style.position=Xr.originalPosition,o.style.top=Xr.originalTop,o.style.width=Xr.originalWidth,n.scrollTo(0,Xr.scrollY),Xr=null}}}var Wl={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},St=e=>(e?.launcher?.mountMode??"floating")==="docked",Qr=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Wo=e=>{let t=e?.launcher?.dock;return{side:t?.side??Wl.side,width:t?.width??Wl.width,animate:t?.animate??Wl.animate,reveal:t?.reveal??Wl.reveal,maxHeight:t?.maxHeight??Wl.maxHeight}};var Cg=e=>e==="followUp"?"follow-up":e,Sg=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let o=e.label.trim();if(!o)return null;let n=e.prompt?.trim()||o;return{id:e.id?.trim()||n||`suggestion-${t}`,label:o,prompt:n,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},tk=e=>{switch(e){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'}},uS=new WeakSet,ok=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,nk=e=>{ok()||e.forEach((t,o)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:o*60,easing:"ease-out",fill:"backwards"})})},wg=e=>{var R,b,A;let{item:t,index:o,surface:n,source:r,variant:a,streaming:i,config:d,plugins:c,chipsConfig:u,session:p,getTextarea:m,eventTarget:h,submitPrompt:y}=e,x=n==="followUp",T=t.behavior,w=()=>{if(p.isStreaming())return;let C={suggestion:{...t},surface:n,source:r,behavior:T},L=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:C,bubbles:!0,composed:!0,cancelable:!0}));if(x&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!L)return;for(let X of c)if(X.onSuggestionSelect?.({suggestion:{...t},surface:n,source:r,variant:a,config:d})===!1)return;let F=m();if(T==="fill"){F.value=t.prompt,F.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),F.focus();return}if(y){y(t.prompt);return}F.value="",p.sendMessage(t.prompt)},k=()=>{let C=I("button",`persona-suggestion persona-suggestion--${a}`);if(C.type="button",C.disabled=i,C.dataset.suggestionId=t.id,C.dataset.emphasis=t.emphasis,C.dataset.behavior=T,a==="chip"&&(u?.fontFamily&&(C.style.fontFamily=tk(u.fontFamily)),u?.fontWeight&&(C.style.fontWeight=u.fontWeight),u?.paddingX&&(C.style.paddingLeft=u.paddingX,C.style.paddingRight=u.paddingX),u?.paddingY&&(C.style.paddingTop=u.paddingY,C.style.paddingBottom=u.paddingY)),t.icon){let F=ce(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);F&&(F.classList.add("persona-suggestion__icon"),t.iconColor&&(F.style.color=t.iconColor),C.appendChild(F))}let L=I("span","persona-suggestion__copy");if(L.appendChild(Y("span",{className:"persona-suggestion__label",text:t.label})),t.description&&a!=="chip"&&L.appendChild(Y("span",{className:"persona-suggestion__description",text:t.description})),C.appendChild(L),a!=="chip"){let F=Ft(ul,16,"currentColor",1.8);F&&(F.classList.add("persona-suggestion__arrow"),C.appendChild(F))}return C.addEventListener("click",w),C},P=null;for(let C of c)if(C.renderSuggestion&&(P=C.renderSuggestion({suggestion:{...t},index:o,surface:n,source:r,variant:a,streaming:i,config:d,defaultRenderer:k,select:w}),P))break;return P??(P=k()),(R=P.dataset).suggestionId||(R.suggestionId=t.id),(b=P.dataset).behavior||(b.behavior=T),(A=P.dataset).emphasis||(A.emphasis=t.emphasis),P instanceof HTMLButtonElement||P.setAttribute("aria-disabled",i?"true":"false"),P},Bl=e=>{let t=[],o=[],n=null,r=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){a();return}let p=Math.max(0,e.scrollWidth-e.clientWidth);if(p<=1){a();return}let m=getComputedStyle(e).direction==="rtl",h=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),y=4,x=h<=y,T=h>=p-y,w=m?!T:!x,k=m?!x:!T;e.toggleAttribute("data-scroll-left",w),e.toggleAttribute("data-scroll-right",k)},d=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",d,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(d):null;return c?.observe(e),{buttons:t,elements:o,destroy:()=>{e.removeEventListener("scroll",d),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,m,h,y,x,T)=>{e.replaceChildren(),t.length=0,o.length=0;let w=T?.source??"config",k=T?.surface??(w==="config"?"starter":"followUp"),P=k==="followUp",R=T?.variant??"chip",b=T?.behavior??"send",A=T?.overflow??"wrap",C=T?.config??{},L=T?.plugins??[],F=typeof T?.maxItems=="number"?Math.max(0,Math.floor(T.maxItems)):void 0,X=P?"followUps":"starters";!uS.has(C)&&C.debug===!0&&R!=="chip"&&C.suggestions?.[X]?.overflow!==void 0&&(uS.add(C),console.info(`[persona] suggestions.${X}.overflow applies to the "chip" variant only; the "${R}" variant manages its own stacking.`));let G=Q=>Q.map(Sg).filter(de=>de!==null).map(de=>({...de,behavior:de.behavior??b})),E=G(p??[]);L.forEach(Q=>{Q.transformSuggestions&&(E=G(Q.transformSuggestions({suggestions:E.map(de=>({...de})),surface:k,source:w,config:C})))});let O=F===void 0?E:E.slice(0,F);if(!O.length){e.hidden=!0,n=null,a();return}if(!P&&(y??m.getMessages()).some(de=>de.role==="user")){e.hidden=!0,n=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Cg(k),e.dataset.variant=R,e.dataset.overflow=A;let D=document.createDocumentFragment(),W=m.isStreaming();O.forEach((Q,de)=>{let pe=wg({item:Q,index:de,surface:k,source:w,variant:R,streaming:W,config:C,plugins:L,chipsConfig:x,session:m,getTextarea:()=>h,eventTarget:e,submitPrompt:T?.submitPrompt});D.appendChild(pe),o.push(pe),[...pe instanceof HTMLButtonElement?[pe]:[],...Array.from(pe.querySelectorAll("button"))].forEach(Ee=>{t.includes(Ee)||(Ee.disabled=W,t.push(Ee))})}),e.appendChild(D),i(),d();let te=JSON.stringify({normalized:O,surface:k,variant:R,source:w});te!==n&&(n=te,nk(o),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:O.map(Q=>({...Q})),surface:k,source:w,variant:R},bubbles:!0,composed:!0})),P&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:O.map(Q=>Q.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"};var rk="persona-header-control",sk="persona-header-control--glyph",ak="persona-header-control--sparse",ik=20,lk={x:[1.4,1.05]},pS="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",dk="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yu=(e,t,o={})=>{let{iconSize:n,iconText:r}=o,[a,i]=lk[t]??[1,1.5],d=!n;e.classList.toggle(sk,d),e.classList.toggle(ak,d&&a!==1);let c=parseFloat(n??"")||ik,u=ce(t,`${Math.round(c*a)}px`,"currentColor",i);u?(u.style.display="block",d||(u.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(u)):r&&(e.textContent=r)},$s=e=>{let{ariaLabel:t,tooltip:o=!0,tooltipHint:n,iconName:r,iconText:a,wrapperClassName:i=pS,size:d,iconSize:c,color:u,backgroundColor:p,borderWidth:m,borderColor:h,borderRadius:y,paddingX:x,paddingY:T,hidden:w,extraClassName:k,attrs:P}=e,R=I("div",i),b=!!(m||h),A=Y("button",{className:bo(rk,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!b&&"persona-border-none",!y&&"persona-rounded-full",k),attrs:{type:"button","aria-label":t,...P},style:{width:d,height:d,minWidth:d,minHeight:d,display:w?"none":void 0,color:u||Co.actionIconColor,backgroundColor:p,border:b?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:y,paddingLeft:x,paddingRight:x,paddingTop:T,paddingBottom:T}});return r?yu(A,r,{iconSize:c,iconText:a}):a&&(A.textContent=a),R.appendChild(A),eo({anchor:A,trigger:R,text:()=>A.getAttribute("aria-label")??t,hint:n,enabled:o}),{button:A,wrapper:R}},Xa=(e,t={})=>{let{showClose:o=!0,wrapperClassName:n=pS,buttonSize:r,iconSize:a}=t,i=e?.launcher??{},d=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:u,wrapper:p}=$s({ariaLabel:d,tooltip:c,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:n,size:r??i.closeButtonSize,iconSize:a,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!o});return{button:u,wrapper:p}},Qa=(e,t={})=>{let{wrapperClassName:o=dk,buttonSize:n,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},d=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:u,wrapper:p}=$s({ariaLabel:d,tooltip:c,iconName:i.iconName??"refresh-cw",wrapperClassName:o,size:n??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:u,wrapper:p}};var Co={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)"},Ag={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)"},ck={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)"},mr=e=>{let{config:t,showClose:o=!0}=e,n=Y("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:Co.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=t?.launcher??{},a=r.headerIconSize??"48px",i=r.closeButtonPlacement??"inline",d=r.headerIconHidden??!1,c=r.headerIconName,u=Y("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!d)if(c){let A=parseFloat(a)||24,C=ce(c,A*.6,"currentColor",1);C?u.replaceChildren(C):u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let A=I("img");A.src=t.launcher.iconUrl,A.alt="",A.className="persona-rounded-xl persona-object-cover",A.style.height=a,A.style.width=a,u.replaceChildren(A)}else u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=I("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Y("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Co.titleColor,...Ag}}),h=Y("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Co.subtitleColor,...ck}});p.append(m,h),d?n.append(p):n.append(u,p);let y=r.clearChat??{},x=y.enabled??!0,T=y.placement??"inline",w=null,k=null;if(x){let C=Qa(t,{wrapperClassName:T==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});w=C.button,k=C.wrapper,T==="top-right"&&(k.style.right="48px"),T==="inline"&&n.appendChild(k)}let P=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&T==="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:R,wrapper:b}=Xa(t,{showClose:o,wrapperClassName:P});return i!=="top-right"&&n.appendChild(b),{header:n,iconHolder:u,headerTitle:m,headerSubtitle:h,closeButton:R,closeButtonWrapper:b,clearChatButton:w,clearChatButtonWrapper:k}},Vs=(e,t,o)=>{let n=o?.launcher??{},r=n.closeButtonPlacement??"inline",a=n.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function js(e){let{items:t,onSelect:o,anchor:n,position:r="bottom-left",portal:a,onOpenChange:i}=e,d=I("div","persona-dropdown-menu persona-hidden");d.setAttribute("role","menu"),d.setAttribute("data-persona-theme-zone","dropdown"),a?(d.style.position="fixed",d.style.zIndex=String($a)):(d.style.position="absolute",d.style.top="100%",d.style.marginTop="4px",r==="bottom-right"?d.style.right="0":d.style.left="0");for(let x of t){if(x.dividerBefore){let k=document.createElement("hr");d.appendChild(k)}let T=document.createElement("button");if(T.type="button",T.setAttribute("role","menuitem"),T.setAttribute("data-dropdown-item-id",x.id),x.destructive&&T.setAttribute("data-destructive",""),x.icon){let k=ce(x.icon,16,"currentColor",1.5);k&&T.appendChild(k)}let w=document.createElement("span");w.textContent=x.label,T.appendChild(w),T.addEventListener("click",k=>{k.stopPropagation(),m(),o(x.id)}),d.appendChild(T)}let c=null;function u(){if(!a)return;let x=n.getBoundingClientRect();d.style.top=`${x.bottom+4}px`,r==="bottom-right"?(d.style.right=`${window.innerWidth-x.right}px`,d.style.left="auto"):(d.style.left=`${x.left}px`,d.style.right="auto")}function p(){let x=d.classList.contains("persona-hidden");u(),d.classList.remove("persona-hidden"),x&&i?.(!0),requestAnimationFrame(()=>{let T=w=>{!d.contains(w.target)&&!n.contains(w.target)&&m()};document.addEventListener("click",T,!0),c=()=>document.removeEventListener("click",T,!0)})}function m(){let x=!d.classList.contains("persona-hidden");d.classList.add("persona-hidden"),c?.(),c=null,x&&i?.(!1)}function h(){d.classList.contains("persona-hidden")?p():m()}function y(){m(),d.remove()}return a&&a.appendChild(d),{element:d,show:p,hide:m,toggle:h,destroy:y}}function zs(e){let{icon:t,label:o,size:n,strokeWidth:r,className:a,chromeless:i,onClick:d,aria:c}=e,u=I("button",bo(!i&&"persona-icon-btn",a));u.type="button",u.setAttribute("aria-label",o),u.title=o;let p=ce(t,n??16,"currentColor",r??2);if(p&&u.appendChild(p),d&&u.addEventListener("click",d),c)for(let[m,h]of Object.entries(c))u.setAttribute(m,h);return u}function Mg(e){let{icon:t,label:o,variant:n="default",size:r="sm",iconSize:a,className:i,onClick:d,aria:c}=e,u="persona-label-btn";n!=="default"&&(u+=" persona-label-btn--"+n),u+=" persona-label-btn--"+r,i&&(u+=" "+i);let p=I("button",u);if(p.type="button",p.setAttribute("aria-label",o),t){let h=ce(t,a??14,"currentColor",2);h&&p.appendChild(h)}let m=I("span");if(m.textContent=o,p.appendChild(m),d&&p.addEventListener("click",d),c)for(let[h,y]of Object.entries(c))p.setAttribute(h,y);return p}function fS(e){let{items:t,selectedId:o,onSelect:n,className:r}=e,a=I("div","persona-toggle-group"+(r?" "+r:""));a.setAttribute("role","group");let i=o,d=[];function c(){for(let p of d)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let m;p.icon?m=zs({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,c(),n(p.id)}}):(m=I("button","persona-icon-btn"+(p.className?" "+p.className:"")),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{i=p.id,c(),n(p.id)})),m.setAttribute("aria-pressed",p.id===i?"true":"false"),d.push({id:p.id,btn:m}),a.appendChild(m)}function u(p){i=p,c()}return{element:a,setSelected:u}}function mS(e){let{label:t,icon:o,iconSize:n,iconOnly:r,menuItems:a,onSelect:i,onPrimary:d,position:c="bottom-left",portal:u,chevronLabel:p="More options",chevronIconSize:m,className:h,primaryClassName:y,chevronClassName:x}=e,T=I("div","persona-split-btn"+(h?" "+h:"")),w={label:t,className:"persona-split-btn-primary"+(y?" "+y:""),onClick:d},k=r&&o?zs({...w,icon:o,size:n??14}):Mg({...w,icon:o,iconSize:n??14}),P=zs({icon:"chevron-down",label:p,size:m??14,className:"persona-split-btn-chevron"+(x?" "+x:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});T.append(k,P);let R=null,b=()=>{if(R)return R;let A=(typeof u=="function"?u():u)??void 0;return R=js({items:a,onSelect:i,anchor:T,position:c,portal:A,onOpenChange:C=>{P.setAttribute("aria-expanded",C?"true":"false")}}),A||T.appendChild(R.element),R};return T.isConnected?b():requestAnimationFrame(()=>{R||b()}),P.addEventListener("click",A=>{A.stopPropagation(),b().toggle()}),{element:T,primaryButton:k,chevronButton:P,openMenu:()=>b().show(),closeMenu:()=>R?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{R?.destroy(),T.remove()}}}function bu(e){let{label:t,icon:o="chevron-down",menuItems:n,onSelect:r,position:a="bottom-left",portal:i,className:d,hover:c}=e,u=I("div","persona-combo-btn"+(d?" "+d:""));u.style.position="relative",u.style.display="inline-flex",u.style.alignItems="center",u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0"),u.setAttribute("aria-haspopup","true"),u.setAttribute("aria-expanded","false"),u.setAttribute("aria-label",t);let p=I("span","persona-combo-btn-label");p.textContent=t,u.appendChild(p);let m=ce(o,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",u.appendChild(m)),c&&(u.style.borderRadius=c.borderRadius??"10px",u.style.padding=c.padding??"6px 4px 6px 12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=c.background??"",u.style.borderColor=c.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}));let h=js({items:n,onSelect:x=>{u.setAttribute("aria-expanded","false"),r(x)},anchor:u,position:a,portal:i});i||u.appendChild(h.element);let y=()=>u.getAttribute("data-persona-menu-locked")==="true";return u.addEventListener("click",x=>{if(x.stopPropagation(),y())return;let T=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",T?"false":"true"),h.toggle()}),u.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),u.click())}),{element:u,setLabel:x=>{p.textContent=x,u.setAttribute("aria-label",x)},open:()=>{u.setAttribute("aria-expanded","true"),h.show()},close:()=>{u.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let x=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",x?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),u.remove()}}}var Tg=e=>{let t=mr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),o=e.layoutHeaderConfig?.onTitleClick;if(o){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>o()),n.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),o())}))}return t};function uk(e,t,o){if(t?.length)for(let n of t){let{button:r,wrapper:a}=$s({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?pu(n.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",n.id),n.shortcut){let i=Tl(n.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(n.menuItems?.length){let i=js({items:n.menuItems,onSelect:d=>o?.(d),anchor:a,position:"bottom-right"});a.appendChild(i.element),r.addEventListener("click",d=>{d.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>o?.(n.id));e.appendChild(a)}}var Eg=e=>{let{config:t,showClose:o=!0,onClose:n,layoutHeaderConfig:r,onHeaderAction:a}=e,i=t?.launcher??{},d=I("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");d.setAttribute("data-persona-theme-zone","header"),d.style.minHeight=Co.minHeight,d.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",d.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",d.style.boxShadow="var(--persona-header-shadow, none)",d.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=r?.titleMenu,u,p;if(c){let b=bu({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:A=>{let C=F=>{F===!1&&b.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:A}}))},L=c.onSelect(A);L instanceof Promise?L.then(C,()=>{}):C(L)},hover:c.hover,className:""});u=b.element,u.style.color=Co.titleColor,p=u.querySelector(".persona-combo-btn-label")??u}else{if(u=I("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=I("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Co.titleColor,Object.assign(p.style,Ag),p.textContent=i.title??"Chat Assistant",u.appendChild(p),r?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let A=r.onTitleClick;u.addEventListener("click",C=>{C.target.closest("button")||A()}),u.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),A())})}let b=r?.titleRowHover;b&&(u.style.borderRadius=b.borderRadius??"10px",u.style.padding=b.padding??"6px 4px 6px 12px",u.style.margin="-6px 0 -6px -12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.style.width="fit-content",u.style.flex="none",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=b.background??"",u.style.borderColor=b.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}))}d.appendChild(u);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:y}=Xa(t,{showClose:o,wrapperClassName:m});n&&h.addEventListener("click",n);let x=I("div","persona-flex persona-items-center persona-gap-1");c||uk(x,r?.trailingActions,r?.onAction??a);let T=i.clearChat??{},w=null,k=null;if(T.enabled??!0){let b=T.placement??"inline",A=Qa(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});w=A.button,k=A.wrapper,b==="top-right"?k.style.right="48px":x.appendChild(k)}x.appendChild(y),d.appendChild(x);let P=I("div");P.style.display="none";let R=I("span");return R.style.display="none",{header:d,iconHolder:P,headerTitle:p,headerSubtitle:R,closeButton:h,closeButtonWrapper:y,clearChatButton:w,clearChatButtonWrapper:k}},vu={default:Tg,minimal:Eg},Pg=e=>vu[e]??vu.default,Ya=(e,t,o)=>{if(t?.render){let i=t.render({config:e,onClose:o?.onClose,onClearChat:o?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),d=I("div");d.style.display="none";let c=I("span"),u=I("span"),p=I("button");p.style.display="none";let m=I("div");return m.style.display="none",{header:i,iconHolder:d,headerTitle:c,headerSubtitle:u,closeButton:p,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let n=t?.layout??"default",a=Pg(n)({config:e,showClose:t?.showCloseButton??o?.showClose??!0,onClose:o?.onClose,onClearChat:o?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var Ks=e=>{let{config:t}=e,o=Y("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),n=Zc(),r=Y("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:a,attachAutoResize:i}=Xc(t);i();let d=Qc(t),c=za(t),u=Yc(t),p=Jc(t),m=Y("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),u&&(u.previewsContainer.style.gap="8px",m.append(u.previewsContainer),r.append(u.input)),r.append(a);let h=Y("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=Y("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),x=Y("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return u&&y.append(u.wrapper),c&&x.append(c.wrapper),x.append(d.wrapper),h.append(y,x),r.append(h),r.addEventListener("click",T=>{T.target!==d.button&&T.target!==d.wrapper&&T.target!==c?.button&&T.target!==c?.wrapper&&T.target!==u?.button&&T.target!==u?.wrapper&&a.focus()}),o.append(n,r,p),{footer:o,suggestions:n,composerForm:r,header:m,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:p,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:h,leftActions:y,rightActions:x,setSendButtonMode:d.setMode}};var gS=()=>{let e=Y("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=I("span","persona-pill-peek__icon"),o=Ft(hl,16,"currentColor",1.5);o&&t.appendChild(o);let n=I("span","persona-pill-peek__text"),r=I("span","persona-pill-peek__caret"),a=Ft(_s,16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,n,r),{root:e,textNode:n}},xu=e=>{let{config:t}=e,o=Y("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=Zc(),r=Jc(t);r.style.display="none";let{textarea:a,attachAutoResize:i}=Xc(t,{defaultMaxLines:5});i();let d=Qc(t),c=za(t),u=Yc(t);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let p=Y("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=Y("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});u&&m.append(u.wrapper);let h=Y("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&h.append(c.wrapper),h.append(d.wrapper),p.addEventListener("click",T=>{T.target!==d.button&&T.target!==d.wrapper&&T.target!==c?.button&&T.target!==c?.wrapper&&T.target!==u?.button&&T.target!==u?.wrapper&&a.focus()}),u&&p.append(u.input),p.append(m,a,h);let y=Y("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});o.append(y),u&&y.append(u.previewsContainer),o.append(n,p,r);let x=p;return{footer:o,suggestions:n,composerForm:p,header:y,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:x,leftActions:m,rightActions:h,setSendButtonMode:d.setMode}};var pk=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},fk=(e,t)=>{if(!e)return null;let o=pk(e);if(o===null)return null;let n=t?.[e],r=n!==void 0?n:o;return r||null},mk=(e,t)=>{let o=I("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return o.setAttribute("data-stop-reason",e),o.setAttribute("role","note"),o.style.opacity="0.75",o.textContent=t,o},gk=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Lg=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Ig=320,xS=320,hk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),yk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),bk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),vk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),xk=e=>{if(!e||e.length===0)return null;let t=Y("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let o of e){let n=Y("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:o.label}}),r=I("span","persona-mention-chip-icon"),a=ce(o.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),n.appendChild(r),n.appendChild(Y("span",{className:"persona-mention-chip-label",text:o.label})),t.appendChild(n)}return t},Ck=(e,t)=>{let o=document.createDocumentFragment();for(let n of e){if(n.kind==="text"){o.appendChild(document.createTextNode(n.text));continue}o.appendChild(Sl(n.ref,{readonly:!0,render:t}))}return o},hS="\uE000",yS="\uE001",Sk=(e,t,o,n)=>{let r=Math.random().toString(36).slice(2,8),a=h=>`${hS}${r}:${h}${yS}`,i=t.map((h,y)=>h.kind==="text"?h.text:a(y)).join(""),d=o(i);if(!t.every((h,y)=>h.kind==="text"||d.includes(a(y)))){e.replaceChildren(Ck(t,n));return}e.innerHTML=d;let u=new RegExp(`${hS}${r}:(\\d+)${yS}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let h=p.nextNode();h;h=p.nextNode())m.push(h);for(let h of m){let y=h;for(let x=u.exec(y.data);x;x=u.exec(y.data)){let T=t[Number(x[1])],w=y.splitText(x.index);w.data=w.data.slice(x[0].length),T?.kind==="mention"&&w.parentNode?.insertBefore(Sl(T.ref,{readonly:!0,render:n}),w),y=w}}},wk=(e,t,o)=>{if(e.length===0)return null;try{let n=I("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let r=0,a=!1,i=()=>{a||(a=!0,n.remove(),o?.())};return e.forEach((d,c)=>{let u=I("img");u.alt=d.alt?.trim()||`Attached image ${c+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${Ig}px`,u.style.maxHeight=`${xS}px`,u.style.height="auto",u.style.objectFit="contain",u.style.borderRadius="10px",u.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",u.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,u.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),u.remove(),r===0&&i())}),u.addEventListener("load",()=>{p=!0}),gk(d.image)?(u.src=d.image,n.appendChild(u)):(p=!0,r=Math.max(0,r-1),u.remove())}),r===0?(i(),null):n}catch{return o?.(),null}},Ak=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let o=0;return e.forEach(n=>{if(!Lg(n.audio))return;let r=I("audio");r.controls=!0,r.preload="metadata",r.src=n.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Ig}px`,t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},Mk=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let o=0;return e.forEach(n=>{if(!Lg(n.video))return;let r=I("video");r.controls=!0,r.preload="metadata",r.src=n.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Ig}px`,r.style.maxHeight=`${xS}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},Tk=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let o=0;return e.forEach(n=>{if(!Lg(n.data))return;let r=I("a");r.href=n.data,r.download=n.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=n.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",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},Gs=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let 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="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(o),e.appendChild(n),e.appendChild(r),e},Rg=(e,t,o)=>{let n={config:o??{},streaming:!0,location:e,defaultRenderer:Gs};if(t){let r=t(n);if(r!==null)return r}return Gs()},Ek=(e,t)=>{let o=I("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=t==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let r=I("img");r.src=n,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",o.appendChild(r)}else o.textContent=n,o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else o.textContent=t==="user"?"U":"A",o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return o},bS=(e,t,o="div")=>{let n=I(o,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Ol=(e,t="bubble")=>{let o=["persona-message-bubble"];switch(t){case"flat":e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):o.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":o.push("persona-text-sm","persona-leading-relaxed"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):o.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:o.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):o.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 o},vS={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"}},Pk=(e,t,o="bubble",n)=>{if(!n)return;let r=t==="user"?"user":"assistant",a=vS[o??"bubble"]??vS.bubble;n.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${a.padding})`),n.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${a.fontSize})`),n.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${a.lineHeight})`),n.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},Cu="custom:",kk=e=>`${Cu}${e}`,CS=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(o=>(o.roles??["assistant"]).includes(t)),Hg=(e,t,o,n)=>{let r=t.showCopy??!0,a=t.showUpvote??!0,i=t.showDownvote??!0,d=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&n?.canRegenerate===!0,u=(t.showEdit??!1)&&n?.canEdit===!0,p=(t.showQuote??!1)&&n?.canQuote!==!1,m=CS(t,e.role);if(!r&&!a&&!i&&!d&&!c&&!u&&!p&&m.length===0){let R=I("div");return R.style.display="none",R.id=`actions-${e.id}`,R.setAttribute("data-actions-for",e.id),R}let h=t.visibility??"hover",y=t.align??"right",x=t.layout??"pill-inside",T={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[y],w={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[x],k=I("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${T} ${w} ${h==="hover"?"persona-message-actions-hover":""}`);k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id);let P=(R,b,A)=>{let C=zs({icon:R,label:b,size:14,className:"persona-message-action-btn",chromeless:!0});return C.setAttribute("data-action",A),C};r&&k.appendChild(P("copy","Copy message","copy")),d&&k.appendChild(P("volume-2","Read aloud","read-aloud")),a&&k.appendChild(P("thumbs-up","Upvote","upvote")),i&&k.appendChild(P("thumbs-down","Downvote","downvote")),c&&k.appendChild(P("refresh-cw","Regenerate response","regenerate")),u&&k.appendChild(P("pencil","Edit message","edit")),p&&k.appendChild(P("quote","Quote message","quote"));for(let R of m)k.appendChild(P(R.iconName??"ellipsis",R.label,kk(R.id)));return k},Ja=(e,t,o,n,r,a)=>{let i=o??{},d=i.layout??"bubble",c=i.avatar,u=i.timestamp,p=c?.show??!1,m=u?.show??!1,h=c?.position??"left",y=u?.position??"below",x=Ol(e.role,d),T=I("div",x.join(" "));T.id=`bubble-${e.id}`,T.setAttribute("data-message-id",e.id),T.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let w=a?.widgetConfig?.theme?.components?.message;Pk(T,e.role,d,e.role==="user"?w?.user:w?.assistant),d==="flat"?(T.style.backgroundColor="transparent",T.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(T.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",T.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(T.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",T.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=hk(e),P=e.content?.trim()??"",b=k.length>0&&P===Ba,A=mu(a?.widgetConfig?.features?.streamAnimation),C=a?.widgetConfig?.features?.streamAnimation?.plugins,L=e.role==="assistant"&&A.type!=="none"?kl(A.type,C):null,F=e.role==="assistant"&&L?.isAnimating?.(e)===!0,X=e.role==="assistant"&&L!==null&&(!!e.streaming||F);X&&L?.bubbleClass&&T.classList.add(L.bubbleClass);let G=document.createElement("div");G.classList.add("persona-message-content"),e.streaming&&G.classList.add("persona-content-streaming"),X&&L&&(L.containerClass&&G.classList.add(L.containerClass),G.style.setProperty("--persona-stream-step",`${A.speed}ms`),G.style.setProperty("--persona-stream-duration",`${A.duration}ms`));let E=X?gu(e.content??"",A.buffer,L,e,!!e.streaming):e.content??"",O=()=>{let Le=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent});return X&&L?.wrap==="char"?Ll(Le,"char",e.id,{skipTags:L.skipTags}):X&&L?.wrap==="word"?Ll(Le,"word",e.id,{skipTags:L.skipTags}):Le},D=null;if(b?(D=document.createElement("div"),D.innerHTML=O(),D.style.display="none",G.appendChild(D)):e.contentSegments?.length?Sk(G,e.contentSegments,Le=>t({text:Le,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):G.innerHTML=O(),X&&L?.useCaret&&!b&&P){let Le=hu(),j=G.querySelectorAll(".persona-stream-char, .persona-stream-word"),qe=j[j.length-1];if(qe?.parentNode)qe.parentNode.insertBefore(Le,qe.nextSibling);else{let Ge=G.lastElementChild;Ge?Ge.appendChild(Le):G.appendChild(Le)}}if(m&&y==="inline"&&e.createdAt){let Le=bS(e,u,"span");Le.classList.add("persona-timestamp-inline");let j=G.lastElementChild;j?j.appendChild(Le):G.appendChild(Le)}if(k.length>0){let Le=wk(k,!b&&!!P,()=>{b&&D&&(D.style.display="")});Le?T.appendChild(Le):b&&D&&(D.style.display="")}let W=yk(e);if(W.length>0){let Le=Ak(W);Le&&T.appendChild(Le)}let te=bk(e);if(te.length>0){let Le=Mk(te);Le&&T.appendChild(Le)}let Q=vk(e);if(Q.length>0){let Le=Tk(Q);Le&&T.appendChild(Le)}let de=e.contentSegments?.length?null:xk(e.contextMentions);if(de&&T.appendChild(de),T.appendChild(G),m&&y==="below"&&e.createdAt){let Le=bS(e,u);Le.classList.add("persona-mt-1"),T.appendChild(Le)}let pe=e.role==="assistant"?fk(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Le=!!(E&&E.trim()),j=A.placeholder==="skeleton",qe=j&&A.buffer==="line"&&Le;if(Le)qe&&T.appendChild(Il());else if(j)T.appendChild(Il());else{let Ge=Rg("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);Ge&&T.appendChild(Ge)}}pe&&e.stopReason&&!e.streaming&&(P||(G.style.display="none"),T.appendChild(mk(e.stopReason,pe)));let Ce=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&n?.enabled!==!1,Ee=a?.actionEligibility,ge=e.role==="user"&&!e.streaming&&n?.enabled!==!1&&(n?.showEdit===!0&&Ee?.canEdit===!0||n?.showQuote===!0&&Ee?.canQuote===!0||CS(n,"user").length>0);if((Ce||ge)&&n){let Le=Hg(e,ge?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,r,Ee);T.appendChild(Le)}if(!p||e.role==="system")return T;let Ke=I("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Bt=Ek(c,e.role);return h==="right"||h==="left"&&e.role==="user"?Ke.append(T,Bt):Ke.append(Bt,T),Ke},SS=(e,t,o,n,r,a)=>{let i=o??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ja(e,t,o,n,r,a)};var Lk=40,Ik=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let o=null;try{o=t()}catch(n){console.warn("[persona] welcome.icon renderer threw",n)}if(!o){e.hidden=!0;return}e.appendChild(o),e.hidden=!1;return}if(t.type==="lucide"){let o=ce(t.name,Lk);if(!o){e.hidden=!0;return}e.appendChild(o)}else t.type==="image"?e.appendChild(Y("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Y("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},wS=(e,t,o={})=>{let n=Y("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});n.hidden=!0;let r=I("p","persona-welcome-kicker");r.hidden=!0;let a=I("h2","persona-welcome-title"),i=I("p","persona-welcome-subtitle"),d=Y("div",{className:"persona-welcome-head-text"},r,a),c=Y("div",{className:"persona-welcome-title-row"},n,d);return{host:Y("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:o.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},c,i,t),iconHolder:n,kicker:r,title:a,subtitle:i,starterSuggestions:t}},Za=(e,t,o)=>{t.hidden=!o,t.style.display=o?"":"none",e.classList.toggle("persona-gap-6",o),e.classList.toggle("persona-gap-3",!o)},wu=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??"",e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",Ik(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss),e.host.setAttribute("data-persona-welcome-anchor",t.anchor??"bottom"),t.iconPlacement==="inline"?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},Rk="data-persona-welcome-plugin",AS="data-persona-welcome-overlay",Su="persona-welcome-overlay-active",Wg=new WeakMap,Bg=(e,t,o)=>{o.setAttribute(Rk,""),t.appendChild(o),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(AS,""),e.classList.contains(Su)||(Wg.set(e,e.scrollTop),e.classList.add(Su),e.scrollTop=0)},Og=(e,t,o)=>{o&&o!==t&&o.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(AS),e.classList.contains(Su)&&(e.classList.remove(Su),e.scrollTop=Wg.get(e)??e.scrollTop,Wg.delete(e))},MS=()=>{let e=Y("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Au=(e,t,o)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let n=o?.layout?.messages?.layout??"bubble",r=Y("div",{className:Ol("assistant",n).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:n==="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))"}});e.appendChild(Y("div",{className:"persona-flex"},r)),e.hidden=!1},TS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,ES=(e,t)=>{if(TS()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let o=e.getBoundingClientRect(),n=e.parentElement,r=0,a=0,i=0;if(n){let x=getComputedStyle(n);r=parseFloat(x.rowGap)||0;let T=e.previousElementSibling,w=e.nextElementSibling,P=n.getBoundingClientRect().top+(parseFloat(x.borderTopWidth)||0)+(parseFloat(x.paddingTop)||0)-n.scrollTop;a=Math.max(0,T?o.top-T.getBoundingClientRect().bottom-r:o.top-P),i=Math.max(0,w?w.getBoundingClientRect().top-o.bottom-r:0)}let d=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),u=parseFloat(c.paddingTop)||0,p=parseFloat(c.paddingBottom)||0,m=e.animate([{opacity:"1",transform:"none",height:`${o.height}px`,minHeight:"0px",paddingTop:`${u}px`,paddingBottom:`${p}px`,marginTop:`${a}px`,marginBottom:`${i}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"}),h=!1,y=()=>{h||(h=!0,e.style.overflow=d,t(m))};return m.finished.then(y).catch(y),m},PS=(e,t,o)=>{if(t<=1||TS()||typeof e.animate!="function"||!e.isConnected)return null;let n=o==="drop"?-t:t;return e.animate([{transform:`translateY(${n}px)`},{transform:"none"}],{duration:260,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var Hk="Hello \u{1F44B}",Wk="I can answer questions and help you get things done here.",kS=new WeakSet,So=(e,t)=>!!e&&e[t]!==void 0,Bk=(e,t)=>{!e||e.debug!==!0||!t.length||kS.has(e)||(kS.add(e),t.forEach(o=>console.warn(`[persona] ${o}`)))},xn=e=>{let t=e?.welcome,o=e?.copy,n=So(t,"variant")?t.variant:o?.showWelcomeCard===!1?"none":"card",r=n==="hero"?"on-first-message":So(t,"dismiss")?t.dismiss:"never",a=[];So(t,"title")&&So(o,"welcomeTitle")&&a.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),So(t,"subtitle")&&So(o,"welcomeSubtitle")&&a.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),So(t,"variant")&&So(o,"showWelcomeCard")&&a.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),n==="hero"&&So(t,"message")&&a.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),n==="hero"&&So(t,"dismiss")&&t.dismiss!=="on-first-message"&&a.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let i=t?.anchor==="center"?"center":"bottom",d=Ml(t?.anchorComposerTop)!==null;return So(t,"anchorComposerTop")&&!d&&a.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),i!=="center"&&(So(t,"anchorComposerTop")||So(t,"composerGap"))&&a.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),Bk(e,a),{title:So(t,"title")?t.title:o?.welcomeTitle??Hk,kicker:t?.kicker??"",subtitle:So(t,"subtitle")?t.subtitle:o?.welcomeSubtitle??Wk,icon:t?.icon,align:t?.align==="start"||t?.align==="center"?t.align:void 0,iconPlacement:t?.icon&&typeof t.icon!="function"&&t.icon.placement==="inline"?"inline":"above",variant:n,dismiss:r,message:n==="hero"?void 0:t?.message,anchor:i,anchorComposerTop:d?t.anchorComposerTop:"44%",composerGap:t?.composerGap?.trim()||du}},LS=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Yr=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(o=>o.role==="user");var IS="16px",_g="10px",Ng="14px",RS=e=>{let t=e?.launcher?.enabled??!0,o=St(e);if(Qr(e)){let p=e?.launcher?.composerBar??{},m=I("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=p.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??so);let h=I("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");h.style.width="100%",m.appendChild(h);let y=I("div","persona-widget-pill-root");return y.setAttribute("data-persona-composer-bar",""),y.dataset.state="collapsed",y.dataset.expandedSize=p.expandedSize??"anchored",y.style.zIndex=String(e?.launcher?.zIndex??so),{wrapper:m,panel:h,pillRoot:y}}if(o){let p=I("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=I("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(m),{wrapper:p,panel:m}}if(!t){let p=I("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=I("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),h=e?.launcher?.width??"100%";return p.style.width=h,m.style.width="100%",p.appendChild(m),{wrapper:p,panel:m}}let r=e?.launcher??{},a=r.position&&Go[r.position]?Go[r.position]:Go["bottom-right"],i=I("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??so);let d=I("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=e?.launcher?.width??e?.launcherWidth??zo;return d.style.width=u,d.style.maxWidth=u,i.appendChild(d),{wrapper:i,panel:d}},Fg=e=>{let t=Y("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Cg(e)}});return t.hidden=!0,t},HS=(e,t)=>{let o=Fg("starter"),n=wS(e,o,{flatShadow:St(e)}),r=xn(e);wu(n,r),Za(t,n.host,Yr(r,e?.initialMessages));let a=MS();return Au(a,r.message,e),{welcome:n,greetingHost:a}},Ok=(e,t)=>{let o=I("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");o.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:r}=Xa(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:IS,iconSize:_g});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let a=e?.launcher?.clearChat?.enabled??!0,i=null,d=null;if(a){let L=Qa(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:IS,iconSize:Ng});i=L.button,d=L.wrapper,d.style.position="absolute",d.style.top="8px",d.style.right="32px",d.style.zIndex="10"}let c=Y("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=Y("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"}});u.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:m}=HS(e,u),{host:h,title:y,subtitle:x}=p,T=p.starterSuggestions,w=I("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),k=Fg("followUp"),P=Gr(e,!0);P&&(w.style.maxWidth=P,w.style.marginLeft="auto",w.style.marginRight="auto",w.style.width="100%"),u.append(h,m,w,k);let R=Y("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"}}),b=xu({config:e}),{root:A,textNode:C}=gS();return o.append(c,r,u,R),d&&o.appendChild(d),{container:o,body:u,messagesWrapper:w,starterSuggestions:T,transcriptSuggestions:k,composerOverlay:R,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:h,welcomeIconHolder:p.iconHolder,greetingHost:m,introKicker:p.kicker,introTitle:y,introSubtitle:x,closeButton:n,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:d,iconHolder:I("span"),headerTitle:I("span"),headerSubtitle:I("span"),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:A,peekTextNode:C}},WS=(e,t=!0)=>{if(Qr(e))return Ok(e,t);let o=Y("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),n=e?.layout?.header,r=e?.layout?.showHeader!==!1,a=n?Ya(e,n,{showClose:t}):mr({config:e,showClose:t}),i=Y("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"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:c}=HS(e,i),{host:u,title:p,subtitle:m}=d,h=d.starterSuggestions,y=I("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),x=Fg("followUp"),T=Gr(e,!1);T&&(y.style.maxWidth=T,y.style.marginLeft="auto",y.style.marginRight="auto",y.style.width="100%"),i.append(u,c,y,x);let w=Ks({config:e}),k=e?.layout?.showFooter!==!1;r?Vs(o,a,e):(a.header.style.display="none",Vs(o,a,e)),o.append(i);let P=Y("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 k||(w.footer.style.display="none"),o.append(w.footer),o.append(P),{container:o,body:i,messagesWrapper:y,starterSuggestions:h,transcriptSuggestions:x,composerOverlay:P,suggestions:w.suggestions,textarea:w.textarea,sendButton:w.sendButton,sendButtonWrapper:w.sendButtonWrapper,micButton:w.micButton,micButtonWrapper:w.micButtonWrapper,composerForm:w.composerForm,statusText:w.statusText,welcomeHost:u,welcomeIconHolder:d.iconHolder,greetingHost:c,introKicker:d.kicker,introTitle:p,introSubtitle:m,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:w.footer,attachmentButton:w.attachmentButton,attachmentButtonWrapper:w.attachmentButtonWrapper,attachmentInput:w.attachmentInput,attachmentPreviewsContainer:w.attachmentPreviewsContainer,actionsRow:w.actionsRow,leftActions:w.leftActions,rightActions:w.rightActions,setSendButtonMode:w.setSendButtonMode}};var Ug=(e,t)=>{let o=I("button");o.type="button",o.innerHTML=`
30
30
  <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>
31
31
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
32
32
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -34,14 +34,14 @@ _Details: ${o.message}_`:n}var Zf=e=>({isError:!0,content:[{type:"text",text:e}]
34
34
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
35
35
  </span>
36
36
  <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>
37
- `,o.addEventListener("click",t);let n=a=>{let i=a.launcher??{},d=St(a),u=o.querySelector("[data-role='launcher-title']");if(u){let R=i.title??"Chat Assistant";u.textContent=R,u.setAttribute("title",R)}let c=o.querySelector("[data-role='launcher-subtitle']");if(c){let R=i.subtitle??"Here to help you get answers fast";c.textContent=R,c.setAttribute("title",R)}let p=o.querySelector(".persona-flex-col");p&&(i.textHidden||d?p.style.display="none":p.style.display="");let m=o.querySelector("[data-role='launcher-icon']");if(m)if(i.agentIconHidden)m.style.display="none";else{let R=i.agentIconSize??"40px";if(m.style.height=R,m.style.width=R,i.agentIconBackgroundColor?(m.style.backgroundColor=i.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",i.agentIconName){let b=parseFloat(R)||24,w=ce(i.agentIconName,b*.6,"var(--persona-text-inverse, #ffffff)",1.5);w?(m.appendChild(w),m.style.display=""):(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}else i.iconUrl?m.style.display="none":(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}let y=o.querySelector("[data-role='launcher-image']");if(y){let R=i.agentIconSize??"40px";y.style.height=R,y.style.width=R,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(y.src=i.iconUrl,y.style.display="block"):y.style.display="none"}let h=o.querySelector("[data-role='launcher-call-to-action-icon']");if(h){let R=i.callToActionIconSize??"32px";h.style.height=R,h.style.width=R,i.callToActionIconBackgroundColor?(h.style.backgroundColor=i.callToActionIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(h.style.color=i.callToActionIconColor,h.classList.remove("persona-text-persona-call-to-action")):(h.style.color="",h.classList.add("persona-text-persona-call-to-action"));let b=0;if(i.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=i.callToActionIconPadding,b=(parseFloat(i.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),i.callToActionIconHidden)h.style.display="none";else if(h.style.display=d?"none":"",h.innerHTML="",i.callToActionIconName){let w=parseFloat(R)||24,x=Math.max(w-b,8),L=ce(i.callToActionIconName,x,"currentColor",1.5);L?h.appendChild(L):h.textContent=i.callToActionIconText??"\u2197"}else h.textContent=i.callToActionIconText??"\u2197"}let S=i.position&&Go[i.position]?Go[i.position]:Go["bottom-right"],A="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",T="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";o.className=d?T:`${A} ${S}`,d||(o.style.zIndex=String(i.zIndex??so));let k="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",P="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";o.style.border=i.border??k,o.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:P,d?(o.style.width="0",o.style.minWidth="0",o.style.maxWidth="0",o.style.padding="0",o.style.overflow="hidden",o.style.border="none",o.style.boxShadow="none"):(o.style.width="",o.style.minWidth="",o.style.maxWidth=i.collapsedMaxWidth??"",o.style.justifyContent="",o.style.padding="",o.style.overflow="")},r=()=>{o.removeEventListener("click",t),o.remove()};return e&&n(e),{element:o,update:n,destroy:r}},IL="teaser-dismissed",RS=new Set,HS=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${IL}`},HL=(e,t)=>{if(RS.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},RL=(e,t)=>{if(RS.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},WL=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,BL=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||St(e??{})?null:t},WS=(e,t)=>{let o=I("div","persona-launcher-surface");o.setAttribute("data-persona-launcher-surface","true");let n=e??{},r=null,a=null,i=null,d=null,u=null,c=!1,p=!1,m=!1,y=!1,h=()=>(r?.frequency??"once")==="once"&&n.persistState!==!1,S=()=>{u!==null&&(clearTimeout(u),u=null)},A=()=>{!a||!c||(c=!1,a.hidden=!0)},T=oe=>{S(),m=!0,A(),RL(HS(n),oe&&h())},k=oe=>{!r||m||T(oe==="user"&&c)},P=()=>{u=null,!(!a||m||y)&&(p=!0,c=!0,a.hidden=!1,!(WL()||typeof a.animate!="function")&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},R=()=>{!r||!a||m||p||y||HL(HS(n),h())||(S(),u=setTimeout(P,Math.max(0,r.delayMs??0)))},b=()=>{T(h()),t()},w=oe=>{oe.stopPropagation(),T(h())},L=_g(e,()=>{k("user"),t()}),F=()=>{S(),d?.removeEventListener("click",b),i?.removeEventListener("click",w),a?.remove(),a=null,d=null,i=null,c=!1},X=()=>{d=Y("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),d.addEventListener("click",b),i=Y("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",w),a=Y("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},d,i),o.insertBefore(a,L.element)},G=()=>{let oe=n.launcher?.position??"bottom-right",Q=Go[oe]??Go["bottom-right"];if(!a){o.className="persona-launcher-surface",o.removeAttribute("data-teaser"),o.style.zIndex="",L.element.style.position="";return}o.className=bo("persona-launcher-surface",Q),o.setAttribute("data-teaser",oe),o.style.zIndex=String(n.launcher?.zIndex??so),L.element.style.position="static"},E=oe=>{let Q=BL(oe);if(r=Q,!Q){F();return}a||X(),d.textContent=Q.text,i.hidden=Q.dismissible===!1,i.setAttribute("aria-label",Q.dismissLabel??"Dismiss message"),R()},_=oe=>{n=oe,L.update(oe),E(oe),G()},O=(oe,Q="user")=>{y=oe,oe&&k(Q)},W=()=>{F(),L.destroy(),o.remove()};return o.appendChild(L.element),e&&(E(e),G()),{element:o,launcher:L,get teaser(){return a?{element:a,show:P,dismiss:T}:null},setPanelOpen:O,update:_,destroy:W}};var BS=({config:e,showClose:t})=>{let{wrapper:o,panel:n,pillRoot:r}=LS(e),a=IS(e,t),i={wrapper:o,panel:n,pillRoot:r},d={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},u={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},c={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:i,panelElements:a,transcript:d,header:u,composer:c,replaceHeader:y=>(u.element.replaceWith(y.header),u.element=y.header,u.iconHolder=y.iconHolder,u.headerTitle=y.headerTitle,u.headerSubtitle=y.headerSubtitle,u.closeButton=y.closeButton,u.closeButtonWrapper=y.closeButtonWrapper,u.clearChatButton=y.clearChatButton,u.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{c.footer.replaceWith(y),c.footer=y}}},Ng=({config:e,plugins:t,onToggle:o})=>{let n=t.find(a=>a.renderLauncher);if(n?.renderLauncher){let a=n.renderLauncher({config:e,defaultRenderer:()=>_g(e,o).element,onToggle:o});if(a)return{instance:null,element:a}}let r=WS(e,o);return{instance:r,element:r.element}};var OL=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},DL=(e,t,o)=>`${OL(e)}plugin:${t}:${o}`,OS=e=>{let t=new Map,o=!1,n=()=>{if(o||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return o=!0,null}};return r=>{let a=i=>DL(e(),r,i);return{get:i=>{let d=a(i),u=n();if(u)try{return u.getItem(d)}catch{o=!0}return t.get(d)??null},set:(i,d)=>{let u=a(i),c=n();if(c)try{c.setItem(u,d);return}catch{o=!0}t.set(u,d)},remove:i=>{let d=a(i);t.delete(d);let u=n();if(u)try{u.removeItem(d)}catch{o=!0}}}}};var Za=(e,t,o)=>{let n=o;for(let r of t){let a=I("span","persona-tool-char");a.style.setProperty("--char-index",String(n)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),n++}return n};var _L=["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"],NL="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",FL="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",UL=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Au=(e,t)=>{let o=I("div",["persona-message-bubble",e,..._L].join(" "));return o.id=`bubble-${t}`,o.setAttribute("data-message-id",t),o},Mu=e=>{let t=I("button",e.expandable?NL:FL);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},Fg=(e,t,o)=>{e.innerHTML="";let n=Ft(t?_s:pl,16,o,2);n?e.appendChild(n):e.textContent=t?"Hide":"Show"},Tu=(e,t,o)=>{if(!o.expandable)return e.append(t),null;let n=I("div","persona-flex persona-items-center");Fg(n,o.expanded,o.iconColor);let r=I("div",o.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(n),e.append(t,r),n},Eu=e=>{let t=I("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let o=e.renderPreview?.();UL(t,o)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Pu=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&Fg(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},Lu=(e,t,o)=>{let n=o.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector(`[data-persona-collapsed-preview="${o.previewKind}"]`);if(!r||!a)return;r.setAttribute("aria-expanded",n?"true":"false");let u=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");u&&Fg(u,n,o.iconColor),a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")};var ei=new Set,qL=(e,t)=>{let o=e.reasoning?.chunks.join("").trim()??"";return o?o.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).slice(0,t).join(`
38
- `):""},DS=(e,t)=>{Lu(e,t,{stateSet:ei,previewKind:"reasoning",iconColor:"currentColor"})},Ug=(e,t)=>{let o=e.reasoning,n=Au("persona-reasoning-bubble",e.id);if(!o)return n;let r=t?.features?.reasoningDisplay??{},a=r.expandable!==!1,i=a&&ei.has(e.id),d=o.status!=="complete",u=qL(e,r.previewMaxLines??3),c=Mu({expandable:a,expanded:i,bubbleType:"reasoning"}),p=I("div","persona-flex persona-flex-col persona-text-left"),m=I("span","persona-text-xs persona-text-persona-primary"),y="Thinking...",h=t?.reasoning??{},S=String(o.startedAt??Date.now()),A=()=>{let W=I("span","");return W.setAttribute("data-tool-elapsed",S),W.textContent=Cc(o),W},T=h.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:y,previewText:u,isActive:d,config:t??{},elapsed:Cc(o),createElapsedElement:A});typeof T=="string"&&T.trim()?(m.textContent=T,p.appendChild(m)):T instanceof HTMLElement?p.appendChild(T):(m.textContent=y,p.appendChild(m));let k=I("span","persona-text-xs persona-text-persona-primary");k.textContent=zv(o),p.appendChild(k);let P=r.loadingAnimation??"none",R=h.activeTextTemplate,b=h.completeTextTemplate,w=d?R:b,x=T instanceof HTMLElement,L=(W,oe)=>{m.textContent="";let Q=Sc(W,""),de=0;for(let pe of Q){let xe=pe.styles.length>0?(()=>{let Pe=I("span",pe.styles.map(ge=>`persona-tool-text-${ge}`).join(" "));return m.appendChild(Pe),Pe})():m;if(pe.isDuration&&d)xe.appendChild(A());else{let Pe=pe.isDuration?Cc(o):pe.text;oe?de=Za(xe,Pe,de):xe.appendChild(document.createTextNode(Pe))}}};if(!x&&w)if(k.style.display="none",m.style.display="",d&&P!=="none"){let W=h.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),P==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),L(w,!1)):(m.classList.add(`persona-tool-loading-${P}`),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),P==="shimmer-color"&&(h.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor)),L(w,!0))}else L(w,!1);else if(!x&&d&&P!=="none"){m.style.display="";let W=h.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),P==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`);else{m.classList.add(`persona-tool-loading-${P}`),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),P==="shimmer-color"&&(h.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor));let oe=m.textContent||y;m.textContent="",Za(m,oe,0)}o.status==="complete"&&(m.style.display="none")}else x||(o.status==="complete"?m.style.display="none":m.style.display="");if(r.iconName&&!x){let W=I("span","persona-reasoning-header-icon"),oe=ce(r.iconName,16,"currentColor",2);oe&&(W.appendChild(oe),c.appendChild(W))}let F="currentColor",X=Tu(c,p,{expandable:a,expanded:i,iconColor:F,metaGap:!1}),G=Eu({bubble:n,previewKind:"reasoning",expanded:i,isActive:d,previewText:u,activePreview:r.activePreview,activeMinHeight:r.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:u,isActive:d,config:t??{}})});if(!a)return n.append(c,G),n;let E=I("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");E.style.display=i?"":"none";let _=o.chunks.join(""),O=I("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return O.textContent=_||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),E.appendChild(O),Pu({expanded:i,header:c,toggleIcon:X,content:E,collapsedPreview:G,iconColor:F}),n.append(c,G,E),n};var ti=new Set,_S=e=>e.toggleTextColor||e.headerTextColor||"var(--persona-primary, #171717)",$L=(e,t)=>{let o=e.toolCall;if(!o)return"";let n=(o.chunks??[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
37
+ `,o.addEventListener("click",t);let n=a=>{let i=a.launcher??{},d=St(a),c=o.querySelector("[data-role='launcher-title']");if(c){let R=i.title??"Chat Assistant";c.textContent=R,c.setAttribute("title",R)}let u=o.querySelector("[data-role='launcher-subtitle']");if(u){let R=i.subtitle??"Here to help you get answers fast";u.textContent=R,u.setAttribute("title",R)}let p=o.querySelector(".persona-flex-col");p&&(i.textHidden||d?p.style.display="none":p.style.display="");let m=o.querySelector("[data-role='launcher-icon']");if(m)if(i.agentIconHidden)m.style.display="none";else{let R=i.agentIconSize??"40px";if(m.style.height=R,m.style.width=R,i.agentIconBackgroundColor?(m.style.backgroundColor=i.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",i.agentIconName){let b=parseFloat(R)||24,A=ce(i.agentIconName,b*.6,"var(--persona-text-inverse, #ffffff)",1.5);A?(m.appendChild(A),m.style.display=""):(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}else i.iconUrl?m.style.display="none":(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}let h=o.querySelector("[data-role='launcher-image']");if(h){let R=i.agentIconSize??"40px";h.style.height=R,h.style.width=R,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(h.src=i.iconUrl,h.style.display="block"):h.style.display="none"}let y=o.querySelector("[data-role='launcher-call-to-action-icon']");if(y){let R=i.callToActionIconSize??"32px";y.style.height=R,y.style.width=R,i.callToActionIconBackgroundColor?(y.style.backgroundColor=i.callToActionIconBackgroundColor,y.classList.remove("persona-bg-persona-primary")):(y.style.backgroundColor="",y.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(y.style.color=i.callToActionIconColor,y.classList.remove("persona-text-persona-call-to-action")):(y.style.color="",y.classList.add("persona-text-persona-call-to-action"));let b=0;if(i.callToActionIconPadding?(y.style.boxSizing="border-box",y.style.padding=i.callToActionIconPadding,b=(parseFloat(i.callToActionIconPadding)||0)*2):(y.style.boxSizing="",y.style.padding=""),i.callToActionIconHidden)y.style.display="none";else if(y.style.display=d?"none":"",y.innerHTML="",i.callToActionIconName){let A=parseFloat(R)||24,C=Math.max(A-b,8),L=ce(i.callToActionIconName,C,"currentColor",1.5);L?y.appendChild(L):y.textContent=i.callToActionIconText??"\u2197"}else y.textContent=i.callToActionIconText??"\u2197"}let x=i.position&&Go[i.position]?Go[i.position]:Go["bottom-right"],T="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",w="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";o.className=d?w:`${T} ${x}`,d||(o.style.zIndex=String(i.zIndex??so));let k="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",P="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";o.style.border=i.border??k,o.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:P,d?(o.style.width="0",o.style.minWidth="0",o.style.maxWidth="0",o.style.padding="0",o.style.overflow="hidden",o.style.border="none",o.style.boxShadow="none"):(o.style.width="",o.style.minWidth="",o.style.maxWidth=i.collapsedMaxWidth??"",o.style.justifyContent="",o.style.padding="",o.style.overflow="")},r=()=>{o.removeEventListener("click",t),o.remove()};return e&&n(e),{element:o,update:n,destroy:r}},Dk="teaser-dismissed",OS=new Set,BS=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${Dk}`},_k=(e,t)=>{if(OS.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},Nk=(e,t)=>{if(OS.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},Fk=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Uk=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||St(e??{})?null:t},DS=(e,t)=>{let o=I("div","persona-launcher-surface");o.setAttribute("data-persona-launcher-surface","true");let n=e??{},r=null,a=null,i=null,d=null,c=null,u=!1,p=!1,m=!1,h=!1,y=()=>(r?.frequency??"once")==="once"&&n.persistState!==!1,x=()=>{c!==null&&(clearTimeout(c),c=null)},T=()=>{!a||!u||(u=!1,a.hidden=!0)},w=te=>{x(),m=!0,T(),Nk(BS(n),te&&y())},k=te=>{!r||m||w(te==="user"&&u)},P=()=>{c=null,!(!a||m||h)&&(p=!0,u=!0,a.hidden=!1,!(Fk()||typeof a.animate!="function")&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},R=()=>{!r||!a||m||p||h||_k(BS(n),y())||(x(),c=setTimeout(P,Math.max(0,r.delayMs??0)))},b=()=>{w(y()),t()},A=te=>{te.stopPropagation(),w(y())},L=Ug(e,()=>{k("user"),t()}),F=()=>{x(),d?.removeEventListener("click",b),i?.removeEventListener("click",A),a?.remove(),a=null,d=null,i=null,u=!1},X=()=>{d=Y("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),d.addEventListener("click",b),i=Y("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",A),a=Y("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},d,i),o.insertBefore(a,L.element)},G=()=>{let te=n.launcher?.position??"bottom-right",Q=Go[te]??Go["bottom-right"];if(!a){o.className="persona-launcher-surface",o.removeAttribute("data-teaser"),o.style.zIndex="",L.element.style.position="";return}o.className=bo("persona-launcher-surface",Q),o.setAttribute("data-teaser",te),o.style.zIndex=String(n.launcher?.zIndex??so),L.element.style.position="static"},E=te=>{let Q=Uk(te);if(r=Q,!Q){F();return}a||X(),d.textContent=Q.text,i.hidden=Q.dismissible===!1,i.setAttribute("aria-label",Q.dismissLabel??"Dismiss message"),R()},O=te=>{n=te,L.update(te),E(te),G()},D=(te,Q="user")=>{h=te,te&&k(Q)},W=()=>{F(),L.destroy(),o.remove()};return o.appendChild(L.element),e&&(E(e),G()),{element:o,launcher:L,get teaser(){return a?{element:a,show:P,dismiss:w}:null},setPanelOpen:D,update:O,destroy:W}};var _S=({config:e,showClose:t})=>{let{wrapper:o,panel:n,pillRoot:r}=RS(e),a=WS(e,t),i={wrapper:o,panel:n,pillRoot:r},d={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},u={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:i,panelElements:a,transcript:d,header:c,composer:u,replaceHeader:h=>(c.element.replaceWith(h.header),c.element=h.header,c.iconHolder=h.iconHolder,c.headerTitle=h.headerTitle,c.headerSubtitle=h.headerSubtitle,c.closeButton=h.closeButton,c.closeButtonWrapper=h.closeButtonWrapper,c.clearChatButton=h.clearChatButton,c.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{u.footer.replaceWith(h),u.footer=h}}},qg=({config:e,plugins:t,onToggle:o})=>{let n=t.find(a=>a.renderLauncher);if(n?.renderLauncher){let a=n.renderLauncher({config:e,defaultRenderer:()=>Ug(e,o).element,onToggle:o});if(a)return{instance:null,element:a}}let r=DS(e,o);return{instance:r,element:r.element}};var qk=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},$k=(e,t,o)=>`${qk(e)}plugin:${t}:${o}`,NS=e=>{let t=new Map,o=!1,n=()=>{if(o||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return o=!0,null}};return r=>{let a=i=>$k(e(),r,i);return{get:i=>{let d=a(i),c=n();if(c)try{return c.getItem(d)}catch{o=!0}return t.get(d)??null},set:(i,d)=>{let c=a(i),u=n();if(u)try{u.setItem(c,d);return}catch{o=!0}t.set(c,d)},remove:i=>{let d=a(i);t.delete(d);let c=n();if(c)try{c.removeItem(d)}catch{o=!0}}}}};var ei=(e,t,o)=>{let n=o;for(let r of t){let a=I("span","persona-tool-char");a.style.setProperty("--char-index",String(n)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),n++}return n};var Vk=["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"],jk="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",zk="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",Kk=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Mu=(e,t)=>{let o=I("div",["persona-message-bubble",e,...Vk].join(" "));return o.id=`bubble-${t}`,o.setAttribute("data-message-id",t),o},Tu=e=>{let t=I("button",e.expandable?jk:zk);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},$g=(e,t,o)=>{e.innerHTML="";let n=Ft(t?_s:pl,16,o,2);n?e.appendChild(n):e.textContent=t?"Hide":"Show"},Eu=(e,t,o)=>{if(!o.expandable)return e.append(t),null;let n=I("div","persona-flex persona-items-center");$g(n,o.expanded,o.iconColor);let r=I("div",o.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(n),e.append(t,r),n},Pu=e=>{let t=I("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let o=e.renderPreview?.();Kk(t,o)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},ku=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&$g(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},Lu=(e,t,o)=>{let n=o.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector(`[data-persona-collapsed-preview="${o.previewKind}"]`);if(!r||!a)return;r.setAttribute("aria-expanded",n?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&$g(c,n,o.iconColor),a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")};var ti=new Set,Gk=(e,t)=>{let o=e.reasoning?.chunks.join("").trim()??"";return o?o.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).slice(0,t).join(`
38
+ `):""},FS=(e,t)=>{Lu(e,t,{stateSet:ti,previewKind:"reasoning",iconColor:"currentColor"})},Vg=(e,t)=>{let o=e.reasoning,n=Mu("persona-reasoning-bubble",e.id);if(!o)return n;let r=t?.features?.reasoningDisplay??{},a=r.expandable!==!1,i=a&&ti.has(e.id),d=o.status!=="complete",c=Gk(e,r.previewMaxLines??3),u=Tu({expandable:a,expanded:i,bubbleType:"reasoning"}),p=I("div","persona-flex persona-flex-col persona-text-left"),m=I("span","persona-text-xs persona-text-persona-primary"),h="Thinking...",y=t?.reasoning??{},x=String(o.startedAt??Date.now()),T=()=>{let W=I("span","");return W.setAttribute("data-tool-elapsed",x),W.textContent=Cc(o),W},w=y.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:h,previewText:c,isActive:d,config:t??{},elapsed:Cc(o),createElapsedElement:T});typeof w=="string"&&w.trim()?(m.textContent=w,p.appendChild(m)):w instanceof HTMLElement?p.appendChild(w):(m.textContent=h,p.appendChild(m));let k=I("span","persona-text-xs persona-text-persona-primary");k.textContent=Xv(o),p.appendChild(k);let P=r.loadingAnimation??"none",R=y.activeTextTemplate,b=y.completeTextTemplate,A=d?R:b,C=w instanceof HTMLElement,L=(W,te)=>{m.textContent="";let Q=Sc(W,""),de=0;for(let pe of Q){let Ce=pe.styles.length>0?(()=>{let Ee=I("span",pe.styles.map(ge=>`persona-tool-text-${ge}`).join(" "));return m.appendChild(Ee),Ee})():m;if(pe.isDuration&&d)Ce.appendChild(T());else{let Ee=pe.isDuration?Cc(o):pe.text;te?de=ei(Ce,Ee,de):Ce.appendChild(document.createTextNode(Ee))}}};if(!C&&A)if(k.style.display="none",m.style.display="",d&&P!=="none"){let W=y.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),P==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),L(A,!1)):(m.classList.add(`persona-tool-loading-${P}`),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),P==="shimmer-color"&&(y.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",y.loadingAnimationColor),y.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",y.loadingAnimationSecondaryColor)),L(A,!0))}else L(A,!1);else if(!C&&d&&P!=="none"){m.style.display="";let W=y.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),P==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`);else{m.classList.add(`persona-tool-loading-${P}`),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),P==="shimmer-color"&&(y.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",y.loadingAnimationColor),y.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",y.loadingAnimationSecondaryColor));let te=m.textContent||h;m.textContent="",ei(m,te,0)}o.status==="complete"&&(m.style.display="none")}else C||(o.status==="complete"?m.style.display="none":m.style.display="");if(r.iconName&&!C){let W=I("span","persona-reasoning-header-icon"),te=ce(r.iconName,16,"currentColor",2);te&&(W.appendChild(te),u.appendChild(W))}let F="currentColor",X=Eu(u,p,{expandable:a,expanded:i,iconColor:F,metaGap:!1}),G=Pu({bubble:n,previewKind:"reasoning",expanded:i,isActive:d,previewText:c,activePreview:r.activePreview,activeMinHeight:r.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:c,isActive:d,config:t??{}})});if(!a)return n.append(u,G),n;let E=I("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");E.style.display=i?"":"none";let O=o.chunks.join(""),D=I("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return D.textContent=O||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),E.appendChild(D),ku({expanded:i,header:u,toggleIcon:X,content:E,collapsedPreview:G,iconColor:F}),n.append(u,G,E),n};var oi=new Set,US=e=>e.toggleTextColor||e.headerTextColor||"var(--persona-primary, #171717)",Xk=(e,t)=>{let o=e.toolCall;if(!o)return"";let n=(o.chunks??[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
39
39
  `);let r=vc(o.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
40
- `):""},qg=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},jL=(e,t)=>{let o=e.toolCall,n=t?.features?.toolCallDisplay,r=n?.collapsedMode??"tool-call",a=$L(e,n?.previewMaxLines??3),i=o?Vv(o):"";if(!o)return{summary:i,previewText:a,isActive:!1};let d=o.status!=="complete",u=t?.toolCall??{},c=i;return r==="tool-name"?c=o.name?.trim()||i:r==="tool-preview"&&a&&(c=a),d&&u.activeTextTemplate?c=$f(o,u.activeTextTemplate,c):!d&&u.completeTextTemplate&&(c=$f(o,u.completeTextTemplate,c)),{summary:c,previewText:a,isActive:d}},NS=(e,t,o)=>{Lu(e,t,{stateSet:ti,previewKind:"tool",iconColor:_S(o?.toolCall??{})})},$g=(e,t)=>{let o=e.toolCall,n=t?.toolCall??{},r=Au("persona-tool-bubble",e.id);if(n.backgroundColor&&(r.style.backgroundColor=n.backgroundColor),n.borderColor&&(r.style.borderColor=n.borderColor),n.borderWidth&&(r.style.borderWidth=n.borderWidth),n.borderRadius&&(r.style.borderRadius=n.borderRadius),r.style.boxShadow=n.shadow!==void 0?n.shadow.trim()===""?"none":n.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!o)return r;let a=t?.features?.toolCallDisplay??{},i=a.expandable!==!1,d=i&&ti.has(e.id),{summary:u,previewText:c,isActive:p}=jL(e,t),m=Mu({expandable:i,expanded:d,bubbleType:"tool"});n.headerBackgroundColor&&(m.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(m.style.paddingLeft=n.headerPaddingX,m.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(m.style.paddingTop=n.headerPaddingY,m.style.paddingBottom=n.headerPaddingY);let y=I("div","persona-flex persona-flex-col persona-text-left"),h=I("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(h.style.color=n.headerTextColor);let S=String(o.startedAt??Date.now()),A=()=>{let E=I("span","");return E.setAttribute("data-tool-elapsed",S),E.textContent=al(o),E},T=n.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:u,previewText:c,collapsedMode:a.collapsedMode??"tool-call",isActive:p,config:t??{},elapsed:al(o),createElapsedElement:A});typeof T=="string"&&T.trim()?(h.textContent=T,y.appendChild(h)):T instanceof HTMLElement?y.appendChild(T):(h.textContent=u,y.appendChild(h));let k=a.loadingAnimation??"none",P=n.activeTextTemplate,R=n.completeTextTemplate,b=p?P:R,w=T instanceof HTMLElement,x=(E,_)=>{h.textContent="";let O=o.name?.trim()||"tool",W=Sc(E,O),oe=0;for(let Q of W){let de=Q.styles.length>0?(()=>{let pe=I("span",Q.styles.map(xe=>`persona-tool-text-${xe}`).join(" "));return h.appendChild(pe),pe})():h;if(Q.isDuration&&p)de.appendChild(A());else{let pe=Q.isDuration?al(o):Q.text;_?oe=Za(de,pe,oe):de.appendChild(document.createTextNode(pe))}}};if(!w)if(p&&k!=="none"){let E=n.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),k==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${E}ms`),b&&x(b,!1);else if(h.classList.add(`persona-tool-loading-${k}`),h.style.setProperty("--persona-tool-anim-duration",`${E}ms`),k==="shimmer-color"&&(n.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),b)x(b,!0);else{let _=h.textContent||u;h.textContent="",Za(h,_,0)}}else b&&x(b,!1);let L=_S(n),F=Tu(m,y,{expandable:i,expanded:d,iconColor:L,metaGap:!0}),X=Eu({bubble:r,previewKind:"tool",expanded:d,isActive:p,previewText:c,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>n.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:c,isActive:p,config:t??{}})});if(!i)return r.append(m,X),r;let G=I("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(G.style.display=d?"":"none",n.contentBackgroundColor&&(G.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(G.style.color=n.contentTextColor),n.contentPaddingX&&(G.style.paddingLeft=n.contentPaddingX,G.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(G.style.paddingTop=n.contentPaddingY,G.style.paddingBottom=n.contentPaddingY),o.name){let E=I("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?E.style.color=n.contentTextColor:n.headerTextColor&&(E.style.color=n.headerTextColor),E.textContent=o.name,G.appendChild(E)}if(o.args!==void 0){let E=I("div","persona-space-y-1"),_=I("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(_.style.color=n.labelTextColor),_.textContent="Arguments";let O=I("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");O.style.fontSize="0.75rem",O.style.lineHeight="1rem",qg(O,n),O.textContent=vc(o.args),E.append(_,O),G.appendChild(E)}if(o.chunks&&o.chunks.length){let E=I("div","persona-space-y-1"),_=I("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(_.style.color=n.labelTextColor),_.textContent="Activity";let O=I("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");O.style.fontSize="0.75rem",O.style.lineHeight="1rem",qg(O,n),O.textContent=o.chunks.join(""),E.append(_,O),G.appendChild(E)}if(o.status==="complete"&&o.result!==void 0){let E=I("div","persona-space-y-1"),_=I("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(_.style.color=n.labelTextColor),_.textContent="Result";let O=I("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");O.style.fontSize="0.75rem",O.style.lineHeight="1rem",qg(O,n),O.textContent=vc(o.result),E.append(_,O),G.appendChild(E)}if(o.status==="complete"&&typeof o.duration=="number"){let E=I("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(E.style.color=n.contentTextColor),E.textContent=`Duration: ${o.duration}ms`,G.appendChild(E)}return Pu({expanded:d,header:m,toggleIcon:F,content:G,collapsedPreview:X,iconColor:L}),r.append(m,X,G),r};var{setLoader:zL,load:VL,provide:aD,getSync:KL}=mt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),FS=zL,US=VL;var qS=KL;var{setLoader:GL,load:XL}=mt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),$S=GL,jg=XL;var zg=class{constructor(){this.components=new Map;this.options=new Map}register(t,o,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,o),n?this.options.set(t,n):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([o,n])=>{this.register(o,n)})}},Cn=new zg;var Vg=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:QL,load:YL,provide:gD,getSync:JL}=mt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),oi=null,ku=new Set,jS=e=>{if(oi)return oi;oi=e,e.initArtifactsUi({componentRegistry:Cn});for(let n of Vg)Cn.has(n)||Cn.register(n,n==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Dn();t?e.__provideMarkdownParsers(t):Pa(()=>{let n=Dn();n&&e.__provideMarkdownParsers(n)}),e.__setIconsExtraLoader(()=>_c());let o=[...ku];ku.clear();for(let n of o)try{n()}catch{}return e},zS=QL,Iu=()=>YL().then(jS);var fr=()=>{if(oi)return oi;let e=JL();return e?jS(e):null},Kg=e=>oi?()=>{}:(ku.add(e),()=>{ku.delete(e)});function wo(e){return e?.features?.artifacts?.enabled===!0}function VS(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!wo(t))return;let o=t.features?.artifacts?.layout,n=o?.paneBorder?.trim(),r=o?.paneBorderLeft?.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function ZL(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var KS=["panel","seamless","detached"];function Gg(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&KS.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Xg(e){return!e||!wo(e)?!1:Gg(e)==="detached"}function Dl(e,t){if(!wo(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),ZL(e),VS(e,t);return}let o=t.features?.artifacts?.layout,n=Gg(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",o?.splitGap??n),e.style.setProperty("--persona-artifact-pane-width",o?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",o?.paneMaxWidth??"28rem"),o?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",o.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),o?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",o.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=o?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let a=o?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let i=[[o?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[o?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[o?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[o?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[d,u]of i){let c=d?.trim();c?e.style.setProperty(u,c):e.style.removeProperty(u)}VS(e,t)}function _l(e,t){for(let d of KS)e.classList.remove(`persona-artifact-appearance-${d}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!wo(t))return;let o=t.features?.artifacts?.layout,n=Gg(t);e.classList.add(`persona-artifact-appearance-${n}`);let r=o?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let a=o?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let i=o?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function GS(e,t){return!t||!wo(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var ek=new Set(["__proto__","prototype","constructor"]),tk=new Set(["collapsed","card","panel","inline"]),XS=new Set(["markdown","component"]),ok=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Xs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ru=e=>!ek.has(e),Qg=e=>typeof e=="string"&&tk.has(e),Qs=e=>Object.keys(e).length>0;function $n(e,t,o,n){e.push({path:t,code:o,message:n})}var nk="Ignored because this key is not part of the persisted preference schema.",Hu="Ignored an unsupported value.",rk="Expected collapsed, panel, or inline.",sk='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',QS={kind:"mode",message:Hu},ni={kind:"string",message:"Expected a CSS length string."},mr={kind:"boolean"},ak={paneWidth:ni,paneMaxWidth:ni,paneMinWidth:ni,expandedPanelWidth:ni,resizableMinWidth:ni,resizableMaxWidth:ni,expandLauncherPanelWhenOpen:mr,resizable:mr},ik={kind:"object",message:"Expected a preference object.",children:{showToolCalls:mr,showReasoning:mr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Hu},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Hu},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Hu},expandable:mr,grouped:mr}},reasoningDisplay:{kind:"object",children:{expandable:mr,activePreview:mr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:QS,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:QS,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:XS,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:XS}}},filePreview:{kind:"object",children:{enabled:mr}},layout:{kind:"object",children:ak}}}}};function YS(e,t,o,n){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:$n(n,o,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:$n(n,o,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:$n(n,o,"invalid_value",t.message);case"mode":return Qg(e)?Ho(e):$n(n,o,"invalid_value",t.message);case"modeMap":{if(!Xs(e))return $n(n,o,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,a={};for(let[i,d]of Object.entries(e)){let u=r?i:Dr(i);Ru(i)&&(r?r.has(i):ok.test(u))?Qg(d)?a[u]=Ho(d):$n(n,`${o}.${i}`,"invalid_value",rk):$n(n,`${o}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":sk)}return Qs(a)?a:void 0}case"object":{if(t.bareMode&&Qg(e))return Ho(e);if(!Xs(e))return $n(n,o,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),a=d=>o?`${o}.${d}`:d;for(let d of Object.keys(e))(!Ru(d)||!r.includes(d))&&$n(n,a(d),"unknown_key",nk);let i={};for(let d of r){let u=t.children[d],c=YS(e[d],u,a(d),n);if(u.deprecated&&e[d]!==void 0&&$n(n,a(d),"deprecated_key",u.deprecated),c===void 0)continue;let p=u.alias??d,m=i[p];i[p]=Xs(m)&&Xs(c)?{...m,...c}:c}return Qs(i)?i:void 0}}}function Yg(e){let t=[];return{preferences:(e===null?void 0:YS(e,ik,"",t))??{},issues:t}}function ri(e){if(Array.isArray(e))return e.map(ri);if(!Xs(e))return e;let t={};for(let[o,n]of Object.entries(e))Ru(o)&&n!==void 0&&(t[o]=ri(n));return t}function JS(e,t){let o=ri(e);for(let[n,r]of Object.entries(t)){if(!Ru(n)||r===void 0)continue;let a=o[n];o[n]=Xs(a)&&Xs(r)?JS(a,r):ri(r)}return o}function lk(e){let t={},o;for(let r of e){let a=Yg(r).preferences;o=ZS(o,a.artifacts?.display),t=JS(t,a)}let n=t;return n.artifacts&&(o!==void 0?n.artifacts.display=o:delete n.artifacts.display),n}function dk(e,t){if(t===void 0)return e===void 0?void 0:ri(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byMediaType,...t.byMediaType},a={...n?{default:n}:{},...Qs(r)?{byMediaType:r}:{}};return Qs(a)?a:void 0}function ZS(e,t){if(t===void 0)return e===void 0?void 0:ri(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byType,...o.byKind,...t.byType,...t.byKind},a=dk(o.files,t.files),i={...n?{default:n}:{},...Qs(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return Qs(i)?i:void 0}function Jg(e={},t){let o=lk(t),n={...e};if(o.showToolCalls!==void 0&&(n.showToolCalls=o.showToolCalls),o.showReasoning!==void 0&&(n.showReasoning=o.showReasoning),o.toolCallDisplay&&(n.toolCallDisplay={...e.toolCallDisplay,...o.toolCallDisplay}),o.reasoningDisplay&&(n.reasoningDisplay={...e.reasoningDisplay,...o.reasoningDisplay}),o.artifacts){let r=e.artifacts??{},a={...r};if(o.artifacts.display!==void 0){let i=ZS(r.display,o.artifacts.display);i!==void 0&&(a.display=i)}o.artifacts.filePreview&&(a.filePreview={...r.filePreview,enabled:o.artifacts.filePreview.enabled}),o.artifacts.layout&&(a.layout={...r.layout,...o.artifacts.layout}),n.artifacts=a}return n}function Nl(e){let t=e.preferences;return!t||!Qs(t)?e:{...e,features:Jg(e.features??{},[t])}}function ck(e,t){if(!e?.trim())return t;let o=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return o?Math.max(0,Number(o[1])):t}function uk(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function pk(e,t,o){return o<t?t:Math.min(o,Math.max(t,e))}function fk(e,t,o,n){let r=e-n-2*t-o;return Math.max(0,r)}function Zg(e,t){let n=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let a=/^([\d.]+)/.exec(n);return a?Number(a[1]):8}function ew(e,t,o,n,r,a,i=200){let d=ck(r,200),u=fk(t,o,n,i);u=Math.max(d,u);let c=uk(a);return c!==null&&(u=Math.min(u,c)),pk(e,d,u)}var{setLoader:mk,load:gk,provide:SD,getSync:hk}=mt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),tw=mk,ow=gk;var nw=hk;var eh=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let o=this.plugins.get(t);o&&(o.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,o)=>(o.priority??0)-(t.priority??0))}getForInstance(t){let o=this.getAll();if(!t||t.length===0)return o;let n=new Set(t.map(a=>a.id));return[...o.filter(a=>!n.has(a.id)),...t].sort((a,i)=>(i.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Fl=new eh;var rw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yk=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),sw=(e,t,o)=>{if(!rw(e)||!rw(t)||yk.has(o))return t;let n={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete n[r];continue}let a=o?`${o}.${r}`:r;n[r]=sw(e[r],t[r],a)}return n};function Wu(e,t){let o=sw(e,t,"");return ja(o)}var aw=()=>{let e=new Map,t=(r,a)=>(e.has(r)||e.set(r,new Set),e.get(r).add(a),()=>o(r,a)),o=(r,a)=>{e.get(r)?.delete(a)};return{on:t,off:o,emit:(r,a)=>{e.get(r)?.forEach(i=>{try{i(a)}catch(d){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var bk=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},vk=e=>{let t=e.trim(),o=t.indexOf("{");if(o===-1)return null;let n=0;for(let r=o;r<t.length;r+=1){let a=t[r];if(a==="{"&&(n+=1),a==="}"&&(n-=1,n===0))return t.slice(o,r+1)}return null},Ul=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=bk(e),o=vk(t);if(!o)return null;let n=JSON.parse(o);if(!n||typeof n!="object"||!n.action)return null;let{action:r,...a}=n;return{type:String(r),payload:a,raw:n}}catch{return null}},th=e=>typeof e=="string"?e:e==null?"":String(e),Ys={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:th(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let o=e.payload,n=th(o.element);if(n&&t.document?.querySelector){let r=t.document.querySelector(n);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:th(o.text)}}},iw=e=>Array.isArray(e)?e.map(t=>String(t)):[],ql=e=>{let t=new Set(iw(e.getSessionMetadata().processedActionMessageIds)),o=()=>{t=new Set(iw(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let a=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let i=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!i&&typeof a.text=="string"&&a.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 d=i?e.parsers.reduce((c,p)=>c||p?.({text:i,message:a.message})||null,null):null;if(!d)return null;t.add(a.message.id),n();let u={action:d,message:a.message};e.emit("action:detected",u);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",u)},m=c(d,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});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(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:o}};var xk=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Ck=e=>e.map(t=>({...t,streaming:!1})),Sk=e=>e.map(t=>({...t,status:"complete"})),Bu=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=t();return o?xk(o.getItem(e)):null},save:o=>{let n=t();if(n)try{let r={...o,messages:o.messages?Ck(o.messages):void 0,artifacts:o.artifacts?Sk(o.artifacts):void 0};n.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=t();if(o)try{o.removeItem(e)}catch(n){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var wk=e=>{let t=2166136261;for(let o=0;o<e.length;o++)t^=e.charCodeAt(o),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},lw=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let o=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(o)).map(n=>n.toString(16).padStart(2,"0")).join("")}catch{}return wk(e)},Ak=async(e,t)=>{let o=await lw(e);return{storageKey:`${t}visitor:${o}`,leaseKey:`${t}visitor-init-lock:${o}`,lockName:`persona-visitor-init:${await lw(`${e}\0${t}`)}`}};var dw=(e,t,o)=>{let n="",r="",a="",i=!1,d=!1,u=0,c=null,p=null,m=new Set,y=()=>{if(o||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},h=()=>{let x=y();if(!x)return c;try{return x.getItem(n)}catch{return i=!0,c}},S=(x,L)=>{if(d||x===c)return;let F=c;c=x,u+=1;let X={previousToken:F,token:x,source:L,revision:u};for(let G of m)G(X)},A=x=>{d||x.key!==null&&x.key!==n||S(x.key===null?null:x.newValue??null,"external")},T=(async()=>{let x=await Ak(e,t);n=x.storageKey,r=x.leaseKey,a=x.lockName,c=h(),!o&&typeof window<"u"&&window.addEventListener("storage",A)})(),k=x=>new Promise(L=>setTimeout(L,x)),P=()=>{let x=y();if(!x)return null;try{let L=x.getItem(r);if(!L)return null;let F=JSON.parse(L);return typeof F?.expiresAt=="number"&&typeof F?.ownerNonce=="string"?F:null}catch{return null}},R=x=>{let L=y();if(L)try{P()?.ownerNonce===x&&L.removeItem(r)}catch{}},b=x=>new Promise(L=>{let F=setTimeout(X,x);function X(){clearTimeout(F),window.removeEventListener("storage",G),L()}function G(E){(E.key===null||E.key===r)&&X()}window.addEventListener("storage",G)}),w=async x=>{let L=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,F=Date.now()+15e3;for(;Date.now()<F;){let X=y();if(!X)break;let G=Date.now(),E=P();if(E&&E.expiresAt>G&&E.ownerNonce!==L){await b(Math.min(E.expiresAt-G,500));continue}try{X.setItem(r,JSON.stringify({ownerNonce:L,expiresAt:G+1e4}))}catch{i=!0;break}if(await k(20+Math.random()*40),P()?.ownerNonce!==L){await b(500);continue}p=L;try{return await x()}finally{p=null,R(L)}}return x()};return{ready:T,async get(){return await T,S(h(),"external"),c},async set(x){await T;let L=y();if(L)try{L.setItem(n,x)}catch{i=!0}S(x,"local")},async clear(){await T;let x=y();if(x)try{x.removeItem(n)}catch{i=!0}S(null,"local")},revision(){return u},subscribe(x){return m.add(x),()=>{m.delete(x)}},async withFirstInitLock(x){await T;let L=globalThis.navigator?.locks;return L?.request?L.request(a,()=>x()):y()?w(x):x()},matches(x,L,F){return x===e&&L===t&&F===o},destroy(){d=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",A),p&&R(p)}}};var{setLoader:Mk,load:Tk}=mt({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),cw=Mk,oh=Tk;var nh=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},gr=e=>Object.freeze({...e}),uw=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),pw=e=>e?gr(e):null;function fw(e){let{plugins:t,config:o}=e,n=!1,r=!1,a=!1,i=!1,d=null,u=[],c=()=>{for(let b of u.splice(0))try{b()}catch(w){nh("renderHistoryView cleanup",w)}},p=(b,w)=>{for(let x of t){let L=x[b];if(L)try{let F=L(w);if(F)return F}catch(F){nh(b,F)}}return null},m=()=>({presentation:e.getPresentation(),config:o}),y={header:b=>i?p("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:gr(b.identityStatus),pendingAction:pw(b.pendingAction),copy:gr(b.copy),actions:Object.freeze({close:A.close,startNewConversation:A.startNewConversation}),defaultRenderer:b.defaultRenderer})):null,conversation:b=>i?p("renderHistoryConversation",Object.freeze({...m(),conversation:uw(b.conversation),active:b.active,pending:b.pending,open:b.open,requestDelete:b.requestDelete,defaultRenderer:b.defaultRenderer})):null,state:b=>i?p("renderHistoryState",Object.freeze({...m(),state:gr(b.state),identityStatus:gr(b.identityStatus),copy:gr(b.copy),...b.retry?{retry:b.retry}:{},...b.startNewConversation?{startNewConversation:b.startNewConversation}:{},defaultRenderer:b.defaultRenderer})):null},h=t.flatMap(b=>(b.railSections??[]).map(w=>({...w,placement:w.placement??"above-conversations",items:[],render:x=>w.render(Object.freeze({collapsed:x,presentation:e.getPresentation(),actions:A}))}))),S=e.createView({slots:y,renderDom:!1,onModelChange:()=>R(),railSections:h}),A=Object.freeze({...S.operations,close:e.close}),T=()=>(i=!0,S.setDomRenderEnabled(!0),S.element),k=b=>Object.freeze({conversations:Object.freeze(b.conversations.map(uw)),activeConversationId:b.activeConversationId,state:gr(b.state),pendingAction:pw(b.pendingAction),identityStatus:gr(b.identityStatus),nextCursor:b.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:o,copy:gr(S.copy),actions:A,defaultRenderer:T,requestRender:()=>R(),onCleanup:w=>{u.push(w)}}),P=()=>{i=!1;let b=null;for(let x of t)if(x.renderHistoryView){try{b=x.renderHistoryView(k(S.getModel()))}catch(L){nh("renderHistoryView",L),b=null}if(b)break}let w=!b||b.contains(S.element);return i=w,S.setDomRenderEnabled(w),b??S.element};function R(){if(!(!a||n||r)){r=!0;try{c();let b=P();if(b===d)return;let w=d;d=b,e.onElementChanged(b,w)}finally{r=!1}}}return a=!0,R(),{view:S,get element(){return d??S.element},requestRender:R,dispose:()=>{n=!0,c()}}}var Ek=null;function mw(){return Ek}var Pk=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"]]),Lk=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."]]),rh=e=>Lk.get(e)??"Conversation history is unavailable right now.";function kk(e){if(e instanceof ln)return e;if(e instanceof qe){let t=Pk.get(e.code)??"unavailable";return new ln(t,rh(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new ln("unavailable",rh("unavailable"))}function gw(e){let t=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],n={scopes:o},r=d=>{if(!o.includes(d))throw new ln("unsupported_scope",rh("unsupported_scope"))},a=async(d,u)=>{r(d);try{return await u()}catch(c){throw kk(c)}},i=d=>{let u=!1;return{conversationId:d.session.conversationId??"",conversationRevision:d.session.conversationRevision??"",async commit(){u||(u=!0,d.commit(),await e.onActivationCommitted(d.session))},discard(){u||(u=!0,d.discard())}}};return{capabilities:n,getIdentityStatus(){return t().getHistoryIdentityStatus()},subscribeIdentityStatus(d){return t().subscribeHistoryIdentityStatus(d)},subscribeAvailability(d){return t().subscribeHistoryAvailability(d)},async list(d){return a(d.context.scope,async()=>{let u=await t().listConversations({...d.cursor?{cursor:d.cursor}:{},...d.limit!==void 0?{limit:d.limit}:{},...d.targetId?{targetId:d.targetId}:{},scope:d.context.scope});return{items:u.data,nextCursor:u.nextCursor}})},async getPage(d,u){return a(u.context.scope,async()=>{let c=await t().getConversation(d,{...u.cursor?{messageCursor:u.cursor}:{},scope:u.context.scope}),p=sx(c.messages,{...u.beforeCreatedAt?{beforeCreatedAt:u.beforeCreatedAt}:{}});return{summary:c.summary,messages:dl([],p),conversationRevision:c.conversationRevision??"",nextCursor:c.nextMessageCursor}})},async prepareOpen(d,u){return a(u.context.scope,async()=>i(await t().prepareConversationSession(d)))},async prepareStartNew(d){return a(d.context.scope,async()=>i(await t().prepareNewConversationSession()))},async delete(d,u){await a(u.context.scope,()=>t().deleteConversation(d,{scope:u.context.scope}))},async deleteAll(d){return a(d.context.scope,()=>t().deleteAllConversations({...d.targetId!==void 0?{targetId:d.targetId}:{},scope:d.context.scope}))},async resetDevice(){try{return await t().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var Ik=["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"],hw={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 sh(e){if(!e)return hw;let t={...hw};for(let o of Ik){let n=e[o];typeof n=="string"&&n.length>0&&(t[o]=n)}return t}var Hk="button:not([disabled])";function Ou(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,o=Math.random().toString(36).slice(2,8),n=`persona-history-confirm-title-${o}`,r=`persona-history-confirm-desc-${o}`,a=Y("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),i=Y("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),d=Y("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":n,"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"}},Y("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:n},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),Y("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),Y("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},a,i));for(let c of[a,i])c.style.minHeight="44px",c.style.minWidth="88px",c.style.padding="0 16px",c.style.borderRadius="var(--persona-radius-md, 0.5rem)",c.style.cursor="pointer",c.style.font="inherit";a.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",a.style.background="transparent",a.style.color="inherit",i.style.border="none",i.style.background="var(--persona-danger, #b42318)",i.style.color="var(--persona-danger-fg, #ffffff)";let u=Y("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))"}},d);return new Promise(c=>{let p=!1,m=h=>{p||(p=!0,u.removeEventListener("keydown",y,!0),u.remove(),t?.focus(),c(h))};function y(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),m(!1);return}if(h.key!=="Tab")return;let S=Array.from(d.querySelectorAll(Hk));if(S.length===0)return;let A=S[0],T=S[S.length-1],k=document.activeElement;h.shiftKey&&(k===A||!d.contains(k))?(h.preventDefault(),T.focus()):!h.shiftKey&&k===T&&(h.preventDefault(),A.focus())}u.addEventListener("keydown",y,!0),u.addEventListener("pointerdown",h=>{h.target===u&&m(!1)}),a.addEventListener("click",()=>m(!1)),i.addEventListener("click",()=>m(!0)),e.host.appendChild(u),a.focus()})}var si=Zt(pc(),1);function Rk(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Wk(e,t){if(!Rk(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:t}}function Du(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e;try{let r=(0,si.parse)(o,si.STR|si.OBJ),a=Wk(r,o);a&&(e=a)}catch{}return t=o.length,e},reset:()=>{e=null,t=0}}}function yw(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _u(e,t){let{config:o,message:n,onPropsUpdate:r}=t,a=Cn.get(e.component);if(!a){if(Vg.includes(e.component)){Iu().catch(()=>{});let d=I("div","persona-w-full");return d.setAttribute("data-persona-artifact-pending","true"),d}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let i={message:n,config:o,updateProps:d=>{r&&r(d)}};try{return a(e.props,i)}catch(d){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,d),null}}function bw(){let e=Du();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function vw(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function $l(e){let t=vw(e);if(!t)return!1;try{let o=JSON.parse(t);return typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"}catch{return!1}}function Nu(e){let t=vw(e);if(!t)return null;try{let o=JSON.parse(t);if(typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"){let n=o;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:t}}}catch{}return null}var Bk=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Fu(e){let{onSubmit:t,onDismiss:o,title:n="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:u=!0,ratingLabels:c=Bk}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,y=document.createElement("div");y.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let S=document.createElement("h3");S.className="persona-feedback-title",S.textContent=n,h.appendChild(S);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=r,h.appendChild(A),y.appendChild(h);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let x=1;x<=5;x++){let L=document.createElement("button");L.type="button",L.className="persona-feedback-rating-btn persona-feedback-star-btn",L.setAttribute("role","radio"),L.setAttribute("aria-checked","false"),L.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${c[x-1]}`),L.title=c[x-1],L.dataset.rating=String(x),L.innerHTML=`
40
+ `):""},jg=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},Qk=(e,t)=>{let o=e.toolCall,n=t?.features?.toolCallDisplay,r=n?.collapsedMode??"tool-call",a=Xk(e,n?.previewMaxLines??3),i=o?Qv(o):"";if(!o)return{summary:i,previewText:a,isActive:!1};let d=o.status!=="complete",c=t?.toolCall??{},u=i;return r==="tool-name"?u=o.name?.trim()||i:r==="tool-preview"&&a&&(u=a),d&&c.activeTextTemplate?u=jf(o,c.activeTextTemplate,u):!d&&c.completeTextTemplate&&(u=jf(o,c.completeTextTemplate,u)),{summary:u,previewText:a,isActive:d}},qS=(e,t,o)=>{Lu(e,t,{stateSet:oi,previewKind:"tool",iconColor:US(o?.toolCall??{})})},zg=(e,t)=>{let o=e.toolCall,n=t?.toolCall??{},r=Mu("persona-tool-bubble",e.id);if(n.backgroundColor&&(r.style.backgroundColor=n.backgroundColor),n.borderColor&&(r.style.borderColor=n.borderColor),n.borderWidth&&(r.style.borderWidth=n.borderWidth),n.borderRadius&&(r.style.borderRadius=n.borderRadius),r.style.boxShadow=n.shadow!==void 0?n.shadow.trim()===""?"none":n.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!o)return r;let a=t?.features?.toolCallDisplay??{},i=a.expandable!==!1,d=i&&oi.has(e.id),{summary:c,previewText:u,isActive:p}=Qk(e,t),m=Tu({expandable:i,expanded:d,bubbleType:"tool"});n.headerBackgroundColor&&(m.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(m.style.paddingLeft=n.headerPaddingX,m.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(m.style.paddingTop=n.headerPaddingY,m.style.paddingBottom=n.headerPaddingY);let h=I("div","persona-flex persona-flex-col persona-text-left"),y=I("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(y.style.color=n.headerTextColor);let x=String(o.startedAt??Date.now()),T=()=>{let E=I("span","");return E.setAttribute("data-tool-elapsed",x),E.textContent=al(o),E},w=n.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:c,previewText:u,collapsedMode:a.collapsedMode??"tool-call",isActive:p,config:t??{},elapsed:al(o),createElapsedElement:T});typeof w=="string"&&w.trim()?(y.textContent=w,h.appendChild(y)):w instanceof HTMLElement?h.appendChild(w):(y.textContent=c,h.appendChild(y));let k=a.loadingAnimation??"none",P=n.activeTextTemplate,R=n.completeTextTemplate,b=p?P:R,A=w instanceof HTMLElement,C=(E,O)=>{y.textContent="";let D=o.name?.trim()||"tool",W=Sc(E,D),te=0;for(let Q of W){let de=Q.styles.length>0?(()=>{let pe=I("span",Q.styles.map(Ce=>`persona-tool-text-${Ce}`).join(" "));return y.appendChild(pe),pe})():y;if(Q.isDuration&&p)de.appendChild(T());else{let pe=Q.isDuration?al(o):Q.text;O?te=ei(de,pe,te):de.appendChild(document.createTextNode(pe))}}};if(!A)if(p&&k!=="none"){let E=n.loadingAnimationDuration??2e3;if(y.setAttribute("data-preserve-animation","true"),k==="pulse")y.classList.add("persona-tool-loading-pulse"),y.style.setProperty("--persona-tool-anim-duration",`${E}ms`),b&&C(b,!1);else if(y.classList.add(`persona-tool-loading-${k}`),y.style.setProperty("--persona-tool-anim-duration",`${E}ms`),k==="shimmer-color"&&(n.loadingAnimationColor&&y.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&y.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),b)C(b,!0);else{let O=y.textContent||c;y.textContent="",ei(y,O,0)}}else b&&C(b,!1);let L=US(n),F=Eu(m,h,{expandable:i,expanded:d,iconColor:L,metaGap:!0}),X=Pu({bubble:r,previewKind:"tool",expanded:d,isActive:p,previewText:u,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>n.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:u,isActive:p,config:t??{}})});if(!i)return r.append(m,X),r;let G=I("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(G.style.display=d?"":"none",n.contentBackgroundColor&&(G.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(G.style.color=n.contentTextColor),n.contentPaddingX&&(G.style.paddingLeft=n.contentPaddingX,G.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(G.style.paddingTop=n.contentPaddingY,G.style.paddingBottom=n.contentPaddingY),o.name){let E=I("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?E.style.color=n.contentTextColor:n.headerTextColor&&(E.style.color=n.headerTextColor),E.textContent=o.name,G.appendChild(E)}if(o.args!==void 0){let E=I("div","persona-space-y-1"),O=I("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(O.style.color=n.labelTextColor),O.textContent="Arguments";let D=I("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");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",jg(D,n),D.textContent=vc(o.args),E.append(O,D),G.appendChild(E)}if(o.chunks&&o.chunks.length){let E=I("div","persona-space-y-1"),O=I("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(O.style.color=n.labelTextColor),O.textContent="Activity";let D=I("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");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",jg(D,n),D.textContent=o.chunks.join(""),E.append(O,D),G.appendChild(E)}if(o.status==="complete"&&o.result!==void 0){let E=I("div","persona-space-y-1"),O=I("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(O.style.color=n.labelTextColor),O.textContent="Result";let D=I("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");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",jg(D,n),D.textContent=vc(o.result),E.append(O,D),G.appendChild(E)}if(o.status==="complete"&&typeof o.duration=="number"){let E=I("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(E.style.color=n.contentTextColor),E.textContent=`Duration: ${o.duration}ms`,G.appendChild(E)}return ku({expanded:d,header:m,toggleIcon:F,content:G,collapsedPreview:X,iconColor:L}),r.append(m,X,G),r};var{setLoader:Yk,load:Jk,provide:fD,getSync:Zk}=mt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),$S=Yk,VS=Jk;var jS=Zk;var{setLoader:eL,load:tL}=mt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),zS=eL,Kg=tL;var Gg=class{constructor(){this.components=new Map;this.options=new Map}register(t,o,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,o),n?this.options.set(t,n):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([o,n])=>{this.register(o,n)})}},Cn=new Gg;var Xg=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:oL,load:nL,provide:SD,getSync:rL}=mt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),ni=null,Iu=new Set,KS=e=>{if(ni)return ni;ni=e,e.initArtifactsUi({componentRegistry:Cn});for(let n of Xg)Cn.has(n)||Cn.register(n,n==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=_n();t?e.__provideMarkdownParsers(t):ka(()=>{let n=_n();n&&e.__provideMarkdownParsers(n)}),e.__setIconsExtraLoader(()=>_c());let o=[...Iu];Iu.clear();for(let n of o)try{n()}catch{}return e},GS=oL,Ru=()=>nL().then(KS);var gr=()=>{if(ni)return ni;let e=rL();return e?KS(e):null},Qg=e=>ni?()=>{}:(Iu.add(e),()=>{Iu.delete(e)});function wo(e){return e?.features?.artifacts?.enabled===!0}function XS(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!wo(t))return;let o=t.features?.artifacts?.layout,n=o?.paneBorder?.trim(),r=o?.paneBorderLeft?.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function sL(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var QS=["panel","seamless","detached"];function Yg(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&QS.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Jg(e){return!e||!wo(e)?!1:Yg(e)==="detached"}function Dl(e,t){if(!wo(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),sL(e),XS(e,t);return}let o=t.features?.artifacts?.layout,n=Yg(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",o?.splitGap??n),e.style.setProperty("--persona-artifact-pane-width",o?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",o?.paneMaxWidth??"28rem"),o?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",o.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),o?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",o.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=o?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let a=o?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let i=[[o?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[o?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[o?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[o?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[d,c]of i){let u=d?.trim();u?e.style.setProperty(c,u):e.style.removeProperty(c)}XS(e,t)}function _l(e,t){for(let d of QS)e.classList.remove(`persona-artifact-appearance-${d}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!wo(t))return;let o=t.features?.artifacts?.layout,n=Yg(t);e.classList.add(`persona-artifact-appearance-${n}`);let r=o?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let a=o?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let i=o?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function YS(e,t){return!t||!wo(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var aL=new Set(["__proto__","prototype","constructor"]),iL=new Set(["collapsed","card","panel","inline"]),JS=new Set(["markdown","component"]),lL=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Xs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wu=e=>!aL.has(e),Zg=e=>typeof e=="string"&&iL.has(e),Qs=e=>Object.keys(e).length>0;function jn(e,t,o,n){e.push({path:t,code:o,message:n})}var dL="Ignored because this key is not part of the persisted preference schema.",Hu="Ignored an unsupported value.",cL="Expected collapsed, panel, or inline.",uL='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',ZS={kind:"mode",message:Hu},ri={kind:"string",message:"Expected a CSS length string."},hr={kind:"boolean"},pL={paneWidth:ri,paneMaxWidth:ri,paneMinWidth:ri,expandedPanelWidth:ri,resizableMinWidth:ri,resizableMaxWidth:ri,expandLauncherPanelWhenOpen:hr,resizable:hr},fL={kind:"object",message:"Expected a preference object.",children:{showToolCalls:hr,showReasoning:hr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Hu},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Hu},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Hu},expandable:hr,grouped:hr}},reasoningDisplay:{kind:"object",children:{expandable:hr,activePreview:hr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:ZS,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:ZS,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:JS,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:JS}}},filePreview:{kind:"object",children:{enabled:hr}},layout:{kind:"object",children:pL}}}}};function ew(e,t,o,n){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:jn(n,o,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:jn(n,o,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:jn(n,o,"invalid_value",t.message);case"mode":return Zg(e)?Ro(e):jn(n,o,"invalid_value",t.message);case"modeMap":{if(!Xs(e))return jn(n,o,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,a={};for(let[i,d]of Object.entries(e)){let c=r?i:Nr(i);Wu(i)&&(r?r.has(i):lL.test(c))?Zg(d)?a[c]=Ro(d):jn(n,`${o}.${i}`,"invalid_value",cL):jn(n,`${o}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":uL)}return Qs(a)?a:void 0}case"object":{if(t.bareMode&&Zg(e))return Ro(e);if(!Xs(e))return jn(n,o,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),a=d=>o?`${o}.${d}`:d;for(let d of Object.keys(e))(!Wu(d)||!r.includes(d))&&jn(n,a(d),"unknown_key",dL);let i={};for(let d of r){let c=t.children[d],u=ew(e[d],c,a(d),n);if(c.deprecated&&e[d]!==void 0&&jn(n,a(d),"deprecated_key",c.deprecated),u===void 0)continue;let p=c.alias??d,m=i[p];i[p]=Xs(m)&&Xs(u)?{...m,...u}:u}return Qs(i)?i:void 0}}}function eh(e){let t=[];return{preferences:(e===null?void 0:ew(e,fL,"",t))??{},issues:t}}function si(e){if(Array.isArray(e))return e.map(si);if(!Xs(e))return e;let t={};for(let[o,n]of Object.entries(e))Wu(o)&&n!==void 0&&(t[o]=si(n));return t}function tw(e,t){let o=si(e);for(let[n,r]of Object.entries(t)){if(!Wu(n)||r===void 0)continue;let a=o[n];o[n]=Xs(a)&&Xs(r)?tw(a,r):si(r)}return o}function mL(e){let t={},o;for(let r of e){let a=eh(r).preferences;o=ow(o,a.artifacts?.display),t=tw(t,a)}let n=t;return n.artifacts&&(o!==void 0?n.artifacts.display=o:delete n.artifacts.display),n}function gL(e,t){if(t===void 0)return e===void 0?void 0:si(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byMediaType,...t.byMediaType},a={...n?{default:n}:{},...Qs(r)?{byMediaType:r}:{}};return Qs(a)?a:void 0}function ow(e,t){if(t===void 0)return e===void 0?void 0:si(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byType,...o.byKind,...t.byType,...t.byKind},a=gL(o.files,t.files),i={...n?{default:n}:{},...Qs(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return Qs(i)?i:void 0}function th(e={},t){let o=mL(t),n={...e};if(o.showToolCalls!==void 0&&(n.showToolCalls=o.showToolCalls),o.showReasoning!==void 0&&(n.showReasoning=o.showReasoning),o.toolCallDisplay&&(n.toolCallDisplay={...e.toolCallDisplay,...o.toolCallDisplay}),o.reasoningDisplay&&(n.reasoningDisplay={...e.reasoningDisplay,...o.reasoningDisplay}),o.artifacts){let r=e.artifacts??{},a={...r};if(o.artifacts.display!==void 0){let i=ow(r.display,o.artifacts.display);i!==void 0&&(a.display=i)}o.artifacts.filePreview&&(a.filePreview={...r.filePreview,enabled:o.artifacts.filePreview.enabled}),o.artifacts.layout&&(a.layout={...r.layout,...o.artifacts.layout}),n.artifacts=a}return n}function Nl(e){let t=e.preferences;return!t||!Qs(t)?e:{...e,features:th(e.features??{},[t])}}function hL(e,t){if(!e?.trim())return t;let o=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return o?Math.max(0,Number(o[1])):t}function yL(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function bL(e,t,o){return o<t?t:Math.min(o,Math.max(t,e))}function vL(e,t,o,n){let r=e-n-2*t-o;return Math.max(0,r)}function oh(e,t){let n=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let a=/^([\d.]+)/.exec(n);return a?Number(a[1]):8}function nw(e,t,o,n,r,a,i=200){let d=hL(r,200),c=vL(t,o,n,i);c=Math.max(d,c);let u=yL(a);return u!==null&&(c=Math.min(c,u)),bL(e,d,c)}var{setLoader:xL,load:CL,provide:kD,getSync:SL}=mt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),rw=xL,sw=CL;var aw=SL;var nh=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let o=this.plugins.get(t);o&&(o.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,o)=>(o.priority??0)-(t.priority??0))}getForInstance(t){let o=this.getAll();if(!t||t.length===0)return o;let n=new Set(t.map(a=>a.id));return[...o.filter(a=>!n.has(a.id)),...t].sort((a,i)=>(i.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Fl=new nh;var iw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wL=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),lw=(e,t,o)=>{if(!iw(e)||!iw(t)||wL.has(o))return t;let n={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete n[r];continue}let a=o?`${o}.${r}`:r;n[r]=lw(e[r],t[r],a)}return n};function Bu(e,t){let o=lw(e,t,"");return ja(o)}var dw=()=>{let e=new Map,t=(r,a)=>(e.has(r)||e.set(r,new Set),e.get(r).add(a),()=>o(r,a)),o=(r,a)=>{e.get(r)?.delete(a)};return{on:t,off:o,emit:(r,a)=>{e.get(r)?.forEach(i=>{try{i(a)}catch(d){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var AL=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},ML=e=>{let t=e.trim(),o=t.indexOf("{");if(o===-1)return null;let n=0;for(let r=o;r<t.length;r+=1){let a=t[r];if(a==="{"&&(n+=1),a==="}"&&(n-=1,n===0))return t.slice(o,r+1)}return null},Ul=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=AL(e),o=ML(t);if(!o)return null;let n=JSON.parse(o);if(!n||typeof n!="object"||!n.action)return null;let{action:r,...a}=n;return{type:String(r),payload:a,raw:n}}catch{return null}},rh=e=>typeof e=="string"?e:e==null?"":String(e),Ys={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:rh(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let o=e.payload,n=rh(o.element);if(n&&t.document?.querySelector){let r=t.document.querySelector(n);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:rh(o.text)}}},cw=e=>Array.isArray(e)?e.map(t=>String(t)):[],ql=e=>{let t=new Set(cw(e.getSessionMetadata().processedActionMessageIds)),o=()=>{t=new Set(cw(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let a=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let i=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!i&&typeof a.text=="string"&&a.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 d=i?e.parsers.reduce((u,p)=>u||p?.({text:i,message:a.message})||null,null):null;if(!d)return null;t.add(a.message.id),n();let c={action:d,message:a.message};e.emit("action:detected",c);for(let u of e.handlers)if(u)try{let p=()=>{e.emit("action:resubmit",c)},m=u(d,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let h=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:h,resubmit:m.resubmit}}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:o}};var TL=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},EL=e=>e.map(t=>({...t,streaming:!1})),PL=e=>e.map(t=>({...t,status:"complete"})),Ou=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=t();return o?TL(o.getItem(e)):null},save:o=>{let n=t();if(n)try{let r={...o,messages:o.messages?EL(o.messages):void 0,artifacts:o.artifacts?PL(o.artifacts):void 0};n.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=t();if(o)try{o.removeItem(e)}catch(n){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var kL=e=>{let t=2166136261;for(let o=0;o<e.length;o++)t^=e.charCodeAt(o),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},uw=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let o=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(o)).map(n=>n.toString(16).padStart(2,"0")).join("")}catch{}return kL(e)},LL=async(e,t)=>{let o=await uw(e);return{storageKey:`${t}visitor:${o}`,leaseKey:`${t}visitor-init-lock:${o}`,lockName:`persona-visitor-init:${await uw(`${e}\0${t}`)}`}};var pw=(e,t,o)=>{let n="",r="",a="",i=!1,d=!1,c=0,u=null,p=null,m=new Set,h=()=>{if(o||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},y=()=>{let C=h();if(!C)return u;try{return C.getItem(n)}catch{return i=!0,u}},x=(C,L)=>{if(d||C===u)return;let F=u;u=C,c+=1;let X={previousToken:F,token:C,source:L,revision:c};for(let G of m)G(X)},T=C=>{d||C.key!==null&&C.key!==n||x(C.key===null?null:C.newValue??null,"external")},w=(async()=>{let C=await LL(e,t);n=C.storageKey,r=C.leaseKey,a=C.lockName,u=y(),!o&&typeof window<"u"&&window.addEventListener("storage",T)})(),k=C=>new Promise(L=>setTimeout(L,C)),P=()=>{let C=h();if(!C)return null;try{let L=C.getItem(r);if(!L)return null;let F=JSON.parse(L);return typeof F?.expiresAt=="number"&&typeof F?.ownerNonce=="string"?F:null}catch{return null}},R=C=>{let L=h();if(L)try{P()?.ownerNonce===C&&L.removeItem(r)}catch{}},b=C=>new Promise(L=>{let F=setTimeout(X,C);function X(){clearTimeout(F),window.removeEventListener("storage",G),L()}function G(E){(E.key===null||E.key===r)&&X()}window.addEventListener("storage",G)}),A=async C=>{let L=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,F=Date.now()+15e3;for(;Date.now()<F;){let X=h();if(!X)break;let G=Date.now(),E=P();if(E&&E.expiresAt>G&&E.ownerNonce!==L){await b(Math.min(E.expiresAt-G,500));continue}try{X.setItem(r,JSON.stringify({ownerNonce:L,expiresAt:G+1e4}))}catch{i=!0;break}if(await k(20+Math.random()*40),P()?.ownerNonce!==L){await b(500);continue}p=L;try{return await C()}finally{p=null,R(L)}}return C()};return{ready:w,async get(){return await w,x(y(),"external"),u},async set(C){await w;let L=h();if(L)try{L.setItem(n,C)}catch{i=!0}x(C,"local")},async clear(){await w;let C=h();if(C)try{C.removeItem(n)}catch{i=!0}x(null,"local")},revision(){return c},subscribe(C){return m.add(C),()=>{m.delete(C)}},async withFirstInitLock(C){await w;let L=globalThis.navigator?.locks;return L?.request?L.request(a,()=>C()):h()?A(C):C()},matches(C,L,F){return C===e&&L===t&&F===o},destroy(){d=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",T),p&&R(p)}}};var{setLoader:IL,load:RL}=mt({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),fw=IL,sh=RL;var ah=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},yr=e=>Object.freeze({...e}),mw=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),gw=e=>e?yr(e):null;function hw(e){let{plugins:t,config:o}=e,n=!1,r=!1,a=!1,i=!1,d=null,c=[],u=()=>{for(let b of c.splice(0))try{b()}catch(A){ah("renderHistoryView cleanup",A)}},p=(b,A)=>{for(let C of t){let L=C[b];if(L)try{let F=L(A);if(F)return F}catch(F){ah(b,F)}}return null},m=()=>({presentation:e.getPresentation(),config:o}),h={header:b=>i?p("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:yr(b.identityStatus),pendingAction:gw(b.pendingAction),copy:yr(b.copy),actions:Object.freeze({close:T.close,startNewConversation:T.startNewConversation}),defaultRenderer:b.defaultRenderer})):null,conversation:b=>i?p("renderHistoryConversation",Object.freeze({...m(),conversation:mw(b.conversation),active:b.active,pending:b.pending,open:b.open,requestDelete:b.requestDelete,defaultRenderer:b.defaultRenderer})):null,state:b=>i?p("renderHistoryState",Object.freeze({...m(),state:yr(b.state),identityStatus:yr(b.identityStatus),copy:yr(b.copy),...b.retry?{retry:b.retry}:{},...b.startNewConversation?{startNewConversation:b.startNewConversation}:{},defaultRenderer:b.defaultRenderer})):null},y=t.flatMap(b=>(b.railSections??[]).map(A=>({...A,placement:A.placement??"above-conversations",items:[],render:C=>A.render(Object.freeze({collapsed:C,presentation:e.getPresentation(),actions:T}))}))),x=e.createView({slots:h,renderDom:!1,onModelChange:()=>R(),railSections:y}),T=Object.freeze({...x.operations,close:e.close}),w=()=>(i=!0,x.setDomRenderEnabled(!0),x.element),k=b=>Object.freeze({conversations:Object.freeze(b.conversations.map(mw)),activeConversationId:b.activeConversationId,state:yr(b.state),pendingAction:gw(b.pendingAction),identityStatus:yr(b.identityStatus),nextCursor:b.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:o,copy:yr(x.copy),actions:T,defaultRenderer:w,requestRender:()=>R(),onCleanup:A=>{c.push(A)}}),P=()=>{i=!1;let b=null;for(let C of t)if(C.renderHistoryView){try{b=C.renderHistoryView(k(x.getModel()))}catch(L){ah("renderHistoryView",L),b=null}if(b)break}let A=!b||b.contains(x.element);return i=A,x.setDomRenderEnabled(A),b??x.element};function R(){if(!(!a||n||r)){r=!0;try{u();let b=P();if(b===d)return;let A=d;d=b,e.onElementChanged(b,A)}finally{r=!1}}}return a=!0,R(),{view:x,get element(){return d??x.element},requestRender:R,dispose:()=>{n=!0,u()}}}var HL=null;function yw(){return HL}var WL=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"]]),BL=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."]]),ih=e=>BL.get(e)??"Conversation history is unavailable right now.";function OL(e){if(e instanceof ln)return e;if(e instanceof Fe){let t=WL.get(e.code)??"unavailable";return new ln(t,ih(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new ln("unavailable",ih("unavailable"))}function bw(e){let t=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],n={scopes:o},r=d=>{if(!o.includes(d))throw new ln("unsupported_scope",ih("unsupported_scope"))},a=async(d,c)=>{r(d);try{return await c()}catch(u){throw OL(u)}},i=d=>{let c=!1;return{conversationId:d.session.conversationId??"",conversationRevision:d.session.conversationRevision??"",async commit(){c||(c=!0,d.commit(),await e.onActivationCommitted(d.session))},discard(){c||(c=!0,d.discard())}}};return{capabilities:n,getIdentityStatus(){return t().getHistoryIdentityStatus()},subscribeIdentityStatus(d){return t().subscribeHistoryIdentityStatus(d)},subscribeAvailability(d){return t().subscribeHistoryAvailability(d)},async list(d){return a(d.context.scope,async()=>{let c=await t().listConversations({...d.cursor?{cursor:d.cursor}:{},...d.limit!==void 0?{limit:d.limit}:{},...d.targetId?{targetId:d.targetId}:{},scope:d.context.scope});return{items:c.data,nextCursor:c.nextCursor}})},async getPage(d,c){return a(c.context.scope,async()=>{let u=await t().getConversation(d,{...c.cursor?{messageCursor:c.cursor}:{},scope:c.context.scope}),p=dx(u.messages,{...c.beforeCreatedAt?{beforeCreatedAt:c.beforeCreatedAt}:{}});return{summary:u.summary,messages:dl([],p),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(d,c){return a(c.context.scope,async()=>i(await t().prepareConversationSession(d)))},async prepareStartNew(d){return a(d.context.scope,async()=>i(await t().prepareNewConversationSession()))},async delete(d,c){await a(c.context.scope,()=>t().deleteConversation(d,{scope:c.context.scope}))},async deleteAll(d){return a(d.context.scope,()=>t().deleteAllConversations({...d.targetId!==void 0?{targetId:d.targetId}:{},scope:d.context.scope}))},async resetDevice(){try{return await t().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var DL=["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"],vw={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 lh(e){if(!e)return vw;let t={...vw};for(let o of DL){let n=e[o];typeof n=="string"&&n.length>0&&(t[o]=n)}return t}var _L="button:not([disabled])";function Du(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,o=Math.random().toString(36).slice(2,8),n=`persona-history-confirm-title-${o}`,r=`persona-history-confirm-desc-${o}`,a=Y("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),i=Y("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),d=Y("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":n,"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"}},Y("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:n},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),Y("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),Y("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},a,i));for(let u of[a,i])u.style.minHeight="44px",u.style.minWidth="88px",u.style.padding="0 16px",u.style.borderRadius="var(--persona-radius-md, 0.5rem)",u.style.cursor="pointer",u.style.font="inherit";a.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",a.style.background="transparent",a.style.color="inherit",i.style.border="none",i.style.background="var(--persona-danger, #b42318)",i.style.color="var(--persona-danger-fg, #ffffff)";let c=Y("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))"}},d);return new Promise(u=>{let p=!1,m=y=>{p||(p=!0,c.removeEventListener("keydown",h,!0),c.remove(),t?.focus(),u(y))};function h(y){if(y.key==="Escape"){y.preventDefault(),y.stopPropagation(),m(!1);return}if(y.key!=="Tab")return;let x=Array.from(d.querySelectorAll(_L));if(x.length===0)return;let T=x[0],w=x[x.length-1],k=document.activeElement;y.shiftKey&&(k===T||!d.contains(k))?(y.preventDefault(),w.focus()):!y.shiftKey&&k===w&&(y.preventDefault(),T.focus())}c.addEventListener("keydown",h,!0),c.addEventListener("pointerdown",y=>{y.target===c&&m(!1)}),a.addEventListener("click",()=>m(!1)),i.addEventListener("click",()=>m(!0)),e.host.appendChild(c),a.focus()})}var ai=Zt(pc(),1);function NL(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function FL(e,t){if(!NL(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:t}}function _u(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e;try{let r=(0,ai.parse)(o,ai.STR|ai.OBJ),a=FL(r,o);a&&(e=a)}catch{}return t=o.length,e},reset:()=>{e=null,t=0}}}function xw(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Nu(e,t){let{config:o,message:n,onPropsUpdate:r}=t,a=Cn.get(e.component);if(!a){if(Xg.includes(e.component)){Ru().catch(()=>{});let d=I("div","persona-w-full");return d.setAttribute("data-persona-artifact-pending","true"),d}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let i={message:n,config:o,updateProps:d=>{r&&r(d)}};try{return a(e.props,i)}catch(d){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,d),null}}function Cw(){let e=_u();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Sw(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function $l(e){let t=Sw(e);if(!t)return!1;try{let o=JSON.parse(t);return typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"}catch{return!1}}function Fu(e){let t=Sw(e);if(!t)return null;try{let o=JSON.parse(t);if(typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"){let n=o;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:t}}}catch{}return null}var UL=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Uu(e){let{onSubmit:t,onDismiss:o,title:n="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:c=!0,ratingLabels:u=UL}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,h=document.createElement("div");h.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=n,y.appendChild(x);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=r,y.appendChild(T),h.appendChild(y);let w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-csat",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let C=1;C<=5;C++){let L=document.createElement("button");L.type="button",L.className="persona-feedback-rating-btn persona-feedback-star-btn",L.setAttribute("role","radio"),L.setAttribute("aria-checked","false"),L.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${u[C-1]}`),L.title=u[C-1],L.dataset.rating=String(C),L.innerHTML=`
41
41
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
42
42
  <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>
43
43
  </svg>
44
- `,L.addEventListener("click",()=>{m=x,k.forEach((F,X)=>{let G=X<x;F.classList.toggle("selected",G),F.setAttribute("aria-checked",X===x-1?"true":"false")})}),k.push(L),T.appendChild(L)}y.appendChild(T);let P=null;if(u){let x=document.createElement("div");x.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=a,P.rows=3,P.setAttribute("aria-label","Additional comments"),x.appendChild(P),y.appendChild(x)}let R=document.createElement("div");R.className="persona-feedback-actions";let b=document.createElement("button");b.type="button",b.className="persona-feedback-btn persona-feedback-btn-skip",b.textContent=d,b.addEventListener("click",()=>{o?.(),p.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=i,w.addEventListener("click",async()=>{if(m===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let x=P?.value.trim()||void 0;await t(m,x),p.remove()}catch(x){w.disabled=!1,w.textContent=i,console.error("[CSAT Feedback] Failed to submit:",x)}}),R.appendChild(b),R.appendChild(w),y.appendChild(R),p.appendChild(y),p}function Uu(e){let{onSubmit:t,onDismiss:o,title:n="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:u=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,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,h=document.createElement("div");h.className="persona-feedback-content";let S=document.createElement("div");S.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=n,S.appendChild(A);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=r,S.appendChild(T),h.appendChild(S);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let P=document.createElement("div");P.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=c;let b=document.createElement("span");b.className="persona-feedback-label-high",b.textContent=p,P.appendChild(R),P.appendChild(b);let w=document.createElement("div");w.className="persona-feedback-numbers";let x=[];for(let E=0;E<=10;E++){let _=document.createElement("button");_.type="button",_.className="persona-feedback-rating-btn persona-feedback-number-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`Rating ${E} out of 10`),_.textContent=String(E),_.dataset.rating=String(E),E<=6?_.classList.add("persona-feedback-detractor"):E<=8?_.classList.add("persona-feedback-passive"):_.classList.add("persona-feedback-promoter"),_.addEventListener("click",()=>{y=E,x.forEach((O,W)=>{O.classList.toggle("selected",W===E),O.setAttribute("aria-checked",W===E?"true":"false")})}),x.push(_),w.appendChild(_)}k.appendChild(P),k.appendChild(w),h.appendChild(k);let L=null;if(u){let E=document.createElement("div");E.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=a,L.rows=3,L.setAttribute("aria-label","Additional comments"),E.appendChild(L),h.appendChild(E)}let F=document.createElement("div");F.className="persona-feedback-actions";let X=document.createElement("button");X.type="button",X.className="persona-feedback-btn persona-feedback-btn-skip",X.textContent=d,X.addEventListener("click",()=>{o?.(),m.remove()});let G=document.createElement("button");return G.type="button",G.className="persona-feedback-btn persona-feedback-btn-submit",G.textContent=i,G.addEventListener("click",async()=>{if(y===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}G.disabled=!0,G.textContent="Submitting...";try{let E=L?.value.trim()||void 0;await t(y,E),m.remove()}catch(E){G.disabled=!1,G.textContent=i,console.error("[NPS Feedback] Failed to submit:",E)}}),F.appendChild(X),F.appendChild(G),h.appendChild(F),m.appendChild(h),m}var ai="persona-chat-history",_k=30*1e3,Nk=641,ii="data-persona-composer-reason",Fk={"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 Uk(e){if(!e)return[];let t=[],o=Array.from(e.items??[]);for(let n of o){if(n.kind!=="file"||!n.type.startsWith("image/"))continue;let r=n.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let a=Fk[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${a}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith("image/")&&t.push(n);return t}function qu(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function qk(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function $k(e){try{let t=e==="local"?localStorage:sessionStorage,o="__persist_test__";return t.setItem(o,"1"),t.removeItem(o),t}catch{return null}}var ah=e=>!e||typeof e!="object"?{}:{...e},xw=e=>e.map(t=>({...t,streaming:!1})),Cw=(e,t,o)=>{let n=e?.markdown?Zi(e.markdown):null,r=lc(e?.sanitize);e?.postprocessMessage&&r&&e?.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 a=!1,i=d=>{let u=d.text??"",c=d.message.rawContent??null;if(t){let y=t.process({text:u,raw:c??u,message:d.message,streaming:d.streaming});y!==null&&(u=y.text,y.persist||(d.message.__skipPersist=!0),y.resubmit&&!d.streaming&&o&&o())}let p=Dn()!==null,m;if(e?.postprocessMessage){let y=e.postprocessMessage({...d,text:u,raw:c??d.text??""});m=r?r(y):y}else if(n){let y=d.streaming?fv(u):u,h=n(y);m=r&&p?r(h):h}else m=ir(u);return m};return d=>{try{return i(d)}catch(u){return a||(a=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",u)),ir(d.text??"")}}};function Sw(e){let t=I("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let o=e?.iconName??"upload",n=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",a=e?.iconStrokeWidth??.5,i=ce(o,n,r,a);if(i&&t.appendChild(i),e?.label){let d=I("span","persona-drop-overlay-label");d.textContent=e.label,t.appendChild(d)}return t}var jk=(e,t)=>{let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];o[n]=a?{...a,...r}:r}return o},zk=e=>e.reduce((t,o)=>({blocks:[...t.blocks,...o.blocks],contentParts:[...t.contentParts,...o.contentParts],context:jk(t.context,o.context)}),{blocks:[],contentParts:[],context:{}}),$u=(e,t,o)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=ja(t),r=()=>{Fx({delayMs:n.tooltip?.delayMs??200,skipDelayMs:n.tooltip?.skipDelayMs??300})};r();let a=n.features;n=Nl(n);let i=Fl.getForInstance(n.plugins),d=UC(e),u=[],c=!1,p=OS(()=>n),m=null,y=null,h=null,S=!1,A=null,T=s=>{m=s,s.initApprovalUi({webMcpToolTitle:dc});let l=s.createBuiltInApprovalPlugin();y=l.plugin,h=l.teardown},k=()=>{if(m)return m;let s=qS();return s?(T(s),s):(US().then(l=>{S||m||(T(l),A?.())}).catch(()=>{}),null)},P=!1,R=!1,b=null,w=(s,l,f,g)=>{if(!s.querySelector("[data-tv-form]"))return;let v=nw();if(v){v.enhanceWithForms(s,l,f,g);return}ow().then(()=>{P||R||!b||(R=!0,b())}).catch(()=>{})};n.components&&Cn.registerAll(n.components);let x=aw(),F=n.persistState===!1?null:n.storageAdapter??Bu(),X={},G=null,E,_=new Promise(s=>{E=s}),O,W=!1,oe=s=>{if(n.onStateLoaded)try{let l=n.onStateLoaded(s);if(l&&typeof l=="object"&&"state"in l){let{state:f,open:g}=l;return g&&(W=!0),f}return l}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}return s};if(F?.load)try{let s=F.load();if(s&&typeof s.then=="function")G=s.then(l=>oe(l??{messages:[],metadata:{}}));else{let f=oe(s??{messages:[],metadata:{}});f.metadata&&(X=ah(f.metadata)),f.messages?.length&&(n={...n,initialMessages:f.messages}),f.artifacts?.length&&(n={...n,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),O=f.draft}}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",s)}else if(n.onStateLoaded)try{let s=oe({messages:[],metadata:{}});s.messages?.length&&(n={...n,initialMessages:s.messages})}catch(s){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",s)}G||E();let Q=()=>X,de=s=>{X=s({...X})??{},Si()},pe=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ul],xe=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Ys.message,Ys.messageAndClick],Pe=ql({parsers:pe,handlers:xe,getSessionMetadata:Q,updateSessionMetadata:de,emit:x.emit,documentRef:typeof document<"u"?document:null});Pe.syncFromMetadata();let ge=n.launcher?.enabled??!0,Ke=n.launcher?.autoExpand??!1,Bt=n.autoFocusInput??!1,ke=Ke,z=ge,Ue=n.layout?.header?.layout,Ge=!1,Ae=()=>Xr(n),De=()=>ge||Ae(),he=Ae()?!1:ge?Ke:!0,gt=!1,dn=null,Js=()=>{gt=!0,dn&&clearTimeout(dn),dn=setTimeout(()=>{gt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),gt=!1)},1e4)},oo=Cw(n,Pe,Js),Xo=n.features?.showReasoning??!0,jn=n.features?.showToolCalls??!0,Ht=n.features?.showEventStreamToggle??!1,Yr=n.features?.scrollToBottom??{},Ao=n.features?.scrollBehavior??{},Sn=()=>(typeof n.persistState=="object"?n.persistState?.keyPrefix:void 0)??"persona-",Jr=`${Sn()}event-stream`,po=null,di=n.features?.eventStream?.maxEvents??2e3,Tt=null,ut=null,cn=null,zl=!1,B=null,te=!1,C=null,U=0,q=(s,l)=>{Tt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:s,timestamp:Date.now(),payload:JSON.stringify(l)})},$=(s,l)=>{ut?.processEvent(s,l),Tt?q(s,l):cn&&(cn.length>=di&&cn.shift(),cn.push({type:s,payload:l}))},ee=()=>{Tt||!Ht||(cn??(cn=[]),jg().then(s=>{if(zl||Tt||!Ht)return;po=new s.EventStreamStore(Jr),Tt=new s.EventStreamBuffer(di,po),ut=ut??new s.ThroughputTracker,po.open().then(()=>Tt?.restore()).catch(f=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let l=cn??[];cn=null;for(let f of l)ut?.processEvent(f.type,f.payload),q(f.type,f.payload)}).catch(()=>{}))};Ht&&ee();let ne=!1,ie=null,Se=()=>{},ht=()=>{},$e=()=>{},Rt=()=>{},wt=()=>{},Zr=()=>te||ne&&ie==="panel",Bo={onCopy:s=>{x.emit("message:copy",s),H?.isClientTokenMode()&&H.submitMessageFeedback(s.id,"copy").catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",l)}),n.messageActions?.onCopy?.(s)},onFeedback:s=>{x.emit("message:feedback",s),H?.isClientTokenMode()&&H.submitMessageFeedback(s.messageId,s.type).catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",l)}),n.messageActions?.onFeedback?.(s)}},qt=n.statusIndicator??{},fo=s=>s==="idle"?qt.idleText??Ut.idle:s==="connecting"?qt.connectingText??Ut.connecting:s==="connected"?qt.connectedText??Ut.connected:s==="error"?qt.errorText??Ut.error:s==="paused"?qt.pausedText??Ut.paused:s==="resuming"?qt.resumingText??Ut.resuming:Ut[s];function ao(s,l,f,g){if(!s.hasAttribute(ii))if(g==="idle"&&f.idleLink){s.textContent="";let v=document.createElement("a");v.href=f.idleLink,v.target="_blank",v.rel="noopener noreferrer",v.textContent=l,v.style.color="inherit",v.style.textDecoration="none",s.appendChild(v)}else s.textContent=l}let Oo=BS({config:n,showClose:De()}),{wrapper:Xe,panel:we,pillRoot:Xt}=Oo.shell,_e=Oo.panelElements,{container:ue,body:re,messagesWrapper:Le,starterSuggestions:Vu,transcriptSuggestions:ci,suggestions:hr,textarea:le,sendButton:Me,composerForm:un,statusText:st,welcomeHost:Mo,welcomeIconHolder:$w,greetingHost:Do,introKicker:jw,introTitle:zw,introSubtitle:Vw,closeButton:Fe,iconHolder:Et,headerTitle:yr,headerSubtitle:es,header:Te,footer:Ie,actionsRow:Kw}=_e,Ku=_e.leftActions,Vl=_e.rightActions,wn=_e.sendButtonWrapper,xh=_e.setSendButtonMode,se=_e.micButton,_o=_e.micButtonWrapper,At=_e.attachmentButton,To=_e.attachmentButtonWrapper,yt=_e.attachmentInput,Eo=_e.attachmentPreviewsContainer;ue.classList.add("persona-relative"),re.classList.add("persona-relative");let Gw=12,ui=()=>Yr.label??"",Xw=()=>Yr.iconName??"arrow-down",Qw=()=>Yr.enabled!==!1,No=()=>Ao.mode??"anchor-top",br=()=>No()==="follow"||No()==="anchor-top"&&Ci,pi=()=>Ao.anchorTopOffset??16,Yw=()=>Ao.restorePosition??"bottom",Ch=()=>Ao.pauseOnInteraction===!0,Sh=()=>Ao.showActivityWhilePinned!==!1,wh=()=>Ao.announce===!0,Gu=()=>Ao.scrollbar??"on-scroll",Ot=I("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");Ot.type="button",Ot.style.display="none",Ot.setAttribute("data-persona-scroll-to-bottom","true");let fi=I("span","persona-flex persona-items-center"),Xu=I("span",""),ts=I("span","");ts.setAttribute("data-persona-scroll-to-bottom-count",""),ts.style.display="none",Ot.append(fi,Xu,ts),ue.appendChild(Ot);let Qo=I("div","persona-stream-anchor-spacer");Qo.setAttribute("aria-hidden","true"),Qo.setAttribute("data-persona-anchor-spacer",""),Qo.style.flexShrink="0",Qo.style.pointerEvents="none",Qo.style.height="0px",Qo.style.display="none",re.appendChild(Qo);let zn=I("div","persona-sr-only");zn.setAttribute("aria-live","polite"),zn.setAttribute("aria-atomic","true"),zn.setAttribute("role","status"),zn.setAttribute("data-persona-live-region",""),Object.assign(zn.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"}),ue.appendChild(zn);let mi=null,Kl=null,Gl=s=>{!wh()||!s||(Kl=s,mi===null&&(mi=setTimeout(()=>{mi=null,Kl&&wh()&&(zn.textContent=Kl),Kl=null},400)))},Xl="empty",Ql=0,Qu=()=>Ql||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,os=()=>{let l=Ie.style.display==="none"?0:Ie.offsetHeight;Ot.style.bottom=`${l+Qu()+Gw}px`};os();let Yu=()=>{na||(Ie.style.marginBottom=Ql>0?`${Ql}px`:"")},Yl=()=>{let s=lg(n,Ae()),l=xn(n),g=Ie.style.display==="none"?0:Ie.offsetHeight,v=l.anchor==="center"&&Xl==="empty"?Ml(l.anchorComposerTop)??Ml("44%"):null,M=v===null||Ae()?0:_C({columnHeight:ue.clientHeight,footerHeight:g,fraction:v});e.style.setProperty("--persona-composer-overlay-height",`${g}px`),e.style.setProperty("--persona-composer-lift",`${s==="overlay"?M:0}px`),Ql=s==="block"?M:0,Yu(),os()},Ah=()=>{let s=!!ui();Ot.setAttribute("aria-label",ui()||"Jump to latest"),Ot.title=ui(),Ot.setAttribute("data-persona-scroll-to-bottom-has-label",s?"true":"false"),fi.innerHTML="";let l=ce(Xw(),"14px","currentColor",2);l?(fi.appendChild(l),fi.style.display=""):fi.style.display="none",Xu.textContent=ui(),Xu.style.display=s?"":"none"};Ah();let Ze=null,Wt=null,Ce=Wx(),Jw=s=>{try{ue.dispatchEvent(new CustomEvent("persona:composer:state",{detail:s,bubbles:!0,composed:!0}))}catch{}};Ce.subscribe(Jw);let An=()=>{Ce.setText(le?.value??"")},ns=()=>{Ce.setMentionRefs(Wt?.getMentionRefs()??[])},Zw=s=>({id:s.id,name:s.file.name,mimeType:s.file.type,size:s.file.size,status:s.status,progress:s.progress,error:s.error}),Mh=s=>{let l=Object.freeze(s.map(Zw));Ce.setAttachments(l);try{n.attachments?.onChange?.(l)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}wp()};Ce.setSelectedModelId(n.composer?.selectedModelId);let gi=()=>n.composer?.modes??[],Zs=()=>iC(gi(),n.composer?.modeGroups);{let s=ou(n.composer?.defaultActiveModeIds??[],gi());s.length&&Ce.setActiveModeIds(s)}function Th(s){if(Ce.getState().selectedModelId!==s){Ce.setSelectedModelId(s),vr?.repaint();try{n.composer?.onModelChange?.(s)}catch(l){console.error("[AgentWidget] composer.onModelChange failed:",l)}}}function Jl(s){Ce.setActiveModeIds(s),Vn?.render(s,Zs()),ea.forEach(l=>l.repaint()),Tn?.resolve(),wd(),pn()}function Ju(s){Jl(lC(Ce.getState().activeModeIds,s,gi(),n.composer?.modeGroups))}let vr=null,Zu=null,Vn=null,ea=new Map,xr=null;function Mn(s){Ce.setQuote(s),xr?.render(Ce.getState().quote),pn(),by()}let Eh=!1;function ep(){let s=n.composer?.streamingSubmitBehavior??"block";return s!=="interrupt"?s:n.clientToken?"interrupt":(!Eh&&n.debug===!0&&(Eh=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Cr=null;function ta(s){Ce.setPendingSubmission(s),Cr?.render(Ce.getState().pendingSubmission),pn()}let eA=s=>{let l=ea.get(s);if(l)return l;let f=uC({groupId:s,getGroup:()=>n.composer?.modeGroups?.find(g=>g.id===s),getModes:()=>gi().filter(g=>g.groupId===s),getActiveIds:()=>Ce.getState().activeModeIds,onSelect:g=>Ju(g)});return ea.set(s,f),f},tA=()=>{let s=[],l=Ce.getState().activeModeIds,f=new Set;if(gi().forEach((g,v)=>{if(tu(g.groupId,n.composer?.modeGroups)){let M=g.groupId;if(f.has(M))return;f.add(M);let N=eA(M);N.action.order=eg(v),N.action.label=n.composer?.modeGroups?.find(V=>V.id===M)?.label??M,s.push(N.action);return}s.push({id:sC(g.id),kind:"button",placement:"start",order:eg(v),presentation:g.presentation??"auto",label:g.label,shortLabel:g.shortLabel,iconName:g.iconName,pressed:l.includes(g.id),onSelect:()=>Ju(g.id)})}),n.composer?.models?.length&&!i.some(g=>g.renderComposer)){let g=n.composer?.modelPicker?.presentation??"native";(!vr||Zu!==g)&&(Zu=g,vr=nC({getModels:()=>n.composer?.models??[],getSelectedModelId:()=>Ce.getState().selectedModelId,onSelect:v=>Th(v),presentation:g,getSuffix:()=>n.composer?.modelPicker?.suffix})),s.push(vr.action)}return s},tp=null,Ph=i.find(s=>s.renderHeader);if(Ph?.renderHeader){let s=Ph.renderHeader({config:n,defaultRenderer:()=>{let l=pr({config:n,showClose:De()});return js(ue,l,n),l.header},onClose:()=>dt(!1,"user")});if(s){let l=Te;l&&(l.replaceWith(s),Te=s,Oo.header.element=s)}}let Lh=()=>{B&&(re.style.display="none",Ie.parentNode?.insertBefore(B.element,Ie),B.update())},op=()=>{if(!Tt){ee();return}if(te=!0,B?Lh():jg().then(l=>{B||!te||!Tt||(B=l.createEventStreamView({buffer:Tt,getFullHistory:()=>Tt.getAllFromStore(),onClose:()=>oa(),config:n,plugins:i,getThroughput:()=>ut?.getMetric()??{status:"idle"},renderIconByName:ce}),Lh())}).catch(()=>{oa()}),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Co.actionIconColor}`;let l=n.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(f=>f&&tt.classList.add(f))}let s=()=>{if(!te)return;let l=Date.now();l-U>=200&&(B?.update(),U=l),C=requestAnimationFrame(s)};U=0,C=requestAnimationFrame(s),jt(),x.emit("eventStream:opened",{timestamp:Date.now()})},oa=()=>{if(te){if(te=!1,B&&B.element.remove(),re.style.display="",tt){tt.style.boxShadow="";let s=n.features?.eventStream?.classNames?.toggleButtonActive;s&&s.split(/\s+/).forEach(l=>l&&tt.classList.remove(l))}C!==null&&(cancelAnimationFrame(C),C=null),jt(),x.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(Ht){let s=n.features?.eventStream?.classNames,l="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"+(s?.toggleButton?" "+s.toggleButton:"");tt=I("button",l),tt.style.width="28px",tt.style.height="28px",tt.style.color=Co.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let f=Ft(_a,"18px","currentColor",1.5);f&&tt.appendChild(f);let g=_e.clearChatButtonWrapper,v=_e.closeButtonWrapper,M=g||v;M&&M.parentNode===Te?Te.insertBefore(tt,M):Te.appendChild(tt),tt.addEventListener("click",()=>{te?oa():op()})}let kh=s=>{let l=n.attachments;if(!l?.enabled)return;let f=s.querySelector("[data-persona-composer-attachment-previews]")??s.querySelector(".persona-attachment-previews");if(!f){f=I("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 v=s.querySelector("[data-persona-composer-form]");v?.parentNode?v.parentNode.insertBefore(f,v):s.insertBefore(f,s.firstChild)}if(!(s.querySelector("[data-persona-composer-attachment-input]")??s.querySelector('input[type="file"]'))){let v=I("input");v.type="file",v.setAttribute("data-persona-composer-attachment-input",""),v.accept=(l.allowedTypes??ur).join(","),v.multiple=(l.maxFiles??4)>1,v.style.display="none",v.setAttribute("aria-label",l.buttonTooltipText??"Attach files"),s.appendChild(v)}},na=!1,Ih=s=>{let l=i.find(v=>v.renderComposer);if(!l?.renderComposer)return null;let f=n.composer,g=c?H.isStreaming():!1;return l.renderComposer({config:n,defaultRenderer:s,requestRender:()=>$b(),storage:p(l.id),onSubmit:v=>{!H||H.isStreaming()||Qd(v.trim(),{consumeDraft:!1})},streaming:g,disabled:g,openAttachmentPicker:()=>{Pr()||yt?.click()},models:f?.models,selectedModelId:Ce.getState().selectedModelId??f?.selectedModelId,onModelChange:v=>Th(v),onVoiceToggle:n.voiceRecognition?.enabled===!0?()=>{tp?.()}:void 0})},Hh=Ih(()=>Ks({config:n}).footer);Hh&&(Oo.replaceComposer(Hh),Ie=Oo.composer.footer,na=!0);let ot=null,oA=s=>{un=s.form,le=s.input,wn=s.sendButton?s.sendButton.parentElement:null,s.sendButton&&(Me=s.sendButton),s.micButton&&(se=s.micButton,_o=s.micButton.parentElement),s.found.status&&(st=s.found.status),s.found.suggestions&&(hr=s.found.suggestions),s.attachmentButton&&(At=s.attachmentButton,To=s.attachmentButton.parentElement),yt=s.attachmentInput??null,Eo=s.attachmentPreviews??null,s.found.actionsRow&&(Kw=s.found.actionsRow),Ku=s.found.actionsStart,Vl=s.found.actionsEnd};function np(){let s=le;if(!s)return;let l=n.composer?.inputAttributes,f=!l?.ariaLabel&&!(s instanceof HTMLTextAreaElement)?s.getAttribute("aria-label"):null;Kc(s,l),f&&s.setAttribute("aria-label",f),Vc(s,{submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Cl(s)}),zx(s,zc(n.composer?.maxLines,Ae()?5:3))}let Rh=s=>{ot=Ox(s,{debug:n.debug===!0}),ot&&oA(ot),np()};kh(Ie),Rh(Ie),An();let hi=Kr(n,Ae());hi&&(Le.style.maxWidth=hi,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%",Do.style.maxWidth=hi,Do.style.marginLeft="auto",Do.style.marginRight="auto",Do.style.width="100%",Vu.style.maxWidth=hi,ci.style.maxWidth=hi,ci.style.marginLeft="auto",ci.style.marginRight="auto",ci.style.width="100%");let Wh=()=>{let s=Kr(n,Ae());if(!(!s||Ae()))for(let l of[un,hr,Eo,st])l&&(l.style.maxWidth=s,l.style.marginLeft="auto",l.style.marginRight="auto",l.style.width="100%")};Wh();let Bh=()=>{!n.attachments?.enabled||!yt||!Eo||(Ze?Ze.remountPreviews(Eo):(Ze=Fs.fromConfig(n.attachments,Mh),Ze.setPreviewsContainer(Eo)),ot?.addListener(yt,"change",s=>{let l=s.target;Ze?.handleFileSelect(l.files),l.value=""}),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(Sw(n.attachments.dropOverlay)))};Bh();let nA=()=>Wt?.prefetch(),Oh=()=>{if(!n.contextMentions?.enabled||!le)return;let s=ot?.header??null,l=s?Zm(s):void 0;if(Wt=RC({config:n,textarea:le,anchor:un??le,getMessages:()=>H.getMessages(),liveRegionHost:ue,chipRow:l}),Wt&&!l){let f=le;f.parentElement?.insertBefore(Wt.contextRow,f)}};Oh();let Tn=null,rA={getState:()=>Ce.getState(),getValue:()=>le?.value??"",setValue:s=>{le&&(le.value=s,le.dispatchEvent(new Event("input",{bubbles:!0})),An())},submit:()=>{CC(ot?.form??null)},openAttachmentPicker:()=>{Pr()||yt?.click()},toggleVoice:()=>{tp?.()},requestRender:()=>Tn?.resolve()},sA=()=>{let s=[];return(Wt?.affordanceButtons??[]).forEach((f,g)=>{s.push({id:`core:mention-${g}`,placement:"start",order:Un.mention+g,element:f,managed:!0})}),To&&s.push({id:"core:attachment",placement:"start",order:Un.attachment,element:To}),_o&&s.push({id:"core:mic",placement:"end",order:Un.mic,element:_o}),wn&&s.push({id:"core:send",placement:"end",order:Un.send,element:wn}),s},Dh=()=>{Tn?.destroy(),Tn=eC({getBindings:()=>ot,collect:()=>({builtIns:sA(),configActions:[...tA(),...n.composer?.actions??[]],plugins:i,contributionContext:{config:n,getState:()=>Ce.getState(),requestRender:()=>Tn?.resolve()},debug:n.debug===!0}),actionContext:rA,getState:()=>Ce.getState(),getOverflow:()=>n.composer?.actionOverflow,reportError:(s,l)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${l.actionId}" failed:`,s)}}),Tn.resolve()};Dh();let rp=()=>{if(Vn?.destroy(),Vn=null,!Zs().length)return;let s=ot?.header;s&&(Vn=rC({row:Zm(s),onRemove:l=>Ju(l),initialIds:Ce.getState().activeModeIds}),Vn.render(Ce.getState().activeModeIds,Zs()))};rp();let _h=()=>{xr?.destroy(),xr=null,Cr?.destroy(),Cr=null;let s=ot?.header;s&&(xr=pC({onDismiss:()=>Mn(void 0)}),s.appendChild(xr.element),xr.render(Ce.getState().quote),ep()==="defer-one"&&(Cr=fC({onEdit:()=>HM(),onRemove:()=>ta(void 0)}),s.appendChild(Cr.element),Cr.render(Ce.getState().pendingSubmission)))};_h();let sp=vC(),aA=()=>{let s=ot?.header?.querySelector(Jm);if(s)return s.childElementCount>0;let l=Ce.getState();return l.mentionRefs.length>0||ou(l.activeModeIds,Zs()).length>0},Nh=()=>!1;function pn(){let s=Ce.getState(),l=sp.observe(xC(le),s.text);Ie.toggleAttribute("data-persona-composer-compact",bC({text:s.text,wrapped:l,hasAttachments:s.attachments.length>0,hasChips:aA(),hasQuote:s.quote!==void 0,hasPendingSubmission:s.pendingSubmission!==void 0,dictationActive:Nh()}))}function Fh(){n.composer?.layout==="single-row"&&!Ae()?Ie.setAttribute("data-persona-composer-layout","single-row"):Ie.removeAttribute("data-persona-composer-layout")}Fh(),Ce.subscribe(()=>{Tn?.sync(),wp(),Cd(),pn(),by()}),Cd();let Uh=!1,iA=s=>{if(Uh||n.debug!==!0)return;let l=["messages","composer"].filter(f=>s[f]);l.length&&(Uh=!0,console.warn(`[persona] layout.slots.${l.join(" and layout.slots.")} ${l.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 s=n.layout?.slots??{};iA(s);let l=g=>{switch(g){case"body-top":return re.querySelector("[data-persona-intro-card]");case"messages":return Le;case"footer-top":return hr;case"composer":return un;case"footer-bottom":return st;default:return null}},f=(g,v)=>{switch(g){case"header-left":case"header-center":case"header-right":if(g==="header-left")Te.insertBefore(v,Te.firstChild);else if(g==="header-right")Te.appendChild(v);else{let M=Te.querySelector(".persona-flex-col");M?M.parentNode?.insertBefore(v,M.nextSibling):Te.appendChild(v)}break;case"body-top":{let M=re.querySelector("[data-persona-intro-card]");M?M.replaceWith(v):re.insertBefore(v,re.firstChild);break}case"body-bottom":re.appendChild(v);break;case"footer-top":hr.replaceWith(v);break;case"footer-bottom":st.replaceWith(v);break;default:break}};for(let[g,v]of Object.entries(s))if(v)try{let M=v({config:n,defaultContent:()=>l(g)});M&&f(g,M)}catch(M){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${g}":`,M)}})();let qh=s=>{let f=s.target.closest('button[data-expand-header="true"]');if(!f)return;let g=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;let M=f.getAttribute("data-bubble-type");if(M==="reasoning")ei.has(v)?ei.delete(v):ei.add(v),DS(v,g);else if(M==="tool")ti.has(v)?ti.delete(v):ti.add(v),NS(v,g,n);else if(M==="approval"&&m){let V=((n.approval!==!1?n.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",j=m.approvalDetailsExpansionState.get(v)??V;m.approvalDetailsExpansionState.set(v,!j),m.updateApprovalDetailsUI(v,g,n)}Dt.delete(v)};Le.addEventListener("pointerdown",s=>{s.target.closest('button[data-expand-header="true"]')&&(s.preventDefault(),qh(s))}),Le.addEventListener("keydown",s=>{let l=s.target;(s.key==="Enter"||s.key===" ")&&l.closest('button[data-expand-header="true"]')&&(s.preventDefault(),qh(s))}),Le.addEventListener("copy",s=>{let{clipboardData:l}=s;if(!l)return;let f=Le.getRootNode(),g=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!g||g.isCollapsed)return;let v=g.toString(),M=$C(v);!M||M===v||(l.setData("text/plain",M),s.preventDefault())});let ap=new Map,$h=null,jh="idle",lA={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},dA=(s,l)=>{let{icon:f,label:g}=lA[l];s.setAttribute("aria-label",g),s.title=g,s.setAttribute("aria-pressed",l==="idle"?"false":"true"),s.classList.toggle("persona-message-action-active",l!=="idle"),s.classList.toggle("persona-message-action-loading",l==="loading");let v=ce(f,14,"currentColor",2);v&&(s.innerHTML="",s.appendChild(v))},zh=()=>{Le.querySelectorAll('[data-action="read-aloud"]').forEach(l=>{let g=l.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;dA(l,g&&g===$h?jh:"idle")})};Le.addEventListener("click",s=>{let f=s.target.closest(".persona-message-action-btn[data-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest("[data-actions-for]");if(!g)return;let v=g.getAttribute("data-actions-for");if(!v)return;let M=f.getAttribute("data-action");if(M==="copy"){let V=H.getMessages().find(j=>j.id===v);if(V&&Bo.onCopy){let j=V.content||"";navigator.clipboard.writeText(j).then(()=>{f.classList.add("persona-message-action-success");let K=Ft(Na,14,"currentColor",2);K&&(f.innerHTML="",f.appendChild(K)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let J=Ft(Fa,14,"currentColor",2);J&&(f.innerHTML="",f.appendChild(J))},2e3)}).catch(K=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",K)}),Bo.onCopy(V)}}else if(M==="read-aloud")H.toggleReadAloud(v);else if(M==="upvote"||M==="downvote"){let V=(ap.get(v)??null)===M,j=M==="upvote"?"thumbs-up":"thumbs-down";if(V){ap.delete(v),f.classList.remove("persona-message-action-active");let K=ce(j,14,"currentColor",2);K&&(f.innerHTML="",f.appendChild(K))}else{let K=M==="upvote"?"downvote":"upvote",J=g.querySelector(`[data-action="${K}"]`);if(J){J.classList.remove("persona-message-action-active");let ct=ce(K==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ct&&(J.innerHTML="",J.appendChild(ct))}ap.set(v,M),f.classList.add("persona-message-action-active");let ae=ce(j,14,"currentColor",2);ae&&(ae.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(ae)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Je=H.getMessages().find(lt=>lt.id===v);Je&&Bo.onFeedback&&Bo.onFeedback({type:M,messageId:Je.id,message:Je})}}else if(M==="regenerate")Zl?.regenerate(v);else if(M==="edit")Zl?.edit(v);else if(M==="quote")Zl?.quote(v);else if(M?.startsWith(xu)){let N=M.slice(xu.length),V=n.messageActions?.custom?.find(K=>K.id===N),j=H.getMessages().find(K=>K.id===v);if(!V||!j)return;try{V.onSelect(j)}catch(K){console.error(`[AgentWidget] messageActions.custom "${N}" onSelect failed:`,K)}}});let Zl=null;Le.addEventListener("click",s=>{let f=s.target.closest("button[data-approval-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest(".persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;let M=f.getAttribute("data-approval-action");if(!M)return;let N=M==="approve"?"approved":"denied",j=H.getMessages().find(J=>J.id===v);if(!j?.approval)return;let K=g.querySelector("[data-approval-buttons]");K&&K.querySelectorAll("button").forEach(ae=>{ae.disabled=!0,ae.style.opacity="0.5",ae.style.cursor="not-allowed"}),j.approval.toolType==="webmcp"?H.resolveWebMcpApproval(v,N):H.resolveApproval(j.approval,N)});let je=null,Vh=!1,yi=null,rs=()=>{},bi="none",ed=null,Yo={artifacts:[],selectedId:null},Kn=!1,fn=!1,vi=!1,ra=!1,Kh=()=>ra||Yo.artifacts.some(s=>_n(n.features?.artifacts,s)==="panel"),td=()=>Yo.artifacts.length>0&&!Kn&&Kh(),it={current:null},ip=(s,l)=>{let f=H.getArtifactById(l),g=f?.markdown,v=f?.title||"artifact",M=f?.file,N=f?.artifactType??"markdown";if(!g){let K=s.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(K){let ae=H.getMessages().find(fe=>fe.id===K);if(ae?.rawContent)try{let fe=JSON.parse(ae.rawContent);g=fe?.props?.markdown,v=fe?.props?.title||v,fe?.props?.file&&typeof fe.props.file=="object"&&(M=fe.props.file),!f&&typeof fe?.props?.artifactType=="string"&&(N=fe.props.artifactType)}catch{}}}return{markdown:g,title:v,file:M,artifactType:N}};Le.addEventListener("click",s=>{let f=s.target.closest("[data-download-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-download-artifact");if(!g||n.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:g})===!0)return;let{markdown:M,title:N,file:V}=ip(f,g);if(!M)return;let j=fr();j&&j.triggerArtifactDownload(j.downloadInfoFor({title:N,markdown:M,file:V}))}),Le.addEventListener("click",s=>{let f=s.target.closest("[data-artifact-custom-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-artifact-custom-action");if(!g)return;let v=f.closest("[data-artifact-inline]"),M=v?null:f.closest("[data-open-artifact]"),N=v?v.getAttribute("data-artifact-inline"):M?.getAttribute("data-open-artifact")??null,j=(v?n.features?.artifacts?.inlineActions:n.features?.artifacts?.cardActions)?.find(lt=>lt.id===g);if(!j)return;let{markdown:K,title:J,file:ae,artifactType:fe}=ip(f,N??""),Je={artifactId:N,title:J,artifactType:fe,markdown:K,file:ae};try{Promise.resolve(j.onClick(Je)).catch(()=>{})}catch{}}),Le.addEventListener("click",s=>{let f=s.target.closest("[data-copy-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-copy-artifact");if(!g)return;let v=H.getArtifactById(g),M=fr();if(!M)return;let N="";if(v)N=M.artifactCopyText(v);else{let{markdown:V,file:j,artifactType:K}=ip(f,g);K==="markdown"&&(N=M.artifactCopyText({id:g,artifactType:"markdown",status:"complete",markdown:V??"",...j?{file:j}:{}}))}N&&navigator.clipboard.writeText(N).then(()=>{let V=Ft(Na,16,"currentColor",2);V&&(f.replaceChildren(V),setTimeout(()=>{let j=Ft(Fa,16,"currentColor",2);j&&f.replaceChildren(j)},1500))}).catch(()=>{})}),Le.addEventListener("click",s=>{let f=s.target.closest("[data-expand-artifact-inline]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-expand-artifact-inline");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(Kn=!1,ra=!0,fn=!0,vi=!0,H.selectArtifact(g),mn())}),Le.addEventListener("click",s=>{let l=s.target;if(l.closest("[data-download-artifact]")||l.closest("[data-artifact-custom-action]"))return;let f=l.closest("[data-open-artifact]");if(!f)return;let g=f.getAttribute("data-open-artifact");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(s.preventDefault(),s.stopPropagation(),Kn=!1,ra=!0,H.selectArtifact(g),mn())}),Le.addEventListener("keydown",s=>{if(s.key!=="Enter"&&s.key!==" ")return;let l=s.target;!l.hasAttribute("data-open-artifact")&&!l.hasAttribute("data-expand-artifact-inline")||(s.preventDefault(),l.click())});let sa=_e.composerOverlay,aa=(s,l,f)=>{let g=l.trim();if(!g||!it.current)return;let v=s.getAttribute("data-tool-call-id")??"",M=f.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:v,answer:g,answers:f.structured,values:f.values??(f.source==="multi"?g.split(", "):[g]),isFreeText:M,source:f.source},bubbles:!0,composed:!0})),Ur(sa,v);let N=it.current.getMessages().find(V=>V.toolCall?.id===v);N?.agentMetadata?.awaitingLocalTool?it.current.resolveAskUserQuestion(N,f.structured??g):it.current.sendMessage(g)},ss=s=>{let l=it.current;if(!l)return;let f=s.getAttribute("data-tool-call-id")??"",g=l.getMessages().find(v=>v.toolCall?.id===f);g&&l.persistAskUserQuestionProgress(g,{answers:mc(s,g),currentIndex:sn(s)})},Gh=s=>Object.entries(s).map(([l,f])=>`${l}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),lp=s=>{if(n.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let l=sn(s),f=Ia(s);if(l>=f-1)return;let g=it.current?.getMessages().find(v=>v.toolCall?.id===s.getAttribute("data-tool-call-id"));g&&(gc(s,g,n,l+1),ss(s))};sa.addEventListener("click",s=>{let f=s.target.closest("[data-ask-user-action]");if(!f)return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;let v=f.getAttribute("data-ask-user-action");if(s.preventDefault(),s.stopPropagation(),v==="dismiss"){let M=g.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:M},bubbles:!0,composed:!0})),Ur(sa,M);let N=it.current?.getMessages().find(V=>V.toolCall?.id===M);N?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved(N),it.current?.resolveAskUserQuestion(N,"(dismissed)"));return}if(v==="pick"){let M=f.getAttribute("data-option-label");if(!M)return;let N=g.getAttribute("data-multi-select")==="true",V=Fr(g);if(V&&N){let j=Ws(g)[sn(g)],K=new Set(Array.isArray(j)?j:[]);K.has(M)?K.delete(M):K.add(M),qr(g,Array.from(K)),ss(g);return}if(V){qr(g,M),ss(g),lp(g);return}if(N){let j=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",j?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!j);let K=g.querySelector('[data-ask-user-action="submit-multi"]');K&&(K.disabled=_f(g).length===0);return}aa(g,M,{source:"pick",values:[M]});return}if(v==="submit-multi"){let M=_f(g);if(M.length===0)return;aa(g,M.join(", "),{source:"multi",values:M});return}if(v==="open-free-text"){let M=g.querySelector('[data-ask-free-text-row="true"]');M&&(M.classList.remove("persona-hidden"),M.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(v==="focus-free-text"){g.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(v==="submit-free-text"){let N=g.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!N.trim())return;if(Fr(g)){qr(g,N.trim()),ss(g),lp(g);return}aa(g,N,{source:"free-text"});return}if(v==="next"||v==="back"){if(!it.current)return;let M=g.getAttribute("data-tool-call-id")??"",N=it.current.getMessages().find(ae=>ae.toolCall?.id===M);if(!N)return;let j=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(j){let ae=Ws(g)[sn(g)];(typeof ae!="string"||ae!==j)&&qr(g,j)}let K=v==="next"?1:-1,J=sn(g)+K;gc(g,N,n,J),ss(g);return}if(v==="submit-all"){if(!it.current)return;let M=g.getAttribute("data-tool-call-id")??"",N=it.current.getMessages().find(ae=>ae.toolCall?.id===M);if(!N)return;let j=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";j&&qr(g,j);let K=mc(g,N);it.current.persistAskUserQuestionProgress(N,{answers:K,currentIndex:sn(g)});let J=Gh(K);aa(g,J||"(submitted)",{source:"submit-all",structured:K});return}if(v==="skip"){if(!it.current)return;let M=g.getAttribute("data-tool-call-id")??"",N=it.current.getMessages().find(fe=>fe.toolCall?.id===M);if(!N)return;let V=Fr(g),j=sn(g),K=Ia(g),J=j>=K-1;if(!V){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:M},bubbles:!0,composed:!0})),Ur(sa,M),N.agentMetadata?.awaitingLocalTool&&(it.current.markAskUserQuestionResolved(N),it.current.resolveAskUserQuestion(N,"(dismissed)"));return}qr(g,"");let ae=g.querySelector('[data-ask-free-text-input="true"]');if(ae&&(ae.value=""),J){let fe=mc(g,N),Je=Gh(fe);aa(g,Je||"(skipped)",{source:"submit-all",structured:fe});return}gc(g,N,n,j+1),ss(g);return}}),sa.addEventListener("keydown",s=>{if(s.key!=="Enter")return;let f=s.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;s.preventDefault();let v=f.value;if(v.trim()){if(Fr(g)){qr(g,v.trim()),ss(g),lp(g);return}aa(g,v,{source:"free-text"})}});let Xh=s=>{if(!/^[1-9]$/.test(s.key)||s.metaKey||s.ctrlKey||s.altKey)return;let l=s.target;if(l?.tagName==="INPUT"||l?.tagName==="TEXTAREA"||l?.isContentEditable)return;let f=sa.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let g=Number(s.key),M=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[g-1];M&&(s.preventDefault(),M.click())};document.addEventListener("keydown",Xh);let En=null,bt=null,xi=null,od=null,nd=()=>{},Qh=!1,rd="",sd="";function dp(){od?.(),od=null}let cA=()=>{let s=ya&&Ts?.isConnected?Ts:null,l=s?s.getBoundingClientRect().width:0;return l<=0?200:l+360},Yh=()=>{if(!En||!bt)return;let s=e.classList.contains("persona-artifact-welded-split"),l=e.ownerDocument.defaultView??window,f=l.innerWidth<=640;if(!s||e.classList.contains("persona-artifact-narrow-host")||f){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let g=En.firstElementChild;if(!g||g===bt)return;let v=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${v}px`,bt.style.zIndex="5";let M=Zg(En,l),N=g.offsetWidth+M/2-v/2;bt.style.left=`${Math.max(0,N)}px`},ad=()=>{},uA=()=>{let s=e.ownerDocument.defaultView??window,l=n.launcher?.mobileFullscreen??!0,f=n.launcher?.mobileBreakpoint??640;return!l||s.innerWidth>f?!1:ge||St(n)},id=()=>!wo(n)||!td()||e.classList.contains("persona-artifact-narrow-host")||uA()||(e.ownerDocument.defaultView??window).innerWidth<Nk?"none":Xg(n)?"detached":"welded",mn=()=>{if(!je||!wo(n))return;Dl(e,n),_l(e,n),ad();let s=n.features?.artifacts?.layout?.narrowHostMaxWidth??520,l=we.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",l>0&&l<=s);let f=td();je.setVisible(f),je.update(Yo),Kn?(je.setMobileOpen(!1),je.element.classList.add("persona-hidden"),je.backdrop?.classList.add("persona-hidden"),fn=!1,vi=!1):Yo.artifacts.length>0&&Kh()?(je.element.classList.remove("persona-hidden"),je.setMobileOpen(!0)):(je.setMobileOpen(!1),je.element.classList.add("persona-hidden"),je.backdrop?.classList.add("persona-hidden"),fn=!1,vi=!1);let g=n.features?.artifacts?.layout?.showExpandToggle===!0;if(je.setExpandToggleVisible(g),je.setCopyButtonVisible(n.features?.artifacts?.layout?.showCopyButton===!0),je.setRefreshButtonVisible(typeof n.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),je.setCustomActions(n.features?.artifacts?.toolbarActions??[]),je.setTabFade(n.features?.artifacts?.layout?.tabFade),je.setRenderTabBar(n.features?.artifacts?.renderTabBar),!g&&!vi&&(fn=!1),fn!==Qh){let M=je.element;fn?(rd=M.style.width,sd=M.style.maxWidth,M.style.removeProperty("width"),M.style.removeProperty("max-width")):(rd&&(M.style.width=rd),sd&&(M.style.maxWidth=sd),rd="",sd=""),Qh=fn}e.classList.toggle("persona-artifact-expanded",fn),je.setExpanded(fn);let v=id();v!==bi&&(bi=v,rs()),nd()};if(wo(n)){we.style.position="relative";let s=I("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),l=I("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");s.appendChild(ue),En=l,l.appendChild(s),we.appendChild(l);let f=v=>{Vh||je||(je=v.createArtifactPane(n,{onSelect:M=>it.current?.selectArtifact(M),onDismiss:()=>{Kn=!0,mn()},onToggleExpand:()=>{let M=!fn,N=Yo.selectedId??Yo.artifacts[Yo.artifacts.length-1]?.id??null;n.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:N,expanded:M})!==!0&&(fn=M,M||(vi=!1),mn())}}),je.element.classList.add("persona-hidden"),l.appendChild(je.element),je.backdrop&&we.appendChild(je.backdrop),nd(),mn())},g=fr();g?f(g):(Kg(()=>{let v=fr();v&&f(v)}),Iu().catch(()=>{})),nd=()=>{if(!En||!je)return;if(!(n.features?.artifacts?.layout?.resizable===!0)){xi?.(),xi=null,dp(),bt&&(bt.remove(),bt=null),je.element.style.removeProperty("width"),je.element.style.removeProperty("maxWidth");return}if(!bt){let M=I("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");M.setAttribute("role","separator"),M.setAttribute("aria-orientation","vertical"),M.setAttribute("aria-label","Resize artifacts panel"),M.tabIndex=0;let N=e.ownerDocument,V=N.defaultView??window,j=K=>{if(!je||K.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||V.innerWidth<=640)return;K.preventDefault(),dp();let J=K.clientX,ae=je.element.getBoundingClientRect().width,fe=n.features?.artifacts?.layout,Je=ct=>{let Qt=En.getBoundingClientRect().width,Nt=e.classList.contains("persona-artifact-welded-split"),kt=Zg(En,V),io=Nt?0:M.getBoundingClientRect().width||6,et=ae-(ct.clientX-J),lo=ew(et,Qt,kt,io,fe?.resizableMinWidth,fe?.resizableMaxWidth,cA());je.element.style.width=`${lo}px`,je.element.style.maxWidth="none",Yh()},lt=()=>{N.removeEventListener("pointermove",Je),N.removeEventListener("pointerup",lt),N.removeEventListener("pointercancel",lt),od=null;try{M.releasePointerCapture(K.pointerId)}catch{}};od=lt,N.addEventListener("pointermove",Je),N.addEventListener("pointerup",lt),N.addEventListener("pointercancel",lt);try{M.setPointerCapture(K.pointerId)}catch{}};M.addEventListener("pointerdown",j),bt=M,En.insertBefore(M,je.element),xi=()=>{M.removeEventListener("pointerdown",j)}}if(bt){let M=td();bt.classList.toggle("persona-hidden",!M),Yh()}},ad=()=>{if(!ge||!je||(n.launcher?.sidebarMode??!1)||St(n)&&Wo(n).reveal==="emerge")return;let M=e.ownerDocument.defaultView??window,N=n.launcher?.mobileFullscreen??!0,V=n.launcher?.mobileBreakpoint??640;if(N&&M.innerWidth<=V||!GS(n,ge))return;let j=n.launcher?.width??n.launcherWidth??Vo,K=n.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";td()?(we.style.width=K,we.style.maxWidth=K):(we.style.width=j,we.style.maxWidth=j)},typeof ResizeObserver<"u"&&(yi=new ResizeObserver(()=>{mn()}),yi.observe(we))}else we.appendChild(ue);Ae()&&Xt&&(_e.peekBanner&&Xt.appendChild(_e.peekBanner),Xt.appendChild(Ie)),e.appendChild(Xe),Xt&&e.appendChild(Xt);let cp=()=>{if(Ae()){we.style.width="100%",we.style.maxWidth="100%";let ve=n.launcher?.composerBar??{},Ne=Xe.dataset.state==="expanded",ft=ve.expandedSize??"anchored";if(!(Ne&&ft!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Gt=n.theme?.components?.panel,zo=Vr(n),Hs=(Rs,oc)=>Rs==null||Rs===""?oc:xo(zo,Rs)??Rs,Zb="1px solid var(--persona-border)",Mt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Af="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Hs(Gt?.border,Zb),ue.style.borderRadius=Hs(Gt?.borderRadius,Af),ue.style.boxShadow=Hs(Gt?.shadow,Mt),ue.style.overflow="hidden";return}let s=St(n),l=n.launcher?.sidebarMode??!1,f=s||l||(n.launcher?.fullHeight??!1),g=n.launcher?.enabled===!1,v=n.launcher?.detachedPanel===!0,M=n.theme?.components?.panel,N=Vr(n),V=(ve,Ne)=>ve==null||ve===""?Ne:xo(N,ve)??ve,j=e.ownerDocument.defaultView??window,K=n.launcher?.mobileFullscreen??!0,J=n.launcher?.mobileBreakpoint??640,ae=j.innerWidth<=J,fe=K&&ae&&ge,Je=s&&K&&ae,lt=n.launcher?.position??"bottom-left",ct=lt==="bottom-left"||lt==="top-left",Qt=n.launcher?.zIndex??so,Nt="var(--persona-panel-border, 1px solid var(--persona-border))",kt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",io="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",et=v&&!fe&&!Je;et?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let lo=et?Nt:l||fe?"none":Nt,ar=et?kt:fe?"none":l?ct?"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))":g?"none":kt;s&&!fe&&!et&&(ar="none",lo="none");let Rn=et?io:l||fe?"0":io,Wn=V(M?.border,lo),D=V(M?.shadow,ar),We=V(M?.borderRadius,Rn),Oe=id(),me=Oe==="detached",pt=Oe==="welded";e.classList.toggle("persona-artifact-detached-split",me),e.classList.toggle("persona-artifact-welded-split",pt);let zt="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)))))",It=(n.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&wo(n)&&Xg(n)&&g&&!s;e.classList.toggle("persona-artifact-chat-flush",It);let Ee=me||It?"none":D,Vt=me?Nt:pt?"none":Wn,Kt=me?io:We;It&&(Vt="none",Kt="0");let rn=M?.borderRadius!=null&&M.borderRadius!=="",He=It&&!rn?"0":We,xt=re.scrollTop;e.style.cssText="",Xe.style.cssText="",we.style.cssText="",ue.style.cssText="",re.style.cssText="",na||(Ie.style.cssText=""),te&&(re.style.display="none"),(f||g)&&(e.style.minWidth="0");let Bn=()=>{if(xt<=0)return;(re.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(re.scrollTop===xt)return;let Ne=re.scrollHeight-re.clientHeight;Ne<=0||(re.scrollTop=Math.min(xt,Ne))})};if(fe){Xe.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"),Xe.style.cssText=`
44
+ `,L.addEventListener("click",()=>{m=C,k.forEach((F,X)=>{let G=X<C;F.classList.toggle("selected",G),F.setAttribute("aria-checked",X===C-1?"true":"false")})}),k.push(L),w.appendChild(L)}h.appendChild(w);let P=null;if(c){let C=document.createElement("div");C.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=a,P.rows=3,P.setAttribute("aria-label","Additional comments"),C.appendChild(P),h.appendChild(C)}let R=document.createElement("div");R.className="persona-feedback-actions";let b=document.createElement("button");b.type="button",b.className="persona-feedback-btn persona-feedback-btn-skip",b.textContent=d,b.addEventListener("click",()=>{o?.(),p.remove()});let A=document.createElement("button");return A.type="button",A.className="persona-feedback-btn persona-feedback-btn-submit",A.textContent=i,A.addEventListener("click",async()=>{if(m===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}A.disabled=!0,A.textContent="Submitting...";try{let C=P?.value.trim()||void 0;await t(m,C),p.remove()}catch(C){A.disabled=!1,A.textContent=i,console.error("[CSAT Feedback] Failed to submit:",C)}}),R.appendChild(b),R.appendChild(A),h.appendChild(R),p.appendChild(h),p}function qu(e){let{onSubmit:t,onDismiss:o,title:n="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:c=!0,lowLabel:u="Not likely",highLabel:p="Very likely"}=e,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 h=null,y=document.createElement("div");y.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let T=document.createElement("h3");T.className="persona-feedback-title",T.textContent=n,x.appendChild(T);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=r,x.appendChild(w),y.appendChild(x);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let P=document.createElement("div");P.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=u;let b=document.createElement("span");b.className="persona-feedback-label-high",b.textContent=p,P.appendChild(R),P.appendChild(b);let A=document.createElement("div");A.className="persona-feedback-numbers";let C=[];for(let E=0;E<=10;E++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${E} out of 10`),O.textContent=String(E),O.dataset.rating=String(E),E<=6?O.classList.add("persona-feedback-detractor"):E<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{h=E,C.forEach((D,W)=>{D.classList.toggle("selected",W===E),D.setAttribute("aria-checked",W===E?"true":"false")})}),C.push(O),A.appendChild(O)}k.appendChild(P),k.appendChild(A),y.appendChild(k);let L=null;if(c){let E=document.createElement("div");E.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=a,L.rows=3,L.setAttribute("aria-label","Additional comments"),E.appendChild(L),y.appendChild(E)}let F=document.createElement("div");F.className="persona-feedback-actions";let X=document.createElement("button");X.type="button",X.className="persona-feedback-btn persona-feedback-btn-skip",X.textContent=d,X.addEventListener("click",()=>{o?.(),m.remove()});let G=document.createElement("button");return G.type="button",G.className="persona-feedback-btn persona-feedback-btn-submit",G.textContent=i,G.addEventListener("click",async()=>{if(h===null){A.classList.add("persona-feedback-shake"),setTimeout(()=>A.classList.remove("persona-feedback-shake"),500);return}G.disabled=!0,G.textContent="Submitting...";try{let E=L?.value.trim()||void 0;await t(h,E),m.remove()}catch(E){G.disabled=!1,G.textContent=i,console.error("[NPS Feedback] Failed to submit:",E)}}),F.appendChild(X),F.appendChild(G),y.appendChild(F),m.appendChild(y),m}var ii="persona-chat-history",VL=30*1e3,jL=641,li="data-persona-composer-reason",zL={"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 KL(e){if(!e)return[];let t=[],o=Array.from(e.items??[]);for(let n of o){if(n.kind!=="file"||!n.type.startsWith("image/"))continue;let r=n.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let a=zL[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${a}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith("image/")&&t.push(n);return t}function $u(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function GL(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function XL(e){try{let t=e==="local"?localStorage:sessionStorage,o="__persist_test__";return t.setItem(o,"1"),t.removeItem(o),t}catch{return null}}var dh=e=>!e||typeof e!="object"?{}:{...e},ww=e=>e.map(t=>({...t,streaming:!1})),Aw=(e,t,o)=>{let n=e?.markdown?Zi(e.markdown):null,r=lc(e?.sanitize);e?.postprocessMessage&&r&&e?.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 a=!1,i=d=>{let c=d.text??"",u=d.message.rawContent??null;if(t){let h=t.process({text:c,raw:u??c,message:d.message,streaming:d.streaming});h!==null&&(c=h.text,h.persist||(d.message.__skipPersist=!0),h.resubmit&&!d.streaming&&o&&o())}let p=_n()!==null,m;if(e?.postprocessMessage){let h=e.postprocessMessage({...d,text:c,raw:u??d.text??""});m=r?r(h):h}else if(n){let h=d.streaming?yv(c):c,y=n(h);m=r&&p?r(y):y}else m=dr(c);return m};return d=>{try{return i(d)}catch(c){return a||(a=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),dr(d.text??"")}}};function Mw(e){let t=I("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let o=e?.iconName??"upload",n=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",a=e?.iconStrokeWidth??.5,i=ce(o,n,r,a);if(i&&t.appendChild(i),e?.label){let d=I("span","persona-drop-overlay-label");d.textContent=e.label,t.appendChild(d)}return t}var QL=(e,t)=>{let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];o[n]=a?{...a,...r}:r}return o},YL=e=>e.reduce((t,o)=>({blocks:[...t.blocks,...o.blocks],contentParts:[...t.contentParts,...o.contentParts],context:QL(t.context,o.context)}),{blocks:[],contentParts:[],context:{}}),Vu=(e,t,o)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=ja(t),r=()=>{$x({delayMs:n.tooltip?.delayMs??200,skipDelayMs:n.tooltip?.skipDelayMs??300})};r();let a=n.features;n=Nl(n);let i=Fl.getForInstance(n.plugins),d=VC(e),c=[],u=!1,p=NS(()=>n),m=null,h=null,y=null,x=!1,T=null,w=s=>{m=s,s.initApprovalUi({webMcpToolTitle:dc});let l=s.createBuiltInApprovalPlugin();h=l.plugin,y=l.teardown},k=()=>{if(m)return m;let s=jS();return s?(w(s),s):(VS().then(l=>{x||m||(w(l),T?.())}).catch(()=>{}),null)},P=!1,R=!1,b=null,A=(s,l,f,g)=>{if(!s.querySelector("[data-tv-form]"))return;let v=aw();if(v){v.enhanceWithForms(s,l,f,g);return}sw().then(()=>{P||R||!b||(R=!0,b())}).catch(()=>{})};n.components&&Cn.registerAll(n.components);let C=dw(),F=n.persistState===!1?null:n.storageAdapter??Ou(),X={},G=null,E,O=new Promise(s=>{E=s}),D,W=!1,te=s=>{if(n.onStateLoaded)try{let l=n.onStateLoaded(s);if(l&&typeof l=="object"&&"state"in l){let{state:f,open:g}=l;return g&&(W=!0),f}return l}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}return s};if(F?.load)try{let s=F.load();if(s&&typeof s.then=="function")G=s.then(l=>te(l??{messages:[],metadata:{}}));else{let f=te(s??{messages:[],metadata:{}});f.metadata&&(X=dh(f.metadata)),f.messages?.length&&(n={...n,initialMessages:f.messages}),f.artifacts?.length&&(n={...n,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),D=f.draft}}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",s)}else if(n.onStateLoaded)try{let s=te({messages:[],metadata:{}});s.messages?.length&&(n={...n,initialMessages:s.messages})}catch(s){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",s)}G||E();let Q=()=>X,de=s=>{X=s({...X})??{},wi()},pe=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ul],Ce=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Ys.message,Ys.messageAndClick],Ee=ql({parsers:pe,handlers:Ce,getSessionMetadata:Q,updateSessionMetadata:de,emit:C.emit,documentRef:typeof document<"u"?document:null});Ee.syncFromMetadata();let ge=n.launcher?.enabled??!0,Ke=n.launcher?.autoExpand??!1,Bt=n.autoFocusInput??!1,Le=Ke,j=ge,qe=n.layout?.header?.layout,Ge=!1,Ae=()=>Qr(n),De=()=>ge||Ae(),he=Ae()?!1:ge?Ke:!0,gt=!1,dn=null,Js=()=>{gt=!0,dn&&clearTimeout(dn),dn=setTimeout(()=>{gt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),gt=!1)},1e4)},oo=Aw(n,Ee,Js),Xo=n.features?.showReasoning??!0,Sn=n.features?.showToolCalls??!0,Rt=n.features?.showEventStreamToggle??!1,Jr=n.features?.scrollToBottom??{},Ao=n.features?.scrollBehavior??{},wn=()=>(typeof n.persistState=="object"?n.persistState?.keyPrefix:void 0)??"persona-",Zr=`${wn()}event-stream`,po=null,ci=n.features?.eventStream?.maxEvents??2e3,Tt=null,ut=null,cn=null,jl=!1,B=null,ee=!1,S=null,U=0,q=(s,l)=>{Tt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:s,timestamp:Date.now(),payload:JSON.stringify(l)})},$=(s,l)=>{ut?.processEvent(s,l),Tt?q(s,l):cn&&(cn.length>=ci&&cn.shift(),cn.push({type:s,payload:l}))},oe=()=>{Tt||!Rt||(cn??(cn=[]),Kg().then(s=>{if(jl||Tt||!Rt)return;po=new s.EventStreamStore(Zr),Tt=new s.EventStreamBuffer(ci,po),ut=ut??new s.ThroughputTracker,po.open().then(()=>Tt?.restore()).catch(f=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let l=cn??[];cn=null;for(let f of l)ut?.processEvent(f.type,f.payload),q(f.type,f.payload)}).catch(()=>{}))};Rt&&oe();let ne=!1,ie=null,xe=()=>{},ht=()=>{},$e=()=>{},Ht=()=>{},wt=()=>{},es=()=>ee||ne&&ie==="panel",Bo={onCopy:s=>{C.emit("message:copy",s),H?.isClientTokenMode()&&H.submitMessageFeedback(s.id,"copy").catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",l)}),n.messageActions?.onCopy?.(s)},onFeedback:s=>{C.emit("message:feedback",s),H?.isClientTokenMode()&&H.submitMessageFeedback(s.messageId,s.type).catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",l)}),n.messageActions?.onFeedback?.(s)}},qt=n.statusIndicator??{},fo=s=>s==="idle"?qt.idleText??Ut.idle:s==="connecting"?qt.connectingText??Ut.connecting:s==="connected"?qt.connectedText??Ut.connected:s==="error"?qt.errorText??Ut.error:s==="paused"?qt.pausedText??Ut.paused:s==="resuming"?qt.resumingText??Ut.resuming:Ut[s];function ao(s,l,f,g){if(!s.hasAttribute(li))if(g==="idle"&&f.idleLink){s.textContent="";let v=document.createElement("a");v.href=f.idleLink,v.target="_blank",v.rel="noopener noreferrer",v.textContent=l,v.style.color="inherit",v.style.textDecoration="none",s.appendChild(v)}else s.textContent=l}let Oo=_S({config:n,showClose:De()}),{wrapper:Xe,panel:we,pillRoot:Xt}=Oo.shell,_e=Oo.panelElements,{container:ue,body:re,messagesWrapper:ke,starterSuggestions:Ku,transcriptSuggestions:ui,suggestions:br,textarea:le,sendButton:Me,composerForm:un,statusText:st,welcomeHost:Mo,welcomeIconHolder:zw,greetingHost:Do,introKicker:Kw,introTitle:Gw,introSubtitle:Xw,closeButton:Ue,iconHolder:Et,headerTitle:vr,headerSubtitle:ts,header:Te,footer:Ie,actionsRow:Qw}=_e,Gu=_e.leftActions,zl=_e.rightActions,An=_e.sendButtonWrapper,wh=_e.setSendButtonMode,se=_e.micButton,_o=_e.micButtonWrapper,At=_e.attachmentButton,To=_e.attachmentButtonWrapper,yt=_e.attachmentInput,Eo=_e.attachmentPreviewsContainer;ue.classList.add("persona-relative"),re.classList.add("persona-relative");let Yw=12,pi=()=>Jr.label??"",Jw=()=>Jr.iconName??"arrow-down",Zw=()=>Jr.enabled!==!1,No=()=>Ao.mode??"anchor-top",xr=()=>No()==="follow"||No()==="anchor-top"&&Si,fi=()=>Ao.anchorTopOffset??16,eA=()=>Ao.restorePosition??"bottom",Ah=()=>Ao.pauseOnInteraction===!0,Mh=()=>Ao.showActivityWhilePinned!==!1,Th=()=>Ao.announce===!0,Xu=()=>Ao.scrollbar??"on-scroll",Ot=I("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");Ot.type="button",Ot.style.display="none",Ot.setAttribute("data-persona-scroll-to-bottom","true");let mi=I("span","persona-flex persona-items-center"),Qu=I("span",""),os=I("span","");os.setAttribute("data-persona-scroll-to-bottom-count",""),os.style.display="none",Ot.append(mi,Qu,os),ue.appendChild(Ot);let Qo=I("div","persona-stream-anchor-spacer");Qo.setAttribute("aria-hidden","true"),Qo.setAttribute("data-persona-anchor-spacer",""),Qo.style.flexShrink="0",Qo.style.pointerEvents="none",Qo.style.height="0px",Qo.style.display="none",re.appendChild(Qo);let zn=I("div","persona-sr-only");zn.setAttribute("aria-live","polite"),zn.setAttribute("aria-atomic","true"),zn.setAttribute("role","status"),zn.setAttribute("data-persona-live-region",""),Object.assign(zn.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"}),ue.appendChild(zn);let gi=null,Kl=null,Gl=s=>{!Th()||!s||(Kl=s,gi===null&&(gi=setTimeout(()=>{gi=null,Kl&&Th()&&(zn.textContent=Kl),Kl=null},400)))},Xl="empty",Ql=0,Yu=()=>Ql||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,ns=()=>{let l=Ie.style.display==="none"?0:Ie.offsetHeight;Ot.style.bottom=`${l+Yu()+Yw}px`};ns();let Ju=()=>{na||(Ie.style.marginBottom=Ql>0?`${Ql}px`:"")},Yl=()=>{let s=ug(n,Ae()),l=xn(n),g=Ie.style.display==="none"?0:Ie.offsetHeight,v=l.anchor==="center"&&Xl==="empty"?Ml(l.anchorComposerTop)??Ml("44%"):null,M=v===null||Ae()?0:UC({columnHeight:ue.clientHeight,footerHeight:g,fraction:v});e.style.setProperty("--persona-composer-overlay-height",`${g}px`),e.style.setProperty("--persona-composer-lift",`${s==="overlay"?M:0}px`),Ql=s==="block"?M:0,Ju(),ns()},Eh=()=>{let s=!!pi();Ot.setAttribute("aria-label",pi()||"Jump to latest"),Ot.title=pi(),Ot.setAttribute("data-persona-scroll-to-bottom-has-label",s?"true":"false"),mi.innerHTML="";let l=ce(Jw(),"14px","currentColor",2);l?(mi.appendChild(l),mi.style.display=""):mi.style.display="none",Qu.textContent=pi(),Qu.style.display=s?"":"none"};Eh();let Ze=null,Wt=null,Se=Dx(),tA=s=>{try{ue.dispatchEvent(new CustomEvent("persona:composer:state",{detail:s,bubbles:!0,composed:!0}))}catch{}};Se.subscribe(tA);let Mn=()=>{Se.setText(le?.value??"")},rs=()=>{Se.setMentionRefs(Wt?.getMentionRefs()??[])},oA=s=>({id:s.id,name:s.file.name,mimeType:s.file.type,size:s.file.size,status:s.status,progress:s.progress,error:s.error}),Ph=s=>{let l=Object.freeze(s.map(oA));Se.setAttachments(l);try{n.attachments?.onChange?.(l)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}Ap()};Se.setSelectedModelId(n.composer?.selectedModelId);let hi=()=>n.composer?.modes??[],Zs=()=>cC(hi(),n.composer?.modeGroups);{let s=nu(n.composer?.defaultActiveModeIds??[],hi());s.length&&Se.setActiveModeIds(s)}function kh(s){if(Se.getState().selectedModelId!==s){Se.setSelectedModelId(s),Cr?.repaint();try{n.composer?.onModelChange?.(s)}catch(l){console.error("[AgentWidget] composer.onModelChange failed:",l)}}}function Jl(s){Se.setActiveModeIds(s),Kn?.render(s,Zs()),ea.forEach(l=>l.repaint()),En?.resolve(),wd(),pn()}function Zu(s){Jl(uC(Se.getState().activeModeIds,s,hi(),n.composer?.modeGroups))}let Cr=null,ep=null,Kn=null,ea=new Map,Sr=null;function Tn(s){Se.setQuote(s),Sr?.render(Se.getState().quote),pn(),Cy()}let Lh=!1;function tp(){let s=n.composer?.streamingSubmitBehavior??"block";return s!=="interrupt"?s:n.clientToken?"interrupt":(!Lh&&n.debug===!0&&(Lh=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let wr=null;function ta(s){Se.setPendingSubmission(s),wr?.render(Se.getState().pendingSubmission),pn()}let nA=s=>{let l=ea.get(s);if(l)return l;let f=mC({groupId:s,getGroup:()=>n.composer?.modeGroups?.find(g=>g.id===s),getModes:()=>hi().filter(g=>g.groupId===s),getActiveIds:()=>Se.getState().activeModeIds,onSelect:g=>Zu(g)});return ea.set(s,f),f},rA=()=>{let s=[],l=Se.getState().activeModeIds,f=new Set;if(hi().forEach((g,v)=>{if(ou(g.groupId,n.composer?.modeGroups)){let M=g.groupId;if(f.has(M))return;f.add(M);let N=nA(M);N.action.order=ng(v),N.action.label=n.composer?.modeGroups?.find(z=>z.id===M)?.label??M,s.push(N.action);return}s.push({id:lC(g.id),kind:"button",placement:"start",order:ng(v),presentation:g.presentation??"auto",label:g.label,shortLabel:g.shortLabel,iconName:g.iconName,pressed:l.includes(g.id),onSelect:()=>Zu(g.id)})}),n.composer?.models?.length&&!i.some(g=>g.renderComposer)){let g=n.composer?.modelPicker?.presentation??"native";(!Cr||ep!==g)&&(ep=g,Cr=aC({getModels:()=>n.composer?.models??[],getSelectedModelId:()=>Se.getState().selectedModelId,onSelect:v=>kh(v),presentation:g,getSuffix:()=>n.composer?.modelPicker?.suffix})),s.push(Cr.action)}return s},op=null,Ih=i.find(s=>s.renderHeader);if(Ih?.renderHeader){let s=Ih.renderHeader({config:n,defaultRenderer:()=>{let l=mr({config:n,showClose:De()});return Vs(ue,l,n),l.header},onClose:()=>dt(!1,"user")});if(s){let l=Te;l&&(l.replaceWith(s),Te=s,Oo.header.element=s)}}let Rh=()=>{B&&(re.style.display="none",Ie.parentNode?.insertBefore(B.element,Ie),B.update())},np=()=>{if(!Tt){oe();return}if(ee=!0,B?Rh():Kg().then(l=>{B||!ee||!Tt||(B=l.createEventStreamView({buffer:Tt,getFullHistory:()=>Tt.getAllFromStore(),onClose:()=>oa(),config:n,plugins:i,getThroughput:()=>ut?.getMetric()??{status:"idle"},renderIconByName:ce}),Rh())}).catch(()=>{oa()}),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Co.actionIconColor}`;let l=n.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(f=>f&&tt.classList.add(f))}let s=()=>{if(!ee)return;let l=Date.now();l-U>=200&&(B?.update(),U=l),S=requestAnimationFrame(s)};U=0,S=requestAnimationFrame(s),Vt(),C.emit("eventStream:opened",{timestamp:Date.now()})},oa=()=>{if(ee){if(ee=!1,B&&B.element.remove(),re.style.display="",tt){tt.style.boxShadow="";let s=n.features?.eventStream?.classNames?.toggleButtonActive;s&&s.split(/\s+/).forEach(l=>l&&tt.classList.remove(l))}S!==null&&(cancelAnimationFrame(S),S=null),Vt(),C.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(Rt){let s=n.features?.eventStream?.classNames,l="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"+(s?.toggleButton?" "+s.toggleButton:"");tt=I("button",l),tt.style.width="28px",tt.style.height="28px",tt.style.color=Co.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let f=Ft(Na,"18px","currentColor",1.5);f&&tt.appendChild(f);let g=_e.clearChatButtonWrapper,v=_e.closeButtonWrapper,M=g||v;M&&M.parentNode===Te?Te.insertBefore(tt,M):Te.appendChild(tt),tt.addEventListener("click",()=>{ee?oa():np()})}let Hh=s=>{let l=n.attachments;if(!l?.enabled)return;let f=s.querySelector("[data-persona-composer-attachment-previews]")??s.querySelector(".persona-attachment-previews");if(!f){f=I("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 v=s.querySelector("[data-persona-composer-form]");v?.parentNode?v.parentNode.insertBefore(f,v):s.insertBefore(f,s.firstChild)}if(!(s.querySelector("[data-persona-composer-attachment-input]")??s.querySelector('input[type="file"]'))){let v=I("input");v.type="file",v.setAttribute("data-persona-composer-attachment-input",""),v.accept=(l.allowedTypes??fr).join(","),v.multiple=(l.maxFiles??4)>1,v.style.display="none",v.setAttribute("aria-label",l.buttonTooltipText??"Attach files"),s.appendChild(v)}},na=!1,Wh=s=>{let l=i.find(v=>v.renderComposer);if(!l?.renderComposer)return null;let f=n.composer,g=u?H.isStreaming():!1;return l.renderComposer({config:n,defaultRenderer:s,requestRender:()=>Kb(),storage:p(l.id),onSubmit:v=>{!H||H.isStreaming()||Qd(v.trim(),{consumeDraft:!1})},streaming:g,disabled:g,openAttachmentPicker:()=>{Lr()||yt?.click()},models:f?.models,selectedModelId:Se.getState().selectedModelId??f?.selectedModelId,onModelChange:v=>kh(v),onVoiceToggle:n.voiceRecognition?.enabled===!0?()=>{op?.()}:void 0})},Bh=Wh(()=>Ks({config:n}).footer);Bh&&(Oo.replaceComposer(Bh),Ie=Oo.composer.footer,na=!0);let ot=null,sA=s=>{un=s.form,le=s.input,An=s.sendButton?s.sendButton.parentElement:null,s.sendButton&&(Me=s.sendButton),s.micButton&&(se=s.micButton,_o=s.micButton.parentElement),s.found.status&&(st=s.found.status),s.found.suggestions&&(br=s.found.suggestions),s.attachmentButton&&(At=s.attachmentButton,To=s.attachmentButton.parentElement),yt=s.attachmentInput??null,Eo=s.attachmentPreviews??null,s.found.actionsRow&&(Qw=s.found.actionsRow),Gu=s.found.actionsStart,zl=s.found.actionsEnd};function rp(){let s=le;if(!s)return;let l=n.composer?.inputAttributes,f=!l?.ariaLabel&&!(s instanceof HTMLTextAreaElement)?s.getAttribute("aria-label"):null;Kc(s,l),f&&s.setAttribute("aria-label",f),zc(s,{submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Cl(s)}),Gx(s,jc(n.composer?.maxLines,Ae()?5:3))}let Oh=s=>{ot=Nx(s,{debug:n.debug===!0}),ot&&sA(ot),rp()};Hh(Ie),Oh(Ie),Mn();let yi=Gr(n,Ae());yi&&(ke.style.maxWidth=yi,ke.style.marginLeft="auto",ke.style.marginRight="auto",ke.style.width="100%",Do.style.maxWidth=yi,Do.style.marginLeft="auto",Do.style.marginRight="auto",Do.style.width="100%",Ku.style.maxWidth=yi,ui.style.maxWidth=yi,ui.style.marginLeft="auto",ui.style.marginRight="auto",ui.style.width="100%");let Dh=()=>{let s=Gr(n,Ae());if(!(!s||Ae()))for(let l of[un,br,Eo,st])l&&(l.style.maxWidth=s,l.style.marginLeft="auto",l.style.marginRight="auto",l.style.width="100%")};Dh();let _h=()=>{!n.attachments?.enabled||!yt||!Eo||(Ze?Ze.remountPreviews(Eo):(Ze=Fs.fromConfig(n.attachments,Ph),Ze.setPreviewsContainer(Eo)),ot?.addListener(yt,"change",s=>{let l=s.target;Ze?.handleFileSelect(l.files),l.value=""}),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(Mw(n.attachments.dropOverlay)))};_h();let aA=()=>Wt?.prefetch(),Nh=()=>{if(!n.contextMentions?.enabled||!le)return;let s=ot?.header??null,l=s?og(s):void 0;if(Wt=OC({config:n,textarea:le,anchor:un??le,getMessages:()=>H.getMessages(),liveRegionHost:ue,chipRow:l}),Wt&&!l){let f=le;f.parentElement?.insertBefore(Wt.contextRow,f)}};Nh();let En=null,iA={getState:()=>Se.getState(),getValue:()=>le?.value??"",setValue:s=>{le&&(le.value=s,le.dispatchEvent(new Event("input",{bubbles:!0})),Mn())},submit:()=>{AC(ot?.form??null)},openAttachmentPicker:()=>{Lr()||yt?.click()},toggleVoice:()=>{op?.()},requestRender:()=>En?.resolve()},lA=()=>{let s=[];return(Wt?.affordanceButtons??[]).forEach((f,g)=>{s.push({id:`core:mention-${g}`,placement:"start",order:$n.mention+g,element:f,managed:!0})}),To&&s.push({id:"core:attachment",placement:"start",order:$n.attachment,element:To}),_o&&s.push({id:"core:mic",placement:"end",order:$n.mic,element:_o}),An&&s.push({id:"core:send",placement:"end",order:$n.send,element:An}),s},Fh=()=>{En?.destroy(),En=nC({getBindings:()=>ot,collect:()=>({builtIns:lA(),configActions:[...rA(),...n.composer?.actions??[]],plugins:i,contributionContext:{config:n,getState:()=>Se.getState(),requestRender:()=>En?.resolve()},debug:n.debug===!0}),actionContext:iA,getState:()=>Se.getState(),getOverflow:()=>n.composer?.actionOverflow,reportError:(s,l)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${l.actionId}" failed:`,s)}}),En.resolve()};Fh();let sp=()=>{if(Kn?.destroy(),Kn=null,!Zs().length)return;let s=ot?.header;s&&(Kn=iC({row:og(s),onRemove:l=>Zu(l),initialIds:Se.getState().activeModeIds}),Kn.render(Se.getState().activeModeIds,Zs()))};sp();let Uh=()=>{Sr?.destroy(),Sr=null,wr?.destroy(),wr=null;let s=ot?.header;s&&(Sr=gC({onDismiss:()=>Tn(void 0)}),s.appendChild(Sr.element),Sr.render(Se.getState().quote),tp()==="defer-one"&&(wr=hC({onEdit:()=>BM(),onRemove:()=>ta(void 0)}),s.appendChild(wr.element),wr.render(Se.getState().pendingSubmission)))};Uh();let ap=SC(),dA=()=>{let s=ot?.header?.querySelector(tg);if(s)return s.childElementCount>0;let l=Se.getState();return l.mentionRefs.length>0||nu(l.activeModeIds,Zs()).length>0},qh=()=>!1;function pn(){let s=Se.getState(),l=ap.observe(wC(le),s.text);Ie.toggleAttribute("data-persona-composer-compact",CC({text:s.text,wrapped:l,hasAttachments:s.attachments.length>0,hasChips:dA(),hasQuote:s.quote!==void 0,hasPendingSubmission:s.pendingSubmission!==void 0,dictationActive:qh()}))}function $h(){n.composer?.layout==="single-row"&&!Ae()?Ie.setAttribute("data-persona-composer-layout","single-row"):Ie.removeAttribute("data-persona-composer-layout")}$h(),Se.subscribe(()=>{En?.sync(),Ap(),Cd(),pn(),Cy()}),Cd();let Vh=!1,cA=s=>{if(Vh||n.debug!==!0)return;let l=["messages","composer"].filter(f=>s[f]);l.length&&(Vh=!0,console.warn(`[persona] layout.slots.${l.join(" and layout.slots.")} ${l.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 s=n.layout?.slots??{};cA(s);let l=g=>{switch(g){case"body-top":return re.querySelector("[data-persona-intro-card]");case"messages":return ke;case"footer-top":return br;case"composer":return un;case"footer-bottom":return st;default:return null}},f=(g,v)=>{switch(g){case"header-left":case"header-center":case"header-right":if(g==="header-left")Te.insertBefore(v,Te.firstChild);else if(g==="header-right")Te.appendChild(v);else{let M=Te.querySelector(".persona-flex-col");M?M.parentNode?.insertBefore(v,M.nextSibling):Te.appendChild(v)}break;case"body-top":{let M=re.querySelector("[data-persona-intro-card]");M?M.replaceWith(v):re.insertBefore(v,re.firstChild);break}case"body-bottom":re.appendChild(v);break;case"footer-top":br.replaceWith(v);break;case"footer-bottom":st.replaceWith(v);break;default:break}};for(let[g,v]of Object.entries(s))if(v)try{let M=v({config:n,defaultContent:()=>l(g)});M&&f(g,M)}catch(M){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${g}":`,M)}})();let jh=s=>{let f=s.target.closest('button[data-expand-header="true"]');if(!f)return;let g=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;let M=f.getAttribute("data-bubble-type");if(M==="reasoning")ti.has(v)?ti.delete(v):ti.add(v),FS(v,g);else if(M==="tool")oi.has(v)?oi.delete(v):oi.add(v),qS(v,g,n);else if(M==="approval"&&m){let z=((n.approval!==!1?n.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",V=m.approvalDetailsExpansionState.get(v)??z;m.approvalDetailsExpansionState.set(v,!V),m.updateApprovalDetailsUI(v,g,n)}Dt.delete(v)};ke.addEventListener("pointerdown",s=>{s.target.closest('button[data-expand-header="true"]')&&(s.preventDefault(),jh(s))}),ke.addEventListener("keydown",s=>{let l=s.target;(s.key==="Enter"||s.key===" ")&&l.closest('button[data-expand-header="true"]')&&(s.preventDefault(),jh(s))}),ke.addEventListener("copy",s=>{let{clipboardData:l}=s;if(!l)return;let f=ke.getRootNode(),g=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!g||g.isCollapsed)return;let v=g.toString(),M=zC(v);!M||M===v||(l.setData("text/plain",M),s.preventDefault())});let ip=new Map,zh=null,Kh="idle",uA={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},pA=(s,l)=>{let{icon:f,label:g}=uA[l];s.setAttribute("aria-label",g),s.title=g,s.setAttribute("aria-pressed",l==="idle"?"false":"true"),s.classList.toggle("persona-message-action-active",l!=="idle"),s.classList.toggle("persona-message-action-loading",l==="loading");let v=ce(f,14,"currentColor",2);v&&(s.innerHTML="",s.appendChild(v))},Gh=()=>{ke.querySelectorAll('[data-action="read-aloud"]').forEach(l=>{let g=l.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;pA(l,g&&g===zh?Kh:"idle")})};ke.addEventListener("click",s=>{let f=s.target.closest(".persona-message-action-btn[data-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest("[data-actions-for]");if(!g)return;let v=g.getAttribute("data-actions-for");if(!v)return;let M=f.getAttribute("data-action");if(M==="copy"){let z=H.getMessages().find(V=>V.id===v);if(z&&Bo.onCopy){let V=z.content||"";navigator.clipboard.writeText(V).then(()=>{f.classList.add("persona-message-action-success");let K=Ft(Fa,14,"currentColor",2);K&&(f.innerHTML="",f.appendChild(K)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let J=Ft(Ua,14,"currentColor",2);J&&(f.innerHTML="",f.appendChild(J))},2e3)}).catch(K=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",K)}),Bo.onCopy(z)}}else if(M==="read-aloud")H.toggleReadAloud(v);else if(M==="upvote"||M==="downvote"){let z=(ip.get(v)??null)===M,V=M==="upvote"?"thumbs-up":"thumbs-down";if(z){ip.delete(v),f.classList.remove("persona-message-action-active");let K=ce(V,14,"currentColor",2);K&&(f.innerHTML="",f.appendChild(K))}else{let K=M==="upvote"?"downvote":"upvote",J=g.querySelector(`[data-action="${K}"]`);if(J){J.classList.remove("persona-message-action-active");let ct=ce(K==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ct&&(J.innerHTML="",J.appendChild(ct))}ip.set(v,M),f.classList.add("persona-message-action-active");let ae=ce(V,14,"currentColor",2);ae&&(ae.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(ae)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Je=H.getMessages().find(lt=>lt.id===v);Je&&Bo.onFeedback&&Bo.onFeedback({type:M,messageId:Je.id,message:Je})}}else if(M==="regenerate")Zl?.regenerate(v);else if(M==="edit")Zl?.edit(v);else if(M==="quote")Zl?.quote(v);else if(M?.startsWith(Cu)){let N=M.slice(Cu.length),z=n.messageActions?.custom?.find(K=>K.id===N),V=H.getMessages().find(K=>K.id===v);if(!z||!V)return;try{z.onSelect(V)}catch(K){console.error(`[AgentWidget] messageActions.custom "${N}" onSelect failed:`,K)}}});let Zl=null;ke.addEventListener("click",s=>{let f=s.target.closest("button[data-approval-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest(".persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;let M=f.getAttribute("data-approval-action");if(!M)return;let N=M==="approve"?"approved":"denied",V=H.getMessages().find(J=>J.id===v);if(!V?.approval)return;let K=g.querySelector("[data-approval-buttons]");K&&K.querySelectorAll("button").forEach(ae=>{ae.disabled=!0,ae.style.opacity="0.5",ae.style.cursor="not-allowed"}),V.approval.toolType==="webmcp"?H.resolveWebMcpApproval(v,N):H.resolveApproval(V.approval,N)});let Ve=null,Xh=!1,bi=null,ss=()=>{},vi="none",ed=null,Yo={artifacts:[],selectedId:null},Gn=!1,fn=!1,xi=!1,ra=!1,Qh=()=>ra||Yo.artifacts.some(s=>Nn(n.features?.artifacts,s)==="panel"),td=()=>Yo.artifacts.length>0&&!Gn&&Qh(),it={current:null},lp=(s,l)=>{let f=H.getArtifactById(l),g=f?.markdown,v=f?.title||"artifact",M=f?.file,N=f?.artifactType??"markdown";if(!g){let K=s.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(K){let ae=H.getMessages().find(fe=>fe.id===K);if(ae?.rawContent)try{let fe=JSON.parse(ae.rawContent);g=fe?.props?.markdown,v=fe?.props?.title||v,fe?.props?.file&&typeof fe.props.file=="object"&&(M=fe.props.file),!f&&typeof fe?.props?.artifactType=="string"&&(N=fe.props.artifactType)}catch{}}}return{markdown:g,title:v,file:M,artifactType:N}};ke.addEventListener("click",s=>{let f=s.target.closest("[data-download-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-download-artifact");if(!g||n.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:g})===!0)return;let{markdown:M,title:N,file:z}=lp(f,g);if(!M)return;let V=gr();V&&V.triggerArtifactDownload(V.downloadInfoFor({title:N,markdown:M,file:z}))}),ke.addEventListener("click",s=>{let f=s.target.closest("[data-artifact-custom-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-artifact-custom-action");if(!g)return;let v=f.closest("[data-artifact-inline]"),M=v?null:f.closest("[data-open-artifact]"),N=v?v.getAttribute("data-artifact-inline"):M?.getAttribute("data-open-artifact")??null,V=(v?n.features?.artifacts?.inlineActions:n.features?.artifacts?.cardActions)?.find(lt=>lt.id===g);if(!V)return;let{markdown:K,title:J,file:ae,artifactType:fe}=lp(f,N??""),Je={artifactId:N,title:J,artifactType:fe,markdown:K,file:ae};try{Promise.resolve(V.onClick(Je)).catch(()=>{})}catch{}}),ke.addEventListener("click",s=>{let f=s.target.closest("[data-copy-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-copy-artifact");if(!g)return;let v=H.getArtifactById(g),M=gr();if(!M)return;let N="";if(v)N=M.artifactCopyText(v);else{let{markdown:z,file:V,artifactType:K}=lp(f,g);K==="markdown"&&(N=M.artifactCopyText({id:g,artifactType:"markdown",status:"complete",markdown:z??"",...V?{file:V}:{}}))}N&&navigator.clipboard.writeText(N).then(()=>{let z=Ft(Fa,16,"currentColor",2);z&&(f.replaceChildren(z),setTimeout(()=>{let V=Ft(Ua,16,"currentColor",2);V&&f.replaceChildren(V)},1500))}).catch(()=>{})}),ke.addEventListener("click",s=>{let f=s.target.closest("[data-expand-artifact-inline]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-expand-artifact-inline");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(Gn=!1,ra=!0,fn=!0,xi=!0,H.selectArtifact(g),mn())}),ke.addEventListener("click",s=>{let l=s.target;if(l.closest("[data-download-artifact]")||l.closest("[data-artifact-custom-action]"))return;let f=l.closest("[data-open-artifact]");if(!f)return;let g=f.getAttribute("data-open-artifact");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(s.preventDefault(),s.stopPropagation(),Gn=!1,ra=!0,H.selectArtifact(g),mn())}),ke.addEventListener("keydown",s=>{if(s.key!=="Enter"&&s.key!==" ")return;let l=s.target;!l.hasAttribute("data-open-artifact")&&!l.hasAttribute("data-expand-artifact-inline")||(s.preventDefault(),l.click())});let sa=_e.composerOverlay,aa=(s,l,f)=>{let g=l.trim();if(!g||!it.current)return;let v=s.getAttribute("data-tool-call-id")??"",M=f.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:v,answer:g,answers:f.structured,values:f.values??(f.source==="multi"?g.split(", "):[g]),isFreeText:M,source:f.source},bubbles:!0,composed:!0})),$r(sa,v);let N=it.current.getMessages().find(z=>z.toolCall?.id===v);N?.agentMetadata?.awaitingLocalTool?it.current.resolveAskUserQuestion(N,f.structured??g):it.current.sendMessage(g)},as=s=>{let l=it.current;if(!l)return;let f=s.getAttribute("data-tool-call-id")??"",g=l.getMessages().find(v=>v.toolCall?.id===f);g&&l.persistAskUserQuestionProgress(g,{answers:mc(s,g),currentIndex:sn(s)})},Yh=s=>Object.entries(s).map(([l,f])=>`${l}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),dp=s=>{if(n.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let l=sn(s),f=Ra(s);if(l>=f-1)return;let g=it.current?.getMessages().find(v=>v.toolCall?.id===s.getAttribute("data-tool-call-id"));g&&(gc(s,g,n,l+1),as(s))};sa.addEventListener("click",s=>{let f=s.target.closest("[data-ask-user-action]");if(!f)return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;let v=f.getAttribute("data-ask-user-action");if(s.preventDefault(),s.stopPropagation(),v==="dismiss"){let M=g.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:M},bubbles:!0,composed:!0})),$r(sa,M);let N=it.current?.getMessages().find(z=>z.toolCall?.id===M);N?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved(N),it.current?.resolveAskUserQuestion(N,"(dismissed)"));return}if(v==="pick"){let M=f.getAttribute("data-option-label");if(!M)return;let N=g.getAttribute("data-multi-select")==="true",z=qr(g);if(z&&N){let V=Ws(g)[sn(g)],K=new Set(Array.isArray(V)?V:[]);K.has(M)?K.delete(M):K.add(M),Vr(g,Array.from(K)),as(g);return}if(z){Vr(g,M),as(g),dp(g);return}if(N){let V=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",V?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!V);let K=g.querySelector('[data-ask-user-action="submit-multi"]');K&&(K.disabled=Ff(g).length===0);return}aa(g,M,{source:"pick",values:[M]});return}if(v==="submit-multi"){let M=Ff(g);if(M.length===0)return;aa(g,M.join(", "),{source:"multi",values:M});return}if(v==="open-free-text"){let M=g.querySelector('[data-ask-free-text-row="true"]');M&&(M.classList.remove("persona-hidden"),M.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(v==="focus-free-text"){g.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(v==="submit-free-text"){let N=g.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!N.trim())return;if(qr(g)){Vr(g,N.trim()),as(g),dp(g);return}aa(g,N,{source:"free-text"});return}if(v==="next"||v==="back"){if(!it.current)return;let M=g.getAttribute("data-tool-call-id")??"",N=it.current.getMessages().find(ae=>ae.toolCall?.id===M);if(!N)return;let V=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(V){let ae=Ws(g)[sn(g)];(typeof ae!="string"||ae!==V)&&Vr(g,V)}let K=v==="next"?1:-1,J=sn(g)+K;gc(g,N,n,J),as(g);return}if(v==="submit-all"){if(!it.current)return;let M=g.getAttribute("data-tool-call-id")??"",N=it.current.getMessages().find(ae=>ae.toolCall?.id===M);if(!N)return;let V=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";V&&Vr(g,V);let K=mc(g,N);it.current.persistAskUserQuestionProgress(N,{answers:K,currentIndex:sn(g)});let J=Yh(K);aa(g,J||"(submitted)",{source:"submit-all",structured:K});return}if(v==="skip"){if(!it.current)return;let M=g.getAttribute("data-tool-call-id")??"",N=it.current.getMessages().find(fe=>fe.toolCall?.id===M);if(!N)return;let z=qr(g),V=sn(g),K=Ra(g),J=V>=K-1;if(!z){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:M},bubbles:!0,composed:!0})),$r(sa,M),N.agentMetadata?.awaitingLocalTool&&(it.current.markAskUserQuestionResolved(N),it.current.resolveAskUserQuestion(N,"(dismissed)"));return}Vr(g,"");let ae=g.querySelector('[data-ask-free-text-input="true"]');if(ae&&(ae.value=""),J){let fe=mc(g,N),Je=Yh(fe);aa(g,Je||"(skipped)",{source:"submit-all",structured:fe});return}gc(g,N,n,V+1),as(g);return}}),sa.addEventListener("keydown",s=>{if(s.key!=="Enter")return;let f=s.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;s.preventDefault();let v=f.value;if(v.trim()){if(qr(g)){Vr(g,v.trim()),as(g),dp(g);return}aa(g,v,{source:"free-text"})}});let Jh=s=>{if(!/^[1-9]$/.test(s.key)||s.metaKey||s.ctrlKey||s.altKey)return;let l=s.target;if(l?.tagName==="INPUT"||l?.tagName==="TEXTAREA"||l?.isContentEditable)return;let f=sa.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let g=Number(s.key),M=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[g-1];M&&(s.preventDefault(),M.click())};document.addEventListener("keydown",Jh);let Pn=null,bt=null,Ci=null,od=null,nd=()=>{},Zh=!1,rd="",sd="";function cp(){od?.(),od=null}let fA=()=>{let s=ba&&Ts?.isConnected?Ts:null,l=s?s.getBoundingClientRect().width:0;return l<=0?200:l+360},ey=()=>{if(!Pn||!bt)return;let s=e.classList.contains("persona-artifact-welded-split"),l=e.ownerDocument.defaultView??window,f=l.innerWidth<=640;if(!s||e.classList.contains("persona-artifact-narrow-host")||f){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let g=Pn.firstElementChild;if(!g||g===bt)return;let v=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${v}px`,bt.style.zIndex="5";let M=oh(Pn,l),N=g.offsetWidth+M/2-v/2;bt.style.left=`${Math.max(0,N)}px`},ad=()=>{},mA=()=>{let s=e.ownerDocument.defaultView??window,l=n.launcher?.mobileFullscreen??!0,f=n.launcher?.mobileBreakpoint??640;return!l||s.innerWidth>f?!1:ge||St(n)},id=()=>!wo(n)||!td()||e.classList.contains("persona-artifact-narrow-host")||mA()||(e.ownerDocument.defaultView??window).innerWidth<jL?"none":Jg(n)?"detached":"welded",mn=()=>{if(!Ve||!wo(n))return;Dl(e,n),_l(e,n),ad();let s=n.features?.artifacts?.layout?.narrowHostMaxWidth??520,l=we.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",l>0&&l<=s);let f=td();Ve.setVisible(f),Ve.update(Yo),Gn?(Ve.setMobileOpen(!1),Ve.element.classList.add("persona-hidden"),Ve.backdrop?.classList.add("persona-hidden"),fn=!1,xi=!1):Yo.artifacts.length>0&&Qh()?(Ve.element.classList.remove("persona-hidden"),Ve.setMobileOpen(!0)):(Ve.setMobileOpen(!1),Ve.element.classList.add("persona-hidden"),Ve.backdrop?.classList.add("persona-hidden"),fn=!1,xi=!1);let g=n.features?.artifacts?.layout?.showExpandToggle===!0;if(Ve.setExpandToggleVisible(g),Ve.setCopyButtonVisible(n.features?.artifacts?.layout?.showCopyButton===!0),Ve.setRefreshButtonVisible(typeof n.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Ve.setCustomActions(n.features?.artifacts?.toolbarActions??[]),Ve.setTabFade(n.features?.artifacts?.layout?.tabFade),Ve.setRenderTabBar(n.features?.artifacts?.renderTabBar),!g&&!xi&&(fn=!1),fn!==Zh){let M=Ve.element;fn?(rd=M.style.width,sd=M.style.maxWidth,M.style.removeProperty("width"),M.style.removeProperty("max-width")):(rd&&(M.style.width=rd),sd&&(M.style.maxWidth=sd),rd="",sd=""),Zh=fn}e.classList.toggle("persona-artifact-expanded",fn),Ve.setExpanded(fn);let v=id();v!==vi&&(vi=v,ss()),nd()};if(wo(n)){we.style.position="relative";let s=I("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),l=I("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");s.appendChild(ue),Pn=l,l.appendChild(s),we.appendChild(l);let f=v=>{Xh||Ve||(Ve=v.createArtifactPane(n,{onSelect:M=>it.current?.selectArtifact(M),onDismiss:()=>{Gn=!0,mn()},onToggleExpand:()=>{let M=!fn,N=Yo.selectedId??Yo.artifacts[Yo.artifacts.length-1]?.id??null;n.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:N,expanded:M})!==!0&&(fn=M,M||(xi=!1),mn())}}),Ve.element.classList.add("persona-hidden"),l.appendChild(Ve.element),Ve.backdrop&&we.appendChild(Ve.backdrop),nd(),mn())},g=gr();g?f(g):(Qg(()=>{let v=gr();v&&f(v)}),Ru().catch(()=>{})),nd=()=>{if(!Pn||!Ve)return;if(!(n.features?.artifacts?.layout?.resizable===!0)){Ci?.(),Ci=null,cp(),bt&&(bt.remove(),bt=null),Ve.element.style.removeProperty("width"),Ve.element.style.removeProperty("maxWidth");return}if(!bt){let M=I("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");M.setAttribute("role","separator"),M.setAttribute("aria-orientation","vertical"),M.setAttribute("aria-label","Resize artifacts panel"),M.tabIndex=0;let N=e.ownerDocument,z=N.defaultView??window,V=K=>{if(!Ve||K.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||z.innerWidth<=640)return;K.preventDefault(),cp();let J=K.clientX,ae=Ve.element.getBoundingClientRect().width,fe=n.features?.artifacts?.layout,Je=ct=>{let Qt=Pn.getBoundingClientRect().width,Nt=e.classList.contains("persona-artifact-welded-split"),Lt=oh(Pn,z),io=Nt?0:M.getBoundingClientRect().width||6,et=ae-(ct.clientX-J),lo=nw(et,Qt,Lt,io,fe?.resizableMinWidth,fe?.resizableMaxWidth,fA());Ve.element.style.width=`${lo}px`,Ve.element.style.maxWidth="none",ey()},lt=()=>{N.removeEventListener("pointermove",Je),N.removeEventListener("pointerup",lt),N.removeEventListener("pointercancel",lt),od=null;try{M.releasePointerCapture(K.pointerId)}catch{}};od=lt,N.addEventListener("pointermove",Je),N.addEventListener("pointerup",lt),N.addEventListener("pointercancel",lt);try{M.setPointerCapture(K.pointerId)}catch{}};M.addEventListener("pointerdown",V),bt=M,Pn.insertBefore(M,Ve.element),Ci=()=>{M.removeEventListener("pointerdown",V)}}if(bt){let M=td();bt.classList.toggle("persona-hidden",!M),ey()}},ad=()=>{if(!ge||!Ve||(n.launcher?.sidebarMode??!1)||St(n)&&Wo(n).reveal==="emerge")return;let M=e.ownerDocument.defaultView??window,N=n.launcher?.mobileFullscreen??!0,z=n.launcher?.mobileBreakpoint??640;if(N&&M.innerWidth<=z||!YS(n,ge))return;let V=n.launcher?.width??n.launcherWidth??zo,K=n.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";td()?(we.style.width=K,we.style.maxWidth=K):(we.style.width=V,we.style.maxWidth=V)},typeof ResizeObserver<"u"&&(bi=new ResizeObserver(()=>{mn()}),bi.observe(we))}else we.appendChild(ue);Ae()&&Xt&&(_e.peekBanner&&Xt.appendChild(_e.peekBanner),Xt.appendChild(Ie)),e.appendChild(Xe),Xt&&e.appendChild(Xt);let up=()=>{if(Ae()){we.style.width="100%",we.style.maxWidth="100%";let ve=n.launcher?.composerBar??{},Ne=Xe.dataset.state==="expanded",ft=ve.expandedSize??"anchored";if(!(Ne&&ft!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Gt=n.theme?.components?.panel,jo=Kr(n),Rs=(Hs,oc)=>Hs==null||Hs===""?oc:xo(jo,Hs)??Hs,nv="1px solid var(--persona-border)",Mt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Tf="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Rs(Gt?.border,nv),ue.style.borderRadius=Rs(Gt?.borderRadius,Tf),ue.style.boxShadow=Rs(Gt?.shadow,Mt),ue.style.overflow="hidden";return}let s=St(n),l=n.launcher?.sidebarMode??!1,f=s||l||(n.launcher?.fullHeight??!1),g=n.launcher?.enabled===!1,v=n.launcher?.detachedPanel===!0,M=n.theme?.components?.panel,N=Kr(n),z=(ve,Ne)=>ve==null||ve===""?Ne:xo(N,ve)??ve,V=e.ownerDocument.defaultView??window,K=n.launcher?.mobileFullscreen??!0,J=n.launcher?.mobileBreakpoint??640,ae=V.innerWidth<=J,fe=K&&ae&&ge,Je=s&&K&&ae,lt=n.launcher?.position??"bottom-left",ct=lt==="bottom-left"||lt==="top-left",Qt=n.launcher?.zIndex??so,Nt="var(--persona-panel-border, 1px solid var(--persona-border))",Lt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",io="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",et=v&&!fe&&!Je;et?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let lo=et?Nt:l||fe?"none":Nt,lr=et?Lt:fe?"none":l?ct?"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))":g?"none":Lt;s&&!fe&&!et&&(lr="none",lo="none");let Wn=et?io:l||fe?"0":io,Bn=z(M?.border,lo),_=z(M?.shadow,lr),We=z(M?.borderRadius,Wn),Oe=id(),me=Oe==="detached",pt=Oe==="welded";e.classList.toggle("persona-artifact-detached-split",me),e.classList.toggle("persona-artifact-welded-split",pt);let jt="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)))))",It=(n.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&wo(n)&&Jg(n)&&g&&!s;e.classList.toggle("persona-artifact-chat-flush",It);let Pe=me||It?"none":_,zt=me?Nt:pt?"none":Bn,Kt=me?io:We;It&&(zt="none",Kt="0");let rn=M?.borderRadius!=null&&M.borderRadius!=="",Re=It&&!rn?"0":We,xt=re.scrollTop;e.style.cssText="",Xe.style.cssText="",we.style.cssText="",ue.style.cssText="",re.style.cssText="",na||(Ie.style.cssText=""),ee&&(re.style.display="none"),(f||g)&&(e.style.minWidth="0");let On=()=>{if(xt<=0)return;(re.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(re.scrollTop===xt)return;let Ne=re.scrollHeight-re.clientHeight;Ne<=0||(re.scrollTop=Math.min(xt,Ne))})};if(fe){Xe.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"),Xe.style.cssText=`
45
45
  position: fixed !important;
46
46
  inset: 0 !important;
47
47
  width: 100% !important;
@@ -77,7 +77,7 @@ _Details: ${o.message}_`:n}var Zf=e=>({isError:!0,content:[{type:"text",text:e}]
77
77
  overflow: hidden !important;
78
78
  border-radius: 0 !important;
79
79
  border: none !important;
80
- `,re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",Ie.style.flexShrink="0",Yu(),Ge=!0,Bn();return}let Be=n?.launcher?.width??n?.launcherWidth??Vo;if(!l&&!s)g&&f?(we.style.width="100%",we.style.maxWidth="100%"):(we.style.width=Be,we.style.maxWidth=Be);else if(s)if(Wo(n).reveal==="emerge"&&!v){let Ne=Wo(n).width;we.style.width=Ne,we.style.maxWidth=Ne}else we.style.width="100%",we.style.maxWidth="100%";if(ad(),we.style.boxShadow=Ee,we.style.borderRadius=He,me?we.style.border="none":pt&&(we.style.border=Wn),ue.style.border=Vt,ue.style.borderRadius=Kt,ue.style.boxShadow=me&&!It?zt:"",It&&(ue.style.background="transparent",re.style.background="transparent",Ie.style.background="transparent",Ie.style.borderTop="none"),pt){let ve=n.features?.artifacts?.layout;ed=ve?.unifiedSplitOuterRadius?.trim()||ve?.paneBorderRadius?.trim()||We}else ed=null;if(s&&!fe&&!et&&!me&&!pt&&M?.border===void 0&&(ue.style.border="none",Wo(n).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),s&&!fe&&pt&&M?.border===void 0&&(Wo(n).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.style.borderRight="1px solid var(--persona-border)"),f&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",g&&(e.style.width="100%"),Xe.style.display="flex",Xe.style.flexDirection="column",Xe.style.flex="1 1 0%",Xe.style.minHeight="0",Xe.style.maxHeight="100%",Xe.style.height="100%",g&&(Xe.style.overflow="hidden"),we.style.display="flex",we.style.flexDirection="column",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.maxHeight="100%",we.style.height="100%",me||(we.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",Ie.style.flexShrink="0"),g&&(et||me||It)&&!s&&(It||(Xe.style.padding="var(--persona-panel-inset)"),Xe.style.background="var(--persona-panel-canvas-bg)"),Xe.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"),!l&&!g&&!s&&(Go[lt]??Go["bottom-right"]).split(" ").forEach(Ne=>Xe.classList.add(Ne)),l){let ve=n.launcher?.sidebarWidth??"420px";v?Xe.style.cssText=`
80
+ `,re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",Ie.style.flexShrink="0",Ju(),Ge=!0,On();return}let Be=n?.launcher?.width??n?.launcherWidth??zo;if(!l&&!s)g&&f?(we.style.width="100%",we.style.maxWidth="100%"):(we.style.width=Be,we.style.maxWidth=Be);else if(s)if(Wo(n).reveal==="emerge"&&!v){let Ne=Wo(n).width;we.style.width=Ne,we.style.maxWidth=Ne}else we.style.width="100%",we.style.maxWidth="100%";if(ad(),we.style.boxShadow=Pe,we.style.borderRadius=Re,me?we.style.border="none":pt&&(we.style.border=Bn),ue.style.border=zt,ue.style.borderRadius=Kt,ue.style.boxShadow=me&&!It?jt:"",It&&(ue.style.background="transparent",re.style.background="transparent",Ie.style.background="transparent",Ie.style.borderTop="none"),pt){let ve=n.features?.artifacts?.layout;ed=ve?.unifiedSplitOuterRadius?.trim()||ve?.paneBorderRadius?.trim()||We}else ed=null;if(s&&!fe&&!et&&!me&&!pt&&M?.border===void 0&&(ue.style.border="none",Wo(n).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),s&&!fe&&pt&&M?.border===void 0&&(Wo(n).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.style.borderRight="1px solid var(--persona-border)"),f&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",g&&(e.style.width="100%"),Xe.style.display="flex",Xe.style.flexDirection="column",Xe.style.flex="1 1 0%",Xe.style.minHeight="0",Xe.style.maxHeight="100%",Xe.style.height="100%",g&&(Xe.style.overflow="hidden"),we.style.display="flex",we.style.flexDirection="column",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.maxHeight="100%",we.style.height="100%",me||(we.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",Ie.style.flexShrink="0"),g&&(et||me||It)&&!s&&(It||(Xe.style.padding="var(--persona-panel-inset)"),Xe.style.background="var(--persona-panel-canvas-bg)"),Xe.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"),!l&&!g&&!s&&(Go[lt]??Go["bottom-right"]).split(" ").forEach(Ne=>Xe.classList.add(Ne)),l){let ve=n.launcher?.sidebarWidth??"420px";v?Xe.style.cssText=`
81
81
  position: fixed !important;
82
82
  top: var(--persona-panel-inset) !important;
83
83
  bottom: var(--persona-panel-inset) !important;
@@ -114,9 +114,9 @@ _Details: ${o.message}_`:n}var Zf=e=>({isError:!0,content:[{type:"text",text:e}]
114
114
  min-height: 0 !important;
115
115
  margin: 0 !important;
116
116
  padding: 0 !important;
117
- box-shadow: ${Ee} !important;
118
- border-radius: ${He} !important;
119
- ${me?"border: none !important;":pt?`border: ${Wn} !important;`:""}
117
+ box-shadow: ${Pe} !important;
118
+ border-radius: ${Re} !important;
119
+ ${me?"border: none !important;":pt?`border: ${Bn} !important;`:""}
120
120
  `,we.style.setProperty("width","100%","important"),we.style.setProperty("max-width","100%","important"),ue.style.cssText=`
121
121
  display: flex !important;
122
122
  flex-direction: column !important;
@@ -127,17 +127,17 @@ _Details: ${o.message}_`:n}var Zf=e=>({isError:!0,content:[{type:"text",text:e}]
127
127
  max-height: 100% !important;
128
128
  overflow: hidden !important;
129
129
  border-radius: ${Kt} !important;
130
- border: ${Vt} !important;
131
- ${me&&!It?`box-shadow: ${zt} !important;`:""}
130
+ border: ${zt} !important;
131
+ ${me&&!It?`box-shadow: ${jt} !important;`:""}
132
132
  ${It?"background: transparent !important;":""}
133
133
  `,na||(Ie.style.cssText=`
134
134
  flex-shrink: 0 !important;
135
135
  border-top: none !important;
136
136
  padding: 8px 16px 12px 16px !important;
137
137
  ${It?"background: transparent !important;":""}
138
- `)}if(!g&&!s){let ve="max-height: -moz-available !important; max-height: stretch !important;",Ne=l?"":"padding-top: 1.25em !important;",ft=l?"":`z-index: ${n.launcher?.zIndex??so} !important;`;Xe.style.cssText+=ve+Ne+ft}Yu(),Bn()},up=()=>{e.style.setProperty("--persona-content-max-width",Kr(n,Ae()))},Jh=!1,Zh=()=>{let s=lg(n,Ae());Ae()&&n.composer?.placement&&n.debug===!0&&!Jh&&(Jh=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let l=xn(n);e.setAttribute("data-persona-composer-placement",s),e.setAttribute("data-persona-conversation-state",Xl),e.setAttribute("data-persona-welcome-anchor",l.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",l.composerGap??lu),Yl()},ey=()=>{if(Ae())return;let s=St(n),l=n.launcher?.sidebarMode??!1;if(s||l||(n.launcher?.fullHeight??!1)||!ge)return;let g=e.ownerDocument.defaultView??window,v=n.launcher?.mobileFullscreen??!0,M=n.launcher?.mobileBreakpoint??640;if(v&&g.innerWidth<=M)return;let N=g.innerHeight,V=64,j=n.launcher?.heightOffset??0,K=Math.max(200,N-V),J=Math.min(640,K);we.style.height=`${Math.max(200,J-j)}px`};cp(),Us(e,n),Dl(e,n),_l(e,n),up(),Zh(),rs=()=>{cp(),ey(),Us(e,n),Dl(e,n),_l(e,n),up(),Zh(),ed?e.style.setProperty("--persona-artifact-welded-outer-radius",ed):e.style.removeProperty("--persona-artifact-welded-outer-radius"),ht(),Se()};let be=[];be.push(()=>{Vh=!0}),be.push(()=>{u.forEach(s=>s()),d.destroy()}),be.push(()=>{document.removeEventListener("keydown",Xh)}),be.push(()=>{mi!==null&&clearTimeout(mi)});let Pn=null,Ln=null;be.push(()=>{Pn?.(),Pn=null,Ln?.(),Ln=null}),yi&&be.push(()=>{yi?.disconnect(),yi=null}),be.push(()=>{xi?.(),xi=null,dp(),bt&&(bt.remove(),bt=null),je?.element.style.removeProperty("width"),je?.element.style.removeProperty("maxWidth"),je?.destroy()}),Ht&&be.push(()=>{zl=!0,cn=null,C!==null&&(cancelAnimationFrame(C),C=null),B?.destroy(),B=null,Tt?.destroy(),Tt=null,po=null});let as=null,ty=()=>{as&&(as(),as=null),n.colorScheme==="auto"&&(as=Va(()=>{Us(e,n)}))};ty(),be.push(()=>{as&&(as(),as=null)}),be.push(()=>{S=!0,h?.()}),be.push(()=>{P=!0});let oy=!1;be.push(()=>{oy=!0});let pp=(s,l)=>{let f=Ll(s,l);return f||!rS.includes(s)?f:(iS().then(g=>{if(oy)return;Ka(g.wipe),Ka(g.glyphCycle);let v=Ll(s,l);v&&Hl(v,e)}).catch(()=>{}),null)},ld=n.features?.streamAnimation;if(ld?.type&&ld.type!=="none"){let s=pp(ld.type,ld.plugins);s&&Hl(s,e),be.push(()=>sS(e))}let Gn=Bl(hr),ny=Bl(Vu),ry=Bl(ci),is=[Gn,ny,ry];be.push(()=>{is.forEach(s=>s.destroy())});let ls=null,H,ds=null,sy=!1,ay=0,iy=null,ly=s=>s.reduce((l,f)=>f.role==="user"?l+1:l,0),dy=s=>{for(let l=s.length-1;l>=0;l--)if(Bs(s[l]))return s[l].id??null;return null},cy=!1,pA=()=>{cy||n.debug!==!0||(cy=!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".'))},uy=!1,py=!1,fy=(s,l)=>{uy||n.debug!==!0||!l.enabled||l.expose||sy||py&&(H.isStreaming()||s.some(Bs)||(uy=!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.")))},ia=s=>{if(!H)return;let l=s??H.getMessages(),f=K=>{K.render([],H,le,l)},g=K=>{is.forEach(J=>{J!==K&&f(J)})};ds&&(ly(l)>ay||dy(l)!==iy)&&(ds=null);let v=$r(n);fy(l,v);let M=v.enabled?yc(l):null,N=ds??M,V=ds?"host":"agent";if(N){let K=n.suggestions?.followUps,J=K?.placement??(K?"auto":"composer"),fe=(J==="auto"?Ae()?"composer":"after-message":J)==="after-message"?ry:Gn;g(fe),fe.render(N,H,le,l,n.suggestionChipsConfig,{source:V,surface:"followUp",variant:K?.variant??"chip",behavior:K?.behavior??"send",overflow:K?.overflow??"wrap",maxItems:K?.maxItems??4,config:n,plugins:i,submitPrompt:Xd});return}if(l.some(K=>K.role==="user")){is.forEach(f);return}let j=n.suggestions?.starters;if(j){let K=Qr(xn(n),l),J=j.placement??"auto",ae=J==="auto"?K?"welcome":"composer":J;if(ae==="welcome"&&!K){pA(),is.forEach(f);return}let fe=ae==="welcome"?ny:Gn;g(fe),fe.render(j.items??n.suggestionChips,H,le,l,n.suggestionChipsConfig,{surface:"starter",variant:j.variant??"card",behavior:j.behavior??"send",overflow:j.overflow??"wrap",maxItems:j.maxItems??4,config:n,plugins:i,submitPrompt:Xd});return}g(Gn),Gn.render(n.suggestionChips,H,le,l,n.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:n,plugins:i,submitPrompt:Xd})},my=()=>{ds&&(ds=null,ia())},fA=s=>{let l=Array.isArray(s)?[...s]:[];if(!l.length){my();return}let f=H?H.getMessages():[];ds=l,sy=!0,ay=ly(f),iy=dy(f),ia(f)},Fo=!1,Dt=VC(),la=new Map,cs=new Map,Sr=new Map,us=null,wr=null;function ps(){if(!us)return;let s=us;us=null,wr?.destroy(),wr=null,Dt.delete(s),ue.querySelector(`#wrapper-${s}`)?.removeAttribute("data-preserve-runtime"),H&&Jo(Le,H.getMessages(),oo)}let fs=0,mA=Dn()!==null,Uo=YC(),qo=0,Ar=null,Po=!1,dd=!1,Mr=0,$t=null,ms=null,fp=!1,da=!1,gs=null,Ci=!0,cd=!1,ca=null,ud=!1,hs=()=>{ud=!0,bA()},mp=null,gA=4,Xn=24,hA=80,yA=1e3,Qn=null,gy=()=>{e.setAttribute("data-persona-scrollbar",Gu()),Gu()!=="on-scroll"&&(Qn!==null&&clearTimeout(Qn),Qn=null,re.removeAttribute("data-persona-scrollbar-visible"))},bA=()=>{Gu()==="on-scroll"&&(re.setAttribute("data-persona-scrollbar-visible",""),Qn!==null&&clearTimeout(Qn),Qn=setTimeout(()=>{Qn=null,qs(re,Xn)&&re.removeAttribute("data-persona-scrollbar-visible")},yA))};gy(),be.push(()=>{Qn!==null&&clearTimeout(Qn)});let gp=new Map,ze={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Nh=()=>ze.active,pn();let hy=n.voiceRecognition?.autoResume??!1,Yn=s=>{x.emit("voice:state",{active:ze.active,source:s,timestamp:Date.now()})},gn=()=>{de(s=>({...s,voiceState:{active:ze.active,timestamp:Date.now(),manuallyDeactivated:ze.manuallyDeactivated}}))},vA=()=>{if(n.voiceRecognition?.enabled===!1)return;let s=ah(X.voiceState),l=!!s.active,f=Number(s.timestamp??0);ze.manuallyDeactivated=!!s.manuallyDeactivated,l&&Date.now()-f<_k&&setTimeout(()=>{ze.active||(ze.manuallyDeactivated=!1,n.voiceRecognition?.provider?.type==="runtype"?H.toggleVoice().then(()=>{ze.active=H.isVoiceActive(),Yn("restore"),H.isVoiceActive()&&Ta()}):Jd("restore"))},1e3)},xA=()=>H?xw(H.getMessages()).filter(s=>!s.__skipPersist):[],pd=null,yy=(s,l)=>{typeof console<"u"&&console.error(s,l)},fd=(s,l)=>{let f=()=>{try{let N=s();return!N||typeof N.then!="function"?null:Promise.resolve(N).catch(V=>{yy(l,V)})}catch(N){return yy(l,N),null}},g=pd,v=g?g.then(()=>f()??void 0):f();if(!v)return;let M=v.finally(()=>{pd===M&&(pd=null)});pd=M};function Si(s){if(!F?.save)return;let f={messages:s?xw(s):H?xA():[],metadata:X,artifacts:Yo.artifacts,selectedArtifactId:Yo.selectedId,...ys?{draft:ys}:{}};fd(()=>F.save(f),"[AgentWidget] Failed to persist state:")}let ys,md=()=>!F?.save||n.persistState===!1?!1:typeof n.persistState=="object"?n.persistState.persist?.draft!==!1:!0,wi=yC({write:()=>{if(!md())return;let s=Ce.getState(),l=gC({text:s.text,mentionRefs:s.mentionRefs,contentSegments:cf(),selectedModelId:s.selectedModelId,activeModeIds:s.activeModeIds,quote:s.quote});JSON.stringify(l)!==JSON.stringify(ys)&&(ys=l,Si())}});function by(){md()&&wi.schedule()}function hp(){wi.flush()}function vy(s){if(!md())return;let l=hC(s,{mentionSourceIds:(n.contextMentions?.sources??[]).map(f=>f.id),modelIds:(n.composer?.models??[]).map(f=>f.id),modes:n.composer?.modes??[]});l&&(ys=s,le&&!le.value&&(le.value=l.text,le.dispatchEvent(new Event("input",{bubbles:!0})),An()),l.selectedModelId&&(Ce.setSelectedModelId(l.selectedModelId),vr?.repaint()),Jl(l.activeModeIds??[]),l.quote&&Mn(l.quote),wi.cancel())}function gd(){wi.cancel(),ys&&(ys=void 0,md()&&Si())}let ua=null,xy=()=>Xe.querySelector("#persona-scroll-container")||re,pa=()=>{ua!==null&&(cancelAnimationFrame(ua),ua=null),Po=!1},Cy=()=>{Ar!==null&&(cancelAnimationFrame(Ar),Ar=null),dd=!1,pa()},CA=()=>Fo&&bp()&&(No()!=="anchor-top"||Sh()),yp=()=>{let s=ui()||"Jump to latest",l=CA();Ot.toggleAttribute("data-persona-scroll-to-bottom-streaming",l),Mr>0?(ts.textContent=String(Mr),ts.style.display="",Ot.setAttribute("aria-label",`${s} (${Mr} new)`)):(ts.textContent="",ts.style.display="none",Ot.setAttribute("aria-label",l?`${s} (response streaming below)`:s))},Sy=()=>{Mr!==0&&(Mr=0,yp())},SA=()=>{let s=$t?.spacerHeight??0;return s<=0?qs(re,Xn):vd(s)-re.scrollTop-re.clientHeight<=Xn},bp=()=>br()?!Uo.isFollowing():!SA(),vp=()=>!!H&&H.getMessages().length>0,jt=()=>{if(!Qw()||Zr()){Ot.parentNode&&Ot.remove(),Ot.style.display="none";return}Ot.parentNode!==ue&&ue.appendChild(Ot),os();let l=qn(re)>0&&bp()&&vp();l?yp():Sy(),Ot.style.display=l?"":"none"},Ai=()=>{Uo.pause()&&(Cy(),jt())},Lo=()=>{Uo.resume(),Sy(),jt()},Tr=(s=!1)=>{br()&&vp()&&Uo.isFollowing()&&(!s&&!Fo||(Ar!==null&&(cancelAnimationFrame(Ar),Ar=null),dd=!0,Ar=requestAnimationFrame(()=>{Ar=null,dd=!1,Uo.isFollowing()&&wA(xy(),s?220:140)})))},wy=(s,l,f,g=()=>!0)=>{let v=s.scrollTop,M=l(),N=M-v;if(pa(),Math.abs(N)<1){Po=!0,s.scrollTop=M,qo=s.scrollTop,Po=!1;return}let V=performance.now();Po=!0;let j=J=>1-Math.pow(1-J,3),K=J=>{if(!g()){pa();return}let ae=l();ae!==M&&(M=ae,N=M-v);let fe=J-V,Je=Math.min(fe/f,1),lt=j(Je),ct=v+N*lt;s.scrollTop=ct,qo=s.scrollTop,Je<1?ua=requestAnimationFrame(K):(s.scrollTop=M,qo=s.scrollTop,ua=null,Po=!1)};ua=requestAnimationFrame(K)},wA=(s,l=500)=>{let f=qn(s)-s.scrollTop;if(Math.abs(f)<1){qo=s.scrollTop;return}if(Math.abs(f)>=hA){pa(),Po=!0,s.scrollTop=qn(s),qo=s.scrollTop,Po=!1;return}wy(s,()=>qn(s),l,()=>Uo.isFollowing())},hd=()=>{if(!vp()){jt();return}let s=xy();Po=!0,s.scrollTop=qn(s),qo=s.scrollTop,Po=!1,jt()},bs=s=>{let l=0,f=s;for(;f&&f!==re;)l+=f.offsetTop,f=f.offsetParent;return l},AA=()=>{let s=re.getRootNode();return(typeof s.getSelection=="function"?s.getSelection():null)??re.ownerDocument.getSelection()},yd=()=>eS(AA(),re),xp=()=>{if(Yw()!=="last-user-turn")return!1;let s=H?.getMessages()??[];if(s.length<2)return!1;let l=[...s].reverse().find(M=>M.role==="user");if(!l)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l.id):l.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),g=re.querySelector(`[data-message-id="${f}"]`);if(!g)return!1;let v=Math.min(Math.max(0,bs(g)-pi()),qn(re));return Po=!0,re.scrollTop=v,qo=re.scrollTop,Po=!1,No()==="follow"&&!qs(re,Xn)&&Uo.pause(),jt(),!0},bd=s=>{let l=Math.max(0,Math.round(s));Qo.style.height=`${l}px`,Qo.style.display=l>0?"":"none",$t&&($t.spacerHeight=Math.max(0,s))},vd=s=>{let l=parseFloat(getComputedStyle(re).paddingBottom)||0,f=0;for(let v of Array.from(re.children)){if(v===Qo||v.offsetHeight===0)continue;let M=bs(v)+v.offsetHeight;M>f&&(f=M)}let g=re.scrollHeight-s;return f>0?Math.min(f+l,g):g},MA=()=>{if(!$t||$t.spacerHeight<=0)return;let s=vd($t.spacerHeight),l=Math.max(0,Math.round(re.scrollTop)+re.clientHeight-s+Xn);l<$t.spacerHeight&&(bd(l),jt())},hn=()=>{ms!==null&&(cancelAnimationFrame(ms),ms=null),pa(),$t=null,Qo.style.height="0px",Qo.style.display="none"},Ay=s=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Cp=s=>re.querySelector(`[data-message-id="${Ay(s)}"]`),My=s=>{ms!==null&&cancelAnimationFrame(ms),ms=requestAnimationFrame(()=>{ms=null;let l=Ay(s),f=re.querySelector(`[data-message-id="${l}"]`);if(!f)return;let g=bs(f),v=$t?.spacerHeight??0,M=vd(v),{targetScrollTop:N,spacerHeight:V}=ug({anchorOffsetTop:g,topOffset:pi(),viewportHeight:re.clientHeight,contentHeight:M,slack:Xn});$t={initialSpacerHeight:V,contentHeightAtAnchor:M,spacerHeight:V},bd(V),wy(re,()=>f.isConnected?Math.max(0,bs(f)-pi()):N,220)})},ko=()=>{if(No()!=="anchor-top"||!$t||!ca)return;let s=Cp(ca);if(!s)return;pa();let l=$t.spacerHeight,f=vd(l),{targetScrollTop:g,spacerHeight:v}=ug({anchorOffsetTop:bs(s),topOffset:pi(),viewportHeight:re.clientHeight,contentHeight:f,slack:Xn});$t={initialSpacerHeight:v,contentHeightAtAnchor:f,spacerHeight:v},bd(v),Po=!0,re.scrollTop=g,qo=re.scrollTop,Po=!1,jt()},TA=()=>{if(br()){if(!Uo.isFollowing()||qs(re,1))return;Tr(!Fo);return}if($t&&$t.initialSpacerHeight>0){let s=re.scrollHeight-$t.spacerHeight,l=tS({initialSpacerHeight:$t.initialSpacerHeight,contentHeightAtAnchor:$t.contentHeightAtAnchor,currentContentHeight:s});l!==$t.spacerHeight&&bd(l)}jt()},EA=s=>{let l=No();l==="follow"?(Lo(),Tr(!0)):l==="anchor-top"&&(Ci=!1,cd=!0,ud=!1,ca=s,My(s))},PA=()=>{if(No()==="anchor-top"){if(cd){Ci=!1;return}Ci=!0,hn(),Lo(),Tr(!0)}},LA=96,kA=s=>{if(gs===null)return!0;let l=Cp(gs),f=Cp(s);if(!l||!f)return!0;let g=bs(f)-bs(l);return pi()+g>re.clientHeight-LA},IA=s=>{if(No()!=="anchor-top"||!cd||ud||yd())return;let l=gs===null;for(let f of s){if(!l){f.id===gs&&(l=!0);continue}if(QC(f)){if(f.id===ca||!kA(f.id))return;ca=f.id,My(f.id);return}}},HA=s=>{let l=new Map;s.forEach(f=>{let g=gp.get(f.id);l.set(f.id,{streaming:f.streaming,role:f.role}),!g&&f.role==="assistant"&&(x.emit("assistant:message",f),!da&&(No()!=="anchor-top"||Sh())&&bp()&&(Mr+=1,yp(),jt(),Gl(Mr===1?"1 new message below.":`${Mr} new messages below.`))),f.role==="assistant"&&g?.streaming&&f.streaming===!1&&x.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(g?f.approval.status!=="pending"&&x.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):x.emit("approval:requested",{approval:f.approval,message:f}))}),gp.clear(),l.forEach((f,g)=>{gp.set(g,f)})},Mi=(s,l)=>{let f=l==="user"?"user":"assistant",g=n.layout?.messages?.[f],v=g?.width??"content",M=g?.maxWidth??(v==="full"?"100%":void 0);s.classList.add("persona-message-row"),s.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),s.classList.add(`persona-message-row-${l}`,`persona-message-width-${v}`),s.classList.toggle("persona-justify-end",l==="user"),s.setAttribute("data-message-role",l),s.setAttribute("data-message-width",v),M?s.style.setProperty("--persona-message-row-max-width",M):s.style.removeProperty("--persona-message-row-max-width")},Jn=(s,l)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${s}`,f.setAttribute("data-wrapper-id",s),Mi(f,l),f},RA=(s,l,f)=>{let g=document.createElement("div"),M=(()=>{let D=i.find(We=>We.renderLoadingIndicator);if(D?.renderLoadingIndicator)return D.renderLoadingIndicator;if(n.loadingIndicator?.render)return n.loadingIndicator.render})(),N=(D,We)=>We==null?!1:typeof We=="string"?(D.textContent=We,!0):(D.appendChild(We),!0),V=new Set,j=new Map,K=new Set,J=i.some(D=>D.renderAskUserQuestion),ae=[],fe=[],Je=n.enableComponentStreaming!==!1,lt=n.approval!==!1,ct=[],Qt=n.messageActions,Nt=Qt?.showRegenerate===!0&&Qt.enabled!==!1&&it.current?.isStreaming()!==!0?vx(l):null,kt=Qt?.showEdit===!0&&Qt.enabled!==!1,io=Qt?.showQuote===!0&&Qt.enabled!==!1,et=null,lo=n.features?.reasoningDisplay?.completedVisibility==="removed";if(l.forEach(D=>{if(lo&&D.variant==="reasoning"&&D.reasoning?.status==="complete")return;if(V.add(D.id),j.set(D.id,D.role),us===D.id&&wr){let He=Jn(D.id,D.role);He.setAttribute("data-persona-message-edit-stub","true"),He.setAttribute("data-preserve-runtime","true"),g.appendChild(He),et={messageId:D.id,element:wr.element};return}let We=J&&lr(D),Oe=lt&&D.variant==="approval"&&!!D.approval,me=!We&&D.role==="assistant"&&!D.variant&&Je&&$l(D);!Oe&&Sr.has(D.id)&&(s.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),Sr.delete(D.id)),!me&&cs.has(D.id)&&(s.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),cs.delete(D.id));let pt=lr(D)?`:${D.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${D.agentMetadata?.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",zt={canRegenerate:Nt===D.id,canEdit:kt&&Kf(D),canQuote:io&&!D.variant&&(D.content?.trim().length??0)>0},co=`${zt.canRegenerate?"r":""}${zt.canEdit?"e":""}${zt.canQuote?"q":""}`,uo=zC(D,fs)+pt+`:${co}`,It=We||Oe||me?null:KC(Dt,D.id,uo);if(It){g.appendChild(It.cloneNode(!0)),lr(D)&&D.toolCall?.id&&D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(K.add(D.toolCall.id),Ha(D,n,_e.composerOverlay));return}let Ee=null,Vt=i.find(He=>!!(D.variant==="reasoning"&&He.renderReasoning||D.variant==="tool"&&He.renderToolCall||!D.variant&&He.renderMessage)),Kt=n.layout?.messages;if(lr(D)&&D.agentMetadata?.askUserQuestionAnswered===!0){la.delete(D.id),s.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime");return}if(Bs(D)&&$r(n).enabled)return;if(lr(D)&&n.features?.askUserQuestion?.enabled!==!1){let He=i.find(xt=>typeof xt.renderAskUserQuestion=="function");if(He&&it.current){let xt=la.get(D.id),Bn=xt!==uo,yn=null;if(Bn){let{payload:Ne,complete:ft}=dr(D),Wr=D.id,Gt=()=>it.current?.getMessages().find(zo=>zo.id===Wr);yn=He.renderAskUserQuestion({message:D,payload:Ne,complete:ft,resolve:zo=>{let Hs=Gt();Hs&&it.current?.resolveAskUserQuestion(Hs,zo)},dismiss:()=>{let zo=Gt();zo?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved(zo),it.current?.resolveAskUserQuestion(zo,"(dismissed)"))},config:n})}let Be=xt!=null;if(Bn&&yn===null&&!Be){D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(K.add(D.toolCall.id),Ha(D,n,_e.composerOverlay));return}let ve=Jn(D.id,D.role);ve.setAttribute("data-ask-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),g.appendChild(ve),ae.push({messageId:D.id,fingerprint:uo,bubble:yn});return}else{D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(K.add(D.toolCall.id),Ha(D,n,_e.composerOverlay));return}}else if(Oe){let He=k();if(!He){g.appendChild(Jn(D.id,D.role));return}let xt=i.find(ve=>typeof ve.renderApproval=="function")??y,yn=Sr.get(D.id)!==uo,Be=null;if(yn&&xt?.renderApproval){let ve=D.id,Ne=(ft,Wr)=>{let Gt=it.current?.getMessages().find(zo=>zo.id===ve);Gt?.approval&&(Gt.approval.toolType==="webmcp"?it.current?.resolveWebMcpApproval(Gt.id,ft):it.current?.resolveApproval(Gt.approval,ft,Wr))};Be=xt.renderApproval({message:D,defaultRenderer:()=>He.createApprovalBubble(D,n),config:n,approve:ft=>Ne("approved",ft),deny:ft=>Ne("denied",ft)})}if(yn&&Be===null)s.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),Sr.delete(D.id),Ee=He.createApprovalBubble(D,n);else{let ve=Jn(D.id,D.role);ve.setAttribute("data-approval-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),g.appendChild(ve),ct.push({messageId:D.id,fingerprint:uo,bubble:Be});return}}else if(Vt)if(D.variant==="reasoning"&&D.reasoning&&Vt.renderReasoning){if(!Xo)return;Ee=Vt.renderReasoning({message:D,defaultRenderer:()=>Ug(D,n),config:n})}else if(D.variant==="tool"&&D.toolCall&&Vt.renderToolCall){if(!jn)return;Ee=Vt.renderToolCall({message:D,defaultRenderer:()=>$g(D,n),config:n})}else Vt.renderMessage&&(Ee=Vt.renderMessage({message:D,defaultRenderer:()=>{let He=Ya(D,f,Kt,n.messageActions,Bo,{loadingIndicatorRenderer:M,widgetConfig:n,actionEligibility:zt});return D.role!=="user"&&w(He,D,n,H),He},config:n}));if(!Ee&&me){let He=Nu(D);if(He){let xt=cs.get(D.id),Bn=xt!==uo,yn=n.wrapComponentDirectiveInBubble!==!1&&Cn.getOptions(He.component)?.bubbleChrome!==!1,Be=null;if(Bn){let ve=_u(He,{config:n,message:D,transform:f});if(ve&&He.component==="PersonaArtifactInline"){let Ne=ve.hasAttribute("data-artifact-inline")?ve:ve.querySelector("[data-artifact-inline]"),ft=Ne?.getAttribute("data-artifact-inline")??"",Wr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(ft):ft,Gt=ft?s.querySelector(`#wrapper-${D.id}`)?.querySelector(`[data-artifact-inline="${Wr}"]`)??null:null;Ne&&Gt&&Gt!==Ne&&fr()?.hasLiveInlineArtifactBlock(Gt)&&(Ne===ve?ve=Gt:Ne.replaceWith(Gt))}if(ve)if(yn){let Ne=document.createElement("div");if(Ne.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ne.id=`bubble-${D.id}`,Ne.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let ft=document.createElement("div");ft.className="persona-mb-3 persona-text-sm persona-leading-relaxed",ft.innerHTML=f({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Ne.appendChild(ft)}Ne.appendChild(ve),Be=Ne}else{let Ne=document.createElement("div");if(Ne.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ne.id=`bubble-${D.id}`,Ne.setAttribute("data-message-id",D.id),Ne.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let ft=document.createElement("div");ft.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",ft.innerHTML=f({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Ne.appendChild(ft)}Ne.appendChild(ve),Be=Ne}}if(Be||xt!=null){let ve=Jn(D.id,D.role);ve.setAttribute("data-component-directive-stub","true"),ve.setAttribute("data-preserve-runtime","true"),g.appendChild(ve),fe.push({messageId:D.id,fingerprint:uo,bubble:Be});return}}}if(!Ee)if(D.variant==="reasoning"&&D.reasoning){if(!Xo)return;Ee=Ug(D,n)}else if(D.variant==="tool"&&D.toolCall){if(!jn)return;Ee=$g(D,n)}else if(D.variant==="approval"&&D.approval){if(n.approval===!1)return;let He=k();if(!He)return;Ee=He.createApprovalBubble(D,n)}else{let He=n.layout?.messages;He?.renderUserMessage&&D.role==="user"?Ee=He.renderUserMessage({message:D,config:n,streaming:!!D.streaming}):He?.renderAssistantMessage&&D.role==="assistant"?Ee=He.renderAssistantMessage({message:D,config:n,streaming:!!D.streaming}):Ee=Ya(D,f,He,n.messageActions,Bo,{loadingIndicatorRenderer:M,widgetConfig:n,actionEligibility:zt}),D.role!=="user"&&Ee&&w(Ee,D,n,H)}let rn=Jn(D.id,D.role);rn.appendChild(Ee),GC(Dt,D.id,uo,rn),g.appendChild(rn)}),_e.composerOverlay&&_e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(We=>{let Oe=We.getAttribute("data-persona-ask-sheet-for");Oe&&!K.has(Oe)&&Ur(_e.composerOverlay,Oe)}),n.features?.toolCallDisplay?.grouped){let D=[],We=[],Oe=n.features.toolCallDisplay.groupedMode==="summary";l.forEach(me=>{if(me.variant==="tool"&&me.toolCall&&jn){We.push(me);return}me.variant==="reasoning"&&(!Xo||lo&&me.reasoning?.status==="complete")||((We.length>1||Oe&&We.length>0)&&D.push(We),We=[])}),(We.length>1||Oe&&We.length>0)&&D.push(We),D.forEach(me=>{let pt=me.map(Kt=>Array.from(g.children).find(rn=>rn instanceof HTMLElement&&rn.getAttribute("data-wrapper-id")===Kt.id)).filter(Kt=>!!Kt);if(pt.length<(Oe?1:2))return;let zt=Jn(`tool-group-${me[0].id}`,"assistant");zt.setAttribute("data-persona-tool-group-row","true");let co=document.createElement("div");co.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",co.setAttribute("data-persona-tool-group","true");let uo=document.createElement("div");uo.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",uo.id=`tool-group-summary-${me[0].id}`;let It=`Called ${me.length} ${me.length===1?"tool":"tools"}`,Ee=n.toolCall?.renderGroupedSummary?.({messages:me,toolCalls:me.map(Kt=>Kt.toolCall).filter(Kt=>!!Kt),defaultSummary:It,config:n});N(uo,Ee)||(uo.textContent=It);let Vt=document.createElement("div");Vt.className="persona-tool-group-stack persona-flex persona-flex-col",Vt.id=`tool-group-stack-${me[0].id}`,Vt.setAttribute("data-persona-tool-group-stack","true"),co.appendChild(uo),Oe||co.appendChild(Vt),zt.appendChild(co),pt[0].before(zt),pt.forEach((Kt,rn)=>{if(Oe){Kt.remove();return}Kt.style.setProperty("--persona-message-row-max-width","100%");let He=document.createElement("div");He.className="persona-tool-group-item persona-relative",He.setAttribute("data-persona-tool-group-item","true"),rn<pt.length-1&&He.setAttribute("data-persona-tool-group-connector","true"),He.appendChild(Kt),Vt.appendChild(He)})})}XC(Dt,V);let ar=l.some(D=>D.role==="assistant"&&D.streaming),Rn=l[l.length-1],Wn=Rn?.role==="assistant"&&!Rn.streaming&&Rn.variant!=="approval";if(Fo&&l.some(D=>D.role==="user")&&!ar&&!Wn){let D={config:n,streaming:!0,location:"standalone",defaultRenderer:Gs},We=i.find(me=>me.renderLoadingIndicator),Oe=null;if(We?.renderLoadingIndicator&&(Oe=We.renderLoadingIndicator(D)),Oe===null&&n.loadingIndicator?.render&&(Oe=n.loadingIndicator.render(D)),Oe===null&&(Oe=Gs()),Oe){let me=document.createElement("div"),pt=n.loadingIndicator?.showBubble!==!1,zt=n.layout?.messages?.layout??"bubble";me.className=pt?Ol("assistant",zt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),me.setAttribute("data-typing-indicator","true"),pt&&(me.style.color="var(--persona-message-assistant-text, var(--persona-text))",zt!=="flat"&&(me.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),me.appendChild(Oe);let co=Jn("typing-indicator","assistant");co.appendChild(me),g.appendChild(co)}}if(!Fo&&l.length>0){let D=l[l.length-1],We={config:n,lastMessage:D,messageCount:l.length},Oe=i.find(pt=>pt.renderIdleIndicator),me=null;if(Oe?.renderIdleIndicator&&(me=Oe.renderIdleIndicator(We)),me===null&&n.loadingIndicator?.renderIdle&&(me=n.loadingIndicator.renderIdle(We)),me){let pt=document.createElement("div"),zt=n.loadingIndicator?.showBubble!==!1;pt.className=zt?["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(" "),pt.setAttribute("data-idle-indicator","true"),pt.appendChild(me);let co=Jn("idle-indicator","assistant");co.appendChild(pt),g.appendChild(co)}}if(yv(g),pu(s,g),Pf(s),et){let{messageId:D,element:We}=et,Oe=s.querySelector(`#wrapper-${D}`);Oe&&We.parentElement!==Oe&&(Mi(Oe,j.get(D)??"user"),Oe.replaceChildren(We))}if(ae.length>0)for(let{messageId:D,fingerprint:We,bubble:Oe}of ae){let me=s.querySelector(`#wrapper-${D}`);me&&(Mi(me,j.get(D)??"assistant"),Oe!==null&&(me.replaceChildren(Oe),me.setAttribute("data-bubble-fp",We),la.set(D,We)))}if(la.size>0)for(let D of la.keys())V.has(D)||la.delete(D);if(fe.length>0)for(let{messageId:D,fingerprint:We,bubble:Oe}of fe){let me=s.querySelector(`#wrapper-${D}`);me&&(Mi(me,j.get(D)??"assistant"),Oe!==null&&(me.replaceChildren(Oe),me.setAttribute("data-bubble-fp",We),cs.set(D,We)))}if(cs.size>0)for(let D of cs.keys())V.has(D)||cs.delete(D);if(ct.length>0)for(let{messageId:D,fingerprint:We,bubble:Oe}of ct){let me=s.querySelector(`#wrapper-${D}`);me&&(Mi(me,j.get(D)??"assistant"),Oe!==null&&(me.replaceChildren(Oe),me.setAttribute("data-bubble-fp",We),Sr.set(D,We)))}if(Sr.size>0)for(let D of Sr.keys())V.has(D)||Sr.delete(D)},Sp=!1,xd=()=>{Sp||(Sp=!0,ic().catch(()=>{Sp=!1}))},Jo=(s,l,f)=>{l.length>0&&xd(),RA(s,l,f),zh()},Ti=null,WA=()=>{if(Ti)return;let s=f=>{let g=f.composedPath();g.includes(Xe)||Xt&&g.includes(Xt)||dt(!1,"user")};Ti=s,(e.ownerDocument??document).addEventListener("pointerdown",s,!0)},Ty=()=>{if(!Ti)return;(e.ownerDocument??document).removeEventListener("pointerdown",Ti,!0),Ti=null};be.push(()=>Ty());let Ei=null,BA=()=>{if(Ei)return;let s=f=>{f.key==="Escape"&&(f.isComposing||dt(!1,"user"))};Ei=s,(e.ownerDocument??document).addEventListener("keydown",s,!0)},Ey=()=>{if(!Ei)return;(e.ownerDocument??document).removeEventListener("keydown",Ei,!0),Ei=null};be.push(()=>Ey());let Pi=!1,Py=new Set,OA=()=>{let s=n.launcher?.composerBar?.peek?.streamAnimation;return s||n.features?.streamAnimation},fa=()=>{if(!Ae())return;let s=_e.peekBanner,l=_e.peekTextNode;if(!s||!l)return;if(he){s.classList.remove("persona-pill-peek--visible");return}let f=H?.getMessages()??[],g;for(let Nt=f.length-1;Nt>=0;Nt--){let kt=f[Nt];if(kt.role==="assistant"&&kt.content){g=kt;break}}if(!g){s.classList.remove("persona-pill-peek--visible");return}let v=g.content,M=!!g.streaming,N=OA(),V=fu(N),j=V.type!=="none"?pp(V.type,N?.plugins):null,K=j?.isAnimating?.(g)===!0,J=j!==null&&(M||K);J&&j&&!Py.has(j.name)&&(Hl(j,e),Py.add(j.name));let ae=J&&j?.containerClass?j.containerClass:null,fe=l.dataset.personaPeekStreamClass??null;fe&&fe!==ae&&(l.classList.remove(fe),delete l.dataset.personaPeekStreamClass),ae&&fe!==ae&&(l.classList.add(ae),l.dataset.personaPeekStreamClass=ae),J?(l.style.setProperty("--persona-stream-step",`${V.speed}ms`),l.style.setProperty("--persona-stream-duration",`${V.duration}ms`)):(l.style.removeProperty("--persona-stream-step"),l.style.removeProperty("--persona-stream-duration"));let Je=J?mu(v,V.buffer,j,g,M):v;if(J&&V.placeholder==="skeleton"&&M&&(!Je||!Je.trim())){let Nt=document.createElement("div"),kt=Il();kt.classList.add("persona-pill-peek__skeleton"),Nt.appendChild(kt),pu(l,Nt)}else{let Nt=Math.max(0,Je.length-100),kt=Je.length>100?Je.slice(-100):Je,io=ir(kt);if(!J||!j){let et=Je.length>100?`\u2026${kt}`:kt;l.textContent!==et&&(l.textContent=et)}else{let et=io;(j.wrap==="char"||j.wrap==="word")&&(et=kl(io,j.wrap,`peek-${g.id}`,{skipTags:j.skipTags,startIndex:Nt}));let lo=document.createElement("div");if(lo.innerHTML=et,j.useCaret&&kt.length>0){let ar=gu(),Rn=lo.querySelectorAll(".persona-stream-char, .persona-stream-word"),Wn=Rn[Rn.length-1];Wn?.parentNode?Wn.parentNode.insertBefore(ar,Wn.nextSibling):lo.appendChild(ar)}pu(l,lo),j.onAfterRender?.({container:l,bubble:s,messageId:g.id,message:g,speed:V.speed,duration:V.duration})}}let Qt=Fo||Pi;s.classList.toggle("persona-pill-peek--visible",Qt)};if(Ae()){let s=_e.peekBanner;if(s){let g=v=>{v.preventDefault(),v.stopPropagation(),dt(!0,"user")};s.addEventListener("pointerdown",g),be.push(()=>{s.removeEventListener("pointerdown",g)})}let l=()=>{Pi||(Pi=!0,fa())},f=()=>{Pi&&(Pi=!1,fa())};we.addEventListener("pointerenter",l),we.addEventListener("pointerleave",f),be.push(()=>{we.removeEventListener("pointerenter",l),we.removeEventListener("pointerleave",f)}),Xt&&(Xt.addEventListener("pointerenter",l),Xt.addEventListener("pointerleave",f),be.push(()=>{Xt.removeEventListener("pointerenter",l),Xt.removeEventListener("pointerleave",f)}))}let DA=s=>{let l=n.launcher?.composerBar??{},f=l.expandedSize??"anchored",g=l.bottomOffset??"16px",v=l.collapsedMaxWidth,M=l.expandedMaxWidth??"880px",N=l.expandedTopOffset??"5vh",V=l.modalMaxWidth??"880px",j=l.modalMaxHeight??"min(90vh, 800px)",K="calc(100vw - 32px)",J="var(--persona-pill-area-height, 80px)",ae=Xe.style;if(ae.left="",ae.right="",ae.top="",ae.bottom="",ae.transform="",ae.width="",ae.maxWidth="",ae.height="",ae.maxHeight="",Xt){let fe=Xt.style;fe.bottom=g,fe.width=v??""}if(s&&f!=="fullscreen"){if(f==="modal"){ae.top="50%",ae.left="50%",ae.transform="translate(-50%, -50%)",ae.bottom="auto",ae.right="auto",ae.width=V,ae.maxWidth=K,ae.maxHeight=j,ae.height=j;return}ae.left="50%",ae.transform="translateX(-50%)",ae.bottom=`calc(${g} + ${J})`,ae.top=N,ae.width=M,ae.maxWidth=K}},Li=()=>{if(he&&xd(),!De())return;if(Ae()){let K=(n.launcher?.composerBar??{}).expandedSize??"anchored",J=he?"expanded":"collapsed";Xe.dataset.state=J,Xe.dataset.expandedSize=K,Xt&&(Xt.dataset.state=J,Xt.dataset.expandedSize=K),Xe.style.removeProperty("display"),Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),DA(he),ue.style.display=he?"flex":"none",rs(),he?(WA(),BA()):(Ty(),Ey()),fa();return}let s=St(n),l=e.ownerDocument.defaultView??window,f=n.launcher?.mobileBreakpoint??640,g=n.launcher?.mobileFullscreen??!0,v=l.innerWidth<=f,M=g&&v&&ge,N=Wo(n).reveal;he?(Xe.style.removeProperty("display"),Xe.style.display=s?"flex":"",Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0"),we.classList.add("persona-scale-100","persona-opacity-100"),Pt?(Pt.setPanelOpen(!0),Pt.element.style.display="none"):go&&(go.style.display="none")):(s?s&&(N==="overlay"||N==="push")&&!M?(Xe.style.removeProperty("display"),Xe.style.display="flex",Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Xe.style.setProperty("display","none","important"),Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Xe.style.display="",Xe.classList.add("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100"),we.classList.add("persona-scale-95","persona-opacity-0")),Pt?(Pt.setPanelOpen(!1),Pt.element.style.display=s?"none":""):go&&(go.style.display=s?"none":""))},dt=(s,l="user")=>{if(!De()||he===s)return;let f=he;he=s,Li();let g=(()=>{let M=n.launcher?.sidebarMode??!1,N=e.ownerDocument.defaultView??window,V=n.launcher?.mobileFullscreen??!0,j=n.launcher?.mobileBreakpoint??640,K=N.innerWidth<=j,J=St(n)&&V&&K,ae=Ae()&&(n.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return M||V&&K&&ge||J||ae})();if(he&&g){if(!Pn){let M=e.getRootNode(),N=M instanceof ShadowRoot?M.host:e.closest(".persona-host");N&&(Pn=hg(N,n.launcher?.zIndex??so))}Ln||(Ln=yg(e.ownerDocument))}else he||(Pn?.(),Pn=null,Ln?.(),Ln=null);he&&(Ki(),xp()||(No()==="follow"?Tr(!0):hd()));let v={open:he,source:l,timestamp:Date.now()};he&&!f?x.emit("widget:opened",v):!he&&f&&x.emit("widget:closed",v),x.emit("widget:state",{open:he,launcherEnabled:ge,voiceActive:ze.active,streaming:H.isStreaming()})},Er={inputDisabled:!1,sendDisabled:!1},Pr=()=>Er.inputDisabled,vs=()=>Er.inputDisabled||Er.sendDisabled,_A=()=>(Er.inputDisabled?Er.inputReason:void 0)??(Er.sendDisabled?Er.sendReason:void 0);function wp(){if(!Me)return;if(Ce.getState().phase==="streaming"){Me.disabled=!1;return}let s=Ze?!Ze.isReady():!1;Me.disabled=vs()||s}function Cd(){if(!wn)return;let s=Ce.getState(),l=n.sendButton?.visibility==="when-text"&&s.phase!=="streaming"&&s.text.trim().length===0&&s.attachments.length===0;wn.toggleAttribute("data-persona-send-hidden",l)}function NA(){let s=_A();if(Ae()){let l=un??Ie;s?l.setAttribute("title",s):l.removeAttribute("title"),Ie.toggleAttribute(ii,!!s);return}if(s){st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.setAttribute(ii,""),st.textContent=s;return}if(st.hasAttribute(ii)&&(st.removeAttribute("role"),st.removeAttribute("aria-live"),st.removeAttribute(ii),c)){let l=H.getStatus();ao(st,fo(l),n.statusIndicator??{},l)}}function Ap(){let s=jm(n.composer?.inputDisabled),l=jm(n.composer?.sendDisabled);Er={inputDisabled:s.disabled,inputReason:s.reason,sendDisabled:l.disabled,sendReason:l.reason},Ce.setInputDisabled(s.disabled),Ce.setSendDisabled(l.disabled);let f=Ce.getState().phase==="streaming",g=s.disabled,v=f||g;le&&(le instanceof HTMLTextAreaElement?le.disabled=g:le.setAttribute("contenteditable",g?"false":"true"),le.setAttribute("aria-disabled",g?"true":"false")),At&&(At.disabled=g),yt&&(yt.disabled=g);for(let M of Wt?.affordanceButtons??[])M.querySelectorAll("button").forEach(N=>{N.disabled=g});se&&(se.disabled=v),is.forEach(M=>{M.elements.forEach(N=>{N.toggleAttribute("data-disabled",v),N instanceof HTMLButtonElement||N.setAttribute("aria-disabled",v?"true":"false")}),M.buttons.forEach(N=>{N.disabled=v})}),Lp.forEach(M=>{M.toggleAttribute("data-disabled",v),M instanceof HTMLButtonElement?M.disabled=v:M.setAttribute("aria-disabled",v?"true":"false"),M.querySelectorAll("button").forEach(N=>{N.disabled=v})}),Ie.dataset.personaComposerStreaming=f?"true":"false",Ie.dataset.personaComposerInputDisabled=g?"true":"false",Ie.dataset.personaComposerSendDisabled=vs()?"true":"false",Ie.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(M=>{(M instanceof HTMLButtonElement||M instanceof HTMLInputElement||M instanceof HTMLTextAreaElement||M instanceof HTMLSelectElement)&&(M.disabled=f)}),wp(),NA()}let ki=s=>{Ce.setStreaming(s),xh(s?"stop":"send"),Ap()},xs=()=>{ze.active||le&&le.focus()};x.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>xs(),200)});let Cs=null,Ii=!1,Mp=!Mo.hidden,Lr=null,Tp=!G,Sd=null;be.push(()=>{Sd?.cancel(),Sd=null});let FA=s=>{let l=ES(s);if(l===Xl)return;Xl=l,e.setAttribute("data-persona-conversation-state",l);let f=Qu();Yl(),Tp&&(Sd?.cancel(),Sd=MS(Ie,l==="active"?f:Qu(),l==="active"?"drop":"rise")),ko()},Ly=null,ky,Iy=null,ma=null,Ep=!1,Hi=s=>{let l=xn(n),f=`${l.variant}|${l.dismiss}|${l.anchor??"bottom"}|${l.align??""}|${l.iconPlacement}|${l.kicker??""}|${l.title}|${l.subtitle}`;(f!==Ly||l.icon!==ky)&&(Ly=f,ky=l.icon,Su({host:Mo,iconHolder:$w,kicker:jw,title:zw,subtitle:Vw,starterSuggestions:Vu},l));let g=l.message===void 0?null:`${n.layout?.messages?.layout??"bubble"}|${l.message}`;g!==Iy&&(Iy=g,wu(Do,l.message,n));let v=s??(H?H.getMessages():n.initialMessages);FA(v);let M=Ii,N=!M&&Qr(l,v),V=N!==Mp;if(Mp=N,ma){Lr?.cancel(),Lr=null,M!==Ep&&(Ep=M,M?Rg(re,Mo,null):Hg(re,Mo,ma)),Ja(re,Mo,!M);return}if(V&&!N&&!M&&l.dismiss==="on-first-message"&&Tp){Lr=AS(Mo,K=>{Lr===K&&(Lr=null),!Mp&&!ma&&(Ja(re,Mo,!1),ko()),K?.cancel()});return}if(Lr){if(!N&&!M)return;Lr.cancel(),Lr=null}let j=!Mo.hidden;Ja(re,Mo,N),!N&&j&&ko()},Pp=[],Lp=[],kp=!1,Hy=null,Ry,Wy=()=>{Lp.length=0;let s=Pp.splice(0,Pp.length);for(let l of s)try{l()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};be.push(Wy);let UA=(s,l)=>{let f=vg(s,l);if(!f)return n.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),I("span");let g=n.suggestions?.starters,v=xg({item:{...f,behavior:f.behavior??g?.behavior??"send"},index:l,surface:"starter",source:"config",variant:g?.variant??"card",streaming:c?H.isStreaming():!1,config:n,plugins:i,chipsConfig:n.suggestionChipsConfig,session:H,getTextarea:()=>le,eventTarget:Mo,submitPrompt:Xd});return Lp.push(v),v},Ip=()=>{if(kp)return;kp=!0;let s=xn(n);Hy=`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`,Ry=s.icon;try{Wy(),Rg(re,Mo,ma),ma=null,Ep=!1;let l=H?H.getMessages():n.initialMessages,f=Qr(s,l),g=0,v=null;for(let M of i)if(M.renderWelcome&&(v=M.renderWelcome({config:s,variant:s.variant,visible:f,defaultRenderer:()=>Mo,sendMessage:N=>{if(!H||H.isStreaming())return;let V=N.trim();V&&H.sendMessage(V)},requestRender:()=>Ip(),renderStarter:N=>UA(N,g++),storage:p(M.id),onCleanup:N=>{Pp.push(N)}}),v))break;v&&v!==Mo&&(ma=v,Hg(re,Mo,v))}finally{kp=!1}Hi()},qA=()=>{let s=xn(n);`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`===Hy&&s.icon===Ry||Ip()},wd=()=>{Hi(),na||(le.placeholder=cC(Ce.getState().activeModeIds,n.composer?.modes)??n.copy?.inputPlaceholder??"How can I help...",!(n.sendButton?.useIcon??!1)&&!H?.isStreaming()&&(Me.textContent=n.copy?.sendButtonLabel??"Send")),le.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',le.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},$A=!!n.setStoredConversationId,Ri=s=>de(l=>{let f={...l};return delete f[s],f}),Ad=s=>{let l=X[s];return typeof l=="string"?l:null};n.clientToken&&(n={...n,getStoredSessionId:()=>Ad("sessionId"),setStoredSessionId:s=>{de(l=>({...l,sessionId:s}))},clearStoredSessionId:n.clearStoredSessionId??(()=>Ri("sessionId")),getStoredConversationId:n.getStoredConversationId??(()=>Ad("conversationId")),setStoredConversationId:n.setStoredConversationId??(s=>{de(l=>({...l,conversationId:s}))}),clearStoredConversationId:n.clearStoredConversationId??(()=>Ri("conversationId"))});let By=()=>n.features?.history?.enabled===!0?n.clientToken??null:null,Oy=s=>dw(s,Sn(),n.persistState===!1),Dy=By(),Zn=Dy?Oy(Dy):null,Ss={...Zn?{visitorStore:Zn}:{},historyBootstrapReady:_,getStoredMessageCursor:()=>Ad("historyMessageCursor"),setStoredMessageCursor:s=>{if(s===null){Ri("historyMessageCursor");return}de(l=>({...l,historyMessageCursor:s}))},getPendingDisplayProjections:()=>{let s=X.pendingDisplayProjections;if(!s||typeof s!="object")return null;let l=s;return typeof l.conversationId!="string"||!Array.isArray(l.messageIds)?null:{conversationId:l.conversationId,messageIds:l.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:s=>{if(!s){Ri("pendingDisplayProjections");return}de(l=>({...l,pendingDisplayProjections:s}))},...$A?{}:{getStoredConversationRevision:()=>Ad("conversationRevision"),setStoredConversationRevision:s=>{if(s===null){Ri("conversationRevision");return}de(l=>({...l,conversationRevision:s}))}}},jA=()=>{let s=By();if(s&&Zn?.matches(s,Sn(),n.persistState===!1)||!s&&!Zn)return;Zn?.destroy(),Zn=s?Oy(s):null;let l={...Ss};Zn?l.visitorStore=Zn:delete l.visitorStore,Ss=l,H.setHistoryInternals(Ss)},ws=null,zA=()=>{ws==null&&(ws=setInterval(()=>{let s=Le.querySelectorAll("[data-tool-elapsed]");if(s.length===0){clearInterval(ws),ws=null;return}let l=Date.now();s.forEach(f=>{let g=Number(f.getAttribute("data-tool-elapsed"));g&&(f.textContent=xc(l-g))})},100))},Hp=(s,l)=>{if(Object.is(s,l))return!0;if(s===null||l===null||typeof s!="object"||typeof l!="object")return!1;if(Array.isArray(s)||Array.isArray(l))return!Array.isArray(s)||!Array.isArray(l)||s.length!==l.length?!1:s.every((N,V)=>Hp(N,l[V]));let f=s,g=l,v=Object.keys(f),M=Object.keys(g);return v.length===M.length&&v.every(N=>Object.prototype.hasOwnProperty.call(g,N)&&Hp(f[N],g[N]))},_y=s=>{let{content:l,rawContent:f,llmContent:g,...v}=s;return v},Rp=s=>s.role==="assistant"&&s.streaming===!0&&!s.variant&&!s.toolCall&&!s.tools&&!s.approval&&!s.reasoning&&!s.contentParts&&!s.stopReason&&!$l(s),VA=(s,l,f)=>{if(s.length!==l.length)return!1;let g=s[f.index],v=l[f.index];return!g||!v||g.id!==f.id||v.id!==f.id?!1:(!Object.is(g.content,v.content)||!Object.is(g.rawContent,v.rawContent)||!Object.is(g.llmContent,v.llmContent))&&Rp(g)&&Rp(v)&&Hp(_y(g),_y(v))},Wp=null,ga=null,As=null,er=null,Md=s=>{Wp=s;let l,f;ga=null;for(let v=s.length-1;v>=0;v-=1){let M=s[v];if(!l&&M.role==="user"&&(l=M),!f&&M.role==="assistant"&&(f=M),!ga&&Rp(M)&&(ga={index:v,id:M.id}),l&&f&&ga)break}Jo(Le,s,oo),fr()?.updateInlineArtifactBlocks(Le,Yo.artifacts,{suppressTransition:Fo}),zA(),Hi(s),ia(s),Tr(!Fo),HA(s),s.length===0&&(hn(),Ci=!0,cd=!1,ca=null,ud=!1),!fp||da?(fp=!0,gs=l?.id??null,mp=f?.id??null):l&&l.id!==gs?(gs=l.id,EA(l.id)):f&&f.id!==mp&&PA(),f&&(mp=f.id),IA(s);let g=ze.lastUserMessageId;l&&l.id!==g&&(ze.lastUserMessageId=l.id,x.emit("user:message",l)),ze.lastUserMessageWasVoice=!!l?.viaVoice,Si(s),fa()},Bp=()=>{er!==null&&(cancelAnimationFrame(er),er=null);let s=As;As=null,s&&Md(s)},Ny=()=>{er!==null&&cancelAnimationFrame(er),er=null,As=null},KA=s=>{let l=As??Wp;if(Fo&&l&&ga&&VA(l,s,ga)){As=s,er===null&&(er=requestAnimationFrame(()=>{er=null;let f=As;As=null,f&&Md(f)}));return}if(s.length===0){Ny(),Md(s);return}Bp(),Md(s)};H=new Da(n,{onMessagesChanged(s){KA(s)},onStatusChanged(s){let l=n.statusIndicator??{};ao(st,(g=>g==="idle"?l.idleText??Ut.idle:g==="connecting"?l.connectingText??Ut.connecting:g==="connected"?l.connectedText??Ut.connected:g==="error"?l.errorText??Ut.error:g==="paused"?l.pausedText??Ut.paused:g==="resuming"?l.resumingText??Ut.resuming:Ut[g])(s),l,s),wt()},onStreamingChanged(s){s||(H?.getMessages().length===0?Ny():Bp()),Fo=s,ki(s),wt(),H&&Jo(Le,H.getMessages(),oo),s||(Tr(!0),MA(),py=!0,H&&fy(H.getMessages(),$r(n))),jt(),Gl(s?"Responding\u2026":"Response complete."),fa()},onVoiceStatusChanged(s){if(x.emit("voice:status",{status:s,timestamp:Date.now()}),n.voiceRecognition?.provider?.type==="runtype")switch(s){case"listening":sr(),Ta();break;case"processing":sr(),XM();break;case"speaking":sr(),QM();break;default:s==="idle"&&H.isBargeInActive()?(sr(),Ta(),se?.setAttribute("aria-label","End voice session")):(ze.active=!1,sr(),Yn("system"),gn());break}},onArtifactsState(s){Yo=s,s.artifacts.length===0&&(ra=!1),fr()?.updateInlineArtifactBlocks(Le,s.artifacts,{suppressTransition:Fo}),mn(),Si()},onHistoryStateChanged(s){$e(s)},onHistoryNotice(s){Rt(s)},onReconnect(s){let{executionId:l,lastEventId:f}=s.handle;s.phase==="paused"?x.emit("stream:paused",{executionId:l,after:f}):s.phase==="resuming"?x.emit("stream:resuming",{executionId:l,after:f,attempt:s.attempt??1}):x.emit("stream:resumed",{executionId:l,after:f})}},Ss),it.current=H,be.push(()=>H.cancel()),be.push(()=>{H.destroy(),Zn?.destroy()});let Op=null;if(H.onReadAloudChange((s,l)=>{$h=s,jh=l,zh();let f=s??Op;s&&(Op=s);let g=f?H.getMessages().find(v=>v.id===f)??null:null;x.emit("message:read-aloud",{messageId:f,message:g,state:l,timestamp:Date.now()}),l==="idle"&&(Op=null)}),c=!0,fp=!0,n.voiceRecognition?.provider?.type==="runtype")try{H.setupVoice()}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",s)}let GA=720,XA=250,Ye=sh(n.features?.history?.copy),$o=null,Dp=!1,at=null,Td=null,Ed="conversation",_p=null,mo=null,kn=null,Pd=H.getHistoryState(),Np=null,Wi=0,Fp=null,Ld=null,kd=null,Up=`persona-history-${Math.random().toString(36).slice(2,8)}`,qp=()=>n.features?.history?.enabled===!0,In=()=>qp()&&!!$o&&!Dp,Fy=()=>{let s=H.getStatus();return Fo||s==="paused"||s==="resuming"},$p=()=>{let s=n.features?.history?.scope;if(s)return s;let l=n.getIdentityProof?"verified-user":"browser",f=$o?.capabilities.scopes;return!f||f.includes(l)?l:f[0]??l},ha=()=>Td?.scope??$p(),Uy=()=>H.getClientSession()?.targetId??null,qy=s=>`${s.state}:${"reason"in s?s.reason:""}`,QA=s=>{let l=qy(s);l!==Np&&(Np=l,x.emit("history:identityStatusChanged",{status:s,timestamp:Date.now()}))},Id=s=>{s&&(zn.textContent="",zn.textContent=s)},$y=null,jy=null,YA=()=>{if(!qp())return null;let s=mw();if(s)return s();let l=n.features?.history?.provider;return l?typeof l!="function"?l:($y!==l&&($y=l,jy=l()),jy):H.isClientTokenMode()?gw({client:H.getClient(),getIdentityProofConfigured:()=>typeof n.getIdentityProof=="function",onActivationCommitted:f=>H.bindActivatedSession(f),getClient:()=>H.getClient()}):null},zy=()=>{Ld?.(),Ld=null,kd?.(),kd=null,Dp=!1,$o=YA();let s={...Ss};$o?s.historyProvider=$o:delete s.historyProvider,Ss=s,H.setHistoryInternals(Ss),$o&&(Ld=$o.subscribeAvailability?.(l=>{Dp=!l,l||Io({restoreFocus:!1}),Ir()})??null,kd=$o.subscribeIdentityStatus(l=>QA(l)),Np=qy($o.getIdentityStatus()))},jp=()=>{let s=n.features?.history?.presentation??"panel";if(s==="panel"||s==="auto"&&!(!ge||St(n)))return"panel";let l=En??ue;return(l.getBoundingClientRect().width||l.clientWidth)>=GA?"rail":"panel"},Zo=(s,l)=>{l?(s.setAttribute("aria-hidden","true"),s.setAttribute("inert","")):(s.removeAttribute("aria-hidden"),s.removeAttribute("inert"))},Hd="data-persona-history-suppressed",jo=null,kr=null,Ms=null,Bi=null,zp=null,Vy="",Ky=()=>Te===zp?Vy:n.layout?.showHeader===!1?"none":"",JA=()=>ie==="panel"&&!!Ms&&Bi===Ms.element&&n.layout?.showHeader!==!1&&Ky()!=="none",ZA=()=>{for(let s of Array.from(Te.children))s!==jo&&s.setAttribute(Hd,"")},eM=()=>{for(let s of Array.from(ue.querySelectorAll(`[${Hd}]`)))s.removeAttribute(Hd)},tM=()=>{let s=Ms;if(!s)return;if(Array.from(Te.children).some(g=>g!==jo&&!g.hasAttribute(Hd))){kr&&kr!==Te&&(kr.style.removeProperty("min-height"),kr=null);let g=Te.offsetHeight;g>0&&(Te.style.minHeight=`${g}px`,kr=Te)}jo||(jo=I("div","persona-history-header-host")),s.setHeaderPlacement("external");let f=s.getHeaderElement();f.parentNode!==jo&&jo.replaceChildren(f),jo.parentNode!==Te&&Te.appendChild(jo),ZA()},Gy=()=>{kr&&(kr.style.removeProperty("min-height"),kr=null),jo&&(Ms?.setHeaderPlacement("inline"),jo.remove(),jo=null,eM())},Rd=null,Vp=()=>{if(Rd){if(re.style.display="none",Zo(re,!0),Ie.hidden=!0,Zo(Ie,!0),JA()){tM(),Te.style.display=Ky(),Zo(Te,!1);return}Gy(),Te.style.display="none",Zo(Te,!0)}};Se=Vp;let oM=s=>{let l=re.style.display,f=Ie.hidden,g=Ie,v=Te,M=Te.style.display;zp=v,Vy=M,Rd=()=>{Rd=null,Gy(),zp=null,re.style.display=l,Zo(re,!1),g.hidden=f,Zo(g,!1),Ie!==g&&(Ie.hidden=!1,Zo(Ie,!1)),v.style.display=M,Zo(v,!1),Te!==v&&(Te.style.display=n.layout?.showHeader===!1?"none":"",Zo(Te,!1))},Ie.parentNode?.insertBefore(s,Ie),Vp()},ya=null,Ts=null,Oi=null,ba=null,Xy=()=>[Te,_e.closeButtonWrapper,_e.clearChatButtonWrapper,re,Ie],nM=52,Wd=()=>n.features?.history?.rail?.collapsible!==!1,va=()=>n.features?.history?.rail?.side==="right"?"right":"left",Kp=200,Gp=400,Xp=s=>Math.min(Gp,Math.max(Kp,Math.round(s))),rM=()=>n.features?.history?.rail?.resizable===!0,Di,sM=()=>{if(Di===void 0&&(Di=null,n.persistState!==!1))try{let s=Number(window.localStorage.getItem(`${Sn()}rail-width`));s&&(Di=s)}catch{}return Di},_i=()=>Xp(sM()??n.features?.history?.rail?.width??260),aM=s=>{if(Di=s,n.persistState!==!1)try{window.localStorage.setItem(`${Sn()}rail-width`,String(s))}catch{}},Bd=()=>Wd()&&n.features?.history?.rail?.collapsedBehavior==="overlay",_t=!1,Qy=s=>{let l=I("img");return l.src=s,l.alt="",l.setAttribute("aria-hidden","true"),l},iM=()=>{let s=n.features?.history?.rail?.brand;if(!s)return;let l=!1,f;return g=>{if(s.render)try{return s.render({collapsed:g})??null}catch(v){return l||(l=!0,console.warn("[persona] history rail brand threw",v)),null}return f===void 0&&(s.iconUrl?f=Qy(s.iconUrl):f=s.icon?ce(s.icon,20):null),f?f.cloneNode(!0):null}},lM=()=>n.features?.history?.rail?.sections?.map(s=>{let l=!1,f=g=>{l||(l=!0,console.warn("[persona] history rail section threw",s.id,g))};return{id:s.id,title:s.title,placement:s.placement??"above-conversations",items:s.items.map(g=>{let v;return{id:g.id,label:g.label,badge:g.badge,iconNode:()=>{if(v!==void 0)return v;try{g.renderIcon?v=g.renderIcon()??null:g.iconUrl?v=Qy(g.iconUrl):v=g.icon?ce(g.icon,20):null}catch(M){f(M),v=null}return v},onSelect:()=>{try{g.onSelect()}catch(M){f(M)}}}})}})??[],dM=s=>{let l=lM();for(let f of s)l.some(g=>g.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):l.push(f);return l.length?l:void 0},Ni=null,Yy=()=>`${Sn()}rail-collapsed`,Qp=()=>{if(Ni===null&&(Ni=n.features?.history?.rail?.defaultCollapsed===!0,n.persistState!==!1))try{let s=window.localStorage.getItem(Yy());s&&(Ni=s==="1")}catch{}return Ni},Yp=s=>{if(Ni=s,n.persistState!==!1)try{window.localStorage.setItem(Yy(),s?"1":"0")}catch{}},Fi=()=>ie==="rail"&&Wd()&&!Bd()&&Qp(),Jp=()=>{},Jy=()=>{if(Bd()){Jp();return}Yp(!Qp()),at?.view.setCollapsed(Fi()),ht(),ko()},Zp=()=>{let s=n.features?.history?.rail?.collapseShortcut;return!s||!cu(s)?null:{combo:s,hint:uu(s),aria:Tl(s)}},Zy=()=>{u.forEach(l=>l()),u=[];let s=Zp();s&&u.push(d.register({id:"history-rail-collapse",combo:s.combo,scope:n.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>ne&&ie==="rail"&&Wd()||Ca(),run:()=>Bd()?Jp():Jy()}));for(let l of n.layout?.header?.trailingActions??[])l.shortcut&&u.push(d.register({id:`header-action-${l.id}`,combo:l.shortcut,run:()=>{let f=e.querySelector(`[data-persona-header-action="${l.id}"]`);f?f.click():n.layout?.header?.onAction?.(l.id)}}));for(let l of i)for(let f of l.shortcuts??[])u.push(d.register({...f,id:`${l.id}:${f.id}`}))};Zy();let cM=300,Od="var(--persona-history-overlay-margin,8px)",en=null,tr=null,Dd=0,or=null,xa=null,Es=!1,ef=0,eb=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Ca=()=>In()&&Bd()&&(ie??jp())==="rail",uM=()=>ne&&!_t,Ui=()=>{xa!==null&&clearTimeout(xa),xa=null},pM=()=>{oh().catch(()=>{})},tb=()=>{Ui(),_t&&(xa=setTimeout(()=>{xa=null,!(Es||!_t)&&(or?.contains(document.activeElement)||Io({restoreFocus:!1}))},cM))},fM=(s,l)=>{let f=or?.getBoundingClientRect();if(!f)return!1;let g=en?.getBoundingClientRect(),v=g?Math.min(g.top,f.top):f.top;return s>=f.left&&s<=f.right&&l>=v&&l<=f.bottom||!!g&&s>=g.left&&s<=g.right&&l>=g.top&&l<=g.bottom},tf=s=>{_t&&(Es=fM(s.clientX,s.clientY),Es?Ui():xa===null&&tb())},ob=s=>{ne||!Ca()||(_t=!0,$i({invoker:en,keyboard:s?.keyboard===!0}).then(()=>{ne?!Es&&document.activeElement!==en&&Io():_t=!1}))},nb=()=>{let s=Bi?.querySelector('[data-persona-history-focus="collapse"]');s&&(s.setAttribute("aria-label",_t?Ye.expandLabel:Ye.collapseLabel),s.setAttribute("aria-expanded",_t?"false":"true"))},rb=()=>{Yp(!1);let s=at;if(!_t||!s){$i({invoker:en});return}let l=document.activeElement===en;_t=!1,_d(),s.element.remove(),nf(s.element),nb(),l&&Fd(),ko(),Ir()},mM=()=>{Yp(!0),Io()};Jp=()=>{!ne||_t?rb():mM()};let gM=()=>{let s=Zp(),l=$s({ariaLabel:Ye.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":Up,...s?{"aria-keyshortcuts":s.aria}:{}}}),f=l.button;f.addEventListener("mouseenter",()=>{Es=!0,Ui(),!(eb()||Date.now()<ef)&&ob()}),f.addEventListener("mouseleave",()=>{Es=!1,ef=0,tb()}),f.addEventListener("focus",()=>{ne||pM()}),f.addEventListener("click",g=>{In()&&(g.detail!==0&&eb()&&!ne?ob():rb())}),en=f,tr=l.wrapper},qi=()=>{if(tr&&!tr.isConnected&&(tr=null,en=null),!Ca()){tr?.remove(),tr=null,en=null;return}en||gM();let s=tr,l=en;if(!s||!l)return;let f=va()!=="right"?Te.firstChild:null;(f??Te.lastChild)!==s&&Te.insertBefore(s,f),s.style.display=uM()||Dd>0?"none":"",l.setAttribute("aria-label",Ye.expandLabel),l.setAttribute("aria-expanded",ne?"true":"false"),or&&ht()},sb=s=>{if(!_t)return;let l=s.target;l instanceof Node&&(or?.contains(l)||tr?.contains(l)||l instanceof Element&&l.closest('.persona-dropdown-menu,[role="alertdialog"]')||Io({restoreFocus:!1}))};document.addEventListener("pointerdown",sb,!0),be.push(()=>{document.removeEventListener("pointerdown",sb,!0),document.removeEventListener("pointermove",tf),Sa?.(),Ui()});let of=null,Sa=null,ab=16,ib=s=>{aM(Xp(s)),ht(),ko()},hM=()=>{let s=I("div","persona-rail-resizer");return s.tabIndex=0,s.setAttribute("role","separator"),s.setAttribute("aria-orientation","vertical"),s.setAttribute("aria-valuemin",String(Kp)),s.setAttribute("aria-valuemax",String(Gp)),s.addEventListener("pointerdown",l=>{let f=Ts;if(!f||l.button!==0)return;l.preventDefault(),Sa?.();let g=l.clientX,v=f.getBoundingClientRect().width||_i(),M=va()==="right"?-1:1,N=v,V=e.ownerDocument;f.style.transition="none";let j=J=>{N=Xp(v+M*(J.clientX-g)),f.style.flex=`0 0 ${N}px`,s.setAttribute("aria-valuenow",String(N))},K=()=>{Sa=null,V.removeEventListener("pointermove",j),V.removeEventListener("pointerup",K),V.removeEventListener("pointercancel",K),f.style.removeProperty("transition");try{s.releasePointerCapture(l.pointerId)}catch{}ib(N)};Sa=K,V.addEventListener("pointermove",j),V.addEventListener("pointerup",K),V.addEventListener("pointercancel",K);try{s.setPointerCapture(l.pointerId)}catch{}}),s.addEventListener("keydown",l=>{let f=va()==="right"?-ab:ab,g=_i(),v=l.key==="ArrowRight"?g+f:l.key==="ArrowLeft"?g-f:l.key==="Home"?Kp:l.key==="End"?Gp:null;v!==null&&(l.preventDefault(),ib(v))}),s},yM=(s,l)=>{if(!rM()||Fi()){Sa?.(),of?.remove();return}let f=of??hM();of=f,f.setAttribute("aria-label",Ye.resizeLabel),f.setAttribute("aria-valuenow",String(_i())),f.nextElementSibling!==l&&s.insertBefore(f,l)};ht=()=>{at?.view.setRailSide(va());let s=va()==="right",l=or;if(l){let V=en?en.getBoundingClientRect().bottom-ue.getBoundingClientRect().top:0;l.style.top=`calc(${Math.max(0,Math.round(V))}px + ${Od})`,l.style.width=`${_i()}px`,l.style.left=s?"":Od,l.style.right=s?Od:""}let f=Ts,g=ya,v=Oi;if(!f||!g||!v)return;f.style.flex=`0 0 ${Fi()?nM:_i()}px`;let M="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=s?"":M,f.style.borderLeft=s?M:"";let N=s?v:f;g.firstElementChild!==N&&g.append(N,s?f:v),yM(g,s?f:v)};let lb=s=>{if(ba&&Ts){ba.replaceWith(s),ba=null,ht();return}let l=I("div","persona-history-rail-shell");l.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=I("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 g=I("div","persona-history-rail-host");g.style.cssText="display:flex;min-height:0;overflow:hidden",ue.insertBefore(l,Te.parentNode===ue?Te:re);for(let v of Xy())v?.parentNode===ue&&f.appendChild(v);l.append(g,f),g.appendChild(s),ya=l,Ts=g,Oi=f,ht()},bM=()=>{if(ya)return;let s=I("div","persona-history-rail-placeholder");s.style.cssText="flex:1 1 auto;min-height:0",ba=s,lb(s),ko()},db=()=>{ba&&(_d(),ko())},vM=s=>{let l=I("div","persona-history-rail-overlay");l.style.cssText=`position:absolute;bottom:${Od};display:flex;overflow:hidden;z-index:${qa-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))`,ue.style.position="relative",ue.appendChild(l),l.appendChild(s),document.addEventListener("pointermove",tf),or=l,ht(),nb()},_d=()=>{Rd?.(),or&&(Es&&(ef=Date.now()+150),document.removeEventListener("pointermove",tf),or.remove(),or=null);let s=ya;if(s){Sa?.();for(let l of Xy())l&&s.contains(l)&&ue.insertBefore(l,s);s.remove(),ya=null,Ts=null,Oi=null,ba=null}},cb=s=>{Bi=s,s.id=Up,s.style.flex="1 1 auto",s.style.minHeight="0"},nf=s=>{cb(s),(ie!=="rail"||_t)&&db(),ie!=="rail"?oM(s):_t?vM(s):lb(s)},Nd=()=>{if(qi(),Cb(),!ne||!at)return;let s=jp();if(s===ie)return;let l=document.activeElement,f=l instanceof HTMLElement&&(at.element.contains(l)||jo?.contains(l)===!0)?l:null;_d(),at.element.remove(),at.view.setHeaderPlacement("inline"),ie=s,at.view.setPresentation(s),at.view.setCollapsed(Fi()),at.requestRender(),at.element.isConnected||nf(at.element),f?.isConnected?f.focus():Fd(),jt(),ko(),Ir()},ub=(s,l)=>jo?.querySelector(l)??s.querySelector(l),Fd=()=>{let s=at?.element??Bi;if(!s)return;let l=ub(s,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(l){l.focus();return}let f=ub(s,".persona-history-title")??s;f.tabIndex=-1,f.focus()},$i=async s=>{if(!In()||ne)return;let l=$o;if(!l)return;if(!_t&&Ca()&&Qp()){qi();return}Ud();let f=++Wi;Ed=s?.returnSurface??"conversation",_p=s?.invoker??mo;let g=Ca()&&!_t;g&&(Dd+=1,qi(),bM());let v;try{v=await oh()}catch{Id(Ye.openHistoryLabel),g&&(Dd-=1,f===Wi&&(db(),qi()));return}if(g&&(Dd-=1),f!==Wi||ne)return;Td={scope:$p()},ie=jp(),ne=!0;let M=ie==="panel"&&n.layout?.showHeader!==!1&&Te.style.display!=="none"?"external":"inline",N=n.features?.history?.rowAvatar,V=Zp(),j=V?{hint:V.hint,aria:V.aria}:null,K={provider:l,context:Td,targetId:Uy(),presentation:ie,collapsible:Wd(),collapsed:Fi(),railSide:va(),renderRailHeader:n.features?.history?.rail?.renderHeader,railBrand:iM(),onToggleCollapse:Jy,...j?{collapseShortcut:j}:{},headerPlacement:M,showScopeStatus:n.features?.history?.showScopeStatus!==!1,showDelete:n.features?.history?.showDelete!==!1,showDeleteAll:n.features?.history?.showDeleteAll!==!1,...n.features?.history?.listActions?.length?{listActions:n.features.history.listActions}:{},rowAvatar:N===!1?!1:typeof N=="string"?N:n.launcher?.iconUrl,activeConversationId:H.getActiveConversationId(),...n.features?.history?.grouping?{grouping:n.features.history.grouping}:{},...n.features?.history?.copy?{copy:n.features.history.copy}:{},...n.features?.history?.pageSize!==void 0?{pageSize:n.features.history.pageSize}:{},onSelect:J=>sf(J,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:J=>Ps(J),attachTooltip:eo,onStartNew:()=>af({focusComposer:!0}),onClose:()=>Io(),onRequestDeleteConversation:J=>xb(J),onRequestClearHistory:()=>MM(),...l.resetDevice?{onRequestResetIdentity:()=>TM()}:{}};at=fw({plugins:i,config:n,getPresentation:()=>ie??"panel",getReturnSurface:()=>Ed,close:()=>Io(),createView:({slots:J,renderDom:ae,onModelChange:fe,railSections:Je})=>(Ms=v.createHistoryView({...K,railSections:dM(Je),slots:J,renderDom:ae,onModelChange:fe,onAnnounce:Id}),Ms),onElementChanged:(J,ae)=>{if(!ae?.isConnected)return nf(J);cb(J),ae.replaceWith(J),Vp()}}),at.view.setNewConversationRequired(Pd.recovery==="new_conversation_required"),s?.focus!==!1&&(ie!=="rail"||s?.keyboard===!0)&&Fd(),jt(),ko(),Ir(),x.emit("history:opened",{presentation:ie,returnSurface:Ed,timestamp:Date.now()})},Ud=()=>{},Io=s=>{if(!ne)return;Wi+=1;let l=Ed,f=_p,g=at,v=s?.restoreFocus!==!1;ne=!1;let M=!1,N=null,V=()=>{if(!M){if(M=!0,Ud=()=>{},N!==null&&clearTimeout(N),_t=!1,Ui(),_d(),g?.dispose(),g?.view.destroy(),g?.element.remove(),at===g&&(at=null,Ms=null,Bi=null,ie=null,Td=null,_p=null),jt(),ko(),Ir(),v){let K=f??mo;K?.isConnected?K.focus():xs()}x.emit("history:closed",{returnSurface:l,timestamp:Date.now()})}},j=g&&g.element===g.view.element?g.view.playExit():null;if(!j){V();return}Ud=V,N=setTimeout(V,XA),j.then(V)},pb=s=>{if(!(s.key!=="Escape"||!ne||!at)){if(ie==="rail"){let l=s.target;if(!(l instanceof Node)||!(at.element.contains(l)||_t&&tr?.contains(l)===!0))return}s.preventDefault(),s.stopPropagation(),Io()}};ue.addEventListener("keydown",pb),be.push(()=>ue.removeEventListener("keydown",pb));let qd=null,fb=!1,ji=()=>{if(!yr)return;let s=n.layout?.header?.titleSource==="conversation",l=s&&qd?.trim()||null;yr.textContent=l??n.launcher?.title??"Chat Assistant";let f=yr.closest(".persona-combo-btn");if(!f)return;let g=!s||H.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",g?"false":"true"),f.setAttribute("aria-haspopup",g?"true":"false"),g||f.setAttribute("aria-expanded","false"),f.style.cursor=g?"pointer":"default";let v=f.querySelector("svg");v&&(v.style.display=g?"":"none")},xM=s=>{s!==qd&&(qd=s,ji())},Ps=s=>{fb=s?.starred===!0,xM(s&&s.title.trim()||null),ji()};ji(),ue.addEventListener("persona:title-menu-builtin",s=>{let l=s.detail?.actionId,f=H.getActiveConversationId();f&&(l==="delete"?xb(f):l==="star"&&H.canUpdateConversations()&&lf(f,{starred:!fb}).catch(()=>{}))});let $d=0,CM=250,jd=null,zd=()=>{jd&&clearTimeout(jd),jd=null};be.push(zd);let mb=()=>{zd();let s=Cs;s&&(Ii=!0,s.hidden=!1,Le.style.display="none",Hi())},Vd=()=>{$d+=1,zd(),Cs&&(Cs.remove(),Cs=null,Ii=!1,Le.style.removeProperty("display"),Zo(Ie,!1),Hi())},SM=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Le.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},rf=(s,l)=>Y("div",{className:bo("persona-conversation-loading-bubble",l&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:s}}),gb=()=>Y("div",{className:"persona-conversation-loading-body"},rf("58%",!1),rf("72%",!0),rf("44%",!1)),hb=s=>{Cs?.remove(),Cs=s,s.hidden=!Ii,re.insertBefore(s,Le),zd(),Ii||(jd=setTimeout(mb,CM)),Zo(Ie,!0)},wM=()=>{let s={config:n,streaming:!1,location:"conversation-open",defaultRenderer:gb},l=null,f=i.find(g=>g.renderLoadingIndicator);f?.renderLoadingIndicator&&(l=f.renderLoadingIndicator(s)),l===null&&n.loadingIndicator?.render&&(l=n.loadingIndicator.render(s)),hb(Y("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ye.openConversationLoadingLabel}},l??gb()))},AM=s=>{let l=()=>{sf(s,{focusComposer:!0}).catch(()=>{})},f=In()?()=>{Vd(),$i()}:void 0,g=(V,j)=>{let K=Y("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:V});return K.addEventListener("click",j),K},v=()=>Y("div",{className:"persona-conversation-loading-error-body"},Y("p",{className:"persona-conversation-loading-error-title",text:Ye.openConversationErrorTitle}),Y("div",{className:"persona-conversation-loading-error-actions"},g(Ye.openConversationRetryLabel,l),f?g(Ye.openConversationBackLabel,f):null)),M=Object.freeze({conversationId:s,config:n,copy:Object.freeze({title:Ye.openConversationErrorTitle,retryLabel:Ye.openConversationRetryLabel,backLabel:Ye.openConversationBackLabel}),retry:l,...f?{back:f}:{},defaultRenderer:v}),N=null;for(let V of i)if(V.renderHistoryOpenError){try{N=V.renderHistoryOpenError(M)}catch(j){console.warn("[persona] renderHistoryOpenError threw",j),N=null}if(N)break}hb(Y("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},N??v())),mb()};x.on("history:closed",()=>{Cs&&Zo(Ie,!0)});let sf=async(s,{focusComposer:l=!1}={})=>{let f=ha(),g=!!at;at?.view.setActiveConversationId(s),Vd();let v=$d;wM(),ne&&(ie==="panel"||_t)&&Io({restoreFocus:!1}),da=!0;try{await H.openConversation(s,{scope:f})}catch(M){throw v===$d&&AM(s),M}finally{da=!1}v===$d&&(Vd(),Dt.clear(),hn(),Lo(),xp()||hd(),SM(),nr(),g||Ps(null),x.emit("history:conversationOpened",{conversationId:s,title:qd,scope:f,timestamp:Date.now()}),l&&xs())},af=async({focusComposer:s=!1}={})=>{Vd(),await H.startNewConversation({scope:ha()}),Ps(null),Dt.clear(),hn(),Lo(),hd(),nr();let l=H.getActiveConversationId();at?.view.setActiveConversationId(l),x.emit("history:conversationStarted",{conversationId:l,timestamp:Date.now()}),ne&&(ie==="panel"||_t)&&Io({restoreFocus:!1}),s&&xs()},lf=async(s,l)=>{let f=await H.updateConversation(s,{...l,...l.title!==void 0?{title:l.title.trim()}:{}});return at?.view.applyConversationSummary(f),!at&&s===H.getActiveConversationId()&&Ps(f),f},yb=async s=>{let l=ha(),f=H.getActiveConversationId()===s;await H.deleteConversation(s,{scope:l}),at?.view.removeConversationSummary(s),f&&(Ps(null),Dt.clear(),hn(),Lo(),nr()),x.emit("history:conversationDeleted",{conversationId:s,scope:l,wasActive:f,timestamp:Date.now()})},bb=async s=>{let l=s?.scope??ha(),f=s?.allTargets?null:s?.targetId??Uy(),g=await H.clearConversationHistory({...f?{targetId:f}:{},scope:l});return Ps(null),Dt.clear(),hn(),Lo(),nr(),x.emit("history:cleared",{deleted:g.deleted,scope:l,targetId:f,timestamp:Date.now()}),g},vb=async()=>{if(!$o?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let s=!1;try{s=(await H.resetHistoryDevice()).remoteRevocationConfirmed}finally{Ps(null),H.clearArtifacts(),Dt.clear(),Wp=null,n.clearStoredSessionId?.(),n.clearStoredConversationId?.(),X={},Pe.syncFromMetadata(),F?.clear&&fd(()=>F.clear(),"[AgentWidget] Failed to clear storage adapter:"),hn(),Lo(),nr(),Io({restoreFocus:!1}),xs(),he||Pt?.launcher.element.focus()}return Id(s?Ye.identityResetNotice:Ye.identityResetUnconfirmedNotice),x.emit("history:identityReset",{remoteRevocationConfirmed:s,timestamp:Date.now()}),{remoteRevocationConfirmed:s}},df=()=>En?we:ue,xb=async s=>await Ou({host:df(),title:Ye.deleteConversationConfirmTitle,description:Ye.deleteConversationConfirm,confirmLabel:Ye.deleteConversationConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await yb(s),"deleted"):"cancelled",MM=async()=>{let s=ha()==="verified-user";return await Ou({host:df(),title:Ye.clearHistoryConfirmTitle,description:s?Ye.clearHistoryVerifiedConfirm:Ye.clearHistoryConfirm,confirmLabel:Ye.clearHistoryConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await bb(),"cleared"):"cancelled"},TM=async()=>{if(!await Ou({host:df(),title:Ye.resetIdentityConfirmTitle,description:Ye.resetIdentityConfirm,confirmLabel:Ye.resetIdentityConfirmLabel,cancelLabel:Ye.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:l}=await vb();return{outcome:"reset",remoteRevocationConfirmed:l}},tn=I("button","persona-history-earlier");tn.type="button",tn.textContent=Ye.showEarlierMessagesLabel,tn.setAttribute("data-persona-history-earlier",""),Object.assign(tn.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 nr=()=>{if(!(In()&&!!Pd.nextMessageCursor&&!!H.getActiveConversationId())){tn.remove();return}tn.textContent=Ye.showEarlierMessagesLabel,tn.parentNode!==re&&re.insertBefore(tn,re.firstChild)};tn.addEventListener("click",()=>{let s=H.getActiveConversationId(),l=Pd.nextMessageCursor;if(!s||!l||tn.disabled)return;tn.disabled=!0;let f=re.scrollHeight,g=re.scrollTop;H.loadOlderMessages(s,l,{scope:ha()}).then(()=>{re.scrollTop=g+(re.scrollHeight-f),ko()}).catch(()=>{}).finally(()=>{tn.disabled=!1,nr()})});let EM=()=>{let s=$s({ariaLabel:Ye.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 s.button.addEventListener("click",l=>{if(!(!In()||Fy())){if(ne){Io();return}$i({invoker:s.button,keyboard:l.detail===0})}}),s},Cb=()=>{if(!In()){kn?.remove(),mo=null,kn=null;return}if(kn&&!kn.isConnected&&(mo=null,kn=null),!mo&&Te){let g=EM();mo=g.button,kn=g.wrapper;let v=_e.clearChatButtonWrapper||_e.closeButtonWrapper;v?.parentNode&&Te.contains(v)?v.parentNode.insertBefore(kn,v):Te.appendChild(kn)}if(!mo||!kn)return;let s=Ca()||ne&&ie==="rail";if(kn.style.display=s?"none":"",s){document.activeElement===mo&&Fd();return}let l=Fy();mo.disabled=l,mo.setAttribute("aria-disabled",l?"true":"false");let f=l?Ye.openHistoryBusyLabel:Ye.openHistoryLabel;mo.setAttribute("aria-label",f),(n.features?.history?.presentation??"panel")==="panel"?(mo.removeAttribute("aria-expanded"),mo.removeAttribute("aria-controls")):(mo.setAttribute("aria-expanded",ne?"true":"false"),mo.setAttribute("aria-controls",Up))},Kd=!1,PM=()=>{let s=_e.clearChatButton;if(s){if(In()){Kd||(Fp=s.getAttribute("aria-label")??"",Kd=!0),s.setAttribute("aria-label",Ye.newConversationLabel),s.removeAttribute("title");return}Kd&&(Kd=!1,Fp&&s.setAttribute("aria-label",Fp))}},Ir=()=>{Ye=sh(n.features?.history?.copy),Cb(),qi(),PM(),nr()};wt=Ir,$e=s=>{Pd=s,at?.view.setNewConversationRequired(s.recovery==="new_conversation_required"),ki(s.sendBlocked||Fo),nr()},Rt=s=>{(s.code==="history_continuity_reset"||s.code==="conversation_deleted_recovered")&&(Dt.clear(),hn(),Lo()),Id(s.message),at?.view.refresh()},zy(),Ir(),be.push(()=>{Ld?.(),kd?.(),Wi+=1,Ud(),at?.dispose(),at?.view.destroy(),at=null}),n.clientToken&&H.initClientSession().then(()=>{if(In())return H.reconcileBootConversation({scope:$p()})}).then(()=>{nr()}).catch(s=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",s)}),(Ht||n.onSSEEvent)&&H.setSSEEventCallback((s,l)=>{n.onSSEEvent?.(s,l),$(s,l)});let Sb=()=>{n.resume&&typeof n.reconnectStream=="function"&&H.resumeFromHandle(n.resume)};G?G.then(s=>{if(s){if(s.metadata&&(X=ah(s.metadata),Pe.syncFromMetadata()),s.messages?.length){da=!0;try{H.hydrateMessages(s.messages)}finally{da=!1}xd()}s.artifacts?.length&&H.hydrateArtifacts(s.artifacts,s.selectedArtifactId??null),vy(s.draft)}}).catch(s=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",s)}).finally(()=>{Tp=!0,E(),Sb()}):(vy(O),Sb());let LM=()=>{!Ae()||he||!(n.launcher?.composerBar?.expandOnSubmit??!0)||dt(!0,"auto")},kM=(s,l)=>s?l?{refs:[...s.refs,...l.refs],finalize:async()=>{let[f,g]=await Promise.allSettled([s.finalize(),l.finalize()]),v=[];return f.status==="fulfilled"?v.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),g.status==="fulfilled"?v.push(g.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",g.reason),zk(v)}}:s:l,cf=()=>{let l=le.getInlineMessageFields?.();return l&&l.contentSegments.some(g=>g.kind==="mention")?l.contentSegments:void 0},rr=!1,Ls=null,Gd=()=>{le.value="",le.style.height="auto",An(),Vi()},uf="data-persona-composer-notice",wa=null;function IM(s){Gl(s),!(Ae()||!st)&&(st.hasAttribute(ii)||(st.setAttribute(uf,""),st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.textContent=s,wa&&clearTimeout(wa),wa=setTimeout(()=>{if(wa=null,!!st?.hasAttribute(uf)&&(st.removeAttribute(uf),st.removeAttribute("role"),st.removeAttribute("aria-live"),c)){let l=H.getStatus();ao(st,fo(l),n.statusIndicator??{},l)}},4e3)))}function HM(){let s=Ce.getState().pendingSubmission;s&&(ta(void 0),le&&(le.value=s.text,le.dispatchEvent(new Event("input",{bubbles:!0})),An()),s.options.selectedModelId&&(Ce.setSelectedModelId(s.options.selectedModelId),vr?.repaint()),s.options.activeModeIds?.length&&Jl(s.options.activeModeIds),s.options.quote&&Mn(s.options.quote),le?.focus())}let RM=s=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",s)},wb=(s={})=>{let l=(s.overrideText??le?.value??"").trim();return s.resolveInlineCommand&&l?(Wt?.takeInlineCommand(l)??Promise.resolve(null)).then(f=>Ab(s,l,f)):Ab(s,l,null)},Ab=(s,l,f)=>{if(f?.kind==="action"){Gd(),Wt?.clear(),ns();return}let g=f?.kind==="server"?f.mentions:null,v=f?.kind==="prompt"?f.sendText:l,M=s.pending?.contentParts,N=(Ze?.hasAttachments()??!1)||(M?.length??0)>0;if(!wC({text:v,hasAttachments:N,attachmentsReady:Ze?.isReady()??!0,hasMentions:Wt?.hasMentions()??!1,hasServerMentions:!!g,inputDisabled:Pr(),sendDisabled:vs()}))return;let V=H.isStreaming()?ep():"block";if(V==="defer-one"&&!s.pending){if(Ce.getState().pendingSubmission){IM("One message is already queued. Edit or remove it first.");return}WM({intent:s,sendText:v,serverMentions:g});return}let j={text:v,mentionRefs:[...Wt?.getMentionRefs()??[],...g?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:cf(),options:{...Ce.getState().selectedModelId&&{selectedModelId:Ce.getState().selectedModelId},...Ce.getState().activeModeIds.length>0&&{activeModeIds:[...Ce.getState().activeModeIds]},...Ce.getState().quote&&{quote:{...Ce.getState().quote}}},viaVoice:s.viaVoice};s.pending&&(j.options={...s.pending.options},j.contentSegments=s.pending.contentSegments,j.mentionRefs=[...s.pending.mentionRefs],j.viaVoice=s.pending.viaVoice);let K=()=>{if(M?.length)return[...M];if(!Ze?.hasAttachments())return;let ct=[...Ze.getContentParts()];return j.text&&ct.push(an(j.text)),ct};j.contentParts=K();let J=()=>{ps(),LM();let ct=Wt?.collectForSubmit()??null,Qt=kM(ct,g),Nt=K();s.consumeDraft!==!1&&Gd();let kt={selectedModelId:j.options.selectedModelId,activeModeIds:j.options.activeModeIds},io=V==="interrupt";io&&H.cancel(),H.sendMessage(j.text,{contentParts:Nt,mentions:Qt??void 0,contentSegments:j.contentSegments,viaVoice:j.viaVoice,composerOptions:kt,...j.options.quote&&{quote:j.options.quote},...io&&{interrupt:!0}}),Ze?.hasAttachments()&&Ze.clearAttachments(),ct&&Wt?.clear(),ns();let et=Ce.getState().activeModeIds,lo=dC(et,n.composer?.modes);lo.length!==et.length&&Jl(lo),Ce.getState().quote&&Mn(void 0),gd(),sp.release(),pn()},ae=n.composer?.onBeforeSend;if(!ae){J();return}let fe=new AbortController;Ls=fe;let Je=ct=>{if(Ls=null,ct.status==="error"){RM(ct.error);return}ct.status==="proceed"&&J()},lt=AC(ae,j,fe.signal);if(!(lt instanceof Promise)){Je(lt);return}return Ce.setPreparing(!0),lt.then(Je).finally(()=>Ce.setPreparing(!1))};function WM(s){let l=Ce.getState(),f=Ze?.hasAttachments()??!1,g=f?[...Ze.getContentParts()]:[];f&&s.sendText&&g.push(an(s.sendText));let v=tg({text:s.sendText,contentParts:g.length?g:void 0,mentionRefs:[...Wt?.getMentionRefs()??[],...s.serverMentions?.refs??[]],contentSegments:cf(),options:{...l.selectedModelId&&{selectedModelId:l.selectedModelId},...l.activeModeIds.length>0&&{activeModeIds:[...l.activeModeIds]},...l.quote&&{quote:{...l.quote}}},viaVoice:s.intent.viaVoice});ta(v),s.intent.consumeDraft!==!1&&Gd(),f&&Ze.clearAttachments(),Wt?.clear(),ns(),l.quote&&Mn(void 0),gd(),sp.release(),pn(),Gl("Message queued. It sends when the response finishes.")}function BM(){let s=Ce.getState().pendingSubmission;s&&(ta(void 0),Qd(s.text,{consumeDraft:!1,pending:s}))}function OM(s){if(n.messageActions?.showEdit!==!0)return;let l=H.getMessages().find(f=>f.id===s);!l||!Kf(l)||us!==s&&(ps(),us=s,wr=mC({messageId:s,initialText:l.content,onSave:f=>DM(s,f),onCancel:()=>ps()}),Dt.delete(s),Jo(Le,H.getMessages(),oo),wr.focus())}function DM(s,l){let f=wr;if(us=null,wr=null,f?.destroy(),Dt.delete(s),!H.resubmitFrom(s,{reason:"edit",replacement:{text:l,mentionRefs:[],options:{}}})){Jo(Le,H.getMessages(),oo);return}ko()}function _M(s){if(H.isStreaming())return;let l=Vf(H.getMessages(),s);l&&(ps(),H.resubmitFrom(l,{reason:"retry"})&&ko())}Zl={regenerate:_M,edit:OM,quote:s=>{let f=H.getMessages().find(g=>g.id===s)?.content?.trim();f&&(Mn({text:f,messageId:s}),le?.focus())}};let zi=async s=>{if(!rr){rr=!0;try{await wb({resolveInlineCommand:!0,...s})}finally{rr=!1}}};function Xd(s){vs()||(Gd(),Qd(s,{consumeDraft:!1}))}let Qd=(s,l)=>{if(rr)return;rr=!0;let f=()=>{rr=!1};try{let g=wb({...l,overrideText:s});g instanceof Promise?g.finally(f):f()}catch(g){throw f(),g}},NM=s=>{if(s.preventDefault(),H.isStreaming()){H.cancel(),ut?.reset(),B?.update();return}rr||zi()},FM=()=>n.features?.composerHistory!==!1,pf={...cg},ff=!1,Vi=()=>{pf={...cg}},UM=()=>H.getMessages().filter(s=>s.role==="user").map(s=>s.content??"").filter(s=>s.length>0),qM=s=>{if(!le)return;ff=!0,le.value=s,le.dispatchEvent(new Event("input",{bubbles:!0})),ff=!1;let l=le.value.length;le.setSelectionRange(l,l)},$M=s=>{ff||(s.isComposing||Wt?.handleInput(s.inputType??void 0),Vi())},jM=()=>({submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Cl(le)}),zM=s=>{if(le&&!Pr()&&!(!s.isComposing&&Wt?.handleKeydown(s))){if(FM()&&(s.key==="ArrowUp"||s.key==="ArrowDown")&&!s.shiftKey&&!s.metaKey&&!s.ctrlKey&&!s.altKey&&!s.isComposing){let l=le.selectionStart===0&&le.selectionEnd===0,f=jC({direction:s.key==="ArrowUp"?"up":"down",history:UM(),currentValue:le.value,atStart:l,state:pf});if(pf=f.state,f.handled){s.preventDefault(),f.value!==void 0&&qM(f.value);return}}if(Kx(s,jM())){if(H.isStreaming()){if(s.preventDefault(),ep()==="block"||rr||vs())return;Vi(),zi();return}if(rr){s.preventDefault();return}if(vs()){s.preventDefault();return}Vi(),s.preventDefault(),Me.click()}}},Mb=s=>{if(!(s.key!=="Escape"||s.isComposing)&&s.composedPath().includes(ue)){if(Ls){Ls.abort(),Ls=null,s.preventDefault(),s.stopImmediatePropagation();return}H.isStreaming()&&(H.cancel(),ut?.reset(),B?.update(),Vi(),s.preventDefault(),s.stopImmediatePropagation())}},VM=async s=>{if(n.attachments?.enabled!==!0||!Ze||Pr())return;let l=Uk(s.clipboardData);l.length!==0&&(s.preventDefault(),await Ze.handleFiles(l))},on=null,Hn=!1,Aa=null,vt=null,mf=()=>n.voiceRecognition?.completionBehavior==="review";function ks(s){se?.setAttribute("data-state",s),s==="recording"?GM():bf()}let Tb="--persona-voice-level",gf=.5,Ma=null,hf=-1,Yd=0,Eb=()=>{let s=[],l=_o??se?.parentElement??null;return l&&s.push(l),Ie&&s.push(Ie),s},yf=s=>{let l=Math.round(Math.max(0,Math.min(1,s))*100)/100;if(l!==hf){hf=l;for(let f of Eb())f.style.setProperty(Tb,String(l))}},KM=()=>{hf=-1,Yd=0;for(let s of Eb())s.style.removeProperty(Tb)};function GM(){if(Ma!==null)return;if(typeof requestAnimationFrame!="function"){yf(c?H.getVoiceLevel()??gf:gf);return}let s=()=>{Ma=requestAnimationFrame(s);let l=c?H.getVoiceLevel():null;if(l===null){yf(gf);return}Yd+=(l-Yd)*.3,yf(Yd)};Ma=requestAnimationFrame(s)}function bf(){Ma!==null&&(cancelAnimationFrame(Ma),Ma=null),KM()}let Pb=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Jd=(s="user")=>{if(Hn||H.isStreaming())return;let l=Pb();if(!l)return;on=new l;let f=n.voiceRecognition??{},g=f.pauseDuration??2e3;on.continuous=f.provider?.browser?.continuous??!0,on.interimResults=!0,on.lang=f.provider?.browser?.language??"en-US";let v=le.value;on.onresult=M=>{let N="",V="";for(let K=0;K<M.results.length;K++){let J=M.results[K],ae=J[0].transcript;J.isFinal?N+=ae+" ":V=ae}let j=v+N+V;le.value=j,An(),Aa&&clearTimeout(Aa),(N||V)&&(Aa=window.setTimeout(()=>{if(le.value.trim()&&on&&Hn){if(Hr(),mf())return;zi({viaVoice:!0})}},g))},on.onerror=M=>{M.error!=="no-speech"&&Hr()},on.onend=()=>{if(Hn){let M=le.value.trim();!mf()&&M&&M!==v.trim()&&zi({viaVoice:!0}),Hr()}};try{if(on.start(),Hn=!0,ze.active=!0,s!=="system"&&(ze.manuallyDeactivated=!1),Yn(s),gn(),pn(),se){let M=n.voiceRecognition??{};vt={backgroundColor:se.style.backgroundColor,color:se.style.color,borderColor:se.style.borderColor,iconName:M.iconName??"mic",iconSize:parseFloat(M.iconSize??"")||vo};let N=M.recordingBackgroundColor,V=M.recordingIconColor,j=M.recordingBorderColor;if(se.classList.add("persona-voice-recording"),ks("recording"),se.style.backgroundColor=N??"var(--persona-voice-recording-bg, #ef4444)",se.style.color=V??"var(--persona-voice-recording-indicator, #ffffff)",V){let K=se.querySelector("svg");K&&K.setAttribute("stroke",V)}j&&(se.style.borderColor=j),se.setAttribute("aria-label","Stop voice recognition")}}catch{Hr("system")}},Hr=(s="user")=>{if(Hn){if(Hn=!1,Aa&&(clearTimeout(Aa),Aa=null),on){try{on.stop()}catch{}on=null}if(ze.active=!1,Yn(s),gn(),pn(),se){if(se.classList.remove("persona-voice-recording"),ks("idle"),vt){se.style.backgroundColor=vt.backgroundColor,se.style.color=vt.color,se.style.borderColor=vt.borderColor;let l=se.querySelector("svg");l&&l.setAttribute("stroke",vt.color||"currentColor"),vt=null}se.setAttribute("aria-label","Start voice recognition")}}},vf=()=>{if(!se||vt)return;let s=n.voiceRecognition??{};vt={backgroundColor:se.style.backgroundColor,color:se.style.color,borderColor:se.style.borderColor,iconName:s.iconName??"mic",iconSize:parseFloat(s.iconSize??"")||vo}},xf=(s,l)=>{if(!se)return;let f=se.querySelector("svg");f&&f.remove();let g=vt?.iconSize??(parseFloat(n.voiceRecognition?.iconSize??"")||vo),v=ce(s,g,l,1.5);v&&se.appendChild(v)},Zd=()=>{se&&se.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ta=()=>{if(!se)return;vf();let s=n.voiceRecognition??{},l=s.recordingBackgroundColor,f=s.recordingIconColor,g=s.recordingBorderColor;if(Zd(),se.classList.add("persona-voice-recording"),ks("recording"),se.style.backgroundColor=l??"var(--persona-voice-recording-bg, #ef4444)",se.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let v=se.querySelector("svg");v&&v.setAttribute("stroke",f)}g&&(se.style.borderColor=g),se.setAttribute("aria-label","Stop voice recognition")},XM=()=>{if(!se)return;vf();let s=n.voiceRecognition??{},l=H.getVoiceInterruptionMode(),f=s.processingIconName??"loader",g=s.processingIconColor??vt?.color??"",v=s.processingBackgroundColor??vt?.backgroundColor??"",M=s.processingBorderColor??vt?.borderColor??"";Zd(),se.classList.add("persona-voice-processing"),ks("processing"),se.style.backgroundColor=v,se.style.borderColor=M;let N=g||"currentColor";se.style.color=N,xf(f,N),se.setAttribute("aria-label","Processing voice input"),l==="none"&&(se.style.cursor="default")},QM=()=>{if(!se)return;vf();let s=n.voiceRecognition??{},l=H.getVoiceInterruptionMode(),f=l==="cancel"?"square":l==="barge-in"?"mic":"volume-2",g=s.speakingIconName??f,v=s.speakingIconColor??(l==="barge-in"?s.recordingIconColor??vt?.color??"":vt?.color??""),M=s.speakingBackgroundColor??(l==="barge-in"?s.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),N=s.speakingBorderColor??(l==="barge-in"?s.recordingBorderColor??"":vt?.borderColor??"");Zd(),se.classList.add("persona-voice-speaking"),ks("speaking"),se.style.backgroundColor=M,se.style.borderColor=N;let V=v||"currentColor";se.style.color=V,xf(g,V);let j=l==="cancel"?"Stop playback and re-record":l==="barge-in"?"Speak to interrupt":"Agent is speaking";se.setAttribute("aria-label",j),l==="none"&&(se.style.cursor="default"),l==="barge-in"&&se.classList.add("persona-voice-recording")},sr=()=>{se&&(Zd(),ks("idle"),vt&&(se.style.backgroundColor=vt.backgroundColor??"",se.style.color=vt.color??"",se.style.borderColor=vt.borderColor??"",xf(vt.iconName,vt.color||"currentColor"),vt=null),se.style.cursor="",se.setAttribute("aria-label","Start voice recognition"))},Cf=()=>{if(!Pr()){if(n.voiceRecognition?.provider?.type==="runtype"){let s=H.getVoiceStatus(),l=H.getVoiceInterruptionMode();if(l==="none"&&(s==="processing"||s==="speaking"))return;if(l==="cancel"&&(s==="processing"||s==="speaking")){H.stopVoicePlayback();return}if(H.isBargeInActive()){H.stopVoicePlayback(),H.deactivateBargeIn().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,gn(),Yn("user"),sr()});return}H.toggleVoice().then(()=>{ze.active=H.isVoiceActive(),ze.manuallyDeactivated=!H.isVoiceActive(),gn(),Yn("user"),H.isVoiceActive()?Ta():sr()});return}if(Hn){let s=le.value.trim();ze.manuallyDeactivated=!0,gn(),Hr("user"),s&&!mf()&&zi()}else ze.manuallyDeactivated=!1,gn(),Jd("user")}};tp=Cf,se&&be.push(()=>{n.voiceRecognition?.provider?.type==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),sr()):Hr("system")});let YM=x.on("assistant:complete",()=>{Ce.getState().pendingSubmission&&setTimeout(()=>{H.isStreaming()||BM()},0)});be.push(YM);let JM=x.on("assistant:complete",()=>{hy&&(ze.active||ze.manuallyDeactivated||hy==="assistant"&&!ze.lastUserMessageWasVoice||setTimeout(()=>{!ze.active&&!ze.manuallyDeactivated&&(n.voiceRecognition?.provider?.type==="runtype"?H.toggleVoice().then(()=>{ze.active=H.isVoiceActive(),Yn("auto"),H.isVoiceActive()&&Ta()}):Jd("auto"))},600))});be.push(JM);let ZM=x.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});be.push(ZM);let Lb=()=>{dt(!he,"user")},Pt=null,go=null;if(ge&&!Ae()){let{instance:s,element:l}=Ng({config:n,plugins:i,onToggle:Lb});Pt=s,s||(go=l)}Pt?e.appendChild(Pt.element):go&&e.appendChild(go),Li(),ia(),wd(),Ip(),ki(H.isStreaming()),xp()||(No()==="follow"?Tr(!0):hd()),vA(),Bt&&(!ge||Ae()?setTimeout(()=>xs(),0):he&&setTimeout(()=>xs(),200));let Is=null,kb=()=>{Is&&(Is.disconnect(),Is.observe(Ie),Is.observe(ue))},Ki=()=>{if(Ae()){os(),Li();return}let s=St(n),l=n.launcher?.sidebarMode??!1,f=e.ownerDocument.defaultView??window,g=n.launcher?.mobileFullscreen??!0,v=n.launcher?.mobileBreakpoint??640,M=f.innerWidth<=v,N=g&&M&&ge;try{if(N){rs(),bi=id();return}let V=!1;Ge&&(Ge=!1,rs(),V=!0);let j=id();if(!V&&j!==bi&&(rs(),V=!0),bi=j,V&&nd(),!ge&&!s){we.style.height="",we.style.width="";return}if(!l&&!s){let J=n?.launcher?.width??n?.launcherWidth??Vo;we.style.width=J,we.style.maxWidth=J}ad(),ey()}finally{if(os(),Yl(),Li(),he&&ge){let j=(e.ownerDocument.defaultView??window).innerWidth<=(n.launcher?.mobileBreakpoint??640),K=n.launcher?.sidebarMode??!1,J=n.launcher?.mobileFullscreen??!0,ae=St(n)&&J&&j,fe=K||J&&j&&ge||ae;if(fe&&!Ln){let Je=e.getRootNode(),lt=Je instanceof ShadowRoot?Je.host:e.closest(".persona-host");lt&&!Pn&&(Pn=hg(lt,n.launcher?.zIndex??so)),Ln=yg(e.ownerDocument)}else fe||(Pn?.(),Pn=null,Ln?.(),Ln=null)}}};Ki();let ec=e.ownerDocument.defaultView??window;if(ec.addEventListener("resize",Ki),be.push(()=>ec.removeEventListener("resize",Ki)),typeof ResizeObserver<"u"){Is=new ResizeObserver(()=>{Yl()}),kb(),be.push(()=>{Is?.disconnect(),Is=null});let s=new ResizeObserver(()=>{Nd()});s.observe(ue),be.push(()=>s.disconnect())}ec.addEventListener("resize",Nd),be.push(()=>ec.removeEventListener("resize",Nd)),qo=re.scrollTop;let Ib=qn(re),Hb=()=>{let s=re.scrollTop,l=qn(re),f=l<Ib;if(Ib=l,!br()){qo=s,jt();return}let{action:g,nextLastScrollTop:v}=JC({following:Uo.isFollowing(),currentScrollTop:s,lastScrollTop:qo,nearBottom:qs(re,Xn),userScrollThreshold:gA,isAutoScrolling:Po||dd||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(qo=v,g==="resume"){yd()||Lo();return}g==="pause"&&Ai()};if(re.addEventListener("scroll",Hb,{passive:!0}),be.push(()=>re.removeEventListener("scroll",Hb)),typeof ResizeObserver<"u"){let s=new ResizeObserver(()=>{TA(),Pf(Le)});s.observe(Le),s.observe(re),be.push(()=>s.disconnect())}let Rb=()=>{br()&&Uo.isFollowing()&&yd()&&Ai()},Wb=re.ownerDocument;Wb.addEventListener("selectionchange",Rb),be.push(()=>{Wb.removeEventListener("selectionchange",Rb)});let eT=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Bb=s=>{eT.has(s.key)&&(hs(),Ch()&&br()&&Uo.isFollowing()&&Ai())},Ob=s=>{s.target?.closest("a, button, [tabindex], input, textarea, select")&&(hs(),Ch()&&br()&&Uo.isFollowing()&&Ai())};re.addEventListener("keydown",Bb),re.addEventListener("focusin",Ob),be.push(()=>{re.removeEventListener("keydown",Bb),re.removeEventListener("focusin",Ob)});let Db=s=>{if(s.deltaY!==0&&hs(),!br())return;let l=ZC({following:Uo.isFollowing(),deltaY:s.deltaY,nearBottom:qs(re,Xn),resumeWhenNearBottom:!0});l==="pause"?Ai():l==="resume"&&!yd()&&Lo()};re.addEventListener("wheel",Db,{passive:!0}),re.addEventListener("touchmove",hs,{passive:!0}),re.addEventListener("pointerdown",hs,{passive:!0}),be.push(()=>{re.removeEventListener("touchmove",hs),re.removeEventListener("pointerdown",hs)}),be.push(()=>re.removeEventListener("wheel",Db)),Ot.addEventListener("click",()=>{hn(),re.scrollTop=re.scrollHeight,qo=re.scrollTop,Lo(),Tr(!0),jt()}),be.push(()=>Ot.remove()),be.push(()=>{Cy(),hn()});let _b=()=>{Fe&&(ls&&(Fe.removeEventListener("click",ls),ls=null),De()?(Fe.style.display="",ls=()=>{dt(!1,"user")},Fe.addEventListener("click",ls)):Fe.style.display="none")};_b(),(()=>{let{clearChatButton:s}=_e;s&&s.addEventListener("click",()=>{if(In()){af({focusComposer:!0}).catch(f=>{n.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}H.clearMessages(),Dt.clear(),Lo(),Ur(_e.composerOverlay);try{localStorage.removeItem(ai),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ai}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ai)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),F?.clear&&fd(()=>F.clear(),"[AgentWidget] Failed to clear storage adapter:"),X={},Pe.syncFromMetadata(),Ze?.clearAttachments(),gd(),ta(void 0),Mn(void 0),ps(),Tt?.clear(),ut?.reset(),B?.update()})})();let Nb=[["keydown",zM],["input",$M],["input",An],["input",ns],["keyup",ns],["paste",VM],["focus",nA]],Fb=s=>{if(s)for(let[l,f]of Nb)ot?.addListener(s,l,f)},tT=s=>{if(s)for(let[l,f]of Nb)ot?.removeListener(s,l,f)},Ub=()=>{ot&&(ot.addListener(ot.form,"submit",NM),ot.addListener(ot.footer,"click",ns),Fb(le),se&&ot.addListener(se,"click",Cf))};Ub();let qb=()=>{Wt?.onComposerSwap((s,l)=>{tT(l),le=s,ot&&(ot.input=s),Fb(s),np(),Ap(),An()})};qb();let Sf=!1;function $b(){if(!Sf){Sf=!0;try{let s=le?.value??"",l=Ie.ownerDocument??document,f=le?l.activeElement===le:!1;bf(),ot?.destroy(),ot=null,Wt?.destroy(),Wt=null;let g=null,v=()=>(g=Ae()?vu({config:n}):Ks({config:n}),g.footer),M=Ih(v)??v();Oo.replaceComposer(M),Ie=Oo.composer.footer;let N=g!==null&&M===g.footer;na=!N,xh=N?g.setSendButtonMode:()=>{},kh(Ie),Rh(Ie),Wh(),Bh(),Oh(),qb(),Dh(),rp(),_h(),Ub();let V=is.indexOf(Gn);Gn.destroy(),Gn=Bl(hr),V>=0&&(is[V]=Gn),le&&(le.value=s),An(),ns(),wd(),ia(),ki(H.isStreaming()),ze.active&&ks("recording"),rs(),kb(),os(),pn(),Cd(),f&&le?.focus()}finally{Sf=!1}}}let Gi=e.ownerDocument??document;Gi.addEventListener("keydown",Mb,!0);let jb=()=>{hp()},zb=()=>{Gi.visibilityState==="hidden"&&hp()};typeof window<"u"&&(window.addEventListener("pagehide",jb),Gi.addEventListener("visibilitychange",zb),be.push(()=>{window.removeEventListener("pagehide",jb),Gi.removeEventListener("visibilitychange",zb)}));let Vb="persona-attachment-drop-active",Xi=0,wf=()=>{Xi=0,ue.classList.remove(Vb)},Ea=()=>n.attachments?.enabled===!0&&Ze!==null&&!Pr(),Kb=s=>{!qu(s.dataTransfer)||!Ea()||(Xi++,Xi===1&&ue.classList.add(Vb))},Gb=s=>{!qu(s.dataTransfer)||!Ea()||(Xi--,Xi<=0&&wf())},Xb=s=>{!qu(s.dataTransfer)||!Ea()||(s.preventDefault(),s.dataTransfer.dropEffect="copy")},Qb=s=>{if(!qu(s.dataTransfer)||!Ea())return;s.preventDefault(),s.stopPropagation(),wf();let l=Array.from(s.dataTransfer.files??[]);l.length!==0&&Ze.handleFiles(l)},Rr=!0;ue.addEventListener("dragenter",Kb,Rr),ue.addEventListener("dragleave",Gb,Rr),e.addEventListener("dragover",Xb,Rr),e.addEventListener("drop",Qb,Rr);let tc=e.ownerDocument,Yb=s=>{Ea()&&s.preventDefault()},Jb=s=>{Ea()&&s.preventDefault()};tc.addEventListener("dragover",Yb),tc.addEventListener("drop",Jb),be.push(()=>{ot?.destroy(),ot=null,bf(),Tn?.destroy(),Tn=null,Vn?.destroy(),Vn=null,xr?.destroy(),xr=null,Cr?.destroy(),Cr=null,vr=null,Zu=null,hp(),wi.destroy(),wa&&clearTimeout(wa),ps(),Ls?.abort(),Ls=null,Ze?.destroy(),Ze=null,Ce.destroy(),Gi.removeEventListener("keydown",Mb,!0),Wt?.destroy()}),be.push(()=>{ue.removeEventListener("dragenter",Kb,Rr),ue.removeEventListener("dragleave",Gb,Rr),e.removeEventListener("dragover",Xb,Rr),e.removeEventListener("drop",Qb,Rr),tc.removeEventListener("dragover",Yb),tc.removeEventListener("drop",Jb),wf()}),be.push(()=>{H.cancel()}),Pt?be.push(()=>{Pt?.destroy()}):go&&be.push(()=>{go?.remove()});let Lt={update(s){let l=n.toolCall,f=n.messageActions,g=n.layout?.messages,v=n.colorScheme,M=n.loadingIndicator,N=n.iterationDisplay,V=n.features?.showReasoning,j=n.features?.showToolCalls,K=n.features?.toolCallDisplay,J=n.features?.reasoningDisplay,ae=n.features?.streamAnimation?.type,fe=n.features?.history?.enabled===!0,Je=n.features?.history?.provider,lt=n.getIdentityProof,ct=n.clientToken,Qt=n.contextMentions;n=Wu({...n,features:a},s),a=n.features,n=Nl(n),r(),cp(),Us(e,n),Dl(e,n),_l(e,n),ht(),mn(),n.colorScheme!==v&&ty();let Nt=Fl.getForInstance(n.plugins);i.length=0,i.push(...Nt),Zy(),ge=n.launcher?.enabled??!0,Ke=n.launcher?.autoExpand??!1,Xo=n.features?.showReasoning??!0,jn=n.features?.showToolCalls??!0,Yr=n.features?.scrollToBottom??{};let kt=No();Ao=n.features?.scrollBehavior??{},kt!==No()&&(hn(),Lo()),gy(),Ah(),jt();let io=Ht;if(Ht=n.features?.showEventStreamToggle??!1,Ht&&!io){if(Tt||(ee(),H.setSSEEventCallback((Z,Ve)=>{n.onSSEEvent?.(Z,Ve),$(Z,Ve)})),!tt&&Te){let Z=n.features?.eventStream?.classNames,Ve="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"+(Z?.toggleButton?" "+Z.toggleButton:"");tt=I("button",Ve),tt.style.width="28px",tt.style.height="28px",tt.style.color=Co.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let Qe=Ft(_a,"18px","currentColor",1.5);Qe&&tt.appendChild(Qe);let nt=_e.clearChatButtonWrapper,Ct=_e.closeButtonWrapper,no=nt||Ct;no&&no.parentNode===Te?Te.insertBefore(tt,no):Te.appendChild(tt),tt.addEventListener("click",()=>{te?oa():op()})}}else!Ht&&io&&(oa(),tt&&(tt.remove(),tt=null),Tt?.clear(),po?.destroy(),Tt=null,po=null,ut?.reset(),ut=null,cn=null);if(n.launcher?.enabled===!1&&Pt&&(Pt.destroy(),Pt=null),n.launcher?.enabled===!1&&go&&(go.remove(),go=null),n.launcher?.enabled!==!1&&!Pt&&!go){let{instance:Z,element:Ve}=Ng({config:n,plugins:i,onToggle:Lb});Pt=Z,Z||(go=Ve),e.appendChild(Ve)}Pt&&Pt.update(n),ji(),es&&n.launcher?.subtitle!==void 0&&(es.textContent=n.launcher.subtitle);let et=n.layout?.header;if(et?.layout!==Ue&&Te){let Z=et?Qa(n,et,{showClose:De(),onClose:()=>dt(!1,"user")}):pr({config:n,showClose:De(),onClose:()=>dt(!1,"user")});Oo.replaceHeader(Z),Te=Oo.header.element,Et=Oo.header.iconHolder,yr=Oo.header.headerTitle,es=Oo.header.headerSubtitle,Fe=Oo.header.closeButton,Ue=et?.layout,ji()}else if(et){if(Et&&(Et.style.display=et.showIcon===!1?"none":""),yr&&(yr.style.display=et.showTitle===!1?"none":""),es&&(es.style.display=et.showSubtitle===!1?"none":""),Fe){let Z=De()&&et.showCloseButton!==!1;Fe.style.display=Z?"":"none"}if(_e.clearChatButtonWrapper){let Z=et.showClearChat;if(Z!==void 0){_e.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:Ve}=_e;Ve&&!Ve.classList.contains("persona-absolute")&&(Z?Ve.classList.remove("persona-ml-auto"):Ve.classList.add("persona-ml-auto"))}}}let ar=n.layout?.showHeader!==!1;Te&&(Te.style.display=ar?"":"none");let Rn=n.layout?.showFooter!==!1;Ie&&(Ie.style.display=Rn?"":"none"),os(),jt(),ge!==z?ge?dt(Ke,"auto"):(he=!0,Li()):Ke!==ke&&dt(Ke,"auto"),ke=Ke,z=ge,Ki(),_b();let We=JSON.stringify(n.toolCall)!==JSON.stringify(l),Oe=JSON.stringify(n.messageActions)!==JSON.stringify(f),me=JSON.stringify(n.layout?.messages)!==JSON.stringify(g),pt=n.loadingIndicator?.render!==M?.render||n.loadingIndicator?.renderIdle!==M?.renderIdle||n.loadingIndicator?.showBubble!==M?.showBubble,zt=n.iterationDisplay!==N,co=(n.features?.showReasoning??!0)!==(V??!0)||(n.features?.showToolCalls??!0)!==(j??!0)||JSON.stringify(n.features?.toolCallDisplay)!==JSON.stringify(K)||JSON.stringify(n.features?.reasoningDisplay)!==JSON.stringify(J);(We||Oe||me||pt||zt||co)&&H&&(fs++,Jo(Le,H.getMessages(),oo));let It=n.features?.streamAnimation?.type;if(It!==ae&&It&&It!=="none"){let Z=pp(It,n.features?.streamAnimation?.plugins);Z&&Hl(Z,e)}let Ee=n.launcher??{},Vt=Ee.headerIconHidden??!1,Kt=n.layout?.header?.showIcon,rn=Vt||Kt===!1,He=Ee.headerIconName,xt=Ee.headerIconSize??"48px";if(Et){let Z=Te,Ve=Z?.querySelector(".persona-flex-col");if(rn)Et.style.display="none",Z&&Ve&&!Z.contains(Ve)&&Z.insertBefore(Ve,Z.firstChild);else{if(Et.style.display="",Et.style.height=xt,Et.style.width=xt,Z&&Ve&&(Z.contains(Et)?Et.nextSibling!==Ve&&(Et.remove(),Z.insertBefore(Et,Ve)):Z.insertBefore(Et,Ve)),He){let nt=parseFloat(xt)||24,Ct=ce(He,nt*.6,"currentColor",1);Ct?Et.replaceChildren(Ct):Et.textContent=Ee.agentIconText??"\u{1F4AC}"}else if(Ee.iconUrl){let nt=Et.querySelector("img");if(nt)nt.src=Ee.iconUrl,nt.style.height=xt,nt.style.width=xt;else{let Ct=document.createElement("img");Ct.src=Ee.iconUrl,Ct.alt="",Ct.className="persona-rounded-xl persona-object-cover",Ct.style.height=xt,Ct.style.width=xt,Et.replaceChildren(Ct)}}else{let nt=Et.querySelector("svg"),Ct=Et.querySelector("img");(nt||Ct)&&Et.replaceChildren(),Et.textContent=Ee.agentIconText??"\u{1F4AC}"}let Qe=Et.querySelector("img");Qe&&(Qe.style.height=xt,Qe.style.width=xt)}}let Bn=n.layout?.header?.showTitle,yn=n.layout?.header?.showSubtitle;if(yr&&(yr.style.display=Bn===!1?"none":""),es&&(es.style.display=yn===!1?"none":""),Fe){let Z=De()&&n.layout?.header?.showCloseButton!==!1;if(Fe.style.display=Z?"":"none",!Ae()){let Yt=Ee.closeButtonSize??"";Fe.style.height=Yt,Fe.style.width=Yt,Fe.style.minWidth=Yt,Fe.style.minHeight=Yt}let Ve=Ee.closeButtonPlacement??"inline",{closeButtonWrapper:Qe}=_e,nt=Ve==="top-right",Ct=Qe?.classList.contains("persona-absolute");if(Qe&&nt!==Ct)if(Qe.remove(),nt){Qe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Yt=Oi??ue;Yt.style.position="relative",Yt.appendChild(Qe)}else{let Yt=Ee.clearChat?.placement??"inline",Jt=Ee.clearChat?.enabled??!0;Qe.className=Jt&&Yt==="inline"?"":"persona-ml-auto",Te&&Te.appendChild(Qe)}if(Fe.style.color=Ee.closeButtonColor||Co.actionIconColor,Ee.closeButtonBackgroundColor?(Fe.style.backgroundColor=Ee.closeButtonBackgroundColor,Fe.classList.remove("hover:persona-bg-gray-100")):(Fe.style.backgroundColor="",Fe.classList.add("hover:persona-bg-gray-100")),Ee.closeButtonBorderWidth||Ee.closeButtonBorderColor){let Yt=Ee.closeButtonBorderWidth||"0px",Jt=Ee.closeButtonBorderColor||"transparent";Fe.style.border=`${Yt} solid ${Jt}`,Fe.classList.remove("persona-border-none")}else Fe.style.border="",Fe.classList.add("persona-border-none");Ee.closeButtonBorderRadius?(Fe.style.borderRadius=Ee.closeButtonBorderRadius,Fe.classList.remove("persona-rounded-full")):(Fe.style.borderRadius="",Fe.classList.add("persona-rounded-full")),Ee.closeButtonPaddingX?(Fe.style.paddingLeft=Ee.closeButtonPaddingX,Fe.style.paddingRight=Ee.closeButtonPaddingX):(Fe.style.paddingLeft="",Fe.style.paddingRight=""),Ee.closeButtonPaddingY?(Fe.style.paddingTop=Ee.closeButtonPaddingY,Fe.style.paddingBottom=Ee.closeButtonPaddingY):(Fe.style.paddingTop="",Fe.style.paddingBottom=""),hu(Fe,Ee.closeButtonIconName??"x",{iconSize:Ae()?Bg:void 0,iconText:Ee.closeButtonIconText??"\xD7"});let no=Ee.closeButtonTooltipText??"Close chat",bn=Ee.closeButtonShowTooltip??!0;Fe.setAttribute("aria-label",no),Qe&&eo({anchor:Fe,trigger:Qe,text:()=>Fe?.getAttribute("aria-label")??no,enabled:bn})}let{clearChatButton:Be,clearChatButtonWrapper:ve}=_e;if(Be){let Z=Ee.clearChat??{},Ve=Z.enabled??!0,Qe=n.layout?.header?.showClearChat,nt=Qe!==void 0?Qe:Ve,Ct=Z.placement??"inline";if(ve){ve.style.display=nt?"":"none";let{closeButtonWrapper:no}=_e;!Ae()&&no&&!no.classList.contains("persona-absolute")&&(nt?no.classList.remove("persona-ml-auto"):no.classList.add("persona-ml-auto"));let bn=Ct==="top-right",Yt=ve.classList.contains("persona-absolute");if(!Ae()&&bn!==Yt&&nt){if(ve.remove(),bn){ve.className="persona-absolute persona-top-4 persona-z-50",ve.style.right="48px";let On=Oi??ue;On.style.position="relative",On.appendChild(ve)}else{ve.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ve.style.right="";let On=_e.closeButtonWrapper;Te&&On&&On.parentElement===Te?Te.insertBefore(ve,On):Te&&Te.appendChild(ve)}let Jt=_e.closeButtonWrapper;Jt&&!Jt.classList.contains("persona-absolute")&&(bn?Jt.classList.add("persona-ml-auto"):Jt.classList.remove("persona-ml-auto"))}}if(nt){if(!Ae()){let Jt=Z.size??"";Be.style.height=Jt,Be.style.width=Jt,Be.style.minWidth=Jt,Be.style.minHeight=Jt}let no=Z.iconColor??"";if(Be.style.color=no||Co.actionIconColor,hu(Be,Z.iconName??"refresh-cw",{iconSize:Ae()?Og:void 0}),Z.backgroundColor?(Be.style.backgroundColor=Z.backgroundColor,Be.classList.remove("hover:persona-bg-gray-100")):(Be.style.backgroundColor="",Be.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let Jt=Z.borderWidth||"0px",On=Z.borderColor||"transparent";Be.style.border=`${Jt} solid ${On}`,Be.classList.remove("persona-border-none")}else Be.style.border="",Be.classList.add("persona-border-none");Z.borderRadius?(Be.style.borderRadius=Z.borderRadius,Be.classList.remove("persona-rounded-full")):(Be.style.borderRadius="",Be.classList.add("persona-rounded-full")),Z.paddingX?(Be.style.paddingLeft=Z.paddingX,Be.style.paddingRight=Z.paddingX):(Be.style.paddingLeft="",Be.style.paddingRight=""),Z.paddingY?(Be.style.paddingTop=Z.paddingY,Be.style.paddingBottom=Z.paddingY):(Be.style.paddingTop="",Be.style.paddingBottom="");let bn=Z.tooltipText??"Clear chat",Yt=Z.showTooltip??!0;Be.setAttribute("aria-label",bn),ve&&eo({anchor:Be,trigger:ve,text:()=>Be?.getAttribute("aria-label")??bn,enabled:Yt})}}let Ne=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ul],ft=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Ys.message,Ys.messageAndClick];Pe=ql({parsers:Ne,handlers:ft,getSessionMetadata:Q,updateSessionMetadata:de,emit:x.emit,documentRef:typeof document<"u"?document:null}),oo=Cw(n,Pe,Js),jA(),H.updateConfig(n),(n.features?.history?.enabled===!0!==fe||n.features?.history?.provider!==Je||n.getIdentityProof!==lt||n.clientToken!==ct)&&(Io({restoreFocus:!1}),zy()),Ir(),Nd(),Jo(Le,H.getMessages(),oo),ia(),wd(),qA(),ki(H.isStreaming()),Qt!==n.contextMentions&&$b();let Wr=n.voiceRecognition?.enabled===!0,Gt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),zo=n.voiceRecognition?.provider?.type==="runtype";if(Wr&&(Gt||zo))if(!se||!_o){let Z=za(n);if(Z){se=Z.button,_o=Z.wrapper;let Ve=wn&&wn.parentElement===Vl?wn:null;Vl?Vl.insertBefore(_o,Ve):un?.appendChild(_o),ot&&(ot.micButton=se),ot?.addListener(se,"click",Cf),se.disabled=H.isStreaming()}}else{let Z=n.voiceRecognition??{},Ve=n.sendButton??{},Qe=Z.iconName??"mic",nt=Z.iconSize,Ct=parseFloat(nt??"")||vo;se.classList.add(Ko),se.classList.toggle(vn,!nt),se.style.width=nt??"",se.style.height=nt??"",se.style.minWidth=nt??"",se.style.minHeight=nt??"";let no=Z.iconColor??Ve.textColor;se.innerHTML="";let bn=ce(Qe,Ct,no||"currentColor",1.5);bn?se.appendChild(bn):se.textContent="\u{1F3A4}";let Yt=Z.backgroundColor??Ve.backgroundColor;Yt?se.style.backgroundColor=Yt:se.style.backgroundColor="",no?se.style.color=no:se.style.color="var(--persona-text, #111827)",Z.borderWidth?(se.style.borderWidth=Z.borderWidth,se.style.borderStyle="solid"):(se.style.borderWidth="",se.style.borderStyle=""),Z.borderColor?se.style.borderColor=Z.borderColor:se.style.borderColor="",Z.paddingX?(se.style.paddingLeft=Z.paddingX,se.style.paddingRight=Z.paddingX):(se.style.paddingLeft="",se.style.paddingRight=""),Z.paddingY?(se.style.paddingTop=Z.paddingY,se.style.paddingBottom=Z.paddingY):(se.style.paddingTop="",se.style.paddingBottom="");let Jt=Z.tooltipText??"Start voice recognition",On=Z.showTooltip??!1;se.setAttribute("aria-label",Jt),_o&&eo({anchor:se,trigger:_o,text:()=>se?.getAttribute("aria-label")??Jt,enabled:On}),_o.style.display="",se.disabled=H.isStreaming()}else se&&_o&&(_o.style.display="none",n.voiceRecognition?.provider?.type==="runtype"?H.isVoiceActive()&&H.toggleVoice():Hn&&Hr());if(n.attachments?.enabled===!0){if(!To||!At){let Z=n.attachments??{};Eo||(Eo=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Eo.style.display="none",(le.parentElement??un).insertBefore(Eo,le)),yt||(yt=document.createElement("input"),yt.type="file",yt.accept=(Z.allowedTypes??ur).join(","),yt.multiple=(Z.maxFiles??4)>1,yt.style.display="none",yt.setAttribute("aria-label","Attach files"),(le.parentElement??un).insertBefore(yt,le)),To=I("div","persona-send-button-wrapper"),At=I("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Ko} ${vn}`),At.type="button",At.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let Ve=Z.buttonIconName??"paperclip";At.style.fontSize="18px",At.style.lineHeight="1";let Qe=ce(Ve,vo,"currentColor",1.5);Qe?At.appendChild(Qe):At.textContent="\u{1F4CE}",At.addEventListener("click",Ct=>{Ct.preventDefault(),yt?.click()}),To.appendChild(At);let nt=Z.buttonTooltipText??"Attach file";eo({anchor:At,trigger:To,text:()=>At?.getAttribute("aria-label")??nt}),Ku?Ku.append(To):un.appendChild(To),ot&&(ot.attachmentButton=At,ot.attachmentInput=yt??void 0,ot.attachmentPreviews=Eo??void 0),!Ze&&yt&&Eo&&(Ze=Fs.fromConfig(Z,Mh),Ze.setPreviewsContainer(Eo),ot?.addListener(yt,"change",async()=>{Ze&&yt?.files&&(await Ze.handleFileSelect(yt.files),yt.value="")}))}else{To.style.display="";let Z=n.attachments??{};yt&&(yt.accept=(Z.allowedTypes??ur).join(","),yt.multiple=(Z.maxFiles??4)>1),Ze&&Ze.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles,adapter:Z.adapter})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(Sw(n.attachments?.dropOverlay)),At){let Z=n.attachments??{},Ve=Z.buttonTooltipText??"Attach file";At.setAttribute("aria-label",Ve),At.textContent="";let Qe=ce(Z.buttonIconName??"paperclip",vo,"currentColor",1.5);Qe?At.appendChild(Qe):At.textContent="\u{1F4CE}",To&&eo({anchor:At,trigger:To,text:()=>At?.getAttribute("aria-label")??Ve})}}else To&&(To.style.display="none"),Ze&&Ze.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Mt=n.sendButton??{},Af=Mt.useIcon??!1,Rs=Mt.iconText??"\u2191",oc=Mt.iconName,ev=Mt.tooltipText??"Send message",rT=Mt.showTooltip??!1,Qi=Mt.size,sT=parseFloat(Qi??"")||Vm,nc=Mt.backgroundColor,Yi=Mt.textColor;if(Af){if(Me.style.width=Qi??"",Me.style.height=Qi??"",Me.style.minWidth=Qi??"",Me.style.minHeight=Qi??"",Me.style.fontSize="18px",Me.style.lineHeight="1",Yi?Me.style.color=Yi:Me.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!H.isStreaming())if(Me.innerHTML="",oc){let Z=parseFloat(Mt.iconSize??"")||Math.round(sT*.5),Ve=Yi?.trim()||"currentColor",Qe=Mt.iconStrokeWidth??2,nt=ce(oc,Z,Ve,Qe),Ct=ce(Mt.stopIconName??"square",Z,Ve,Qe);nt&&Ct?Me.appendChild(Km(nt,Ct)):nt?Me.appendChild(nt):Me.textContent=Rs}else Me.textContent=Rs;Me.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Ko}`,nc?(Me.style.backgroundColor=nc,Me.classList.remove("persona-bg-persona-primary")):(Me.style.backgroundColor="",Me.classList.add("persona-bg-persona-primary"))}else Me.textContent=n.copy?.sendButtonLabel??"Send",Me.style.width="",Me.style.height="",Me.style.minWidth="",Me.style.minHeight="",Me.style.fontSize="",Me.style.lineHeight="",Me.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",nc?(Me.style.backgroundColor=nc,Me.classList.remove("persona-bg-persona-accent")):Me.classList.add("persona-bg-persona-accent"),Yi?Me.style.color=Yi:Me.classList.add("persona-text-white");Mt.borderWidth?(Me.style.borderWidth=Mt.borderWidth,Me.style.borderStyle="solid"):(Me.style.borderWidth="",Me.style.borderStyle=""),Mt.borderColor?Me.style.borderColor=Mt.borderColor:Me.style.borderColor="",Mt.paddingX?(Me.style.paddingLeft=Mt.paddingX,Me.style.paddingRight=Mt.paddingX):(Me.style.paddingLeft="",Me.style.paddingRight=""),Mt.paddingY?(Me.style.paddingTop=Mt.paddingY,Me.style.paddingBottom=Mt.paddingY):(Me.style.paddingTop="",Me.style.paddingBottom=""),H.isStreaming()||Me.setAttribute("aria-label",ev),Cd(),wn&&eo({anchor:Me,trigger:wn,text:()=>Me.getAttribute("aria-label")??ev,enabled:rT}),Fh();let tv=ou(Ce.getState().activeModeIds,n.composer?.modes);Ce.setActiveModeIds(tv),Zs().length>0!==!!Vn&&rp(),Vn?.render(tv,Zs());for(let Z of[...ea.keys()])tu(Z,n.composer?.modeGroups)||ea.delete(Z);ea.forEach(Z=>Z.repaint()),vr?.repaint(),Tn?.resolve();let rc=Kr(n,Ae());if(up(),rc){Le.style.maxWidth=rc,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%",Do.style.maxWidth=rc,Do.style.marginLeft="auto",Do.style.marginRight="auto",Do.style.width="100%";for(let Z of[un,hr,Eo,st])Z&&(Z.style.maxWidth=rc,Z.style.marginLeft="auto",Z.style.marginRight="auto",Z.style.width="100%")}else{Le.style.maxWidth="",Le.style.marginLeft="",Le.style.marginRight="",Le.style.width="",Do.style.maxWidth="",Do.style.marginLeft="",Do.style.marginRight="",Do.style.width="";for(let Z of[un,hr,Eo,st])Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight="",Z.style.width="")}let Br=n.statusIndicator??{},aT=Br.visible??!0;if(st.style.display=aT?"":"none",H){let Z=H.getStatus();ao(st,(Qe=>Qe==="idle"?Br.idleText??Ut.idle:Qe==="connecting"?Br.connectingText??Ut.connecting:Qe==="connected"?Br.connectedText??Ut.connected:Qe==="error"?Br.errorText??Ut.error:Ut[Qe])(Z),Br,Z)}st.classList.remove("persona-text-left","persona-text-center","persona-text-right");let iT=Br.align==="left"?"persona-text-left":Br.align==="center"?"persona-text-center":"persona-text-right";st.classList.add(iT),np(),Ap(),pn(),Se()},open(){De()&&dt(!0,"api")},close(){De()&&dt(!1,"api")},toggle(){De()&&dt(!he,"api")},reconnect(){H.reconnectNow()},clearChat(){Kn=!1,H.clearMessages(),Dt.clear(),Lo();try{localStorage.removeItem(ai),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ai}`)}catch(l){console.error("[AgentWidget] Failed to clear default localStorage:",l)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ai)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(l){console.error("[AgentWidget] Failed to clear custom localStorage:",l)}let s=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(s),F?.clear&&fd(()=>F.clear(),"[AgentWidget] Failed to clear storage adapter:"),X={},Pe.syncFromMetadata(),Ze?.clearAttachments(),gd(),ta(void 0),Mn(void 0),ps(),Tt?.clear(),ut?.reset(),B?.update()},setMessage(s){return!le||H.isStreaming()||Pr()?!1:(!he&&De()&&dt(!0,"system"),le.value=s,le.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(s){if(H.isStreaming()||vs())return!1;let l=s?.trim()||le.value.trim();return l?(!he&&De()&&dt(!0,"system"),le.value="",le.style.height="auto",An(),Qd(l,{consumeDraft:!1}),!0):!1},getComposerState(){return Ce.getState()},setQuote(s){let l=s?.text?.trim();l&&Mn({...s,text:l})},clearQuote(){Mn(void 0)},startVoiceRecognition(){return H.isStreaming()?!1:n.voiceRecognition?.provider?.type==="runtype"?(H.isVoiceActive()||(!he&&De()&&dt(!0,"system"),ze.manuallyDeactivated=!1,gn(),H.toggleVoice().then(()=>{ze.active=H.isVoiceActive(),Yn("user"),H.isVoiceActive()&&Ta()})),!0):Hn?!0:Pb()?(!he&&De()&&dt(!0,"system"),ze.manuallyDeactivated=!1,gn(),Jd("user"),!0):!1},stopVoiceRecognition(){return n.voiceRecognition?.provider?.type==="runtype"?H.isVoiceActive()?(H.toggleVoice().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,gn(),Yn("user"),sr()}),!0):!1:Hn?(ze.manuallyDeactivated=!0,gn(),Hr("user"),!0):!1},injectMessage(s){return!he&&De()&&dt(!0,"system"),H.injectMessage(s)},injectAssistantMessage(s){!he&&De()&&dt(!0,"system");let l=H.injectAssistantMessage(s);return gt&&(gt=!1,dn&&(clearTimeout(dn),dn=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),l},injectUserMessage(s){return!he&&De()&&dt(!0,"system"),H.injectUserMessage(s)},injectSystemMessage(s){return!he&&De()&&dt(!0,"system"),H.injectSystemMessage(s)},injectMessageBatch(s){return!he&&De()&&dt(!0,"system"),H.injectMessageBatch(s)},injectComponentDirective(s){return!he&&De()&&dt(!0,"system"),H.injectComponentDirective(s)},injectTestMessage(s){!he&&De()&&dt(!0,"system"),H.injectTestEvent(s)},async connectStream(s,l){return H.connectStream(s,l)},__pushEventStreamEvent(s){Ht&&(ee(),$(s.type,s.payload))},showEventStream(){Ht&&op()},hideEventStream(){te&&oa()},isEventStreamVisible(){return te},listConversations(s){return H.listConversations(s)},getActiveConversationId(){return H.getActiveConversationId()},openConversation(s,l){return sf(s,{focusComposer:l?.focus===!0})},startNewConversation(s){return af({focusComposer:s?.focus===!0})},deleteConversation(s){return yb(s)},renameConversation(s,l){return lf(s,{title:l})},setConversationStarred(s,l){return lf(s,{starred:l})},clearConversationHistory(s){return bb(s)},resetHistoryIdentity(){return vb()},getHistoryIdentityStatus(){return $o?$o.getIdentityStatus():qp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(s){return $i({...s?.returnSurface?{returnSurface:s.returnSurface}:{},...s?.focus!==void 0?{focus:s.focus}:{}})},hideHistory(s){Io(s?.restoreFocus!==void 0?{restoreFocus:s.restoreFocus}:void 0)},isHistoryVisible(){return ne},showArtifacts(){wo(n)&&(Kn=!1,ra=!0,mn(),je?.setMobileOpen(!0))},hideArtifacts(){wo(n)&&(Kn=!0,mn())},upsertArtifact(s){return wo(n)?(_n(n.features?.artifacts,{artifactType:s.artifactType,...s.artifactType==="markdown"&&s.file?{file:s.file}:{},...s.presentation?{presentation:s.presentation}:{}})==="panel"&&(Kn=!1,ra=!0),H.upsertArtifact(s)):null},selectArtifact(s){wo(n)&&H.selectArtifact(s)},clearArtifacts(){wo(n)&&H.clearArtifacts()},getArtifacts(){return H?.getArtifacts()??[]},getSelectedArtifactId(){return H?.getSelectedArtifactId()??null},focusInput(){return ge&&!he&&!Ae()||!le?!1:(le.focus(),!0)},async resolveApproval(s,l,f){let v=H.getMessages().find(M=>M.variant==="approval"&&M.approval?.id===s);if(!v?.approval)throw new Error(`Approval not found: ${s}`);if(v.approval.toolType==="webmcp"){H.resolveWebMcpApproval(v.id,l);return}return H.resolveApproval(v.approval,l,f)},setFollowUpSuggestions(s){fA(s)},clearFollowUpSuggestions(){my()},getMessages(){return H.getMessages()},getStatus(){return H.getStatus()},getPersistentMetadata(){return{...X}},updatePersistentMetadata(s){de(s)},on(s,l){return x.on(s,l)},off(s,l){x.off(s,l)},isOpen(){return De()&&he},isVoiceActive(){return ze.active},toggleReadAloud(s){H.toggleReadAloud(s)},stopReadAloud(){H.stopSpeaking()},getReadAloudState(s){return H.getReadAloudState(s)},onReadAloudChange(s){return H.onReadAloudChange(s)},getState(){return{open:De()&&he,launcherEnabled:ge,voiceActive:ze.active,streaming:H.isStreaming()}},showCSATFeedback(s){!he&&De()&&dt(!0,"system");let l=Le.querySelector(".persona-feedback-container");l&&l.remove();let f=Fu({onSubmit:async(g,v)=>{H.isClientTokenMode()&&await H.submitCSATFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});Le.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(s){!he&&De()&&dt(!0,"system");let l=Le.querySelector(".persona-feedback-container");l&&l.remove();let f=Uu({onSubmit:async(g,v)=>{H.isClientTokenMode()&&await H.submitNPSFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});Le.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(s,l){return H.submitCSATFeedback(s,l)},async submitNPSFeedback(s,l){return H.submitNPSFeedback(s,l)},destroy(){Bp(),ws!=null&&(clearInterval(ws),ws=null),be.forEach(s=>s()),Xe.remove(),Xt?.remove(),Pt?.destroy(),go?.remove(),ls&&Fe.removeEventListener("click",ls)}};if(((o?.debugTools??!1)||!!n.debug)&&typeof window<"u"){let s=window.AgentWidgetBrowser,l={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:f=>f?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=l,be.push(()=>{window.AgentWidgetBrowser===l&&(window.AgentWidgetBrowser=s)})}if(typeof window<"u"){let s=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),l=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",l),be.push(()=>{window.removeEventListener("persona:focusInput",l)}),Ht){let K=ae=>{let fe=ae.detail;(!fe?.instanceId||fe.instanceId===s)&&Lt.showEventStream()},J=ae=>{let fe=ae.detail;(!fe?.instanceId||fe.instanceId===s)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",K),window.addEventListener("persona:hideEventStream",J),be.push(()=>{window.removeEventListener("persona:showEventStream",K),window.removeEventListener("persona:hideEventStream",J)})}let f=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&Lt.showHistory()},g=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&Lt.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",g),be.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",g)});let v=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&Lt.showArtifacts()},M=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&Lt.hideArtifacts()},N=K=>{let J=K.detail;J?.instanceId&&J.instanceId!==s||J?.artifact&&Lt.upsertArtifact(J.artifact)},V=K=>{let J=K.detail;J?.instanceId&&J.instanceId!==s||typeof J?.id=="string"&&Lt.selectArtifact(J.id)},j=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&Lt.clearArtifacts()};window.addEventListener("persona:showArtifacts",v),window.addEventListener("persona:hideArtifacts",M),window.addEventListener("persona:upsertArtifact",N),window.addEventListener("persona:selectArtifact",V),window.addEventListener("persona:clearArtifacts",j),be.push(()=>{window.removeEventListener("persona:showArtifacts",v),window.removeEventListener("persona:hideArtifacts",M),window.removeEventListener("persona:upsertArtifact",N),window.removeEventListener("persona:selectArtifact",V),window.removeEventListener("persona:clearArtifacts",j)})}let nn=qk(n.persistState);if(nn&&De()){let s=$k(nn.storage),l=`${nn.keyPrefix}widget-open`,f=`${nn.keyPrefix}widget-voice`,g=`${nn.keyPrefix}widget-voice-mode`;if(s){let v=nn.persist?.openState&&s.getItem(l)==="true",M=nn.persist?.voiceState&&s.getItem(f)==="true",N=nn.persist?.voiceState&&s.getItem(g)==="true";if(v&&(Pt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Lt.open(),setTimeout(()=>{if(M||N)Lt.startVoiceRecognition();else if(nn.persist?.focusInput){let V=e.querySelector("textarea");V&&V.focus()}},100)},0)),nn.persist?.openState&&(x.on("widget:opened",()=>{s.setItem(l,"true")}),x.on("widget:closed",()=>{s.setItem(l,"false")})),nn.persist?.voiceState&&(x.on("voice:state",V=>{s.setItem(f,V.active?"true":"false")}),x.on("user:message",V=>{s.setItem(g,V.viaVoice?"true":"false")})),nn.clearOnChatClear){let V=()=>{s.removeItem(l),s.removeItem(f),s.removeItem(g)},j=()=>V();window.addEventListener("persona:clear-chat",j),be.push(()=>{window.removeEventListener("persona:clear-chat",j)})}}}if(W&&De()&&(Pt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Lt.open()},0)),fa(),!mA){let s=Pa(()=>{H&&(fs++,Dt.clear(),Jo(Le,H.getMessages(),oo))});be.push(s)}A=()=>{H&&(fs++,Dt.clear(),Jo(Le,H.getMessages(),oo))},H.getMessages().length>0&&xd(),b=()=>{H&&(fs++,Dt.clear(),Jo(Le,H.getMessages(),oo))};let oT=kx(()=>{H&&(fs++,Dt.clear(),Jo(Le,H.getMessages(),oo))});be.push(oT);let nT=Kg(()=>{H&&(fs++,Dt.clear(),Jo(Le,H.getMessages(),oo),fr()?.updateInlineArtifactBlocks(Le,Yo.artifacts,{suppressTransition:!0}),mn())});return be.push(nT),Lt};var ww=(e,t)=>{let o=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(o);if(n)return Math.max(0,parseFloat(n[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(o);return r?Math.max(0,t*parseFloat(r[1])/100):420},Vk=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Kk=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Gk=(e,t)=>{let o=e.parentElement;if(!o)return;let n=e.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",o.appendChild(n);let r=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),!(!r||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.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 ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Aw=(e,t)=>{let o=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=o?"":"100%",e.style.display=o?"":"flex",e.style.flexDirection=o?"":"column",e.style.flex=o?"":"1 1 auto",e.style.minHeight=o?"":"0",e.style.minWidth=o?"":"0"},ch=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Mw=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",ch(e)},ih=e=>{e.style.transition=""},lh=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},dh=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ju=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Xk=(e,t,o,n,r)=>{r?o.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(o,n),e.appendChild(t)):o.parentElement===t&&(t.replaceChildren(),e.appendChild(o),e.appendChild(n))},Qk=(e,t,o,n,r,a)=>{let i=a?t:e;r==="left"?i.firstElementChild!==n&&i.replaceChildren(n,o):i.lastElementChild!==n&&i.replaceChildren(o,n)},Yk=e=>{let t=Vr(e),o=t.components?.panel,n=(r,a)=>r==null||r===""?a:xo(t,r)??r;return{inset:n(o?.inset,nu),canvasBackground:n(o?.canvasBackground,ru)}},Tw=(e,t,o,n)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=o,e.style.background=n},Jk=(e,t,o,n,r,a,i,d)=>{let u=Wo(a),c=u.reveal==="push",p=d!=null,m=d?.inset??"",y=d?.canvasBackground??"";Xk(e,t,o,n,c),Qk(e,t,o,n,u.side,c),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=u.side,e.dataset.personaDockOpen=i?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",o.style.display="flex",o.style.flexDirection="column",o.style.minHeight="0",o.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=e.ownerDocument.defaultView,S=a?.launcher?.mobileFullscreen??!0,A=a?.launcher?.mobileBreakpoint??640,T=h!=null?h.innerWidth<=A:!1;if(S&&T&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),lh(t),ih(n),Mw(n),dh(o),ju(r,n),Tw(n,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",o.style.flex="1 1 auto",o.style.width="100%",o.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String(a?.launcher?.zIndex??so),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",c&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",o.style.flex="1 1 auto",o.style.width="100%",o.style.maxWidth="100%",o.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Mw(n),Vk(n,u.maxHeight),Tw(n,p&&i,m,y),u.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",lh(t),ih(n),dh(o),ju(r,n);let P=u.animate?"transform 180ms ease":"none",R=u.side==="right"?"translateX(100%)":"translateX(-100%)",b=i?"translateX(0)":R;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=u.width,n.style.maxWidth=u.width,n.style.minWidth=u.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=P,n.style.transform=b,n.style.pointerEvents=i?"auto":"none",n.style.zIndex="2",u.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(u.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",ih(n),ch(n),ju(r,n);let P=ww(u.width,e.clientWidth),R=Math.max(0,e.clientWidth),b=u.animate?"margin-left 180ms ease":"none",w=u.side==="right"?i?-P:0:i?0:-P;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${R+P}px`,t.style.transition=b,t.style.marginLeft=`${w}px`,t.style.transform="",o.style.flex="0 0 auto",o.style.flexGrow="0",o.style.flexShrink="0",o.style.width=`${R}px`,o.style.maxWidth=`${R}px`,o.style.minWidth=`${R}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=u.width,n.style.minWidth=u.width,n.style.maxWidth=u.width,n.style.position="relative",n.style.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",lh(t),ch(n),dh(o),ju(r,n);let P=u.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let R=i?u.width:"0px",b=u.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",w=!i;if(n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${R}`,n.style.width=R,n.style.maxWidth=R,n.style.minWidth=R,n.style.minHeight="0",Kk(n,u.maxHeight),n.style.overflow=P||w?"hidden":"visible",n.style.transition=b,P){n.style.alignItems=u.side==="right"?"flex-start":"flex-end";let x=p?`calc(${ww(u.width,e.clientWidth)}px - (2 * ${m}))`:u.width;r.style.width=x,r.style.minWidth=x,r.style.maxWidth=x,r.style.boxSizing="border-box"}}},Zk=(e,t)=>{let o=e.ownerDocument.createElement("div");return Aw(o,t),e.appendChild(o),{mode:"direct",host:o,shell:null,syncWidgetState:()=>{},updateConfig(n){Aw(o,n)},destroy(){o.remove()}}},e0=(e,t)=>{let{ownerDocument:o}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,i=o.createElement("div"),d=o.createElement("div"),u=o.createElement("div"),c=o.createElement("aside"),p=o.createElement("div"),m=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;d.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),n.insertBefore(i,e),u.appendChild(e);let y=null,h=()=>{y?.disconnect(),y=null},S=null,A=()=>{S=t?.launcher?.detachedPanel===!0?Yk(t):null};A();let T=()=>{Jk(i,d,u,c,p,t,m,S)},k=null,P=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=Va(()=>{A(),T()}))},R=()=>{h(),Wo(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{T()}),y.observe(i)))},b=!1,w=()=>{T(),R(),m&&!b&&i.dataset.personaDockMobileFullscreen!=="true"&&(b=!0,Gk(i,Wo(t)))},x=i.ownerDocument.defaultView,L=()=>{w()};return x?.addEventListener("resize",L),Wo(t).reveal==="push"?(d.appendChild(u),d.appendChild(c),i.appendChild(d)):(i.appendChild(u),i.appendChild(c)),w(),P(),{mode:"docked",host:p,shell:i,syncWidgetState(F){let X=F.launcherEnabled?F.open:!0;m!==X&&(m=X,w())},updateConfig(F){t=F,(t?.launcher?.enabled??!0)===!1&&(m=!0),A(),w(),P()},destroy(){x?.removeEventListener("resize",L),k?.(),k=null,h(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),i.remove()}}},jl=(e,t)=>St(t)?e0(e,t):Zk(e,t);var t0=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Ew=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let n=o.cloneNode(!0);e.insertBefore(n,e.firstChild)},Pw=e=>{let t=t0(e.target),o=e.useShadowDom===!0,n=t.ownerDocument,r=e.config,a=jl(t,r),i,d=[],u=(T,k)=>{let R=!(k?.launcher?.enabled??!0)||St(k),b=n.createElement("div");if(b.setAttribute("data-persona-root","true"),R&&(b.style.height="100%",b.style.display="flex",b.style.flexDirection="column",b.style.flex="1",b.style.minHeight="0",b.style.minWidth="0"),o){let w=T.attachShadow({mode:"open"});w.appendChild(b),Ew(w,n)}else T.appendChild(b),Ew(T,n);return t.id&&b.setAttribute("data-persona-instance",t.id),b},c=()=>{a.syncWidgetState(i.getState())},p=()=>{d.forEach(T=>T()),d=[i.on("widget:opened",c),i.on("widget:closed",c)],c()},m=()=>{let T=u(a.host,r);i=$u(T,r,{debugTools:e.debugTools}),p()},y=()=>{d.forEach(T=>T()),d=[],i.destroy()};m(),e.onChatReady?.();let h=T=>{y(),a.destroy(),a=jl(t,T),r=T,m()},S={update(T){let k=Wu(r??{},T),P=St(r),R=St(k),b=Xr(r),w=Xr(k);if(P!==R||b!==w){h(k);return}r=k,a.updateConfig(r),i.update(T),c()},destroy(){y(),a.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},A=new Proxy(S,{get(T,k,P){if(k==="host")return a.host;if(k in T)return Reflect.get(T,k,P);let R=i[k];return typeof R=="function"?R.bind(i):R}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=A),A};var Rw=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),o0=new Set(["button","a","input","select","textarea","details","summary"]),n0=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),uh=/\b(product|card|item|listing|result)\b/i,fh=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,r0=3e3,s0=100;function Ww(e){let t=typeof e.className=="string"?e.className:"";if(uh.test(t)||e.id&&uh.test(e.id))return!0;for(let o=0;o<e.attributes.length;o++){let n=e.attributes[o];if(n.name.startsWith("data-")&&uh.test(n.value))return!0}return!1}function Bw(e){return fh.test((e.textContent??"").trim())}function Ow(e){let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let n=t[o].getAttribute("href")??"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function a0(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Lw(e){let t=e.match(fh);return t?t[0]:null}function kw(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let n=t.getAttribute("href");return{title:t.textContent.trim(),href:n&&n!=="#"?n:null}}let o=e.querySelector("h1, h2, h3, h4, h5, h6");return o?.textContent?.trim()?{title:o.textContent.trim(),href:null}:{title:"",href:null}}function i0(e){let t=[],o=n=>{let r=n.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(n=>o(n.textContent??"")),e.querySelectorAll('[role="button"]').forEach(n=>o(n.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{o(n.value??"")}),t.slice(0,6)}var l0="commerce-card",d0="result-card";function Iw(e){return!Ww(e)||!Bw(e)||!Ow(e)&&!a0(e)?0:5200}function Hw(e){return!Ww(e)||Bw(e)||!Ow(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var mh=[{id:l0,scoreElement(e){return Iw(e)},shouldSuppressDescendant(e,t,o){if(t===e||!e.contains(t))return!1;if(o.interactivity==="static"){let n=o.text.trim();return!!(n.length===0||fh.test(n)&&n.length<32)}return!0},formatSummary(e,t){if(Iw(e)===0)return null;let{title:o,href:n}=kw(e),r=Lw((e.textContent??"").trim())??Lw(t.text)??"",a=i0(e);return[n&&o?`[${o}](${n})${r?`: ${r}`:""}`:o?`${o}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
139
- `)}},{id:d0,scoreElement(e){return Hw(e)},formatSummary(e,t){if(Hw(e)===0)return null;let{title:o,href:n}=kw(e);return[n&&o?`[${o}](${n})`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
140
- `)}}];function c0(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function u0(e){let t=e.options??{},o=t.maxElements??e.maxElements??80,n=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,i=t.root??e.root,d=t.mode??"structured",u=t.maxCandidates??Math.max(500,o*10),c=e.rules??mh;return d==="simple"&&e.rules&&e.rules.length>0?(c0(),c=[]):d==="simple"&&(c=[]),{mode:d,maxElements:o,maxCandidates:u,excludeSelector:n,maxTextLength:r,visibleOnly:a,root:i,rules:c}}function ph(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var p0=["data-testid","data-product","data-action","data-id","data-name","data-type"];function f0(e){let t=e.tagName.toLowerCase(),o=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||o==="textbox"||o==="combobox"||o==="listbox"||o==="spinbutton"?"input":t==="button"||o==="button"||o0.has(t)||o&&n0.has(o)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Dw(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function m0(e){let t={},o=e.id;o&&(t.id=o);let n=e.getAttribute("href");n&&(t.href=n);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let a=e.getAttribute("type");a&&(t.type=a);let i=e.getAttribute("value");i&&(t.value=i);let d=e.getAttribute("name");d&&(t.name=d);let u=e.getAttribute("role");u&&(t.role=u);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function gh(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${ph(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of p0){let a=e.getAttribute(r);if(a){let i=`${t}[${r}="${ph(a)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let o=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(o.length>0){let r=`${t}.${o.map(i=>ph(i)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let a=e.parentElement;if(a){let d=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(d>=0){let u=`${r}:nth-of-type(${d+1})`;try{if(e.ownerDocument.querySelectorAll(u).length===1)return u}catch{}}}}let n=e.parentElement;if(n){let a=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function g0(e){return e==="static"?s0:r0}function _w(e,t){let o=e.tagName.toLowerCase(),n=(e.textContent??"").trim().substring(0,t);return{selector:gh(e),tagName:o,text:n,role:e.getAttribute("role"),interactivity:f0(e),attributes:m0(e)}}function h0(e,t,o,n){let r=g0(t.interactivity),a=null;for(let i of o){let d=i.scoreElement(e,t,n);d>0&&(r+=d,i.formatSummary&&!a&&(a=i))}return{score:r,formattingRule:a}}function y0(e,t){for(let o of e)if(t.el!==o.el&&o.formattingRule?.shouldSuppressDescendant&&o.el.contains(t.el)&&o.formattingRule.shouldSuppressDescendant(o.el,t.el,t.enriched))return!0;return!1}function b0(e,t){let o={doc:t.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,r=[],a=0,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),d=i.currentNode;for(;d&&r.length<e.maxCandidates;){if(d.nodeType===Node.ELEMENT_NODE){let c=d,p=c.tagName.toLowerCase();if(Rw.has(p)){d=i.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){d=i.nextNode();continue}}catch{}if(e.visibleOnly&&!Dw(c)){d=i.nextNode();continue}let m=_w(c,e.maxTextLength),y=m.text.length>0,h=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(T=>T==="role");if(!y&&!h){d=i.nextNode();continue}if(n.has(m.selector)){d=i.nextNode();continue}n.add(m.selector);let{score:S,formattingRule:A}=h0(c,m,e.rules,o);r.push({el:c,domIndex:a,enriched:m,score:S,formattingRule:A}),a+=1}d=i.nextNode()}r.sort((c,p)=>{let m=c.enriched.interactivity==="static"?1:0,y=p.enriched.interactivity==="static"?1:0;return m!==y?m-y:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let u=[];for(let c of r){if(u.length>=e.maxElements)break;y0(u,c)||u.push(c)}return u.sort((c,p)=>{let m=c.enriched.interactivity==="static"?1:0,y=p.enriched.interactivity==="static"?1:0;return m!==y?m-y:m===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),u.map(c=>{let p;if(c.formattingRule?.formatSummary){let y=c.formattingRule.formatSummary(c.el,c.enriched,o);y&&(p=y)}let m={...c.enriched};return p&&(m.formattedSummary=p),m})}function v0(e,t){let o=[],n=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=r.currentNode;for(;a&&o.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let u=a,c=u.tagName.toLowerCase();if(Rw.has(c)){a=r.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Dw(u)){a=r.nextNode();continue}let p=_w(u,e.maxTextLength),m=p.text.length>0,y=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(h=>h==="role");if(!m&&!y){a=r.nextNode();continue}n.has(p.selector)||(n.add(p.selector),o.push(p))}a=r.nextNode()}let i=[],d=[];for(let u of o)u.interactivity!=="static"?i.push(u):d.push(u);return[...i,...d].slice(0,e.maxElements)}function Nw(e={}){let t=u0(e),o=t.root??document.body;return o?t.mode==="simple"?v0(t,o):b0(t,o):[]}var zu=100;function Fw(e,t={}){if(e.length===0)return"No page elements found.";let o=t.mode??"structured",n=[];if(o==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
138
+ `)}if(!g&&!s){let ve="max-height: -moz-available !important; max-height: stretch !important;",Ne=l?"":"padding-top: 1.25em !important;",ft=l?"":`z-index: ${n.launcher?.zIndex??so} !important;`;Xe.style.cssText+=ve+Ne+ft}Ju(),On()},pp=()=>{e.style.setProperty("--persona-content-max-width",Gr(n,Ae()))},ty=!1,oy=()=>{let s=ug(n,Ae());Ae()&&n.composer?.placement&&n.debug===!0&&!ty&&(ty=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let l=xn(n);e.setAttribute("data-persona-composer-placement",s),e.setAttribute("data-persona-conversation-state",Xl),e.setAttribute("data-persona-welcome-anchor",l.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",l.composerGap??du),Yl()},ny=()=>{if(Ae())return;let s=St(n),l=n.launcher?.sidebarMode??!1;if(s||l||(n.launcher?.fullHeight??!1)||!ge)return;let g=e.ownerDocument.defaultView??window,v=n.launcher?.mobileFullscreen??!0,M=n.launcher?.mobileBreakpoint??640;if(v&&g.innerWidth<=M)return;let N=g.innerHeight,z=64,V=n.launcher?.heightOffset??0,K=Math.max(200,N-z),J=Math.min(640,K);we.style.height=`${Math.max(200,J-V)}px`};up(),Us(e,n),Dl(e,n),_l(e,n),pp(),oy(),ss=()=>{up(),ny(),Us(e,n),Dl(e,n),_l(e,n),pp(),oy(),ed?e.style.setProperty("--persona-artifact-welded-outer-radius",ed):e.style.removeProperty("--persona-artifact-welded-outer-radius"),ht(),xe()};let ye=[];ye.push(()=>{Xh=!0}),ye.push(()=>{c.forEach(s=>s()),d.destroy()}),ye.push(()=>{document.removeEventListener("keydown",Jh)}),ye.push(()=>{gi!==null&&clearTimeout(gi)});let kn=null,Ln=null;ye.push(()=>{kn?.(),kn=null,Ln?.(),Ln=null}),bi&&ye.push(()=>{bi?.disconnect(),bi=null}),ye.push(()=>{Ci?.(),Ci=null,cp(),bt&&(bt.remove(),bt=null),Ve?.element.style.removeProperty("width"),Ve?.element.style.removeProperty("maxWidth"),Ve?.destroy()}),Rt&&ye.push(()=>{jl=!0,cn=null,S!==null&&(cancelAnimationFrame(S),S=null),B?.destroy(),B=null,Tt?.destroy(),Tt=null,po=null});let is=null,ry=()=>{is&&(is(),is=null),n.colorScheme==="auto"&&(is=Ka(()=>{Us(e,n)}))};ry(),ye.push(()=>{is&&(is(),is=null)}),ye.push(()=>{x=!0,y?.()}),ye.push(()=>{P=!0});let sy=!1;ye.push(()=>{sy=!0});let fp=(s,l)=>{let f=kl(s,l);return f||!iS.includes(s)?f:(cS().then(g=>{if(sy)return;Ga(g.wipe),Ga(g.glyphCycle);let v=kl(s,l);v&&Rl(v,e)}).catch(()=>{}),null)},ld=n.features?.streamAnimation;if(ld?.type&&ld.type!=="none"){let s=fp(ld.type,ld.plugins);s&&Rl(s,e),ye.push(()=>lS(e))}let Xn=Bl(br),ay=Bl(Ku),iy=Bl(ui),ls=[Xn,ay,iy];ye.push(()=>{ls.forEach(s=>s.destroy())});let ds=null,H,cs=null,ly=!1,dy=0,cy=null,uy=s=>s.reduce((l,f)=>f.role==="user"?l+1:l,0),py=s=>{for(let l=s.length-1;l>=0;l--)if(Bs(s[l]))return s[l].id??null;return null},fy=!1,gA=()=>{fy||n.debug!==!0||(fy=!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".'))},my=!1,gy=!1,hy=(s,l)=>{my||n.debug!==!0||!l.enabled||l.expose||ly||gy&&(H.isStreaming()||s.some(Bs)||(my=!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.")))},ia=s=>{if(!H)return;let l=s??H.getMessages(),f=K=>{K.render([],H,le,l)},g=K=>{ls.forEach(J=>{J!==K&&f(J)})};cs&&(uy(l)>dy||py(l)!==cy)&&(cs=null);let v=jr(n);hy(l,v);let M=v.enabled?yc(l):null,N=cs??M,z=cs?"host":"agent";if(N){let K=n.suggestions?.followUps,J=K?.placement??(K?"auto":"composer"),fe=(J==="auto"?Ae()?"composer":"after-message":J)==="after-message"?iy:Xn;g(fe),fe.render(N,H,le,l,n.suggestionChipsConfig,{source:z,surface:"followUp",variant:K?.variant??"chip",behavior:K?.behavior??"send",overflow:K?.overflow??"wrap",maxItems:K?.maxItems??4,config:n,plugins:i,submitPrompt:Xd});return}if(l.some(K=>K.role==="user")){ls.forEach(f);return}let V=n.suggestions?.starters;if(V){let K=Yr(xn(n),l),J=V.placement??"auto",ae=J==="auto"?K?"welcome":"composer":J;if(ae==="welcome"&&!K){gA(),ls.forEach(f);return}let fe=ae==="welcome"?ay:Xn;g(fe),fe.render(V.items??n.suggestionChips,H,le,l,n.suggestionChipsConfig,{surface:"starter",variant:V.variant??"card",behavior:V.behavior??"send",overflow:V.overflow??"wrap",maxItems:V.maxItems??4,config:n,plugins:i,submitPrompt:Xd});return}g(Xn),Xn.render(n.suggestionChips,H,le,l,n.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:n,plugins:i,submitPrompt:Xd})},yy=()=>{cs&&(cs=null,ia())},hA=s=>{let l=Array.isArray(s)?[...s]:[];if(!l.length){yy();return}let f=H?H.getMessages():[];cs=l,ly=!0,dy=uy(f),cy=py(f),ia(f)},Fo=!1,Dt=XC(),la=new Map,us=new Map,Ar=new Map,ps=null,Mr=null;function fs(){if(!ps)return;let s=ps;ps=null,Mr?.destroy(),Mr=null,Dt.delete(s),ue.querySelector(`#wrapper-${s}`)?.removeAttribute("data-preserve-runtime"),H&&Jo(ke,H.getMessages(),oo)}let ms=0,yA=_n()!==null,Uo=eS(),qo=0,Tr=null,Po=!1,dd=!1,Er=0,$t=null,gs=null,mp=!1,da=!1,hs=null,Si=!0,cd=!1,ca=null,ud=!1,ys=()=>{ud=!0,CA()},gp=null,bA=4,Qn=24,vA=80,xA=1e3,Yn=null,by=()=>{e.setAttribute("data-persona-scrollbar",Xu()),Xu()!=="on-scroll"&&(Yn!==null&&clearTimeout(Yn),Yn=null,re.removeAttribute("data-persona-scrollbar-visible"))},CA=()=>{Xu()==="on-scroll"&&(re.setAttribute("data-persona-scrollbar-visible",""),Yn!==null&&clearTimeout(Yn),Yn=setTimeout(()=>{Yn=null,qs(re,Qn)&&re.removeAttribute("data-persona-scrollbar-visible")},xA))};by(),ye.push(()=>{Yn!==null&&clearTimeout(Yn)});let hp=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};qh=()=>je.active,pn();let vy=n.voiceRecognition?.autoResume??!1,Jn=s=>{C.emit("voice:state",{active:je.active,source:s,timestamp:Date.now()})},gn=()=>{de(s=>({...s,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},SA=()=>{if(n.voiceRecognition?.enabled===!1)return;let s=dh(X.voiceState),l=!!s.active,f=Number(s.timestamp??0);je.manuallyDeactivated=!!s.manuallyDeactivated,l&&Date.now()-f<VL&&setTimeout(()=>{je.active||(je.manuallyDeactivated=!1,n.voiceRecognition?.provider?.type==="runtype"?H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),Jn("restore"),H.isVoiceActive()&&Ea()}):Jd("restore"))},1e3)},wA=()=>H?ww(H.getMessages()).filter(s=>!s.__skipPersist):[],pd=null,xy=(s,l)=>{typeof console<"u"&&console.error(s,l)},fd=(s,l)=>{let f=()=>{try{let N=s();return!N||typeof N.then!="function"?null:Promise.resolve(N).catch(z=>{xy(l,z)})}catch(N){return xy(l,N),null}},g=pd,v=g?g.then(()=>f()??void 0):f();if(!v)return;let M=v.finally(()=>{pd===M&&(pd=null)});pd=M};function wi(s){if(!F?.save)return;let f={messages:s?ww(s):H?wA():[],metadata:X,artifacts:Yo.artifacts,selectedArtifactId:Yo.selectedId,...bs?{draft:bs}:{}};fd(()=>F.save(f),"[AgentWidget] Failed to persist state:")}let bs,md=()=>!F?.save||n.persistState===!1?!1:typeof n.persistState=="object"?n.persistState.persist?.draft!==!1:!0,Ai=xC({write:()=>{if(!md())return;let s=Se.getState(),l=bC({text:s.text,mentionRefs:s.mentionRefs,contentSegments:pf(),selectedModelId:s.selectedModelId,activeModeIds:s.activeModeIds,quote:s.quote});JSON.stringify(l)!==JSON.stringify(bs)&&(bs=l,wi())}});function Cy(){md()&&Ai.schedule()}function yp(){Ai.flush()}function Sy(s){if(!md())return;let l=vC(s,{mentionSourceIds:(n.contextMentions?.sources??[]).map(f=>f.id),modelIds:(n.composer?.models??[]).map(f=>f.id),modes:n.composer?.modes??[]});l&&(bs=s,le&&!le.value&&(le.value=l.text,le.dispatchEvent(new Event("input",{bubbles:!0})),Mn()),l.selectedModelId&&(Se.setSelectedModelId(l.selectedModelId),Cr?.repaint()),Jl(l.activeModeIds??[]),l.quote&&Tn(l.quote),Ai.cancel())}function gd(){Ai.cancel(),bs&&(bs=void 0,md()&&wi())}let ua=null,wy=()=>Xe.querySelector("#persona-scroll-container")||re,pa=()=>{ua!==null&&(cancelAnimationFrame(ua),ua=null),Po=!1},Ay=()=>{Tr!==null&&(cancelAnimationFrame(Tr),Tr=null),dd=!1,pa()},AA=()=>Fo&&vp()&&(No()!=="anchor-top"||Mh()),bp=()=>{let s=pi()||"Jump to latest",l=AA();Ot.toggleAttribute("data-persona-scroll-to-bottom-streaming",l),Er>0?(os.textContent=String(Er),os.style.display="",Ot.setAttribute("aria-label",`${s} (${Er} new)`)):(os.textContent="",os.style.display="none",Ot.setAttribute("aria-label",l?`${s} (response streaming below)`:s))},My=()=>{Er!==0&&(Er=0,bp())},MA=()=>{let s=$t?.spacerHeight??0;return s<=0?qs(re,Qn):vd(s)-re.scrollTop-re.clientHeight<=Qn},vp=()=>xr()?!Uo.isFollowing():!MA(),xp=()=>!!H&&H.getMessages().length>0,Vt=()=>{if(!Zw()||es()){Ot.parentNode&&Ot.remove(),Ot.style.display="none";return}Ot.parentNode!==ue&&ue.appendChild(Ot),ns();let l=Vn(re)>0&&vp()&&xp();l?bp():My(),Ot.style.display=l?"":"none"},Mi=()=>{Uo.pause()&&(Ay(),Vt())},ko=()=>{Uo.resume(),My(),Vt()},Pr=(s=!1)=>{xr()&&xp()&&Uo.isFollowing()&&(!s&&!Fo||(Tr!==null&&(cancelAnimationFrame(Tr),Tr=null),dd=!0,Tr=requestAnimationFrame(()=>{Tr=null,dd=!1,Uo.isFollowing()&&TA(wy(),s?220:140)})))},Ty=(s,l,f,g=()=>!0)=>{let v=s.scrollTop,M=l(),N=M-v;if(pa(),Math.abs(N)<1){Po=!0,s.scrollTop=M,qo=s.scrollTop,Po=!1;return}let z=performance.now();Po=!0;let V=J=>1-Math.pow(1-J,3),K=J=>{if(!g()){pa();return}let ae=l();ae!==M&&(M=ae,N=M-v);let fe=J-z,Je=Math.min(fe/f,1),lt=V(Je),ct=v+N*lt;s.scrollTop=ct,qo=s.scrollTop,Je<1?ua=requestAnimationFrame(K):(s.scrollTop=M,qo=s.scrollTop,ua=null,Po=!1)};ua=requestAnimationFrame(K)},TA=(s,l=500)=>{let f=Vn(s)-s.scrollTop;if(Math.abs(f)<1){qo=s.scrollTop;return}if(Math.abs(f)>=vA){pa(),Po=!0,s.scrollTop=Vn(s),qo=s.scrollTop,Po=!1;return}Ty(s,()=>Vn(s),l,()=>Uo.isFollowing())},hd=()=>{if(!xp()){Vt();return}let s=wy();Po=!0,s.scrollTop=Vn(s),qo=s.scrollTop,Po=!1,Vt()},vs=s=>{let l=0,f=s;for(;f&&f!==re;)l+=f.offsetTop,f=f.offsetParent;return l},EA=()=>{let s=re.getRootNode();return(typeof s.getSelection=="function"?s.getSelection():null)??re.ownerDocument.getSelection()},yd=()=>nS(EA(),re),Cp=()=>{if(eA()!=="last-user-turn")return!1;let s=H?.getMessages()??[];if(s.length<2)return!1;let l=[...s].reverse().find(M=>M.role==="user");if(!l)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l.id):l.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),g=re.querySelector(`[data-message-id="${f}"]`);if(!g)return!1;let v=Math.min(Math.max(0,vs(g)-fi()),Vn(re));return Po=!0,re.scrollTop=v,qo=re.scrollTop,Po=!1,No()==="follow"&&!qs(re,Qn)&&Uo.pause(),Vt(),!0},bd=s=>{let l=Math.max(0,Math.round(s));Qo.style.height=`${l}px`,Qo.style.display=l>0?"":"none",$t&&($t.spacerHeight=Math.max(0,s))},vd=s=>{let l=parseFloat(getComputedStyle(re).paddingBottom)||0,f=0;for(let v of Array.from(re.children)){if(v===Qo||v.offsetHeight===0)continue;let M=vs(v)+v.offsetHeight;M>f&&(f=M)}let g=re.scrollHeight-s;return f>0?Math.min(f+l,g):g},PA=()=>{if(!$t||$t.spacerHeight<=0)return;let s=vd($t.spacerHeight),l=Math.max(0,Math.round(re.scrollTop)+re.clientHeight-s+Qn);l<$t.spacerHeight&&(bd(l),Vt())},hn=()=>{gs!==null&&(cancelAnimationFrame(gs),gs=null),pa(),$t=null,Qo.style.height="0px",Qo.style.display="none"},Ey=s=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Sp=s=>re.querySelector(`[data-message-id="${Ey(s)}"]`),Py=s=>{gs!==null&&cancelAnimationFrame(gs),gs=requestAnimationFrame(()=>{gs=null;let l=Ey(s),f=re.querySelector(`[data-message-id="${l}"]`);if(!f)return;let g=vs(f),v=$t?.spacerHeight??0,M=vd(v),{targetScrollTop:N,spacerHeight:z}=mg({anchorOffsetTop:g,topOffset:fi(),viewportHeight:re.clientHeight,contentHeight:M,slack:Qn});$t={initialSpacerHeight:z,contentHeightAtAnchor:M,spacerHeight:z},bd(z),Ty(re,()=>f.isConnected?Math.max(0,vs(f)-fi()):N,220)})},Lo=()=>{if(No()!=="anchor-top"||!$t||!ca)return;let s=Sp(ca);if(!s)return;pa();let l=$t.spacerHeight,f=vd(l),{targetScrollTop:g,spacerHeight:v}=mg({anchorOffsetTop:vs(s),topOffset:fi(),viewportHeight:re.clientHeight,contentHeight:f,slack:Qn});$t={initialSpacerHeight:v,contentHeightAtAnchor:f,spacerHeight:v},bd(v),Po=!0,re.scrollTop=g,qo=re.scrollTop,Po=!1,Vt()},kA=()=>{if(xr()){if(!Uo.isFollowing()||qs(re,1))return;Pr(!Fo);return}if($t&&$t.initialSpacerHeight>0){let s=re.scrollHeight-$t.spacerHeight,l=rS({initialSpacerHeight:$t.initialSpacerHeight,contentHeightAtAnchor:$t.contentHeightAtAnchor,currentContentHeight:s});l!==$t.spacerHeight&&bd(l)}Vt()},LA=s=>{let l=No();l==="follow"?(ko(),Pr(!0)):l==="anchor-top"&&(Si=!1,cd=!0,ud=!1,ca=s,Py(s))},IA=()=>{if(No()==="anchor-top"){if(cd){Si=!1;return}Si=!0,hn(),ko(),Pr(!0)}},RA=96,HA=s=>{if(hs===null)return!0;let l=Sp(hs),f=Sp(s);if(!l||!f)return!0;let g=vs(f)-vs(l);return fi()+g>re.clientHeight-RA},WA=s=>{if(No()!=="anchor-top"||!cd||ud||yd())return;let l=hs===null;for(let f of s){if(!l){f.id===hs&&(l=!0);continue}if(ZC(f)){if(f.id===ca||!HA(f.id))return;ca=f.id,Py(f.id);return}}},BA=s=>{let l=new Map;s.forEach(f=>{let g=hp.get(f.id);l.set(f.id,{streaming:f.streaming,role:f.role}),!g&&f.role==="assistant"&&(C.emit("assistant:message",f),!da&&(No()!=="anchor-top"||Mh())&&vp()&&(Er+=1,bp(),Vt(),Gl(Er===1?"1 new message below.":`${Er} new messages below.`))),f.role==="assistant"&&g?.streaming&&f.streaming===!1&&C.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(g?f.approval.status!=="pending"&&C.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):C.emit("approval:requested",{approval:f.approval,message:f}))}),hp.clear(),l.forEach((f,g)=>{hp.set(g,f)})},Ti=(s,l)=>{let f=l==="user"?"user":"assistant",g=n.layout?.messages?.[f],v=g?.width??"content",M=g?.maxWidth??(v==="full"?"100%":void 0);s.classList.add("persona-message-row"),s.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),s.classList.add(`persona-message-row-${l}`,`persona-message-width-${v}`),s.classList.toggle("persona-justify-end",l==="user"),s.setAttribute("data-message-role",l),s.setAttribute("data-message-width",v),M?s.style.setProperty("--persona-message-row-max-width",M):s.style.removeProperty("--persona-message-row-max-width")},Zn=(s,l)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${s}`,f.setAttribute("data-wrapper-id",s),Ti(f,l),f},OA=(s,l,f)=>{let g=document.createElement("div"),M=(()=>{let _=i.find(We=>We.renderLoadingIndicator);if(_?.renderLoadingIndicator)return _.renderLoadingIndicator;if(n.loadingIndicator?.render)return n.loadingIndicator.render})(),N=(_,We)=>We==null?!1:typeof We=="string"?(_.textContent=We,!0):(_.appendChild(We),!0),z=new Set,V=new Map,K=new Set,J=i.some(_=>_.renderAskUserQuestion),ae=[],fe=[],Je=n.enableComponentStreaming!==!1,lt=n.approval!==!1,ct=[],Qt=n.messageActions,Nt=Qt?.showRegenerate===!0&&Qt.enabled!==!1&&it.current?.isStreaming()!==!0?Sx(l):null,Lt=Qt?.showEdit===!0&&Qt.enabled!==!1,io=Qt?.showQuote===!0&&Qt.enabled!==!1,et=null,lo=n.features?.reasoningDisplay?.completedVisibility==="removed";if(l.forEach(_=>{if(lo&&_.variant==="reasoning"&&_.reasoning?.status==="complete")return;if(z.add(_.id),V.set(_.id,_.role),ps===_.id&&Mr){let Re=Zn(_.id,_.role);Re.setAttribute("data-persona-message-edit-stub","true"),Re.setAttribute("data-preserve-runtime","true"),g.appendChild(Re),et={messageId:_.id,element:Mr.element};return}let We=J&&cr(_),Oe=lt&&_.variant==="approval"&&!!_.approval,me=!We&&_.role==="assistant"&&!_.variant&&Je&&$l(_);!Oe&&Ar.has(_.id)&&(s.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),Ar.delete(_.id)),!me&&us.has(_.id)&&(s.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),us.delete(_.id));let pt=cr(_)?`:${_.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${_.agentMetadata?.askUserQuestionAnswers?Object.keys(_.agentMetadata.askUserQuestionAnswers).length:0}`:"",jt={canRegenerate:Nt===_.id,canEdit:Lt&&Qf(_),canQuote:io&&!_.variant&&(_.content?.trim().length??0)>0},co=`${jt.canRegenerate?"r":""}${jt.canEdit?"e":""}${jt.canQuote?"q":""}`,uo=GC(_,ms)+pt+`:${co}`,It=We||Oe||me?null:QC(Dt,_.id,uo);if(It){g.appendChild(It.cloneNode(!0)),cr(_)&&_.toolCall?.id&&_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(K.add(_.toolCall.id),Ha(_,n,_e.composerOverlay));return}let Pe=null,zt=i.find(Re=>!!(_.variant==="reasoning"&&Re.renderReasoning||_.variant==="tool"&&Re.renderToolCall||!_.variant&&Re.renderMessage)),Kt=n.layout?.messages;if(cr(_)&&_.agentMetadata?.askUserQuestionAnswered===!0){la.delete(_.id),s.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime");return}if(Bs(_)&&jr(n).enabled)return;if(cr(_)&&n.features?.askUserQuestion?.enabled!==!1){let Re=i.find(xt=>typeof xt.renderAskUserQuestion=="function");if(Re&&it.current){let xt=la.get(_.id),On=xt!==uo,yn=null;if(On){let{payload:Ne,complete:ft}=ur(_),Or=_.id,Gt=()=>it.current?.getMessages().find(jo=>jo.id===Or);yn=Re.renderAskUserQuestion({message:_,payload:Ne,complete:ft,resolve:jo=>{let Rs=Gt();Rs&&it.current?.resolveAskUserQuestion(Rs,jo)},dismiss:()=>{let jo=Gt();jo?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved(jo),it.current?.resolveAskUserQuestion(jo,"(dismissed)"))},config:n})}let Be=xt!=null;if(On&&yn===null&&!Be){_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(K.add(_.toolCall.id),Ha(_,n,_e.composerOverlay));return}let ve=Zn(_.id,_.role);ve.setAttribute("data-ask-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),g.appendChild(ve),ae.push({messageId:_.id,fingerprint:uo,bubble:yn});return}else{_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(K.add(_.toolCall.id),Ha(_,n,_e.composerOverlay));return}}else if(Oe){let Re=k();if(!Re){g.appendChild(Zn(_.id,_.role));return}let xt=i.find(ve=>typeof ve.renderApproval=="function")??h,yn=Ar.get(_.id)!==uo,Be=null;if(yn&&xt?.renderApproval){let ve=_.id,Ne=(ft,Or)=>{let Gt=it.current?.getMessages().find(jo=>jo.id===ve);Gt?.approval&&(Gt.approval.toolType==="webmcp"?it.current?.resolveWebMcpApproval(Gt.id,ft):it.current?.resolveApproval(Gt.approval,ft,Or))};Be=xt.renderApproval({message:_,defaultRenderer:()=>Re.createApprovalBubble(_,n),config:n,approve:ft=>Ne("approved",ft),deny:ft=>Ne("denied",ft)})}if(yn&&Be===null)s.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),Ar.delete(_.id),Pe=Re.createApprovalBubble(_,n);else{let ve=Zn(_.id,_.role);ve.setAttribute("data-approval-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),g.appendChild(ve),ct.push({messageId:_.id,fingerprint:uo,bubble:Be});return}}else if(zt)if(_.variant==="reasoning"&&_.reasoning&&zt.renderReasoning){if(!Xo)return;Pe=zt.renderReasoning({message:_,defaultRenderer:()=>Vg(_,n),config:n})}else if(_.variant==="tool"&&_.toolCall&&zt.renderToolCall){if(!Sn)return;Pe=zt.renderToolCall({message:_,defaultRenderer:()=>zg(_,n),config:n})}else zt.renderMessage&&(Pe=zt.renderMessage({message:_,defaultRenderer:()=>{let Re=Ja(_,f,Kt,n.messageActions,Bo,{loadingIndicatorRenderer:M,widgetConfig:n,actionEligibility:jt});return _.role!=="user"&&A(Re,_,n,H),Re},config:n}));if(!Pe&&me){let Re=Fu(_);if(Re){let xt=us.get(_.id),On=xt!==uo,yn=n.wrapComponentDirectiveInBubble!==!1&&Cn.getOptions(Re.component)?.bubbleChrome!==!1,Be=null;if(On){let ve=Nu(Re,{config:n,message:_,transform:f});if(ve&&Re.component==="PersonaArtifactInline"){let Ne=ve.hasAttribute("data-artifact-inline")?ve:ve.querySelector("[data-artifact-inline]"),ft=Ne?.getAttribute("data-artifact-inline")??"",Or=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(ft):ft,Gt=ft?s.querySelector(`#wrapper-${_.id}`)?.querySelector(`[data-artifact-inline="${Or}"]`)??null:null;Ne&&Gt&&Gt!==Ne&&gr()?.hasLiveInlineArtifactBlock(Gt)&&(Ne===ve?ve=Gt:Ne.replaceWith(Gt))}if(ve)if(yn){let Ne=document.createElement("div");if(Ne.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ne.id=`bubble-${_.id}`,Ne.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let ft=document.createElement("div");ft.className="persona-mb-3 persona-text-sm persona-leading-relaxed",ft.innerHTML=f({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),Ne.appendChild(ft)}Ne.appendChild(ve),Be=Ne}else{let Ne=document.createElement("div");if(Ne.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ne.id=`bubble-${_.id}`,Ne.setAttribute("data-message-id",_.id),Ne.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let ft=document.createElement("div");ft.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",ft.innerHTML=f({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),Ne.appendChild(ft)}Ne.appendChild(ve),Be=Ne}}if(Be||xt!=null){let ve=Zn(_.id,_.role);ve.setAttribute("data-component-directive-stub","true"),ve.setAttribute("data-preserve-runtime","true"),g.appendChild(ve),fe.push({messageId:_.id,fingerprint:uo,bubble:Be});return}}}if(!Pe)if(_.variant==="reasoning"&&_.reasoning){if(!Xo)return;Pe=Vg(_,n)}else if(_.variant==="tool"&&_.toolCall){if(!Sn)return;Pe=zg(_,n)}else if(_.variant==="approval"&&_.approval){if(n.approval===!1)return;let Re=k();if(!Re)return;Pe=Re.createApprovalBubble(_,n)}else{let Re=n.layout?.messages;Re?.renderUserMessage&&_.role==="user"?Pe=Re.renderUserMessage({message:_,config:n,streaming:!!_.streaming}):Re?.renderAssistantMessage&&_.role==="assistant"?Pe=Re.renderAssistantMessage({message:_,config:n,streaming:!!_.streaming}):Pe=Ja(_,f,Re,n.messageActions,Bo,{loadingIndicatorRenderer:M,widgetConfig:n,actionEligibility:jt}),_.role!=="user"&&Pe&&A(Pe,_,n,H)}let rn=Zn(_.id,_.role);rn.appendChild(Pe),YC(Dt,_.id,uo,rn),g.appendChild(rn)}),_e.composerOverlay&&_e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(We=>{let Oe=We.getAttribute("data-persona-ask-sheet-for");Oe&&!K.has(Oe)&&$r(_e.composerOverlay,Oe)}),n.features?.toolCallDisplay?.grouped){let _=[],We=[],Oe=n.features.toolCallDisplay.groupedMode==="summary";l.forEach(me=>{if(me.variant==="tool"&&me.toolCall&&Sn){We.push(me);return}me.variant==="reasoning"&&(!Xo||lo&&me.reasoning?.status==="complete")||((We.length>1||Oe&&We.length>0)&&_.push(We),We=[])}),(We.length>1||Oe&&We.length>0)&&_.push(We),_.forEach(me=>{let pt=me.map(Kt=>Array.from(g.children).find(rn=>rn instanceof HTMLElement&&rn.getAttribute("data-wrapper-id")===Kt.id)).filter(Kt=>!!Kt);if(pt.length<(Oe?1:2))return;let jt=Zn(`tool-group-${me[0].id}`,"assistant");jt.setAttribute("data-persona-tool-group-row","true");let co=document.createElement("div");co.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",co.setAttribute("data-persona-tool-group","true");let uo=document.createElement("div");uo.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",uo.id=`tool-group-summary-${me[0].id}`;let It=`Called ${me.length} ${me.length===1?"tool":"tools"}`,Pe=n.toolCall?.renderGroupedSummary?.({messages:me,toolCalls:me.map(Kt=>Kt.toolCall).filter(Kt=>!!Kt),defaultSummary:It,config:n});N(uo,Pe)||(uo.textContent=It);let zt=document.createElement("div");zt.className="persona-tool-group-stack persona-flex persona-flex-col",zt.id=`tool-group-stack-${me[0].id}`,zt.setAttribute("data-persona-tool-group-stack","true"),co.appendChild(uo),Oe||co.appendChild(zt),jt.appendChild(co),pt[0].before(jt),pt.forEach((Kt,rn)=>{if(Oe){Kt.remove();return}Kt.style.setProperty("--persona-message-row-max-width","100%");let Re=document.createElement("div");Re.className="persona-tool-group-item persona-relative",Re.setAttribute("data-persona-tool-group-item","true"),rn<pt.length-1&&Re.setAttribute("data-persona-tool-group-connector","true"),Re.appendChild(Kt),zt.appendChild(Re)})})}JC(Dt,z);let lr=l.some(_=>_.role==="assistant"&&_.streaming),Wn=l[l.length-1],Bn=Wn?.role==="assistant"&&!Wn.streaming&&Wn.variant!=="approval";if(Fo&&l.some(_=>_.role==="user")&&!lr&&!Bn){let _={config:n,streaming:!0,location:"standalone",defaultRenderer:Gs},We=i.find(me=>me.renderLoadingIndicator),Oe=null;if(We?.renderLoadingIndicator&&(Oe=We.renderLoadingIndicator(_)),Oe===null&&n.loadingIndicator?.render&&(Oe=n.loadingIndicator.render(_)),Oe===null&&(Oe=Gs()),Oe){let me=document.createElement("div"),pt=n.loadingIndicator?.showBubble!==!1,jt=n.layout?.messages?.layout??"bubble";me.className=pt?Ol("assistant",jt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),me.setAttribute("data-typing-indicator","true"),pt&&(me.style.color="var(--persona-message-assistant-text, var(--persona-text))",jt!=="flat"&&(me.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),me.appendChild(Oe);let co=Zn("typing-indicator","assistant");co.appendChild(me),g.appendChild(co)}}if(!Fo&&l.length>0){let _=l[l.length-1],We={config:n,lastMessage:_,messageCount:l.length},Oe=i.find(pt=>pt.renderIdleIndicator),me=null;if(Oe?.renderIdleIndicator&&(me=Oe.renderIdleIndicator(We)),me===null&&n.loadingIndicator?.renderIdle&&(me=n.loadingIndicator.renderIdle(We)),me){let pt=document.createElement("div"),jt=n.loadingIndicator?.showBubble!==!1;pt.className=jt?["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(" "),pt.setAttribute("data-idle-indicator","true"),pt.appendChild(me);let co=Zn("idle-indicator","assistant");co.appendChild(pt),g.appendChild(co)}}if(Cv(g),fu(s,g),Lf(s),et){let{messageId:_,element:We}=et,Oe=s.querySelector(`#wrapper-${_}`);Oe&&We.parentElement!==Oe&&(Ti(Oe,V.get(_)??"user"),Oe.replaceChildren(We))}if(ae.length>0)for(let{messageId:_,fingerprint:We,bubble:Oe}of ae){let me=s.querySelector(`#wrapper-${_}`);me&&(Ti(me,V.get(_)??"assistant"),Oe!==null&&(me.replaceChildren(Oe),me.setAttribute("data-bubble-fp",We),la.set(_,We)))}if(la.size>0)for(let _ of la.keys())z.has(_)||la.delete(_);if(fe.length>0)for(let{messageId:_,fingerprint:We,bubble:Oe}of fe){let me=s.querySelector(`#wrapper-${_}`);me&&(Ti(me,V.get(_)??"assistant"),Oe!==null&&(me.replaceChildren(Oe),me.setAttribute("data-bubble-fp",We),us.set(_,We)))}if(us.size>0)for(let _ of us.keys())z.has(_)||us.delete(_);if(ct.length>0)for(let{messageId:_,fingerprint:We,bubble:Oe}of ct){let me=s.querySelector(`#wrapper-${_}`);me&&(Ti(me,V.get(_)??"assistant"),Oe!==null&&(me.replaceChildren(Oe),me.setAttribute("data-bubble-fp",We),Ar.set(_,We)))}if(Ar.size>0)for(let _ of Ar.keys())z.has(_)||Ar.delete(_)},wp=!1,xd=()=>{wp||(wp=!0,ic().catch(()=>{wp=!1}))},Jo=(s,l,f)=>{l.length>0&&xd(),OA(s,l,f),Gh()},Ei=null,DA=()=>{if(Ei)return;let s=f=>{let g=f.composedPath();g.includes(Xe)||Xt&&g.includes(Xt)||dt(!1,"user")};Ei=s,(e.ownerDocument??document).addEventListener("pointerdown",s,!0)},ky=()=>{if(!Ei)return;(e.ownerDocument??document).removeEventListener("pointerdown",Ei,!0),Ei=null};ye.push(()=>ky());let Pi=null,_A=()=>{if(Pi)return;let s=f=>{f.key==="Escape"&&(f.isComposing||dt(!1,"user"))};Pi=s,(e.ownerDocument??document).addEventListener("keydown",s,!0)},Ly=()=>{if(!Pi)return;(e.ownerDocument??document).removeEventListener("keydown",Pi,!0),Pi=null};ye.push(()=>Ly());let ki=!1,Iy=new Set,NA=()=>{let s=n.launcher?.composerBar?.peek?.streamAnimation;return s||n.features?.streamAnimation},fa=()=>{if(!Ae())return;let s=_e.peekBanner,l=_e.peekTextNode;if(!s||!l)return;if(he){s.classList.remove("persona-pill-peek--visible");return}let f=H?.getMessages()??[],g;for(let Nt=f.length-1;Nt>=0;Nt--){let Lt=f[Nt];if(Lt.role==="assistant"&&Lt.content){g=Lt;break}}if(!g){s.classList.remove("persona-pill-peek--visible");return}let v=g.content,M=!!g.streaming,N=NA(),z=mu(N),V=z.type!=="none"?fp(z.type,N?.plugins):null,K=V?.isAnimating?.(g)===!0,J=V!==null&&(M||K);J&&V&&!Iy.has(V.name)&&(Rl(V,e),Iy.add(V.name));let ae=J&&V?.containerClass?V.containerClass:null,fe=l.dataset.personaPeekStreamClass??null;fe&&fe!==ae&&(l.classList.remove(fe),delete l.dataset.personaPeekStreamClass),ae&&fe!==ae&&(l.classList.add(ae),l.dataset.personaPeekStreamClass=ae),J?(l.style.setProperty("--persona-stream-step",`${z.speed}ms`),l.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(l.style.removeProperty("--persona-stream-step"),l.style.removeProperty("--persona-stream-duration"));let Je=J?gu(v,z.buffer,V,g,M):v;if(J&&z.placeholder==="skeleton"&&M&&(!Je||!Je.trim())){let Nt=document.createElement("div"),Lt=Il();Lt.classList.add("persona-pill-peek__skeleton"),Nt.appendChild(Lt),fu(l,Nt)}else{let Nt=Math.max(0,Je.length-100),Lt=Je.length>100?Je.slice(-100):Je,io=dr(Lt);if(!J||!V){let et=Je.length>100?`\u2026${Lt}`:Lt;l.textContent!==et&&(l.textContent=et)}else{let et=io;(V.wrap==="char"||V.wrap==="word")&&(et=Ll(io,V.wrap,`peek-${g.id}`,{skipTags:V.skipTags,startIndex:Nt}));let lo=document.createElement("div");if(lo.innerHTML=et,V.useCaret&&Lt.length>0){let lr=hu(),Wn=lo.querySelectorAll(".persona-stream-char, .persona-stream-word"),Bn=Wn[Wn.length-1];Bn?.parentNode?Bn.parentNode.insertBefore(lr,Bn.nextSibling):lo.appendChild(lr)}fu(l,lo),V.onAfterRender?.({container:l,bubble:s,messageId:g.id,message:g,speed:z.speed,duration:z.duration})}}let Qt=Fo||ki;s.classList.toggle("persona-pill-peek--visible",Qt)};if(Ae()){let s=_e.peekBanner;if(s){let g=v=>{v.preventDefault(),v.stopPropagation(),dt(!0,"user")};s.addEventListener("pointerdown",g),ye.push(()=>{s.removeEventListener("pointerdown",g)})}let l=()=>{ki||(ki=!0,fa())},f=()=>{ki&&(ki=!1,fa())};we.addEventListener("pointerenter",l),we.addEventListener("pointerleave",f),ye.push(()=>{we.removeEventListener("pointerenter",l),we.removeEventListener("pointerleave",f)}),Xt&&(Xt.addEventListener("pointerenter",l),Xt.addEventListener("pointerleave",f),ye.push(()=>{Xt.removeEventListener("pointerenter",l),Xt.removeEventListener("pointerleave",f)}))}let FA=s=>{let l=n.launcher?.composerBar??{},f=l.expandedSize??"anchored",g=l.bottomOffset??"16px",v=l.collapsedMaxWidth,M=l.expandedMaxWidth??"880px",N=l.expandedTopOffset??"5vh",z=l.modalMaxWidth??"880px",V=l.modalMaxHeight??"min(90vh, 800px)",K="calc(100vw - 32px)",J="var(--persona-pill-area-height, 80px)",ae=Xe.style;if(ae.left="",ae.right="",ae.top="",ae.bottom="",ae.transform="",ae.width="",ae.maxWidth="",ae.height="",ae.maxHeight="",Xt){let fe=Xt.style;fe.bottom=g,fe.width=v??""}if(s&&f!=="fullscreen"){if(f==="modal"){ae.top="50%",ae.left="50%",ae.transform="translate(-50%, -50%)",ae.bottom="auto",ae.right="auto",ae.width=z,ae.maxWidth=K,ae.maxHeight=V,ae.height=V;return}ae.left="50%",ae.transform="translateX(-50%)",ae.bottom=`calc(${g} + ${J})`,ae.top=N,ae.width=M,ae.maxWidth=K}},Li=()=>{if(he&&xd(),!De())return;if(Ae()){let K=(n.launcher?.composerBar??{}).expandedSize??"anchored",J=he?"expanded":"collapsed";Xe.dataset.state=J,Xe.dataset.expandedSize=K,Xt&&(Xt.dataset.state=J,Xt.dataset.expandedSize=K),Xe.style.removeProperty("display"),Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),FA(he),ue.style.display=he?"flex":"none",ss(),he?(DA(),_A()):(ky(),Ly()),fa();return}let s=St(n),l=e.ownerDocument.defaultView??window,f=n.launcher?.mobileBreakpoint??640,g=n.launcher?.mobileFullscreen??!0,v=l.innerWidth<=f,M=g&&v&&ge,N=Wo(n).reveal;he?(Xe.style.removeProperty("display"),Xe.style.display=s?"flex":"",Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0"),we.classList.add("persona-scale-100","persona-opacity-100"),Pt?(Pt.setPanelOpen(!0),Pt.element.style.display="none"):go&&(go.style.display="none")):(s?s&&(N==="overlay"||N==="push")&&!M?(Xe.style.removeProperty("display"),Xe.style.display="flex",Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Xe.style.setProperty("display","none","important"),Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Xe.style.display="",Xe.classList.add("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100"),we.classList.add("persona-scale-95","persona-opacity-0")),Pt?(Pt.setPanelOpen(!1),Pt.element.style.display=s?"none":""):go&&(go.style.display=s?"none":""))},dt=(s,l="user")=>{if(!De()||he===s)return;let f=he;he=s,Li();let g=(()=>{let M=n.launcher?.sidebarMode??!1,N=e.ownerDocument.defaultView??window,z=n.launcher?.mobileFullscreen??!0,V=n.launcher?.mobileBreakpoint??640,K=N.innerWidth<=V,J=St(n)&&z&&K,ae=Ae()&&(n.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return M||z&&K&&ge||J||ae})();if(he&&g){if(!kn){let M=e.getRootNode(),N=M instanceof ShadowRoot?M.host:e.closest(".persona-host");N&&(kn=vg(N,n.launcher?.zIndex??so))}Ln||(Ln=xg(e.ownerDocument))}else he||(kn?.(),kn=null,Ln?.(),Ln=null);he&&(Ki(),Cp()||(No()==="follow"?Pr(!0):hd()));let v={open:he,source:l,timestamp:Date.now()};he&&!f?C.emit("widget:opened",v):!he&&f&&C.emit("widget:closed",v),C.emit("widget:state",{open:he,launcherEnabled:ge,voiceActive:je.active,streaming:H.isStreaming()})},kr={inputDisabled:!1,sendDisabled:!1},Lr=()=>kr.inputDisabled,xs=()=>kr.inputDisabled||kr.sendDisabled,UA=()=>(kr.inputDisabled?kr.inputReason:void 0)??(kr.sendDisabled?kr.sendReason:void 0);function Ap(){if(!Me)return;if(Se.getState().phase==="streaming"){Me.disabled=!1;return}let s=Ze?!Ze.isReady():!1;Me.disabled=xs()||s}function Cd(){if(!An)return;let s=Se.getState(),l=n.sendButton?.visibility==="when-text"&&s.phase!=="streaming"&&s.text.trim().length===0&&s.attachments.length===0;An.toggleAttribute("data-persona-send-hidden",l)}function qA(){let s=UA();if(Ae()){let l=un??Ie;s?l.setAttribute("title",s):l.removeAttribute("title"),Ie.toggleAttribute(li,!!s);return}if(s){st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.setAttribute(li,""),st.textContent=s;return}if(st.hasAttribute(li)&&(st.removeAttribute("role"),st.removeAttribute("aria-live"),st.removeAttribute(li),u)){let l=H.getStatus();ao(st,fo(l),n.statusIndicator??{},l)}}function Mp(){let s=Km(n.composer?.inputDisabled),l=Km(n.composer?.sendDisabled);kr={inputDisabled:s.disabled,inputReason:s.reason,sendDisabled:l.disabled,sendReason:l.reason},Se.setInputDisabled(s.disabled),Se.setSendDisabled(l.disabled);let f=Se.getState().phase==="streaming",g=s.disabled,v=f||g;le&&(le instanceof HTMLTextAreaElement?le.disabled=g:le.setAttribute("contenteditable",g?"false":"true"),le.setAttribute("aria-disabled",g?"true":"false")),At&&(At.disabled=g),yt&&(yt.disabled=g);for(let M of Wt?.affordanceButtons??[])M.querySelectorAll("button").forEach(N=>{N.disabled=g});se&&(se.disabled=v),ls.forEach(M=>{M.elements.forEach(N=>{N.toggleAttribute("data-disabled",v),N instanceof HTMLButtonElement||N.setAttribute("aria-disabled",v?"true":"false")}),M.buttons.forEach(N=>{N.disabled=v})}),Lp.forEach(M=>{M.toggleAttribute("data-disabled",v),M instanceof HTMLButtonElement?M.disabled=v:M.setAttribute("aria-disabled",v?"true":"false"),M.querySelectorAll("button").forEach(N=>{N.disabled=v})}),Ie.dataset.personaComposerStreaming=f?"true":"false",Ie.dataset.personaComposerInputDisabled=g?"true":"false",Ie.dataset.personaComposerSendDisabled=xs()?"true":"false",Ie.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(M=>{(M instanceof HTMLButtonElement||M instanceof HTMLInputElement||M instanceof HTMLTextAreaElement||M instanceof HTMLSelectElement)&&(M.disabled=f)}),Ap(),qA()}let Ii=s=>{Se.setStreaming(s),wh(s?"stop":"send"),Mp()},Cs=()=>{je.active||le&&le.focus()};C.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Cs(),200)});let Ss=null,Ri=!1,Tp=!Mo.hidden,Ir=null,Ep=!G,Sd=null;ye.push(()=>{Sd?.cancel(),Sd=null});let $A=s=>{let l=LS(s);if(l===Xl)return;Xl=l,e.setAttribute("data-persona-conversation-state",l);let f=Yu();Yl(),Ep&&(Sd?.cancel(),Sd=PS(Ie,l==="active"?f:Yu(),l==="active"?"drop":"rise")),Lo()},Ry=null,Hy,Wy=null,ma=null,Pp=!1,Hi=s=>{let l=xn(n),f=`${l.variant}|${l.dismiss}|${l.anchor??"bottom"}|${l.align??""}|${l.iconPlacement}|${l.kicker??""}|${l.title}|${l.subtitle}`;(f!==Ry||l.icon!==Hy)&&(Ry=f,Hy=l.icon,wu({host:Mo,iconHolder:zw,kicker:Kw,title:Gw,subtitle:Xw,starterSuggestions:Ku},l));let g=l.message===void 0?null:`${n.layout?.messages?.layout??"bubble"}|${l.message}`;g!==Wy&&(Wy=g,Au(Do,l.message,n));let v=s??(H?H.getMessages():n.initialMessages);$A(v);let M=Ri,N=!M&&Yr(l,v),z=N!==Tp;if(Tp=N,ma){Ir?.cancel(),Ir=null,M!==Pp&&(Pp=M,M?Og(re,Mo,null):Bg(re,Mo,ma)),Za(re,Mo,!M);return}if(z&&!N&&!M&&l.dismiss==="on-first-message"&&Ep){Ir=ES(Mo,K=>{Ir===K&&(Ir=null),!Tp&&!ma&&(Za(re,Mo,!1),Lo()),K?.cancel()});return}if(Ir){if(!N&&!M)return;Ir.cancel(),Ir=null}let V=!Mo.hidden;Za(re,Mo,N),!N&&V&&Lo()},kp=[],Lp=[],Ip=!1,By=null,Oy,Dy=()=>{Lp.length=0;let s=kp.splice(0,kp.length);for(let l of s)try{l()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};ye.push(Dy);let VA=(s,l)=>{let f=Sg(s,l);if(!f)return n.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),I("span");let g=n.suggestions?.starters,v=wg({item:{...f,behavior:f.behavior??g?.behavior??"send"},index:l,surface:"starter",source:"config",variant:g?.variant??"card",streaming:u?H.isStreaming():!1,config:n,plugins:i,chipsConfig:n.suggestionChipsConfig,session:H,getTextarea:()=>le,eventTarget:Mo,submitPrompt:Xd});return Lp.push(v),v},Rp=()=>{if(Ip)return;Ip=!0;let s=xn(n);By=`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`,Oy=s.icon;try{Dy(),Og(re,Mo,ma),ma=null,Pp=!1;let l=H?H.getMessages():n.initialMessages,f=Yr(s,l),g=0,v=null;for(let M of i)if(M.renderWelcome&&(v=M.renderWelcome({config:s,variant:s.variant,visible:f,defaultRenderer:()=>Mo,sendMessage:N=>{if(!H||H.isStreaming())return;let z=N.trim();z&&H.sendMessage(z)},requestRender:()=>Rp(),renderStarter:N=>VA(N,g++),storage:p(M.id),onCleanup:N=>{kp.push(N)}}),v))break;v&&v!==Mo&&(ma=v,Bg(re,Mo,v))}finally{Ip=!1}Hi()},jA=()=>{let s=xn(n);`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`===By&&s.icon===Oy||Rp()},wd=()=>{Hi(),na||(le.placeholder=fC(Se.getState().activeModeIds,n.composer?.modes)??n.copy?.inputPlaceholder??"How can I help...",!(n.sendButton?.useIcon??!1)&&!H?.isStreaming()&&(Me.textContent=n.copy?.sendButtonLabel??"Send")),le.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',le.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},zA=!!n.setStoredConversationId,ga=s=>de(l=>{let f={...l};return delete f[s],f}),Ad=s=>{let l=X[s];return typeof l=="string"?l:null},_y=()=>{let s=X.durableResume;if(!s||typeof s!="object")return null;let l=s;return typeof l.executionId=="string"&&l.executionId.length>0&&typeof l.after=="string"&&l.after.length>0?{executionId:l.executionId,after:l.after}:null},Hp=!!n.clientToken&&typeof n.reconnectStream!="function";n.clientToken&&(n={...n,getStoredSessionId:()=>Ad("sessionId"),setStoredSessionId:s=>{de(l=>({...l,sessionId:s}))},clearStoredSessionId:n.clearStoredSessionId??(()=>ga("sessionId")),getStoredConversationId:n.getStoredConversationId??(()=>Ad("conversationId")),setStoredConversationId:n.setStoredConversationId??(s=>{de(l=>({...l,conversationId:s}))}),clearStoredConversationId:n.clearStoredConversationId??(()=>ga("conversationId"))});let Ny=()=>n.clientToken??null,Fy=s=>pw(s,wn(),n.persistState===!1),Uy=Ny(),er=Uy?Fy(Uy):null,tr={...er?{visitorStore:er}:{},historyBootstrapReady:O,getStoredMessageCursor:()=>Ad("historyMessageCursor"),setStoredMessageCursor:s=>{if(s===null){ga("historyMessageCursor");return}de(l=>({...l,historyMessageCursor:s}))},getPendingDisplayProjections:()=>{let s=X.pendingDisplayProjections;if(!s||typeof s!="object")return null;let l=s;return typeof l.conversationId!="string"||!Array.isArray(l.messageIds)?null:{conversationId:l.conversationId,messageIds:l.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:s=>{if(!s){ga("pendingDisplayProjections");return}de(l=>({...l,pendingDisplayProjections:s}))},getStoredResumableHandle:_y,setStoredResumableHandle:s=>{if(!s){ga("durableResume");return}de(l=>({...l,durableResume:s}))},shouldResumeDurableConversation:()=>Hp&&_y()!==null,...zA?{}:{getStoredConversationRevision:()=>Ad("conversationRevision"),setStoredConversationRevision:s=>{if(s===null){ga("conversationRevision");return}de(l=>({...l,conversationRevision:s}))}}};if(Hp){let s=n.onExecutionState,l=e.ownerDocument.defaultView,f=!1,g=()=>{f=!0},v=()=>{f=!1};l?.addEventListener("beforeunload",g),l?.addEventListener("pagehide",g),l?.addEventListener("pageshow",v),ye.push(()=>{l?.removeEventListener("beforeunload",g),l?.removeEventListener("pagehide",g),l?.removeEventListener("pageshow",v)}),n={...n,reconnectStream:n.reconnectStream??(M=>H.getClient().reconnectClientTokenStream(M)),onExecutionState:M=>{(M||!f)&&tr.setStoredResumableHandle?.(M?{executionId:M.executionId,after:M.lastEventId}:null),s?.(M)}}}let KA=()=>{let s=Ny();if(s&&er?.matches(s,wn(),n.persistState===!1)||!s&&!er)return;er?.destroy(),er=s?Fy(s):null;let l={...tr};er?l.visitorStore=er:delete l.visitorStore,tr=l,H.setHistoryInternals(tr)},ws=null,GA=()=>{ws==null&&(ws=setInterval(()=>{let s=ke.querySelectorAll("[data-tool-elapsed]");if(s.length===0){clearInterval(ws),ws=null;return}let l=Date.now();s.forEach(f=>{let g=Number(f.getAttribute("data-tool-elapsed"));g&&(f.textContent=xc(l-g))})},100))},Wp=(s,l)=>{if(Object.is(s,l))return!0;if(s===null||l===null||typeof s!="object"||typeof l!="object")return!1;if(Array.isArray(s)||Array.isArray(l))return!Array.isArray(s)||!Array.isArray(l)||s.length!==l.length?!1:s.every((N,z)=>Wp(N,l[z]));let f=s,g=l,v=Object.keys(f),M=Object.keys(g);return v.length===M.length&&v.every(N=>Object.prototype.hasOwnProperty.call(g,N)&&Wp(f[N],g[N]))},qy=s=>{let{content:l,rawContent:f,llmContent:g,...v}=s;return v},Bp=s=>s.role==="assistant"&&s.streaming===!0&&!s.variant&&!s.toolCall&&!s.tools&&!s.approval&&!s.reasoning&&!s.contentParts&&!s.stopReason&&!$l(s),XA=(s,l,f)=>{if(s.length!==l.length)return!1;let g=s[f.index],v=l[f.index];return!g||!v||g.id!==f.id||v.id!==f.id?!1:(!Object.is(g.content,v.content)||!Object.is(g.rawContent,v.rawContent)||!Object.is(g.llmContent,v.llmContent))&&Bp(g)&&Bp(v)&&Wp(qy(g),qy(v))},Op=null,ha=null,As=null,or=null,Md=s=>{Op=s;let l,f;ha=null;for(let v=s.length-1;v>=0;v-=1){let M=s[v];if(!l&&M.role==="user"&&(l=M),!f&&M.role==="assistant"&&(f=M),!ha&&Bp(M)&&(ha={index:v,id:M.id}),l&&f&&ha)break}Jo(ke,s,oo),gr()?.updateInlineArtifactBlocks(ke,Yo.artifacts,{suppressTransition:Fo}),GA(),Hi(s),ia(s),Pr(!Fo),BA(s),s.length===0&&(hn(),Si=!0,cd=!1,ca=null,ud=!1),!mp||da?(mp=!0,hs=l?.id??null,gp=f?.id??null):l&&l.id!==hs?(hs=l.id,LA(l.id)):f&&f.id!==gp&&IA(),f&&(gp=f.id),WA(s);let g=je.lastUserMessageId;l&&l.id!==g&&(je.lastUserMessageId=l.id,C.emit("user:message",l)),je.lastUserMessageWasVoice=!!l?.viaVoice,wi(s),fa()},Dp=()=>{or!==null&&(cancelAnimationFrame(or),or=null);let s=As;As=null,s&&Md(s)},$y=()=>{or!==null&&cancelAnimationFrame(or),or=null,As=null},QA=s=>{let l=As??Op;if(Fo&&l&&ha&&XA(l,s,ha)){As=s,or===null&&(or=requestAnimationFrame(()=>{or=null;let f=As;As=null,f&&Md(f)}));return}if(s.length===0){$y(),Md(s);return}Dp(),Md(s)};H=new _a(n,{onMessagesChanged(s){QA(s)},onStatusChanged(s){let l=n.statusIndicator??{};ao(st,(g=>g==="idle"?l.idleText??Ut.idle:g==="connecting"?l.connectingText??Ut.connecting:g==="connected"?l.connectedText??Ut.connected:g==="error"?l.errorText??Ut.error:g==="paused"?l.pausedText??Ut.paused:g==="resuming"?l.resumingText??Ut.resuming:Ut[g])(s),l,s),wt()},onStreamingChanged(s){s||(H?.getMessages().length===0?$y():Dp()),Fo=s,Ii(s),wt(),H&&Jo(ke,H.getMessages(),oo),s||(Pr(!0),PA(),gy=!0,H&&hy(H.getMessages(),jr(n))),Vt(),Gl(s?"Responding\u2026":"Response complete."),fa()},onVoiceStatusChanged(s){if(C.emit("voice:status",{status:s,timestamp:Date.now()}),n.voiceRecognition?.provider?.type==="runtype")switch(s){case"listening":ir(),Ea();break;case"processing":ir(),JM();break;case"speaking":ir(),ZM();break;default:s==="idle"&&H.isBargeInActive()?(ir(),Ea(),se?.setAttribute("aria-label","End voice session")):(je.active=!1,ir(),Jn("system"),gn());break}},onArtifactsState(s){Yo=s,s.artifacts.length===0&&(ra=!1),gr()?.updateInlineArtifactBlocks(ke,s.artifacts,{suppressTransition:Fo}),mn(),wi()},onHistoryStateChanged(s){$e(s)},onHistoryNotice(s){Ht(s)},onReconnect(s){let{executionId:l,lastEventId:f}=s.handle;s.phase==="paused"?C.emit("stream:paused",{executionId:l,after:f}):s.phase==="resuming"?C.emit("stream:resuming",{executionId:l,after:f,attempt:s.attempt??1}):C.emit("stream:resumed",{executionId:l,after:f})}},tr),it.current=H,ye.push(()=>H.cancel()),ye.push(()=>{H.destroy(),er?.destroy()});let _p=null;if(H.onReadAloudChange((s,l)=>{zh=s,Kh=l,Gh();let f=s??_p;s&&(_p=s);let g=f?H.getMessages().find(v=>v.id===f)??null:null;C.emit("message:read-aloud",{messageId:f,message:g,state:l,timestamp:Date.now()}),l==="idle"&&(_p=null)}),u=!0,mp=!0,n.voiceRecognition?.provider?.type==="runtype")try{H.setupVoice()}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",s)}let YA=720,JA=250,Ye=lh(n.features?.history?.copy),$o=null,Np=!1,at=null,Td=null,Ed="conversation",Fp=null,mo=null,In=null,Pd=H.getHistoryState(),Up=null,Wi=0,qp=null,kd=null,Ld=null,$p=`persona-history-${Math.random().toString(36).slice(2,8)}`,Vp=()=>n.features?.history?.enabled===!0,Rn=()=>Vp()&&!!$o&&!Np,Vy=()=>{let s=H.getStatus();return Fo||s==="paused"||s==="resuming"},jp=()=>{let s=n.features?.history?.scope;if(s)return s;let l=n.getIdentityProof?"verified-user":"browser",f=$o?.capabilities.scopes;return!f||f.includes(l)?l:f[0]??l},ya=()=>Td?.scope??jp(),jy=()=>H.getClientSession()?.targetId??null,zy=s=>`${s.state}:${"reason"in s?s.reason:""}`,ZA=s=>{let l=zy(s);l!==Up&&(Up=l,C.emit("history:identityStatusChanged",{status:s,timestamp:Date.now()}))},Id=s=>{s&&(zn.textContent="",zn.textContent=s)},Ky=null,Gy=null,eM=()=>{if(!Vp())return null;let s=yw();if(s)return s();let l=n.features?.history?.provider;return l?typeof l!="function"?l:(Ky!==l&&(Ky=l,Gy=l()),Gy):H.isClientTokenMode()?bw({client:H.getClient(),getIdentityProofConfigured:()=>typeof n.getIdentityProof=="function",onActivationCommitted:f=>H.bindActivatedSession(f),getClient:()=>H.getClient()}):null},Xy=()=>{kd?.(),kd=null,Ld?.(),Ld=null,Np=!1,$o=eM();let s={...tr};$o?s.historyProvider=$o:delete s.historyProvider,tr=s,H.setHistoryInternals(tr),$o&&(kd=$o.subscribeAvailability?.(l=>{Np=!l,l||Io({restoreFocus:!1}),Hr()})??null,Ld=$o.subscribeIdentityStatus(l=>ZA(l)),Up=zy($o.getIdentityStatus()))},zp=()=>{let s=n.features?.history?.presentation??"panel";if(s==="panel"||s==="auto"&&!(!ge||St(n)))return"panel";let l=Pn??ue;return(l.getBoundingClientRect().width||l.clientWidth)>=YA?"rail":"panel"},Zo=(s,l)=>{l?(s.setAttribute("aria-hidden","true"),s.setAttribute("inert","")):(s.removeAttribute("aria-hidden"),s.removeAttribute("inert"))},Rd="data-persona-history-suppressed",Vo=null,Rr=null,Ms=null,Bi=null,Kp=null,Qy="",Yy=()=>Te===Kp?Qy:n.layout?.showHeader===!1?"none":"",tM=()=>ie==="panel"&&!!Ms&&Bi===Ms.element&&n.layout?.showHeader!==!1&&Yy()!=="none",oM=()=>{for(let s of Array.from(Te.children))s!==Vo&&s.setAttribute(Rd,"")},nM=()=>{for(let s of Array.from(ue.querySelectorAll(`[${Rd}]`)))s.removeAttribute(Rd)},rM=()=>{let s=Ms;if(!s)return;if(Array.from(Te.children).some(g=>g!==Vo&&!g.hasAttribute(Rd))){Rr&&Rr!==Te&&(Rr.style.removeProperty("min-height"),Rr=null);let g=Te.offsetHeight;g>0&&(Te.style.minHeight=`${g}px`,Rr=Te)}Vo||(Vo=I("div","persona-history-header-host")),s.setHeaderPlacement("external");let f=s.getHeaderElement();f.parentNode!==Vo&&Vo.replaceChildren(f),Vo.parentNode!==Te&&Te.appendChild(Vo),oM()},Jy=()=>{Rr&&(Rr.style.removeProperty("min-height"),Rr=null),Vo&&(Ms?.setHeaderPlacement("inline"),Vo.remove(),Vo=null,nM())},Hd=null,Gp=()=>{if(Hd){if(re.style.display="none",Zo(re,!0),Ie.hidden=!0,Zo(Ie,!0),tM()){rM(),Te.style.display=Yy(),Zo(Te,!1);return}Jy(),Te.style.display="none",Zo(Te,!0)}};xe=Gp;let sM=s=>{let l=re.style.display,f=Ie.hidden,g=Ie,v=Te,M=Te.style.display;Kp=v,Qy=M,Hd=()=>{Hd=null,Jy(),Kp=null,re.style.display=l,Zo(re,!1),g.hidden=f,Zo(g,!1),Ie!==g&&(Ie.hidden=!1,Zo(Ie,!1)),v.style.display=M,Zo(v,!1),Te!==v&&(Te.style.display=n.layout?.showHeader===!1?"none":"",Zo(Te,!1))},Ie.parentNode?.insertBefore(s,Ie),Gp()},ba=null,Ts=null,Oi=null,va=null,Zy=()=>[Te,_e.closeButtonWrapper,_e.clearChatButtonWrapper,re,Ie],aM=52,Wd=()=>n.features?.history?.rail?.collapsible!==!1,xa=()=>n.features?.history?.rail?.side==="right"?"right":"left",Xp=200,Qp=400,Yp=s=>Math.min(Qp,Math.max(Xp,Math.round(s))),iM=()=>n.features?.history?.rail?.resizable===!0,Di,lM=()=>{if(Di===void 0&&(Di=null,n.persistState!==!1))try{let s=Number(window.localStorage.getItem(`${wn()}rail-width`));s&&(Di=s)}catch{}return Di},_i=()=>Yp(lM()??n.features?.history?.rail?.width??260),dM=s=>{if(Di=s,n.persistState!==!1)try{window.localStorage.setItem(`${wn()}rail-width`,String(s))}catch{}},Bd=()=>Wd()&&n.features?.history?.rail?.collapsedBehavior==="overlay",_t=!1,eb=s=>{let l=I("img");return l.src=s,l.alt="",l.setAttribute("aria-hidden","true"),l},cM=()=>{let s=n.features?.history?.rail?.brand;if(!s)return;let l=!1,f;return g=>{if(s.render)try{return s.render({collapsed:g})??null}catch(v){return l||(l=!0,console.warn("[persona] history rail brand threw",v)),null}return f===void 0&&(s.iconUrl?f=eb(s.iconUrl):f=s.icon?ce(s.icon,20):null),f?f.cloneNode(!0):null}},uM=()=>n.features?.history?.rail?.sections?.map(s=>{let l=!1,f=g=>{l||(l=!0,console.warn("[persona] history rail section threw",s.id,g))};return{id:s.id,title:s.title,placement:s.placement??"above-conversations",items:s.items.map(g=>{let v;return{id:g.id,label:g.label,badge:g.badge,iconNode:()=>{if(v!==void 0)return v;try{g.renderIcon?v=g.renderIcon()??null:g.iconUrl?v=eb(g.iconUrl):v=g.icon?ce(g.icon,20):null}catch(M){f(M),v=null}return v},onSelect:()=>{try{g.onSelect()}catch(M){f(M)}}}})}})??[],pM=s=>{let l=uM();for(let f of s)l.some(g=>g.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):l.push(f);return l.length?l:void 0},Ni=null,tb=()=>`${wn()}rail-collapsed`,Jp=()=>{if(Ni===null&&(Ni=n.features?.history?.rail?.defaultCollapsed===!0,n.persistState!==!1))try{let s=window.localStorage.getItem(tb());s&&(Ni=s==="1")}catch{}return Ni},Zp=s=>{if(Ni=s,n.persistState!==!1)try{window.localStorage.setItem(tb(),s?"1":"0")}catch{}},Fi=()=>ie==="rail"&&Wd()&&!Bd()&&Jp(),ef=()=>{},ob=()=>{if(Bd()){ef();return}Zp(!Jp()),at?.view.setCollapsed(Fi()),ht(),Lo()},tf=()=>{let s=n.features?.history?.rail?.collapseShortcut;return!s||!uu(s)?null:{combo:s,hint:pu(s),aria:Tl(s)}},nb=()=>{c.forEach(l=>l()),c=[];let s=tf();s&&c.push(d.register({id:"history-rail-collapse",combo:s.combo,scope:n.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>ne&&ie==="rail"&&Wd()||Sa(),run:()=>Bd()?ef():ob()}));for(let l of n.layout?.header?.trailingActions??[])l.shortcut&&c.push(d.register({id:`header-action-${l.id}`,combo:l.shortcut,run:()=>{let f=e.querySelector(`[data-persona-header-action="${l.id}"]`);f?f.click():n.layout?.header?.onAction?.(l.id)}}));for(let l of i)for(let f of l.shortcuts??[])c.push(d.register({...f,id:`${l.id}:${f.id}`}))};nb();let fM=300,Od="var(--persona-history-overlay-margin,8px)",en=null,nr=null,Dd=0,rr=null,Ca=null,Es=!1,of=0,rb=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Sa=()=>Rn()&&Bd()&&(ie??zp())==="rail",mM=()=>ne&&!_t,Ui=()=>{Ca!==null&&clearTimeout(Ca),Ca=null},gM=()=>{sh().catch(()=>{})},sb=()=>{Ui(),_t&&(Ca=setTimeout(()=>{Ca=null,!(Es||!_t)&&(rr?.contains(document.activeElement)||Io({restoreFocus:!1}))},fM))},hM=(s,l)=>{let f=rr?.getBoundingClientRect();if(!f)return!1;let g=en?.getBoundingClientRect(),v=g?Math.min(g.top,f.top):f.top;return s>=f.left&&s<=f.right&&l>=v&&l<=f.bottom||!!g&&s>=g.left&&s<=g.right&&l>=g.top&&l<=g.bottom},nf=s=>{_t&&(Es=hM(s.clientX,s.clientY),Es?Ui():Ca===null&&sb())},ab=s=>{ne||!Sa()||(_t=!0,$i({invoker:en,keyboard:s?.keyboard===!0}).then(()=>{ne?!Es&&document.activeElement!==en&&Io():_t=!1}))},ib=()=>{let s=Bi?.querySelector('[data-persona-history-focus="collapse"]');s&&(s.setAttribute("aria-label",_t?Ye.expandLabel:Ye.collapseLabel),s.setAttribute("aria-expanded",_t?"false":"true"))},lb=()=>{Zp(!1);let s=at;if(!_t||!s){$i({invoker:en});return}let l=document.activeElement===en;_t=!1,_d(),s.element.remove(),sf(s.element),ib(),l&&Fd(),Lo(),Hr()},yM=()=>{Zp(!0),Io()};ef=()=>{!ne||_t?lb():yM()};let bM=()=>{let s=tf(),l=$s({ariaLabel:Ye.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":$p,...s?{"aria-keyshortcuts":s.aria}:{}}}),f=l.button;f.addEventListener("mouseenter",()=>{Es=!0,Ui(),!(rb()||Date.now()<of)&&ab()}),f.addEventListener("mouseleave",()=>{Es=!1,of=0,sb()}),f.addEventListener("focus",()=>{ne||gM()}),f.addEventListener("click",g=>{Rn()&&(g.detail!==0&&rb()&&!ne?ab():lb())}),en=f,nr=l.wrapper},qi=()=>{if(nr&&!nr.isConnected&&(nr=null,en=null),!Sa()){nr?.remove(),nr=null,en=null;return}en||bM();let s=nr,l=en;if(!s||!l)return;let f=xa()!=="right"?Te.firstChild:null;(f??Te.lastChild)!==s&&Te.insertBefore(s,f),s.style.display=mM()||Dd>0?"none":"",l.setAttribute("aria-label",Ye.expandLabel),l.setAttribute("aria-expanded",ne?"true":"false"),rr&&ht()},db=s=>{if(!_t)return;let l=s.target;l instanceof Node&&(rr?.contains(l)||nr?.contains(l)||l instanceof Element&&l.closest('.persona-dropdown-menu,[role="alertdialog"]')||Io({restoreFocus:!1}))};document.addEventListener("pointerdown",db,!0),ye.push(()=>{document.removeEventListener("pointerdown",db,!0),document.removeEventListener("pointermove",nf),wa?.(),Ui()});let rf=null,wa=null,cb=16,ub=s=>{dM(Yp(s)),ht(),Lo()},vM=()=>{let s=I("div","persona-rail-resizer");return s.tabIndex=0,s.setAttribute("role","separator"),s.setAttribute("aria-orientation","vertical"),s.setAttribute("aria-valuemin",String(Xp)),s.setAttribute("aria-valuemax",String(Qp)),s.addEventListener("pointerdown",l=>{let f=Ts;if(!f||l.button!==0)return;l.preventDefault(),wa?.();let g=l.clientX,v=f.getBoundingClientRect().width||_i(),M=xa()==="right"?-1:1,N=v,z=e.ownerDocument;f.style.transition="none";let V=J=>{N=Yp(v+M*(J.clientX-g)),f.style.flex=`0 0 ${N}px`,s.setAttribute("aria-valuenow",String(N))},K=()=>{wa=null,z.removeEventListener("pointermove",V),z.removeEventListener("pointerup",K),z.removeEventListener("pointercancel",K),f.style.removeProperty("transition");try{s.releasePointerCapture(l.pointerId)}catch{}ub(N)};wa=K,z.addEventListener("pointermove",V),z.addEventListener("pointerup",K),z.addEventListener("pointercancel",K);try{s.setPointerCapture(l.pointerId)}catch{}}),s.addEventListener("keydown",l=>{let f=xa()==="right"?-cb:cb,g=_i(),v=l.key==="ArrowRight"?g+f:l.key==="ArrowLeft"?g-f:l.key==="Home"?Xp:l.key==="End"?Qp:null;v!==null&&(l.preventDefault(),ub(v))}),s},xM=(s,l)=>{if(!iM()||Fi()){wa?.(),rf?.remove();return}let f=rf??vM();rf=f,f.setAttribute("aria-label",Ye.resizeLabel),f.setAttribute("aria-valuenow",String(_i())),f.nextElementSibling!==l&&s.insertBefore(f,l)};ht=()=>{at?.view.setRailSide(xa());let s=xa()==="right",l=rr;if(l){let z=en?en.getBoundingClientRect().bottom-ue.getBoundingClientRect().top:0;l.style.top=`calc(${Math.max(0,Math.round(z))}px + ${Od})`,l.style.width=`${_i()}px`,l.style.left=s?"":Od,l.style.right=s?Od:""}let f=Ts,g=ba,v=Oi;if(!f||!g||!v)return;f.style.flex=`0 0 ${Fi()?aM:_i()}px`;let M="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=s?"":M,f.style.borderLeft=s?M:"";let N=s?v:f;g.firstElementChild!==N&&g.append(N,s?f:v),xM(g,s?f:v)};let pb=s=>{if(va&&Ts){va.replaceWith(s),va=null,ht();return}let l=I("div","persona-history-rail-shell");l.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=I("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 g=I("div","persona-history-rail-host");g.style.cssText="display:flex;min-height:0;overflow:hidden",ue.insertBefore(l,Te.parentNode===ue?Te:re);for(let v of Zy())v?.parentNode===ue&&f.appendChild(v);l.append(g,f),g.appendChild(s),ba=l,Ts=g,Oi=f,ht()},CM=()=>{if(ba)return;let s=I("div","persona-history-rail-placeholder");s.style.cssText="flex:1 1 auto;min-height:0",va=s,pb(s),Lo()},fb=()=>{va&&(_d(),Lo())},SM=s=>{let l=I("div","persona-history-rail-overlay");l.style.cssText=`position:absolute;bottom:${Od};display:flex;overflow:hidden;z-index:${$a-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))`,ue.style.position="relative",ue.appendChild(l),l.appendChild(s),document.addEventListener("pointermove",nf),rr=l,ht(),ib()},_d=()=>{Hd?.(),rr&&(Es&&(of=Date.now()+150),document.removeEventListener("pointermove",nf),rr.remove(),rr=null);let s=ba;if(s){wa?.();for(let l of Zy())l&&s.contains(l)&&ue.insertBefore(l,s);s.remove(),ba=null,Ts=null,Oi=null,va=null}},mb=s=>{Bi=s,s.id=$p,s.style.flex="1 1 auto",s.style.minHeight="0"},sf=s=>{mb(s),(ie!=="rail"||_t)&&fb(),ie!=="rail"?sM(s):_t?SM(s):pb(s)},Nd=()=>{if(qi(),Mb(),!ne||!at)return;let s=zp();if(s===ie)return;let l=document.activeElement,f=l instanceof HTMLElement&&(at.element.contains(l)||Vo?.contains(l)===!0)?l:null;_d(),at.element.remove(),at.view.setHeaderPlacement("inline"),ie=s,at.view.setPresentation(s),at.view.setCollapsed(Fi()),at.requestRender(),at.element.isConnected||sf(at.element),f?.isConnected?f.focus():Fd(),Vt(),Lo(),Hr()},gb=(s,l)=>Vo?.querySelector(l)??s.querySelector(l),Fd=()=>{let s=at?.element??Bi;if(!s)return;let l=gb(s,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(l){l.focus();return}let f=gb(s,".persona-history-title")??s;f.tabIndex=-1,f.focus()},$i=async s=>{if(!Rn()||ne)return;let l=$o;if(!l)return;if(!_t&&Sa()&&Jp()){qi();return}Ud();let f=++Wi;Ed=s?.returnSurface??"conversation",Fp=s?.invoker??mo;let g=Sa()&&!_t;g&&(Dd+=1,qi(),CM());let v;try{v=await sh()}catch{Id(Ye.openHistoryLabel),g&&(Dd-=1,f===Wi&&(fb(),qi()));return}if(g&&(Dd-=1),f!==Wi||ne)return;Td={scope:jp()},ie=zp(),ne=!0;let M=ie==="panel"&&n.layout?.showHeader!==!1&&Te.style.display!=="none"?"external":"inline",N=n.features?.history?.rowAvatar,z=tf(),V=z?{hint:z.hint,aria:z.aria}:null,K={provider:l,context:Td,targetId:jy(),presentation:ie,collapsible:Wd(),collapsed:Fi(),railSide:xa(),renderRailHeader:n.features?.history?.rail?.renderHeader,railBrand:cM(),onToggleCollapse:ob,...V?{collapseShortcut:V}:{},headerPlacement:M,showScopeStatus:n.features?.history?.showScopeStatus!==!1,showDelete:n.features?.history?.showDelete!==!1,showDeleteAll:n.features?.history?.showDeleteAll!==!1,...n.features?.history?.listActions?.length?{listActions:n.features.history.listActions}:{},rowAvatar:N===!1?!1:typeof N=="string"?N:n.launcher?.iconUrl,activeConversationId:H.getActiveConversationId(),...n.features?.history?.grouping?{grouping:n.features.history.grouping}:{},...n.features?.history?.copy?{copy:n.features.history.copy}:{},...n.features?.history?.pageSize!==void 0?{pageSize:n.features.history.pageSize}:{},onSelect:J=>lf(J,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:J=>Ps(J),attachTooltip:eo,onStartNew:()=>df({focusComposer:!0}),onClose:()=>Io(),onRequestDeleteConversation:J=>Ab(J),onRequestClearHistory:()=>PM(),...l.resetDevice?{onRequestResetIdentity:()=>kM()}:{}};at=hw({plugins:i,config:n,getPresentation:()=>ie??"panel",getReturnSurface:()=>Ed,close:()=>Io(),createView:({slots:J,renderDom:ae,onModelChange:fe,railSections:Je})=>(Ms=v.createHistoryView({...K,railSections:pM(Je),slots:J,renderDom:ae,onModelChange:fe,onAnnounce:Id}),Ms),onElementChanged:(J,ae)=>{if(!ae?.isConnected)return sf(J);mb(J),ae.replaceWith(J),Gp()}}),at.view.setNewConversationRequired(Pd.recovery==="new_conversation_required"),s?.focus!==!1&&(ie!=="rail"||s?.keyboard===!0)&&Fd(),Vt(),Lo(),Hr(),C.emit("history:opened",{presentation:ie,returnSurface:Ed,timestamp:Date.now()})},Ud=()=>{},Io=s=>{if(!ne)return;Wi+=1;let l=Ed,f=Fp,g=at,v=s?.restoreFocus!==!1;ne=!1;let M=!1,N=null,z=()=>{if(!M){if(M=!0,Ud=()=>{},N!==null&&clearTimeout(N),_t=!1,Ui(),_d(),g?.dispose(),g?.view.destroy(),g?.element.remove(),at===g&&(at=null,Ms=null,Bi=null,ie=null,Td=null,Fp=null),Vt(),Lo(),Hr(),v){let K=f??mo;K?.isConnected?K.focus():Cs()}C.emit("history:closed",{returnSurface:l,timestamp:Date.now()})}},V=g&&g.element===g.view.element?g.view.playExit():null;if(!V){z();return}Ud=z,N=setTimeout(z,JA),V.then(z)},hb=s=>{if(!(s.key!=="Escape"||!ne||!at)){if(ie==="rail"){let l=s.target;if(!(l instanceof Node)||!(at.element.contains(l)||_t&&nr?.contains(l)===!0))return}s.preventDefault(),s.stopPropagation(),Io()}};ue.addEventListener("keydown",hb),ye.push(()=>ue.removeEventListener("keydown",hb));let qd=null,yb=!1,Vi=()=>{if(!vr)return;let s=n.layout?.header?.titleSource==="conversation",l=s&&qd?.trim()||null;vr.textContent=l??n.launcher?.title??"Chat Assistant";let f=vr.closest(".persona-combo-btn");if(!f)return;let g=!s||H.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",g?"false":"true"),f.setAttribute("aria-haspopup",g?"true":"false"),g||f.setAttribute("aria-expanded","false"),f.style.cursor=g?"pointer":"default";let v=f.querySelector("svg");v&&(v.style.display=g?"":"none")},wM=s=>{s!==qd&&(qd=s,Vi())},Ps=s=>{yb=s?.starred===!0,wM(s&&s.title.trim()||null),Vi()};Vi(),ue.addEventListener("persona:title-menu-builtin",s=>{let l=s.detail?.actionId,f=H.getActiveConversationId();f&&(l==="delete"?Ab(f):l==="star"&&H.canUpdateConversations()&&cf(f,{starred:!yb}).catch(()=>{}))});let $d=0,AM=250,Vd=null,jd=()=>{Vd&&clearTimeout(Vd),Vd=null};ye.push(jd);let bb=()=>{jd();let s=Ss;s&&(Ri=!0,s.hidden=!1,ke.style.display="none",Hi())},zd=()=>{$d+=1,jd(),Ss&&(Ss.remove(),Ss=null,Ri=!1,ke.style.removeProperty("display"),Zo(Ie,!1),Hi())},MM=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;ke.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},af=(s,l)=>Y("div",{className:bo("persona-conversation-loading-bubble",l&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:s}}),vb=()=>Y("div",{className:"persona-conversation-loading-body"},af("58%",!1),af("72%",!0),af("44%",!1)),xb=s=>{Ss?.remove(),Ss=s,s.hidden=!Ri,re.insertBefore(s,ke),jd(),Ri||(Vd=setTimeout(bb,AM)),Zo(Ie,!0)},TM=()=>{let s={config:n,streaming:!1,location:"conversation-open",defaultRenderer:vb},l=null,f=i.find(g=>g.renderLoadingIndicator);f?.renderLoadingIndicator&&(l=f.renderLoadingIndicator(s)),l===null&&n.loadingIndicator?.render&&(l=n.loadingIndicator.render(s)),xb(Y("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ye.openConversationLoadingLabel}},l??vb()))},EM=s=>{let l=()=>{lf(s,{focusComposer:!0}).catch(()=>{})},f=Rn()?()=>{zd(),$i()}:void 0,g=(z,V)=>{let K=Y("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:z});return K.addEventListener("click",V),K},v=()=>Y("div",{className:"persona-conversation-loading-error-body"},Y("p",{className:"persona-conversation-loading-error-title",text:Ye.openConversationErrorTitle}),Y("div",{className:"persona-conversation-loading-error-actions"},g(Ye.openConversationRetryLabel,l),f?g(Ye.openConversationBackLabel,f):null)),M=Object.freeze({conversationId:s,config:n,copy:Object.freeze({title:Ye.openConversationErrorTitle,retryLabel:Ye.openConversationRetryLabel,backLabel:Ye.openConversationBackLabel}),retry:l,...f?{back:f}:{},defaultRenderer:v}),N=null;for(let z of i)if(z.renderHistoryOpenError){try{N=z.renderHistoryOpenError(M)}catch(V){console.warn("[persona] renderHistoryOpenError threw",V),N=null}if(N)break}xb(Y("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},N??v())),bb()};C.on("history:closed",()=>{Ss&&Zo(Ie,!0)});let lf=async(s,{focusComposer:l=!1}={})=>{let f=ya(),g=!!at;at?.view.setActiveConversationId(s),zd();let v=$d;TM(),ne&&(ie==="panel"||_t)&&Io({restoreFocus:!1}),da=!0;try{await H.openConversation(s,{scope:f})}catch(M){throw v===$d&&EM(s),M}finally{da=!1}v===$d&&(zd(),Dt.clear(),hn(),ko(),Cp()||hd(),MM(),sr(),g||Ps(null),C.emit("history:conversationOpened",{conversationId:s,title:qd,scope:f,timestamp:Date.now()}),l&&Cs())},df=async({focusComposer:s=!1}={})=>{zd(),await H.startNewConversation({scope:ya()}),Ps(null),Dt.clear(),hn(),ko(),hd(),sr();let l=H.getActiveConversationId();at?.view.setActiveConversationId(l),C.emit("history:conversationStarted",{conversationId:l,timestamp:Date.now()}),ne&&(ie==="panel"||_t)&&Io({restoreFocus:!1}),s&&Cs()},cf=async(s,l)=>{let f=await H.updateConversation(s,{...l,...l.title!==void 0?{title:l.title.trim()}:{}});return at?.view.applyConversationSummary(f),!at&&s===H.getActiveConversationId()&&Ps(f),f},Cb=async s=>{let l=ya(),f=H.getActiveConversationId()===s;await H.deleteConversation(s,{scope:l}),at?.view.removeConversationSummary(s),f&&(Ps(null),Dt.clear(),hn(),ko(),sr()),C.emit("history:conversationDeleted",{conversationId:s,scope:l,wasActive:f,timestamp:Date.now()})},Sb=async s=>{let l=s?.scope??ya(),f=s?.allTargets?null:s?.targetId??jy(),g=await H.clearConversationHistory({...f?{targetId:f}:{},scope:l});return Ps(null),Dt.clear(),hn(),ko(),sr(),C.emit("history:cleared",{deleted:g.deleted,scope:l,targetId:f,timestamp:Date.now()}),g},wb=async()=>{if(!$o?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let s=!1;try{s=(await H.resetHistoryDevice()).remoteRevocationConfirmed}finally{Ps(null),H.clearArtifacts(),Dt.clear(),Op=null,n.clearStoredSessionId?.(),n.clearStoredConversationId?.(),X={},Ee.syncFromMetadata(),F?.clear&&fd(()=>F.clear(),"[AgentWidget] Failed to clear storage adapter:"),hn(),ko(),sr(),Io({restoreFocus:!1}),Cs(),he||Pt?.launcher.element.focus()}return Id(s?Ye.identityResetNotice:Ye.identityResetUnconfirmedNotice),C.emit("history:identityReset",{remoteRevocationConfirmed:s,timestamp:Date.now()}),{remoteRevocationConfirmed:s}},uf=()=>Pn?we:ue,Ab=async s=>await Du({host:uf(),title:Ye.deleteConversationConfirmTitle,description:Ye.deleteConversationConfirm,confirmLabel:Ye.deleteConversationConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await Cb(s),"deleted"):"cancelled",PM=async()=>{let s=ya()==="verified-user";return await Du({host:uf(),title:Ye.clearHistoryConfirmTitle,description:s?Ye.clearHistoryVerifiedConfirm:Ye.clearHistoryConfirm,confirmLabel:Ye.clearHistoryConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await Sb(),"cleared"):"cancelled"},kM=async()=>{if(!await Du({host:uf(),title:Ye.resetIdentityConfirmTitle,description:Ye.resetIdentityConfirm,confirmLabel:Ye.resetIdentityConfirmLabel,cancelLabel:Ye.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:l}=await wb();return{outcome:"reset",remoteRevocationConfirmed:l}},tn=I("button","persona-history-earlier");tn.type="button",tn.textContent=Ye.showEarlierMessagesLabel,tn.setAttribute("data-persona-history-earlier",""),Object.assign(tn.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 sr=()=>{if(!(Rn()&&!!Pd.nextMessageCursor&&!!H.getActiveConversationId())){tn.remove();return}tn.textContent=Ye.showEarlierMessagesLabel,tn.parentNode!==re&&re.insertBefore(tn,re.firstChild)};tn.addEventListener("click",()=>{let s=H.getActiveConversationId(),l=Pd.nextMessageCursor;if(!s||!l||tn.disabled)return;tn.disabled=!0;let f=re.scrollHeight,g=re.scrollTop;H.loadOlderMessages(s,l,{scope:ya()}).then(()=>{re.scrollTop=g+(re.scrollHeight-f),Lo()}).catch(()=>{}).finally(()=>{tn.disabled=!1,sr()})});let LM=()=>{let s=$s({ariaLabel:Ye.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 s.button.addEventListener("click",l=>{if(!(!Rn()||Vy())){if(ne){Io();return}$i({invoker:s.button,keyboard:l.detail===0})}}),s},Mb=()=>{if(!Rn()){In?.remove(),mo=null,In=null;return}if(In&&!In.isConnected&&(mo=null,In=null),!mo&&Te){let g=LM();mo=g.button,In=g.wrapper;let v=_e.clearChatButtonWrapper||_e.closeButtonWrapper;v?.parentNode&&Te.contains(v)?v.parentNode.insertBefore(In,v):Te.appendChild(In)}if(!mo||!In)return;let s=Sa()||ne&&ie==="rail";if(In.style.display=s?"none":"",s){document.activeElement===mo&&Fd();return}let l=Vy();mo.disabled=l,mo.setAttribute("aria-disabled",l?"true":"false");let f=l?Ye.openHistoryBusyLabel:Ye.openHistoryLabel;mo.setAttribute("aria-label",f),(n.features?.history?.presentation??"panel")==="panel"?(mo.removeAttribute("aria-expanded"),mo.removeAttribute("aria-controls")):(mo.setAttribute("aria-expanded",ne?"true":"false"),mo.setAttribute("aria-controls",$p))},Kd=!1,IM=()=>{let s=_e.clearChatButton;if(s){if(Rn()){Kd||(qp=s.getAttribute("aria-label")??"",Kd=!0),s.setAttribute("aria-label",Ye.newConversationLabel),s.removeAttribute("title");return}Kd&&(Kd=!1,qp&&s.setAttribute("aria-label",qp))}},Hr=()=>{Ye=lh(n.features?.history?.copy),Mb(),qi(),IM(),sr()};wt=Hr,$e=s=>{Pd=s,at?.view.setNewConversationRequired(s.recovery==="new_conversation_required"),Ii(s.sendBlocked||Fo),sr()},Ht=s=>{(s.code==="history_continuity_reset"||s.code==="conversation_deleted_recovered")&&(Dt.clear(),hn(),ko()),Id(s.message),at?.view.refresh()},Xy(),Hr(),ye.push(()=>{kd?.(),Ld?.(),Wi+=1,Ud(),at?.dispose(),at?.view.destroy(),at=null}),n.clientToken&&H.initClientSession().then(()=>{if(Rn())return H.reconcileBootConversation({scope:jp()})}).then(()=>{sr()}).catch(s=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",s)}),(Rt||n.onSSEEvent)&&H.setSSEEventCallback((s,l)=>{n.onSSEEvent?.(s,l),$(s,l)});let Tb=()=>{let s=n.resume??(Hp?tr.getStoredResumableHandle?.():null);s&&typeof n.reconnectStream=="function"&&H.resumeFromHandle(s)};G?G.then(s=>{if(s){if(s.metadata&&(X=dh(s.metadata),Ee.syncFromMetadata()),s.messages?.length){da=!0;try{H.hydrateMessages(s.messages)}finally{da=!1}xd()}s.artifacts?.length&&H.hydrateArtifacts(s.artifacts,s.selectedArtifactId??null),Sy(s.draft)}}).catch(s=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",s)}).finally(()=>{Ep=!0,E(),Tb()}):(Sy(D),Tb());let RM=()=>{!Ae()||he||!(n.launcher?.composerBar?.expandOnSubmit??!0)||dt(!0,"auto")},HM=(s,l)=>s?l?{refs:[...s.refs,...l.refs],finalize:async()=>{let[f,g]=await Promise.allSettled([s.finalize(),l.finalize()]),v=[];return f.status==="fulfilled"?v.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),g.status==="fulfilled"?v.push(g.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",g.reason),YL(v)}}:s:l,pf=()=>{let l=le.getInlineMessageFields?.();return l&&l.contentSegments.some(g=>g.kind==="mention")?l.contentSegments:void 0},ar=!1,ks=null,Gd=()=>{le.value="",le.style.height="auto",Mn(),zi()},ff="data-persona-composer-notice",Aa=null;function WM(s){Gl(s),!(Ae()||!st)&&(st.hasAttribute(li)||(st.setAttribute(ff,""),st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.textContent=s,Aa&&clearTimeout(Aa),Aa=setTimeout(()=>{if(Aa=null,!!st?.hasAttribute(ff)&&(st.removeAttribute(ff),st.removeAttribute("role"),st.removeAttribute("aria-live"),u)){let l=H.getStatus();ao(st,fo(l),n.statusIndicator??{},l)}},4e3)))}function BM(){let s=Se.getState().pendingSubmission;s&&(ta(void 0),le&&(le.value=s.text,le.dispatchEvent(new Event("input",{bubbles:!0})),Mn()),s.options.selectedModelId&&(Se.setSelectedModelId(s.options.selectedModelId),Cr?.repaint()),s.options.activeModeIds?.length&&Jl(s.options.activeModeIds),s.options.quote&&Tn(s.options.quote),le?.focus())}let OM=s=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",s)},Eb=(s={})=>{let l=(s.overrideText??le?.value??"").trim();return s.resolveInlineCommand&&l?(Wt?.takeInlineCommand(l)??Promise.resolve(null)).then(f=>Pb(s,l,f)):Pb(s,l,null)},Pb=(s,l,f)=>{if(f?.kind==="action"){Gd(),Wt?.clear(),rs();return}let g=f?.kind==="server"?f.mentions:null,v=f?.kind==="prompt"?f.sendText:l,M=s.pending?.contentParts,N=(Ze?.hasAttachments()??!1)||(M?.length??0)>0;if(!TC({text:v,hasAttachments:N,attachmentsReady:Ze?.isReady()??!0,hasMentions:Wt?.hasMentions()??!1,hasServerMentions:!!g,inputDisabled:Lr(),sendDisabled:xs()}))return;let z=H.isStreaming()?tp():"block";if(z==="defer-one"&&!s.pending){if(Se.getState().pendingSubmission){WM("One message is already queued. Edit or remove it first.");return}DM({intent:s,sendText:v,serverMentions:g});return}let V={text:v,mentionRefs:[...Wt?.getMentionRefs()??[],...g?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:pf(),options:{...Se.getState().selectedModelId&&{selectedModelId:Se.getState().selectedModelId},...Se.getState().activeModeIds.length>0&&{activeModeIds:[...Se.getState().activeModeIds]},...Se.getState().quote&&{quote:{...Se.getState().quote}}},viaVoice:s.viaVoice};s.pending&&(V.options={...s.pending.options},V.contentSegments=s.pending.contentSegments,V.mentionRefs=[...s.pending.mentionRefs],V.viaVoice=s.pending.viaVoice);let K=()=>{if(M?.length)return[...M];if(!Ze?.hasAttachments())return;let ct=[...Ze.getContentParts()];return V.text&&ct.push(an(V.text)),ct};V.contentParts=K();let J=()=>{fs(),RM();let ct=Wt?.collectForSubmit()??null,Qt=HM(ct,g),Nt=K();s.consumeDraft!==!1&&Gd();let Lt={selectedModelId:V.options.selectedModelId,activeModeIds:V.options.activeModeIds},io=z==="interrupt";io&&H.cancel(),H.sendMessage(V.text,{contentParts:Nt,mentions:Qt??void 0,contentSegments:V.contentSegments,viaVoice:V.viaVoice,composerOptions:Lt,...V.options.quote&&{quote:V.options.quote},...io&&{interrupt:!0}}),Ze?.hasAttachments()&&Ze.clearAttachments(),ct&&Wt?.clear(),rs();let et=Se.getState().activeModeIds,lo=pC(et,n.composer?.modes);lo.length!==et.length&&Jl(lo),Se.getState().quote&&Tn(void 0),gd(),ap.release(),pn()},ae=n.composer?.onBeforeSend;if(!ae){J();return}let fe=new AbortController;ks=fe;let Je=ct=>{if(ks=null,ct.status==="error"){OM(ct.error);return}ct.status==="proceed"&&J()},lt=EC(ae,V,fe.signal);if(!(lt instanceof Promise)){Je(lt);return}return Se.setPreparing(!0),lt.then(Je).finally(()=>Se.setPreparing(!1))};function DM(s){let l=Se.getState(),f=Ze?.hasAttachments()??!1,g=f?[...Ze.getContentParts()]:[];f&&s.sendText&&g.push(an(s.sendText));let v=rg({text:s.sendText,contentParts:g.length?g:void 0,mentionRefs:[...Wt?.getMentionRefs()??[],...s.serverMentions?.refs??[]],contentSegments:pf(),options:{...l.selectedModelId&&{selectedModelId:l.selectedModelId},...l.activeModeIds.length>0&&{activeModeIds:[...l.activeModeIds]},...l.quote&&{quote:{...l.quote}}},viaVoice:s.intent.viaVoice});ta(v),s.intent.consumeDraft!==!1&&Gd(),f&&Ze.clearAttachments(),Wt?.clear(),rs(),l.quote&&Tn(void 0),gd(),ap.release(),pn(),Gl("Message queued. It sends when the response finishes.")}function _M(){let s=Se.getState().pendingSubmission;s&&(ta(void 0),Qd(s.text,{consumeDraft:!1,pending:s}))}function NM(s){if(n.messageActions?.showEdit!==!0)return;let l=H.getMessages().find(f=>f.id===s);!l||!Qf(l)||ps!==s&&(fs(),ps=s,Mr=yC({messageId:s,initialText:l.content,onSave:f=>FM(s,f),onCancel:()=>fs()}),Dt.delete(s),Jo(ke,H.getMessages(),oo),Mr.focus())}function FM(s,l){let f=Mr;if(ps=null,Mr=null,f?.destroy(),Dt.delete(s),!H.resubmitFrom(s,{reason:"edit",replacement:{text:l,mentionRefs:[],options:{}}})){Jo(ke,H.getMessages(),oo);return}Lo()}function UM(s){if(H.isStreaming())return;let l=Xf(H.getMessages(),s);l&&(fs(),H.resubmitFrom(l,{reason:"retry"})&&Lo())}Zl={regenerate:UM,edit:NM,quote:s=>{let f=H.getMessages().find(g=>g.id===s)?.content?.trim();f&&(Tn({text:f,messageId:s}),le?.focus())}};let ji=async s=>{if(!ar){ar=!0;try{await Eb({resolveInlineCommand:!0,...s})}finally{ar=!1}}};function Xd(s){xs()||(Gd(),Qd(s,{consumeDraft:!1}))}let Qd=(s,l)=>{if(ar)return;ar=!0;let f=()=>{ar=!1};try{let g=Eb({...l,overrideText:s});g instanceof Promise?g.finally(f):f()}catch(g){throw f(),g}},qM=s=>{if(s.preventDefault(),H.isStreaming()){H.cancel(),ut?.reset(),B?.update();return}ar||ji()},$M=()=>n.features?.composerHistory!==!1,mf={...fg},gf=!1,zi=()=>{mf={...fg}},VM=()=>H.getMessages().filter(s=>s.role==="user").map(s=>s.content??"").filter(s=>s.length>0),jM=s=>{if(!le)return;gf=!0,le.value=s,le.dispatchEvent(new Event("input",{bubbles:!0})),gf=!1;let l=le.value.length;le.setSelectionRange(l,l)},zM=s=>{gf||(s.isComposing||Wt?.handleInput(s.inputType??void 0),zi())},KM=()=>({submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Cl(le)}),GM=s=>{if(le&&!Lr()&&!(!s.isComposing&&Wt?.handleKeydown(s))){if($M()&&(s.key==="ArrowUp"||s.key==="ArrowDown")&&!s.shiftKey&&!s.metaKey&&!s.ctrlKey&&!s.altKey&&!s.isComposing){let l=le.selectionStart===0&&le.selectionEnd===0,f=KC({direction:s.key==="ArrowUp"?"up":"down",history:VM(),currentValue:le.value,atStart:l,state:mf});if(mf=f.state,f.handled){s.preventDefault(),f.value!==void 0&&jM(f.value);return}}if(Qx(s,KM())){if(H.isStreaming()){if(s.preventDefault(),tp()==="block"||ar||xs())return;zi(),ji();return}if(ar){s.preventDefault();return}if(xs()){s.preventDefault();return}zi(),s.preventDefault(),Me.click()}}},kb=s=>{if(!(s.key!=="Escape"||s.isComposing)&&s.composedPath().includes(ue)){if(ks){ks.abort(),ks=null,s.preventDefault(),s.stopImmediatePropagation();return}H.isStreaming()&&(H.cancel(),ut?.reset(),B?.update(),zi(),s.preventDefault(),s.stopImmediatePropagation())}},XM=async s=>{if(n.attachments?.enabled!==!0||!Ze||Lr())return;let l=KL(s.clipboardData);l.length!==0&&(s.preventDefault(),await Ze.handleFiles(l))},on=null,Hn=!1,Ma=null,vt=null,hf=()=>n.voiceRecognition?.completionBehavior==="review";function Ls(s){se?.setAttribute("data-state",s),s==="recording"?YM():xf()}let Lb="--persona-voice-level",yf=.5,Ta=null,bf=-1,Yd=0,Ib=()=>{let s=[],l=_o??se?.parentElement??null;return l&&s.push(l),Ie&&s.push(Ie),s},vf=s=>{let l=Math.round(Math.max(0,Math.min(1,s))*100)/100;if(l!==bf){bf=l;for(let f of Ib())f.style.setProperty(Lb,String(l))}},QM=()=>{bf=-1,Yd=0;for(let s of Ib())s.style.removeProperty(Lb)};function YM(){if(Ta!==null)return;if(typeof requestAnimationFrame!="function"){vf(u?H.getVoiceLevel()??yf:yf);return}let s=()=>{Ta=requestAnimationFrame(s);let l=u?H.getVoiceLevel():null;if(l===null){vf(yf);return}Yd+=(l-Yd)*.3,vf(Yd)};Ta=requestAnimationFrame(s)}function xf(){Ta!==null&&(cancelAnimationFrame(Ta),Ta=null),QM()}let Rb=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Jd=(s="user")=>{if(Hn||H.isStreaming())return;let l=Rb();if(!l)return;on=new l;let f=n.voiceRecognition??{},g=f.pauseDuration??2e3;on.continuous=f.provider?.browser?.continuous??!0,on.interimResults=!0,on.lang=f.provider?.browser?.language??"en-US";let v=le.value;on.onresult=M=>{let N="",z="";for(let K=0;K<M.results.length;K++){let J=M.results[K],ae=J[0].transcript;J.isFinal?N+=ae+" ":z=ae}let V=v+N+z;le.value=V,Mn(),Ma&&clearTimeout(Ma),(N||z)&&(Ma=window.setTimeout(()=>{if(le.value.trim()&&on&&Hn){if(Wr(),hf())return;ji({viaVoice:!0})}},g))},on.onerror=M=>{M.error!=="no-speech"&&Wr()},on.onend=()=>{if(Hn){let M=le.value.trim();!hf()&&M&&M!==v.trim()&&ji({viaVoice:!0}),Wr()}};try{if(on.start(),Hn=!0,je.active=!0,s!=="system"&&(je.manuallyDeactivated=!1),Jn(s),gn(),pn(),se){let M=n.voiceRecognition??{};vt={backgroundColor:se.style.backgroundColor,color:se.style.color,borderColor:se.style.borderColor,iconName:M.iconName??"mic",iconSize:parseFloat(M.iconSize??"")||vo};let N=M.recordingBackgroundColor,z=M.recordingIconColor,V=M.recordingBorderColor;if(se.classList.add("persona-voice-recording"),Ls("recording"),se.style.backgroundColor=N??"var(--persona-voice-recording-bg, #ef4444)",se.style.color=z??"var(--persona-voice-recording-indicator, #ffffff)",z){let K=se.querySelector("svg");K&&K.setAttribute("stroke",z)}V&&(se.style.borderColor=V),se.setAttribute("aria-label","Stop voice recognition")}}catch{Wr("system")}},Wr=(s="user")=>{if(Hn){if(Hn=!1,Ma&&(clearTimeout(Ma),Ma=null),on){try{on.stop()}catch{}on=null}if(je.active=!1,Jn(s),gn(),pn(),se){if(se.classList.remove("persona-voice-recording"),Ls("idle"),vt){se.style.backgroundColor=vt.backgroundColor,se.style.color=vt.color,se.style.borderColor=vt.borderColor;let l=se.querySelector("svg");l&&l.setAttribute("stroke",vt.color||"currentColor"),vt=null}se.setAttribute("aria-label","Start voice recognition")}}},Cf=()=>{if(!se||vt)return;let s=n.voiceRecognition??{};vt={backgroundColor:se.style.backgroundColor,color:se.style.color,borderColor:se.style.borderColor,iconName:s.iconName??"mic",iconSize:parseFloat(s.iconSize??"")||vo}},Sf=(s,l)=>{if(!se)return;let f=se.querySelector("svg");f&&f.remove();let g=vt?.iconSize??(parseFloat(n.voiceRecognition?.iconSize??"")||vo),v=ce(s,g,l,1.5);v&&se.appendChild(v)},Zd=()=>{se&&se.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ea=()=>{if(!se)return;Cf();let s=n.voiceRecognition??{},l=s.recordingBackgroundColor,f=s.recordingIconColor,g=s.recordingBorderColor;if(Zd(),se.classList.add("persona-voice-recording"),Ls("recording"),se.style.backgroundColor=l??"var(--persona-voice-recording-bg, #ef4444)",se.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let v=se.querySelector("svg");v&&v.setAttribute("stroke",f)}g&&(se.style.borderColor=g),se.setAttribute("aria-label","Stop voice recognition")},JM=()=>{if(!se)return;Cf();let s=n.voiceRecognition??{},l=H.getVoiceInterruptionMode(),f=s.processingIconName??"loader",g=s.processingIconColor??vt?.color??"",v=s.processingBackgroundColor??vt?.backgroundColor??"",M=s.processingBorderColor??vt?.borderColor??"";Zd(),se.classList.add("persona-voice-processing"),Ls("processing"),se.style.backgroundColor=v,se.style.borderColor=M;let N=g||"currentColor";se.style.color=N,Sf(f,N),se.setAttribute("aria-label","Processing voice input"),l==="none"&&(se.style.cursor="default")},ZM=()=>{if(!se)return;Cf();let s=n.voiceRecognition??{},l=H.getVoiceInterruptionMode(),f=l==="cancel"?"square":l==="barge-in"?"mic":"volume-2",g=s.speakingIconName??f,v=s.speakingIconColor??(l==="barge-in"?s.recordingIconColor??vt?.color??"":vt?.color??""),M=s.speakingBackgroundColor??(l==="barge-in"?s.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),N=s.speakingBorderColor??(l==="barge-in"?s.recordingBorderColor??"":vt?.borderColor??"");Zd(),se.classList.add("persona-voice-speaking"),Ls("speaking"),se.style.backgroundColor=M,se.style.borderColor=N;let z=v||"currentColor";se.style.color=z,Sf(g,z);let V=l==="cancel"?"Stop playback and re-record":l==="barge-in"?"Speak to interrupt":"Agent is speaking";se.setAttribute("aria-label",V),l==="none"&&(se.style.cursor="default"),l==="barge-in"&&se.classList.add("persona-voice-recording")},ir=()=>{se&&(Zd(),Ls("idle"),vt&&(se.style.backgroundColor=vt.backgroundColor??"",se.style.color=vt.color??"",se.style.borderColor=vt.borderColor??"",Sf(vt.iconName,vt.color||"currentColor"),vt=null),se.style.cursor="",se.setAttribute("aria-label","Start voice recognition"))},wf=()=>{if(!Lr()){if(n.voiceRecognition?.provider?.type==="runtype"){let s=H.getVoiceStatus(),l=H.getVoiceInterruptionMode();if(l==="none"&&(s==="processing"||s==="speaking"))return;if(l==="cancel"&&(s==="processing"||s==="speaking")){H.stopVoicePlayback();return}if(H.isBargeInActive()){H.stopVoicePlayback(),H.deactivateBargeIn().then(()=>{je.active=!1,je.manuallyDeactivated=!0,gn(),Jn("user"),ir()});return}H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),je.manuallyDeactivated=!H.isVoiceActive(),gn(),Jn("user"),H.isVoiceActive()?Ea():ir()});return}if(Hn){let s=le.value.trim();je.manuallyDeactivated=!0,gn(),Wr("user"),s&&!hf()&&ji()}else je.manuallyDeactivated=!1,gn(),Jd("user")}};op=wf,se&&ye.push(()=>{n.voiceRecognition?.provider?.type==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),ir()):Wr("system")});let eT=C.on("assistant:complete",()=>{Se.getState().pendingSubmission&&setTimeout(()=>{H.isStreaming()||_M()},0)});ye.push(eT);let tT=C.on("assistant:complete",()=>{vy&&(je.active||je.manuallyDeactivated||vy==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{!je.active&&!je.manuallyDeactivated&&(n.voiceRecognition?.provider?.type==="runtype"?H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),Jn("auto"),H.isVoiceActive()&&Ea()}):Jd("auto"))},600))});ye.push(tT);let oT=C.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});ye.push(oT);let Hb=()=>{dt(!he,"user")},Pt=null,go=null;if(ge&&!Ae()){let{instance:s,element:l}=qg({config:n,plugins:i,onToggle:Hb});Pt=s,s||(go=l)}Pt?e.appendChild(Pt.element):go&&e.appendChild(go),Li(),ia(),wd(),Rp(),Ii(H.isStreaming()),Cp()||(No()==="follow"?Pr(!0):hd()),SA(),Bt&&(!ge||Ae()?setTimeout(()=>Cs(),0):he&&setTimeout(()=>Cs(),200));let Is=null,Wb=()=>{Is&&(Is.disconnect(),Is.observe(Ie),Is.observe(ue))},Ki=()=>{if(Ae()){ns(),Li();return}let s=St(n),l=n.launcher?.sidebarMode??!1,f=e.ownerDocument.defaultView??window,g=n.launcher?.mobileFullscreen??!0,v=n.launcher?.mobileBreakpoint??640,M=f.innerWidth<=v,N=g&&M&&ge;try{if(N){ss(),vi=id();return}let z=!1;Ge&&(Ge=!1,ss(),z=!0);let V=id();if(!z&&V!==vi&&(ss(),z=!0),vi=V,z&&nd(),!ge&&!s){we.style.height="",we.style.width="";return}if(!l&&!s){let J=n?.launcher?.width??n?.launcherWidth??zo;we.style.width=J,we.style.maxWidth=J}ad(),ny()}finally{if(ns(),Yl(),Li(),he&&ge){let V=(e.ownerDocument.defaultView??window).innerWidth<=(n.launcher?.mobileBreakpoint??640),K=n.launcher?.sidebarMode??!1,J=n.launcher?.mobileFullscreen??!0,ae=St(n)&&J&&V,fe=K||J&&V&&ge||ae;if(fe&&!Ln){let Je=e.getRootNode(),lt=Je instanceof ShadowRoot?Je.host:e.closest(".persona-host");lt&&!kn&&(kn=vg(lt,n.launcher?.zIndex??so)),Ln=xg(e.ownerDocument)}else fe||(kn?.(),kn=null,Ln?.(),Ln=null)}}};Ki();let ec=e.ownerDocument.defaultView??window;if(ec.addEventListener("resize",Ki),ye.push(()=>ec.removeEventListener("resize",Ki)),typeof ResizeObserver<"u"){Is=new ResizeObserver(()=>{Yl()}),Wb(),ye.push(()=>{Is?.disconnect(),Is=null});let s=new ResizeObserver(()=>{Nd()});s.observe(ue),ye.push(()=>s.disconnect())}ec.addEventListener("resize",Nd),ye.push(()=>ec.removeEventListener("resize",Nd)),qo=re.scrollTop;let Bb=Vn(re),Ob=()=>{let s=re.scrollTop,l=Vn(re),f=l<Bb;if(Bb=l,!xr()){qo=s,Vt();return}let{action:g,nextLastScrollTop:v}=tS({following:Uo.isFollowing(),currentScrollTop:s,lastScrollTop:qo,nearBottom:qs(re,Qn),userScrollThreshold:bA,isAutoScrolling:Po||dd||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(qo=v,g==="resume"){yd()||ko();return}g==="pause"&&Mi()};if(re.addEventListener("scroll",Ob,{passive:!0}),ye.push(()=>re.removeEventListener("scroll",Ob)),typeof ResizeObserver<"u"){let s=new ResizeObserver(()=>{kA(),Lf(ke)});s.observe(ke),s.observe(re),ye.push(()=>s.disconnect())}let Db=()=>{xr()&&Uo.isFollowing()&&yd()&&Mi()},_b=re.ownerDocument;_b.addEventListener("selectionchange",Db),ye.push(()=>{_b.removeEventListener("selectionchange",Db)});let nT=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Nb=s=>{nT.has(s.key)&&(ys(),Ah()&&xr()&&Uo.isFollowing()&&Mi())},Fb=s=>{s.target?.closest("a, button, [tabindex], input, textarea, select")&&(ys(),Ah()&&xr()&&Uo.isFollowing()&&Mi())};re.addEventListener("keydown",Nb),re.addEventListener("focusin",Fb),ye.push(()=>{re.removeEventListener("keydown",Nb),re.removeEventListener("focusin",Fb)});let Ub=s=>{if(s.deltaY!==0&&ys(),!xr())return;let l=oS({following:Uo.isFollowing(),deltaY:s.deltaY,nearBottom:qs(re,Qn),resumeWhenNearBottom:!0});l==="pause"?Mi():l==="resume"&&!yd()&&ko()};re.addEventListener("wheel",Ub,{passive:!0}),re.addEventListener("touchmove",ys,{passive:!0}),re.addEventListener("pointerdown",ys,{passive:!0}),ye.push(()=>{re.removeEventListener("touchmove",ys),re.removeEventListener("pointerdown",ys)}),ye.push(()=>re.removeEventListener("wheel",Ub)),Ot.addEventListener("click",()=>{hn(),re.scrollTop=re.scrollHeight,qo=re.scrollTop,ko(),Pr(!0),Vt()}),ye.push(()=>Ot.remove()),ye.push(()=>{Ay(),hn()});let qb=()=>{Ue&&(ds&&(Ue.removeEventListener("click",ds),ds=null),De()?(Ue.style.display="",ds=()=>{dt(!1,"user")},Ue.addEventListener("click",ds)):Ue.style.display="none")};qb(),(()=>{let{clearChatButton:s}=_e;s&&s.addEventListener("click",()=>{if(Rn()){df({focusComposer:!0}).catch(f=>{n.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}H.clearMessages(),Dt.clear(),ko(),$r(_e.composerOverlay);try{localStorage.removeItem(ii),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ii}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ii)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),F?.clear&&fd(()=>F.clear(),"[AgentWidget] Failed to clear storage adapter:"),X={},Ee.syncFromMetadata(),Ze?.clearAttachments(),gd(),ta(void 0),Tn(void 0),fs(),Tt?.clear(),ut?.reset(),B?.update()})})();let $b=[["keydown",GM],["input",zM],["input",Mn],["input",rs],["keyup",rs],["paste",XM],["focus",aA]],Vb=s=>{if(s)for(let[l,f]of $b)ot?.addListener(s,l,f)},rT=s=>{if(s)for(let[l,f]of $b)ot?.removeListener(s,l,f)},jb=()=>{ot&&(ot.addListener(ot.form,"submit",qM),ot.addListener(ot.footer,"click",rs),Vb(le),se&&ot.addListener(se,"click",wf))};jb();let zb=()=>{Wt?.onComposerSwap((s,l)=>{rT(l),le=s,ot&&(ot.input=s),Vb(s),rp(),Mp(),Mn()})};zb();let Af=!1;function Kb(){if(!Af){Af=!0;try{let s=le?.value??"",l=Ie.ownerDocument??document,f=le?l.activeElement===le:!1;xf(),ot?.destroy(),ot=null,Wt?.destroy(),Wt=null;let g=null,v=()=>(g=Ae()?xu({config:n}):Ks({config:n}),g.footer),M=Wh(v)??v();Oo.replaceComposer(M),Ie=Oo.composer.footer;let N=g!==null&&M===g.footer;na=!N,wh=N?g.setSendButtonMode:()=>{},Hh(Ie),Oh(Ie),Dh(),_h(),Nh(),zb(),Fh(),sp(),Uh(),jb();let z=ls.indexOf(Xn);Xn.destroy(),Xn=Bl(br),z>=0&&(ls[z]=Xn),le&&(le.value=s),Mn(),rs(),wd(),ia(),Ii(H.isStreaming()),je.active&&Ls("recording"),ss(),Wb(),ns(),pn(),Cd(),f&&le?.focus()}finally{Af=!1}}}let Gi=e.ownerDocument??document;Gi.addEventListener("keydown",kb,!0);let Gb=()=>{yp()},Xb=()=>{Gi.visibilityState==="hidden"&&yp()};typeof window<"u"&&(window.addEventListener("pagehide",Gb),Gi.addEventListener("visibilitychange",Xb),ye.push(()=>{window.removeEventListener("pagehide",Gb),Gi.removeEventListener("visibilitychange",Xb)}));let Qb="persona-attachment-drop-active",Xi=0,Mf=()=>{Xi=0,ue.classList.remove(Qb)},Pa=()=>n.attachments?.enabled===!0&&Ze!==null&&!Lr(),Yb=s=>{!$u(s.dataTransfer)||!Pa()||(Xi++,Xi===1&&ue.classList.add(Qb))},Jb=s=>{!$u(s.dataTransfer)||!Pa()||(Xi--,Xi<=0&&Mf())},Zb=s=>{!$u(s.dataTransfer)||!Pa()||(s.preventDefault(),s.dataTransfer.dropEffect="copy")},ev=s=>{if(!$u(s.dataTransfer)||!Pa())return;s.preventDefault(),s.stopPropagation(),Mf();let l=Array.from(s.dataTransfer.files??[]);l.length!==0&&Ze.handleFiles(l)},Br=!0;ue.addEventListener("dragenter",Yb,Br),ue.addEventListener("dragleave",Jb,Br),e.addEventListener("dragover",Zb,Br),e.addEventListener("drop",ev,Br);let tc=e.ownerDocument,tv=s=>{Pa()&&s.preventDefault()},ov=s=>{Pa()&&s.preventDefault()};tc.addEventListener("dragover",tv),tc.addEventListener("drop",ov),ye.push(()=>{ot?.destroy(),ot=null,xf(),En?.destroy(),En=null,Kn?.destroy(),Kn=null,Sr?.destroy(),Sr=null,wr?.destroy(),wr=null,Cr=null,ep=null,yp(),Ai.destroy(),Aa&&clearTimeout(Aa),fs(),ks?.abort(),ks=null,Ze?.destroy(),Ze=null,Se.destroy(),Gi.removeEventListener("keydown",kb,!0),Wt?.destroy()}),ye.push(()=>{ue.removeEventListener("dragenter",Yb,Br),ue.removeEventListener("dragleave",Jb,Br),e.removeEventListener("dragover",Zb,Br),e.removeEventListener("drop",ev,Br),tc.removeEventListener("dragover",tv),tc.removeEventListener("drop",ov),Mf()}),ye.push(()=>{H.cancel()}),Pt?ye.push(()=>{Pt?.destroy()}):go&&ye.push(()=>{go?.remove()});let kt={update(s){let l=n.toolCall,f=n.messageActions,g=n.layout?.messages,v=n.colorScheme,M=n.loadingIndicator,N=n.iterationDisplay,z=n.features?.showReasoning,V=n.features?.showToolCalls,K=n.features?.toolCallDisplay,J=n.features?.reasoningDisplay,ae=n.features?.streamAnimation?.type,fe=n.features?.history?.enabled===!0,Je=n.features?.history?.provider,lt=n.getIdentityProof,ct=n.clientToken,Qt=n.contextMentions;n=Bu({...n,features:a},s),a=n.features,n=Nl(n),r(),up(),Us(e,n),Dl(e,n),_l(e,n),ht(),mn(),n.colorScheme!==v&&ry();let Nt=Fl.getForInstance(n.plugins);i.length=0,i.push(...Nt),nb(),ge=n.launcher?.enabled??!0,Ke=n.launcher?.autoExpand??!1,Xo=n.features?.showReasoning??!0,Sn=n.features?.showToolCalls??!0,Jr=n.features?.scrollToBottom??{};let Lt=No();Ao=n.features?.scrollBehavior??{},Lt!==No()&&(hn(),ko()),by(),Eh(),Vt();let io=Rt;if(Rt=n.features?.showEventStreamToggle??!1,Rt&&!io){if(Tt||(oe(),H.setSSEEventCallback((Z,ze)=>{n.onSSEEvent?.(Z,ze),$(Z,ze)})),!tt&&Te){let Z=n.features?.eventStream?.classNames,ze="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"+(Z?.toggleButton?" "+Z.toggleButton:"");tt=I("button",ze),tt.style.width="28px",tt.style.height="28px",tt.style.color=Co.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let Qe=Ft(Na,"18px","currentColor",1.5);Qe&&tt.appendChild(Qe);let nt=_e.clearChatButtonWrapper,Ct=_e.closeButtonWrapper,no=nt||Ct;no&&no.parentNode===Te?Te.insertBefore(tt,no):Te.appendChild(tt),tt.addEventListener("click",()=>{ee?oa():np()})}}else!Rt&&io&&(oa(),tt&&(tt.remove(),tt=null),Tt?.clear(),po?.destroy(),Tt=null,po=null,ut?.reset(),ut=null,cn=null);if(n.launcher?.enabled===!1&&Pt&&(Pt.destroy(),Pt=null),n.launcher?.enabled===!1&&go&&(go.remove(),go=null),n.launcher?.enabled!==!1&&!Pt&&!go){let{instance:Z,element:ze}=qg({config:n,plugins:i,onToggle:Hb});Pt=Z,Z||(go=ze),e.appendChild(ze)}Pt&&Pt.update(n),Vi(),ts&&n.launcher?.subtitle!==void 0&&(ts.textContent=n.launcher.subtitle);let et=n.layout?.header;if(et?.layout!==qe&&Te){let Z=et?Ya(n,et,{showClose:De(),onClose:()=>dt(!1,"user")}):mr({config:n,showClose:De(),onClose:()=>dt(!1,"user")});Oo.replaceHeader(Z),Te=Oo.header.element,Et=Oo.header.iconHolder,vr=Oo.header.headerTitle,ts=Oo.header.headerSubtitle,Ue=Oo.header.closeButton,qe=et?.layout,Vi()}else if(et){if(Et&&(Et.style.display=et.showIcon===!1?"none":""),vr&&(vr.style.display=et.showTitle===!1?"none":""),ts&&(ts.style.display=et.showSubtitle===!1?"none":""),Ue){let Z=De()&&et.showCloseButton!==!1;Ue.style.display=Z?"":"none"}if(_e.clearChatButtonWrapper){let Z=et.showClearChat;if(Z!==void 0){_e.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:ze}=_e;ze&&!ze.classList.contains("persona-absolute")&&(Z?ze.classList.remove("persona-ml-auto"):ze.classList.add("persona-ml-auto"))}}}let lr=n.layout?.showHeader!==!1;Te&&(Te.style.display=lr?"":"none");let Wn=n.layout?.showFooter!==!1;Ie&&(Ie.style.display=Wn?"":"none"),ns(),Vt(),ge!==j?ge?dt(Ke,"auto"):(he=!0,Li()):Ke!==Le&&dt(Ke,"auto"),Le=Ke,j=ge,Ki(),qb();let We=JSON.stringify(n.toolCall)!==JSON.stringify(l),Oe=JSON.stringify(n.messageActions)!==JSON.stringify(f),me=JSON.stringify(n.layout?.messages)!==JSON.stringify(g),pt=n.loadingIndicator?.render!==M?.render||n.loadingIndicator?.renderIdle!==M?.renderIdle||n.loadingIndicator?.showBubble!==M?.showBubble,jt=n.iterationDisplay!==N,co=(n.features?.showReasoning??!0)!==(z??!0)||(n.features?.showToolCalls??!0)!==(V??!0)||JSON.stringify(n.features?.toolCallDisplay)!==JSON.stringify(K)||JSON.stringify(n.features?.reasoningDisplay)!==JSON.stringify(J);(We||Oe||me||pt||jt||co)&&H&&(ms++,Jo(ke,H.getMessages(),oo));let It=n.features?.streamAnimation?.type;if(It!==ae&&It&&It!=="none"){let Z=fp(It,n.features?.streamAnimation?.plugins);Z&&Rl(Z,e)}let Pe=n.launcher??{},zt=Pe.headerIconHidden??!1,Kt=n.layout?.header?.showIcon,rn=zt||Kt===!1,Re=Pe.headerIconName,xt=Pe.headerIconSize??"48px";if(Et){let Z=Te,ze=Z?.querySelector(".persona-flex-col");if(rn)Et.style.display="none",Z&&ze&&!Z.contains(ze)&&Z.insertBefore(ze,Z.firstChild);else{if(Et.style.display="",Et.style.height=xt,Et.style.width=xt,Z&&ze&&(Z.contains(Et)?Et.nextSibling!==ze&&(Et.remove(),Z.insertBefore(Et,ze)):Z.insertBefore(Et,ze)),Re){let nt=parseFloat(xt)||24,Ct=ce(Re,nt*.6,"currentColor",1);Ct?Et.replaceChildren(Ct):Et.textContent=Pe.agentIconText??"\u{1F4AC}"}else if(Pe.iconUrl){let nt=Et.querySelector("img");if(nt)nt.src=Pe.iconUrl,nt.style.height=xt,nt.style.width=xt;else{let Ct=document.createElement("img");Ct.src=Pe.iconUrl,Ct.alt="",Ct.className="persona-rounded-xl persona-object-cover",Ct.style.height=xt,Ct.style.width=xt,Et.replaceChildren(Ct)}}else{let nt=Et.querySelector("svg"),Ct=Et.querySelector("img");(nt||Ct)&&Et.replaceChildren(),Et.textContent=Pe.agentIconText??"\u{1F4AC}"}let Qe=Et.querySelector("img");Qe&&(Qe.style.height=xt,Qe.style.width=xt)}}let On=n.layout?.header?.showTitle,yn=n.layout?.header?.showSubtitle;if(vr&&(vr.style.display=On===!1?"none":""),ts&&(ts.style.display=yn===!1?"none":""),Ue){let Z=De()&&n.layout?.header?.showCloseButton!==!1;if(Ue.style.display=Z?"":"none",!Ae()){let Yt=Pe.closeButtonSize??"";Ue.style.height=Yt,Ue.style.width=Yt,Ue.style.minWidth=Yt,Ue.style.minHeight=Yt}let ze=Pe.closeButtonPlacement??"inline",{closeButtonWrapper:Qe}=_e,nt=ze==="top-right",Ct=Qe?.classList.contains("persona-absolute");if(Qe&&nt!==Ct)if(Qe.remove(),nt){Qe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Yt=Oi??ue;Yt.style.position="relative",Yt.appendChild(Qe)}else{let Yt=Pe.clearChat?.placement??"inline",Jt=Pe.clearChat?.enabled??!0;Qe.className=Jt&&Yt==="inline"?"":"persona-ml-auto",Te&&Te.appendChild(Qe)}if(Ue.style.color=Pe.closeButtonColor||Co.actionIconColor,Pe.closeButtonBackgroundColor?(Ue.style.backgroundColor=Pe.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),Pe.closeButtonBorderWidth||Pe.closeButtonBorderColor){let Yt=Pe.closeButtonBorderWidth||"0px",Jt=Pe.closeButtonBorderColor||"transparent";Ue.style.border=`${Yt} solid ${Jt}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");Pe.closeButtonBorderRadius?(Ue.style.borderRadius=Pe.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),Pe.closeButtonPaddingX?(Ue.style.paddingLeft=Pe.closeButtonPaddingX,Ue.style.paddingRight=Pe.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),Pe.closeButtonPaddingY?(Ue.style.paddingTop=Pe.closeButtonPaddingY,Ue.style.paddingBottom=Pe.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom=""),yu(Ue,Pe.closeButtonIconName??"x",{iconSize:Ae()?_g:void 0,iconText:Pe.closeButtonIconText??"\xD7"});let no=Pe.closeButtonTooltipText??"Close chat",bn=Pe.closeButtonShowTooltip??!0;Ue.setAttribute("aria-label",no),Qe&&eo({anchor:Ue,trigger:Qe,text:()=>Ue?.getAttribute("aria-label")??no,enabled:bn})}let{clearChatButton:Be,clearChatButtonWrapper:ve}=_e;if(Be){let Z=Pe.clearChat??{},ze=Z.enabled??!0,Qe=n.layout?.header?.showClearChat,nt=Qe!==void 0?Qe:ze,Ct=Z.placement??"inline";if(ve){ve.style.display=nt?"":"none";let{closeButtonWrapper:no}=_e;!Ae()&&no&&!no.classList.contains("persona-absolute")&&(nt?no.classList.remove("persona-ml-auto"):no.classList.add("persona-ml-auto"));let bn=Ct==="top-right",Yt=ve.classList.contains("persona-absolute");if(!Ae()&&bn!==Yt&&nt){if(ve.remove(),bn){ve.className="persona-absolute persona-top-4 persona-z-50",ve.style.right="48px";let Dn=Oi??ue;Dn.style.position="relative",Dn.appendChild(ve)}else{ve.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ve.style.right="";let Dn=_e.closeButtonWrapper;Te&&Dn&&Dn.parentElement===Te?Te.insertBefore(ve,Dn):Te&&Te.appendChild(ve)}let Jt=_e.closeButtonWrapper;Jt&&!Jt.classList.contains("persona-absolute")&&(bn?Jt.classList.add("persona-ml-auto"):Jt.classList.remove("persona-ml-auto"))}}if(nt){if(!Ae()){let Jt=Z.size??"";Be.style.height=Jt,Be.style.width=Jt,Be.style.minWidth=Jt,Be.style.minHeight=Jt}let no=Z.iconColor??"";if(Be.style.color=no||Co.actionIconColor,yu(Be,Z.iconName??"refresh-cw",{iconSize:Ae()?Ng:void 0}),Z.backgroundColor?(Be.style.backgroundColor=Z.backgroundColor,Be.classList.remove("hover:persona-bg-gray-100")):(Be.style.backgroundColor="",Be.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let Jt=Z.borderWidth||"0px",Dn=Z.borderColor||"transparent";Be.style.border=`${Jt} solid ${Dn}`,Be.classList.remove("persona-border-none")}else Be.style.border="",Be.classList.add("persona-border-none");Z.borderRadius?(Be.style.borderRadius=Z.borderRadius,Be.classList.remove("persona-rounded-full")):(Be.style.borderRadius="",Be.classList.add("persona-rounded-full")),Z.paddingX?(Be.style.paddingLeft=Z.paddingX,Be.style.paddingRight=Z.paddingX):(Be.style.paddingLeft="",Be.style.paddingRight=""),Z.paddingY?(Be.style.paddingTop=Z.paddingY,Be.style.paddingBottom=Z.paddingY):(Be.style.paddingTop="",Be.style.paddingBottom="");let bn=Z.tooltipText??"Clear chat",Yt=Z.showTooltip??!0;Be.setAttribute("aria-label",bn),ve&&eo({anchor:Be,trigger:ve,text:()=>Be?.getAttribute("aria-label")??bn,enabled:Yt})}}let Ne=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ul],ft=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Ys.message,Ys.messageAndClick];Ee=ql({parsers:Ne,handlers:ft,getSessionMetadata:Q,updateSessionMetadata:de,emit:C.emit,documentRef:typeof document<"u"?document:null}),oo=Aw(n,Ee,Js),KA(),H.updateConfig(n),(n.features?.history?.enabled===!0!==fe||n.features?.history?.provider!==Je||n.getIdentityProof!==lt||n.clientToken!==ct)&&(Io({restoreFocus:!1}),Xy()),Hr(),Nd(),Jo(ke,H.getMessages(),oo),ia(),wd(),jA(),Ii(H.isStreaming()),Qt!==n.contextMentions&&Kb();let Or=n.voiceRecognition?.enabled===!0,Gt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),jo=n.voiceRecognition?.provider?.type==="runtype";if(Or&&(Gt||jo))if(!se||!_o){let Z=za(n);if(Z){se=Z.button,_o=Z.wrapper;let ze=An&&An.parentElement===zl?An:null;zl?zl.insertBefore(_o,ze):un?.appendChild(_o),ot&&(ot.micButton=se),ot?.addListener(se,"click",wf),se.disabled=H.isStreaming()}}else{let Z=n.voiceRecognition??{},ze=n.sendButton??{},Qe=Z.iconName??"mic",nt=Z.iconSize,Ct=parseFloat(nt??"")||vo;se.classList.add(Ko),se.classList.toggle(vn,!nt),se.style.width=nt??"",se.style.height=nt??"",se.style.minWidth=nt??"",se.style.minHeight=nt??"";let no=Z.iconColor??ze.textColor;se.innerHTML="";let bn=ce(Qe,Ct,no||"currentColor",1.5);bn?se.appendChild(bn):se.textContent="\u{1F3A4}";let Yt=Z.backgroundColor??ze.backgroundColor;Yt?se.style.backgroundColor=Yt:se.style.backgroundColor="",no?se.style.color=no:se.style.color="var(--persona-text, #111827)",Z.borderWidth?(se.style.borderWidth=Z.borderWidth,se.style.borderStyle="solid"):(se.style.borderWidth="",se.style.borderStyle=""),Z.borderColor?se.style.borderColor=Z.borderColor:se.style.borderColor="",Z.paddingX?(se.style.paddingLeft=Z.paddingX,se.style.paddingRight=Z.paddingX):(se.style.paddingLeft="",se.style.paddingRight=""),Z.paddingY?(se.style.paddingTop=Z.paddingY,se.style.paddingBottom=Z.paddingY):(se.style.paddingTop="",se.style.paddingBottom="");let Jt=Z.tooltipText??"Start voice recognition",Dn=Z.showTooltip??!1;se.setAttribute("aria-label",Jt),_o&&eo({anchor:se,trigger:_o,text:()=>se?.getAttribute("aria-label")??Jt,enabled:Dn}),_o.style.display="",se.disabled=H.isStreaming()}else se&&_o&&(_o.style.display="none",n.voiceRecognition?.provider?.type==="runtype"?H.isVoiceActive()&&H.toggleVoice():Hn&&Wr());if(n.attachments?.enabled===!0){if(!To||!At){let Z=n.attachments??{};Eo||(Eo=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Eo.style.display="none",(le.parentElement??un).insertBefore(Eo,le)),yt||(yt=document.createElement("input"),yt.type="file",yt.accept=(Z.allowedTypes??fr).join(","),yt.multiple=(Z.maxFiles??4)>1,yt.style.display="none",yt.setAttribute("aria-label","Attach files"),(le.parentElement??un).insertBefore(yt,le)),To=I("div","persona-send-button-wrapper"),At=I("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Ko} ${vn}`),At.type="button",At.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let ze=Z.buttonIconName??"paperclip";At.style.fontSize="18px",At.style.lineHeight="1";let Qe=ce(ze,vo,"currentColor",1.5);Qe?At.appendChild(Qe):At.textContent="\u{1F4CE}",At.addEventListener("click",Ct=>{Ct.preventDefault(),yt?.click()}),To.appendChild(At);let nt=Z.buttonTooltipText??"Attach file";eo({anchor:At,trigger:To,text:()=>At?.getAttribute("aria-label")??nt}),Gu?Gu.append(To):un.appendChild(To),ot&&(ot.attachmentButton=At,ot.attachmentInput=yt??void 0,ot.attachmentPreviews=Eo??void 0),!Ze&&yt&&Eo&&(Ze=Fs.fromConfig(Z,Ph),Ze.setPreviewsContainer(Eo),ot?.addListener(yt,"change",async()=>{Ze&&yt?.files&&(await Ze.handleFileSelect(yt.files),yt.value="")}))}else{To.style.display="";let Z=n.attachments??{};yt&&(yt.accept=(Z.allowedTypes??fr).join(","),yt.multiple=(Z.maxFiles??4)>1),Ze&&Ze.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles,adapter:Z.adapter})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(Mw(n.attachments?.dropOverlay)),At){let Z=n.attachments??{},ze=Z.buttonTooltipText??"Attach file";At.setAttribute("aria-label",ze),At.textContent="";let Qe=ce(Z.buttonIconName??"paperclip",vo,"currentColor",1.5);Qe?At.appendChild(Qe):At.textContent="\u{1F4CE}",To&&eo({anchor:At,trigger:To,text:()=>At?.getAttribute("aria-label")??ze})}}else To&&(To.style.display="none"),Ze&&Ze.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Mt=n.sendButton??{},Tf=Mt.useIcon??!1,Hs=Mt.iconText??"\u2191",oc=Mt.iconName,rv=Mt.tooltipText??"Send message",iT=Mt.showTooltip??!1,Qi=Mt.size,lT=parseFloat(Qi??"")||Xm,nc=Mt.backgroundColor,Yi=Mt.textColor;if(Tf){if(Me.style.width=Qi??"",Me.style.height=Qi??"",Me.style.minWidth=Qi??"",Me.style.minHeight=Qi??"",Me.style.fontSize="18px",Me.style.lineHeight="1",Yi?Me.style.color=Yi:Me.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!H.isStreaming())if(Me.innerHTML="",oc){let Z=parseFloat(Mt.iconSize??"")||Math.round(lT*.5),ze=Yi?.trim()||"currentColor",Qe=Mt.iconStrokeWidth??2,nt=ce(oc,Z,ze,Qe),Ct=ce(Mt.stopIconName??"square",Z,ze,Qe);nt&&Ct?Me.appendChild(Qm(nt,Ct)):nt?Me.appendChild(nt):Me.textContent=Hs}else Me.textContent=Hs;Me.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Ko}`,nc?(Me.style.backgroundColor=nc,Me.classList.remove("persona-bg-persona-primary")):(Me.style.backgroundColor="",Me.classList.add("persona-bg-persona-primary"))}else Me.textContent=n.copy?.sendButtonLabel??"Send",Me.style.width="",Me.style.height="",Me.style.minWidth="",Me.style.minHeight="",Me.style.fontSize="",Me.style.lineHeight="",Me.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",nc?(Me.style.backgroundColor=nc,Me.classList.remove("persona-bg-persona-accent")):Me.classList.add("persona-bg-persona-accent"),Yi?Me.style.color=Yi:Me.classList.add("persona-text-white");Mt.borderWidth?(Me.style.borderWidth=Mt.borderWidth,Me.style.borderStyle="solid"):(Me.style.borderWidth="",Me.style.borderStyle=""),Mt.borderColor?Me.style.borderColor=Mt.borderColor:Me.style.borderColor="",Mt.paddingX?(Me.style.paddingLeft=Mt.paddingX,Me.style.paddingRight=Mt.paddingX):(Me.style.paddingLeft="",Me.style.paddingRight=""),Mt.paddingY?(Me.style.paddingTop=Mt.paddingY,Me.style.paddingBottom=Mt.paddingY):(Me.style.paddingTop="",Me.style.paddingBottom=""),H.isStreaming()||Me.setAttribute("aria-label",rv),Cd(),An&&eo({anchor:Me,trigger:An,text:()=>Me.getAttribute("aria-label")??rv,enabled:iT}),$h();let sv=nu(Se.getState().activeModeIds,n.composer?.modes);Se.setActiveModeIds(sv),Zs().length>0!==!!Kn&&sp(),Kn?.render(sv,Zs());for(let Z of[...ea.keys()])ou(Z,n.composer?.modeGroups)||ea.delete(Z);ea.forEach(Z=>Z.repaint()),Cr?.repaint(),En?.resolve();let rc=Gr(n,Ae());if(pp(),rc){ke.style.maxWidth=rc,ke.style.marginLeft="auto",ke.style.marginRight="auto",ke.style.width="100%",Do.style.maxWidth=rc,Do.style.marginLeft="auto",Do.style.marginRight="auto",Do.style.width="100%";for(let Z of[un,br,Eo,st])Z&&(Z.style.maxWidth=rc,Z.style.marginLeft="auto",Z.style.marginRight="auto",Z.style.width="100%")}else{ke.style.maxWidth="",ke.style.marginLeft="",ke.style.marginRight="",ke.style.width="",Do.style.maxWidth="",Do.style.marginLeft="",Do.style.marginRight="",Do.style.width="";for(let Z of[un,br,Eo,st])Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight="",Z.style.width="")}let Dr=n.statusIndicator??{},dT=Dr.visible??!0;if(st.style.display=dT?"":"none",H){let Z=H.getStatus();ao(st,(Qe=>Qe==="idle"?Dr.idleText??Ut.idle:Qe==="connecting"?Dr.connectingText??Ut.connecting:Qe==="connected"?Dr.connectedText??Ut.connected:Qe==="error"?Dr.errorText??Ut.error:Ut[Qe])(Z),Dr,Z)}st.classList.remove("persona-text-left","persona-text-center","persona-text-right");let cT=Dr.align==="left"?"persona-text-left":Dr.align==="center"?"persona-text-center":"persona-text-right";st.classList.add(cT),rp(),Mp(),pn(),xe()},open(){De()&&dt(!0,"api")},close(){De()&&dt(!1,"api")},toggle(){De()&&dt(!he,"api")},reconnect(){H.reconnectNow()},clearChat(){Gn=!1,H.clearMessages(),Dt.clear(),ko();try{localStorage.removeItem(ii),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ii}`)}catch(l){console.error("[AgentWidget] Failed to clear default localStorage:",l)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ii)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(l){console.error("[AgentWidget] Failed to clear custom localStorage:",l)}let s=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(s),F?.clear&&fd(()=>F.clear(),"[AgentWidget] Failed to clear storage adapter:"),X={},Ee.syncFromMetadata(),Ze?.clearAttachments(),gd(),ta(void 0),Tn(void 0),fs(),Tt?.clear(),ut?.reset(),B?.update()},setMessage(s){return!le||H.isStreaming()||Lr()?!1:(!he&&De()&&dt(!0,"system"),le.value=s,le.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(s){if(H.isStreaming()||xs())return!1;let l=s?.trim()||le.value.trim();return l?(!he&&De()&&dt(!0,"system"),le.value="",le.style.height="auto",Mn(),Qd(l,{consumeDraft:!1}),!0):!1},getComposerState(){return Se.getState()},setQuote(s){let l=s?.text?.trim();l&&Tn({...s,text:l})},clearQuote(){Tn(void 0)},startVoiceRecognition(){return H.isStreaming()?!1:n.voiceRecognition?.provider?.type==="runtype"?(H.isVoiceActive()||(!he&&De()&&dt(!0,"system"),je.manuallyDeactivated=!1,gn(),H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),Jn("user"),H.isVoiceActive()&&Ea()})),!0):Hn?!0:Rb()?(!he&&De()&&dt(!0,"system"),je.manuallyDeactivated=!1,gn(),Jd("user"),!0):!1},stopVoiceRecognition(){return n.voiceRecognition?.provider?.type==="runtype"?H.isVoiceActive()?(H.toggleVoice().then(()=>{je.active=!1,je.manuallyDeactivated=!0,gn(),Jn("user"),ir()}),!0):!1:Hn?(je.manuallyDeactivated=!0,gn(),Wr("user"),!0):!1},injectMessage(s){return!he&&De()&&dt(!0,"system"),H.injectMessage(s)},injectAssistantMessage(s){!he&&De()&&dt(!0,"system");let l=H.injectAssistantMessage(s);return gt&&(gt=!1,dn&&(clearTimeout(dn),dn=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),l},injectUserMessage(s){return!he&&De()&&dt(!0,"system"),H.injectUserMessage(s)},injectSystemMessage(s){return!he&&De()&&dt(!0,"system"),H.injectSystemMessage(s)},injectMessageBatch(s){return!he&&De()&&dt(!0,"system"),H.injectMessageBatch(s)},injectComponentDirective(s){return!he&&De()&&dt(!0,"system"),H.injectComponentDirective(s)},injectTestMessage(s){!he&&De()&&dt(!0,"system"),H.injectTestEvent(s)},async connectStream(s,l){return H.connectStream(s,l)},__pushEventStreamEvent(s){Rt&&(oe(),$(s.type,s.payload))},showEventStream(){Rt&&np()},hideEventStream(){ee&&oa()},isEventStreamVisible(){return ee},listConversations(s){return H.listConversations(s)},getActiveConversationId(){return H.getActiveConversationId()},openConversation(s,l){return lf(s,{focusComposer:l?.focus===!0})},startNewConversation(s){return df({focusComposer:s?.focus===!0})},deleteConversation(s){return Cb(s)},renameConversation(s,l){return cf(s,{title:l})},setConversationStarred(s,l){return cf(s,{starred:l})},clearConversationHistory(s){return Sb(s)},resetHistoryIdentity(){return wb()},getHistoryIdentityStatus(){return $o?$o.getIdentityStatus():Vp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(s){return $i({...s?.returnSurface?{returnSurface:s.returnSurface}:{},...s?.focus!==void 0?{focus:s.focus}:{}})},hideHistory(s){Io(s?.restoreFocus!==void 0?{restoreFocus:s.restoreFocus}:void 0)},isHistoryVisible(){return ne},showArtifacts(){wo(n)&&(Gn=!1,ra=!0,mn(),Ve?.setMobileOpen(!0))},hideArtifacts(){wo(n)&&(Gn=!0,mn())},upsertArtifact(s){return wo(n)?(Nn(n.features?.artifacts,{artifactType:s.artifactType,...s.artifactType==="markdown"&&s.file?{file:s.file}:{},...s.presentation?{presentation:s.presentation}:{}})==="panel"&&(Gn=!1,ra=!0),H.upsertArtifact(s)):null},selectArtifact(s){wo(n)&&H.selectArtifact(s)},clearArtifacts(){wo(n)&&H.clearArtifacts()},getArtifacts(){return H?.getArtifacts()??[]},getSelectedArtifactId(){return H?.getSelectedArtifactId()??null},focusInput(){return ge&&!he&&!Ae()||!le?!1:(le.focus(),!0)},async resolveApproval(s,l,f){let v=H.getMessages().find(M=>M.variant==="approval"&&M.approval?.id===s);if(!v?.approval)throw new Error(`Approval not found: ${s}`);if(v.approval.toolType==="webmcp"){H.resolveWebMcpApproval(v.id,l);return}return H.resolveApproval(v.approval,l,f)},setFollowUpSuggestions(s){hA(s)},clearFollowUpSuggestions(){yy()},getMessages(){return H.getMessages()},getStatus(){return H.getStatus()},getPersistentMetadata(){return{...X}},updatePersistentMetadata(s){de(s)},on(s,l){return C.on(s,l)},off(s,l){C.off(s,l)},isOpen(){return De()&&he},isVoiceActive(){return je.active},toggleReadAloud(s){H.toggleReadAloud(s)},stopReadAloud(){H.stopSpeaking()},getReadAloudState(s){return H.getReadAloudState(s)},onReadAloudChange(s){return H.onReadAloudChange(s)},getState(){return{open:De()&&he,launcherEnabled:ge,voiceActive:je.active,streaming:H.isStreaming()}},showCSATFeedback(s){!he&&De()&&dt(!0,"system");let l=ke.querySelector(".persona-feedback-container");l&&l.remove();let f=Uu({onSubmit:async(g,v)=>{H.isClientTokenMode()&&await H.submitCSATFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});ke.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(s){!he&&De()&&dt(!0,"system");let l=ke.querySelector(".persona-feedback-container");l&&l.remove();let f=qu({onSubmit:async(g,v)=>{H.isClientTokenMode()&&await H.submitNPSFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});ke.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(s,l){return H.submitCSATFeedback(s,l)},async submitNPSFeedback(s,l){return H.submitNPSFeedback(s,l)},destroy(){Dp(),ws!=null&&(clearInterval(ws),ws=null),ye.forEach(s=>s()),Xe.remove(),Xt?.remove(),Pt?.destroy(),go?.remove(),ds&&Ue.removeEventListener("click",ds)}};if(((o?.debugTools??!1)||!!n.debug)&&typeof window<"u"){let s=window.AgentWidgetBrowser,l={controller:kt,getMessages:kt.getMessages,getStatus:kt.getStatus,getMetadata:kt.getPersistentMetadata,updateMetadata:kt.updatePersistentMetadata,clearHistory:()=>kt.clearChat(),setVoiceActive:f=>f?kt.startVoiceRecognition():kt.stopVoiceRecognition()};window.AgentWidgetBrowser=l,ye.push(()=>{window.AgentWidgetBrowser===l&&(window.AgentWidgetBrowser=s)})}if(typeof window<"u"){let s=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),l=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&kt.focusInput()};if(window.addEventListener("persona:focusInput",l),ye.push(()=>{window.removeEventListener("persona:focusInput",l)}),Rt){let K=ae=>{let fe=ae.detail;(!fe?.instanceId||fe.instanceId===s)&&kt.showEventStream()},J=ae=>{let fe=ae.detail;(!fe?.instanceId||fe.instanceId===s)&&kt.hideEventStream()};window.addEventListener("persona:showEventStream",K),window.addEventListener("persona:hideEventStream",J),ye.push(()=>{window.removeEventListener("persona:showEventStream",K),window.removeEventListener("persona:hideEventStream",J)})}let f=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&kt.showHistory()},g=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&kt.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",g),ye.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",g)});let v=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&kt.showArtifacts()},M=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&kt.hideArtifacts()},N=K=>{let J=K.detail;J?.instanceId&&J.instanceId!==s||J?.artifact&&kt.upsertArtifact(J.artifact)},z=K=>{let J=K.detail;J?.instanceId&&J.instanceId!==s||typeof J?.id=="string"&&kt.selectArtifact(J.id)},V=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&kt.clearArtifacts()};window.addEventListener("persona:showArtifacts",v),window.addEventListener("persona:hideArtifacts",M),window.addEventListener("persona:upsertArtifact",N),window.addEventListener("persona:selectArtifact",z),window.addEventListener("persona:clearArtifacts",V),ye.push(()=>{window.removeEventListener("persona:showArtifacts",v),window.removeEventListener("persona:hideArtifacts",M),window.removeEventListener("persona:upsertArtifact",N),window.removeEventListener("persona:selectArtifact",z),window.removeEventListener("persona:clearArtifacts",V)})}let nn=GL(n.persistState);if(nn&&De()){let s=XL(nn.storage),l=`${nn.keyPrefix}widget-open`,f=`${nn.keyPrefix}widget-voice`,g=`${nn.keyPrefix}widget-voice-mode`;if(s){let v=nn.persist?.openState&&s.getItem(l)==="true",M=nn.persist?.voiceState&&s.getItem(f)==="true",N=nn.persist?.voiceState&&s.getItem(g)==="true";if(v&&(Pt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open(),setTimeout(()=>{if(M||N)kt.startVoiceRecognition();else if(nn.persist?.focusInput){let z=e.querySelector("textarea");z&&z.focus()}},100)},0)),nn.persist?.openState&&(C.on("widget:opened",()=>{s.setItem(l,"true")}),C.on("widget:closed",()=>{s.setItem(l,"false")})),nn.persist?.voiceState&&(C.on("voice:state",z=>{s.setItem(f,z.active?"true":"false")}),C.on("user:message",z=>{s.setItem(g,z.viaVoice?"true":"false")})),nn.clearOnChatClear){let z=()=>{s.removeItem(l),s.removeItem(f),s.removeItem(g)},V=()=>z();window.addEventListener("persona:clear-chat",V),ye.push(()=>{window.removeEventListener("persona:clear-chat",V)})}}}if(W&&De()&&(Pt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open()},0)),fa(),!yA){let s=ka(()=>{H&&(ms++,Dt.clear(),Jo(ke,H.getMessages(),oo))});ye.push(s)}T=()=>{H&&(ms++,Dt.clear(),Jo(ke,H.getMessages(),oo))},H.getMessages().length>0&&xd(),b=()=>{H&&(ms++,Dt.clear(),Jo(ke,H.getMessages(),oo))};let sT=Hx(()=>{H&&(ms++,Dt.clear(),Jo(ke,H.getMessages(),oo))});ye.push(sT);let aT=Qg(()=>{H&&(ms++,Dt.clear(),Jo(ke,H.getMessages(),oo),gr()?.updateInlineArtifactBlocks(ke,Yo.artifacts,{suppressTransition:!0}),mn())});return ye.push(aT),kt};var Tw=(e,t)=>{let o=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(o);if(n)return Math.max(0,parseFloat(n[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(o);return r?Math.max(0,t*parseFloat(r[1])/100):420},JL=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},ZL=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},e0=(e,t)=>{let o=e.parentElement;if(!o)return;let n=e.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",o.appendChild(n);let r=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),!(!r||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.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 ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Ew=(e,t)=>{let o=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=o?"":"100%",e.style.display=o?"":"flex",e.style.flexDirection=o?"":"column",e.style.flex=o?"":"1 1 auto",e.style.minHeight=o?"":"0",e.style.minWidth=o?"":"0"},fh=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Pw=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",fh(e)},ch=e=>{e.style.transition=""},uh=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},ph=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ju=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},t0=(e,t,o,n,r)=>{r?o.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(o,n),e.appendChild(t)):o.parentElement===t&&(t.replaceChildren(),e.appendChild(o),e.appendChild(n))},o0=(e,t,o,n,r,a)=>{let i=a?t:e;r==="left"?i.firstElementChild!==n&&i.replaceChildren(n,o):i.lastElementChild!==n&&i.replaceChildren(o,n)},n0=e=>{let t=Kr(e),o=t.components?.panel,n=(r,a)=>r==null||r===""?a:xo(t,r)??r;return{inset:n(o?.inset,ru),canvasBackground:n(o?.canvasBackground,su)}},kw=(e,t,o,n)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=o,e.style.background=n},r0=(e,t,o,n,r,a,i,d)=>{let c=Wo(a),u=c.reveal==="push",p=d!=null,m=d?.inset??"",h=d?.canvasBackground??"";t0(e,t,o,n,u),o0(e,t,o,n,c.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=i?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",o.style.display="flex",o.style.flexDirection="column",o.style.minHeight="0",o.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 y=e.ownerDocument.defaultView,x=a?.launcher?.mobileFullscreen??!0,T=a?.launcher?.mobileBreakpoint??640,w=y!=null?y.innerWidth<=T:!1;if(x&&w&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),uh(t),ch(n),Pw(n),ph(o),ju(r,n),kw(n,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",o.style.flex="1 1 auto",o.style.width="100%",o.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String(a?.launcher?.zIndex??so),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",o.style.flex="1 1 auto",o.style.width="100%",o.style.maxWidth="100%",o.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Pw(n),JL(n,c.maxHeight),kw(n,p&&i,m,h),c.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",uh(t),ch(n),ph(o),ju(r,n);let P=c.animate?"transform 180ms ease":"none",R=c.side==="right"?"translateX(100%)":"translateX(-100%)",b=i?"translateX(0)":R;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=c.width,n.style.maxWidth=c.width,n.style.minWidth=c.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=P,n.style.transform=b,n.style.pointerEvents=i?"auto":"none",n.style.zIndex="2",c.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(c.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",ch(n),fh(n),ju(r,n);let P=Tw(c.width,e.clientWidth),R=Math.max(0,e.clientWidth),b=c.animate?"margin-left 180ms ease":"none",A=c.side==="right"?i?-P:0:i?0:-P;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${R+P}px`,t.style.transition=b,t.style.marginLeft=`${A}px`,t.style.transform="",o.style.flex="0 0 auto",o.style.flexGrow="0",o.style.flexShrink="0",o.style.width=`${R}px`,o.style.maxWidth=`${R}px`,o.style.minWidth=`${R}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=c.width,n.style.minWidth=c.width,n.style.maxWidth=c.width,n.style.position="relative",n.style.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",uh(t),fh(n),ph(o),ju(r,n);let P=c.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let R=i?c.width:"0px",b=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",A=!i;if(n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${R}`,n.style.width=R,n.style.maxWidth=R,n.style.minWidth=R,n.style.minHeight="0",ZL(n,c.maxHeight),n.style.overflow=P||A?"hidden":"visible",n.style.transition=b,P){n.style.alignItems=c.side==="right"?"flex-start":"flex-end";let C=p?`calc(${Tw(c.width,e.clientWidth)}px - (2 * ${m}))`:c.width;r.style.width=C,r.style.minWidth=C,r.style.maxWidth=C,r.style.boxSizing="border-box"}}},s0=(e,t)=>{let o=e.ownerDocument.createElement("div");return Ew(o,t),e.appendChild(o),{mode:"direct",host:o,shell:null,syncWidgetState:()=>{},updateConfig(n){Ew(o,n)},destroy(){o.remove()}}},a0=(e,t)=>{let{ownerDocument:o}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,i=o.createElement("div"),d=o.createElement("div"),c=o.createElement("div"),u=o.createElement("aside"),p=o.createElement("div"),m=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;d.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",u.appendChild(p),n.insertBefore(i,e),c.appendChild(e);let h=null,y=()=>{h?.disconnect(),h=null},x=null,T=()=>{x=t?.launcher?.detachedPanel===!0?n0(t):null};T();let w=()=>{r0(i,d,c,u,p,t,m,x)},k=null,P=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=Ka(()=>{T(),w()}))},R=()=>{y(),Wo(t).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{w()}),h.observe(i)))},b=!1,A=()=>{w(),R(),m&&!b&&i.dataset.personaDockMobileFullscreen!=="true"&&(b=!0,e0(i,Wo(t)))},C=i.ownerDocument.defaultView,L=()=>{A()};return C?.addEventListener("resize",L),Wo(t).reveal==="push"?(d.appendChild(c),d.appendChild(u),i.appendChild(d)):(i.appendChild(c),i.appendChild(u)),A(),P(),{mode:"docked",host:p,shell:i,syncWidgetState(F){let X=F.launcherEnabled?F.open:!0;m!==X&&(m=X,A())},updateConfig(F){t=F,(t?.launcher?.enabled??!0)===!1&&(m=!0),T(),A(),P()},destroy(){C?.removeEventListener("resize",L),k?.(),k=null,y(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),i.remove()}}},Vl=(e,t)=>St(t)?a0(e,t):s0(e,t);var i0=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Lw=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let n=o.cloneNode(!0);e.insertBefore(n,e.firstChild)},Iw=e=>{let t=i0(e.target),o=e.useShadowDom===!0,n=t.ownerDocument,r=e.config,a=Vl(t,r),i,d=[],c=(w,k)=>{let R=!(k?.launcher?.enabled??!0)||St(k),b=n.createElement("div");if(b.setAttribute("data-persona-root","true"),R&&(b.style.height="100%",b.style.display="flex",b.style.flexDirection="column",b.style.flex="1",b.style.minHeight="0",b.style.minWidth="0"),o){let A=w.attachShadow({mode:"open"});A.appendChild(b),Lw(A,n)}else w.appendChild(b),Lw(w,n);return t.id&&b.setAttribute("data-persona-instance",t.id),b},u=()=>{a.syncWidgetState(i.getState())},p=()=>{d.forEach(w=>w()),d=[i.on("widget:opened",u),i.on("widget:closed",u)],u()},m=()=>{let w=c(a.host,r);i=Vu(w,r,{debugTools:e.debugTools}),p()},h=()=>{d.forEach(w=>w()),d=[],i.destroy()};m(),e.onChatReady?.();let y=w=>{h(),a.destroy(),a=Vl(t,w),r=w,m()},x={update(w){let k=Bu(r??{},w),P=St(r),R=St(k),b=Qr(r),A=Qr(k);if(P!==R||b!==A){y(k);return}r=k,a.updateConfig(r),i.update(w),u()},destroy(){h(),a.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},T=new Proxy(x,{get(w,k,P){if(k==="host")return a.host;if(k in w)return Reflect.get(w,k,P);let R=i[k];return typeof R=="function"?R.bind(i):R}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=T),T};var Ow=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),l0=new Set(["button","a","input","select","textarea","details","summary"]),d0=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),mh=/\b(product|card|item|listing|result)\b/i,hh=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,c0=3e3,u0=100;function Dw(e){let t=typeof e.className=="string"?e.className:"";if(mh.test(t)||e.id&&mh.test(e.id))return!0;for(let o=0;o<e.attributes.length;o++){let n=e.attributes[o];if(n.name.startsWith("data-")&&mh.test(n.value))return!0}return!1}function _w(e){return hh.test((e.textContent??"").trim())}function Nw(e){let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let n=t[o].getAttribute("href")??"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function p0(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Rw(e){let t=e.match(hh);return t?t[0]:null}function Hw(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let n=t.getAttribute("href");return{title:t.textContent.trim(),href:n&&n!=="#"?n:null}}let o=e.querySelector("h1, h2, h3, h4, h5, h6");return o?.textContent?.trim()?{title:o.textContent.trim(),href:null}:{title:"",href:null}}function f0(e){let t=[],o=n=>{let r=n.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(n=>o(n.textContent??"")),e.querySelectorAll('[role="button"]').forEach(n=>o(n.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{o(n.value??"")}),t.slice(0,6)}var m0="commerce-card",g0="result-card";function Ww(e){return!Dw(e)||!_w(e)||!Nw(e)&&!p0(e)?0:5200}function Bw(e){return!Dw(e)||_w(e)||!Nw(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var yh=[{id:m0,scoreElement(e){return Ww(e)},shouldSuppressDescendant(e,t,o){if(t===e||!e.contains(t))return!1;if(o.interactivity==="static"){let n=o.text.trim();return!!(n.length===0||hh.test(n)&&n.length<32)}return!0},formatSummary(e,t){if(Ww(e)===0)return null;let{title:o,href:n}=Hw(e),r=Rw((e.textContent??"").trim())??Rw(t.text)??"",a=f0(e);return[n&&o?`[${o}](${n})${r?`: ${r}`:""}`:o?`${o}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
139
+ `)}},{id:g0,scoreElement(e){return Bw(e)},formatSummary(e,t){if(Bw(e)===0)return null;let{title:o,href:n}=Hw(e);return[n&&o?`[${o}](${n})`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
140
+ `)}}];function h0(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function y0(e){let t=e.options??{},o=t.maxElements??e.maxElements??80,n=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,i=t.root??e.root,d=t.mode??"structured",c=t.maxCandidates??Math.max(500,o*10),u=e.rules??yh;return d==="simple"&&e.rules&&e.rules.length>0?(h0(),u=[]):d==="simple"&&(u=[]),{mode:d,maxElements:o,maxCandidates:c,excludeSelector:n,maxTextLength:r,visibleOnly:a,root:i,rules:u}}function gh(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var b0=["data-testid","data-product","data-action","data-id","data-name","data-type"];function v0(e){let t=e.tagName.toLowerCase(),o=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||o==="textbox"||o==="combobox"||o==="listbox"||o==="spinbutton"?"input":t==="button"||o==="button"||l0.has(t)||o&&d0.has(o)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Fw(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function x0(e){let t={},o=e.id;o&&(t.id=o);let n=e.getAttribute("href");n&&(t.href=n);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let a=e.getAttribute("type");a&&(t.type=a);let i=e.getAttribute("value");i&&(t.value=i);let d=e.getAttribute("name");d&&(t.name=d);let c=e.getAttribute("role");c&&(t.role=c);for(let u=0;u<e.attributes.length;u++){let p=e.attributes[u];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function bh(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${gh(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of b0){let a=e.getAttribute(r);if(a){let i=`${t}[${r}="${gh(a)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let o=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(o.length>0){let r=`${t}.${o.map(i=>gh(i)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let a=e.parentElement;if(a){let d=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(d>=0){let c=`${r}:nth-of-type(${d+1})`;try{if(e.ownerDocument.querySelectorAll(c).length===1)return c}catch{}}}}let n=e.parentElement;if(n){let a=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function C0(e){return e==="static"?u0:c0}function Uw(e,t){let o=e.tagName.toLowerCase(),n=(e.textContent??"").trim().substring(0,t);return{selector:bh(e),tagName:o,text:n,role:e.getAttribute("role"),interactivity:v0(e),attributes:x0(e)}}function S0(e,t,o,n){let r=C0(t.interactivity),a=null;for(let i of o){let d=i.scoreElement(e,t,n);d>0&&(r+=d,i.formatSummary&&!a&&(a=i))}return{score:r,formattingRule:a}}function w0(e,t){for(let o of e)if(t.el!==o.el&&o.formattingRule?.shouldSuppressDescendant&&o.el.contains(t.el)&&o.formattingRule.shouldSuppressDescendant(o.el,t.el,t.enriched))return!0;return!1}function A0(e,t){let o={doc:t.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,r=[],a=0,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),d=i.currentNode;for(;d&&r.length<e.maxCandidates;){if(d.nodeType===Node.ELEMENT_NODE){let u=d,p=u.tagName.toLowerCase();if(Ow.has(p)){d=i.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){d=i.nextNode();continue}}catch{}if(e.visibleOnly&&!Fw(u)){d=i.nextNode();continue}let m=Uw(u,e.maxTextLength),h=m.text.length>0,y=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(w=>w==="role");if(!h&&!y){d=i.nextNode();continue}if(n.has(m.selector)){d=i.nextNode();continue}n.add(m.selector);let{score:x,formattingRule:T}=S0(u,m,e.rules,o);r.push({el:u,domIndex:a,enriched:m,score:x,formattingRule:T}),a+=1}d=i.nextNode()}r.sort((u,p)=>{let m=u.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return m!==h?m-h:p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex});let c=[];for(let u of r){if(c.length>=e.maxElements)break;w0(c,u)||c.push(u)}return c.sort((u,p)=>{let m=u.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return m!==h?m-h:m===1&&p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex}),c.map(u=>{let p;if(u.formattingRule?.formatSummary){let h=u.formattingRule.formatSummary(u.el,u.enriched,o);h&&(p=h)}let m={...u.enriched};return p&&(m.formattedSummary=p),m})}function M0(e,t){let o=[],n=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=r.currentNode;for(;a&&o.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let c=a,u=c.tagName.toLowerCase();if(Ow.has(u)){a=r.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Fw(c)){a=r.nextNode();continue}let p=Uw(c,e.maxTextLength),m=p.text.length>0,h=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(y=>y==="role");if(!m&&!h){a=r.nextNode();continue}n.has(p.selector)||(n.add(p.selector),o.push(p))}a=r.nextNode()}let i=[],d=[];for(let c of o)c.interactivity!=="static"?i.push(c):d.push(c);return[...i,...d].slice(0,e.maxElements)}function qw(e={}){let t=y0(e),o=t.root??document.body;return o?t.mode==="simple"?M0(t,o):A0(t,o):[]}var zu=100;function $w(e,t={}){if(e.length===0)return"No page elements found.";let o=t.mode??"structured",n=[];if(o==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
141
141
  ${a.map(i=>`- ${i.split(`
142
142
  `).join(`
143
143
  `)}`).join(`
@@ -151,7 +151,7 @@ ${a.join(`
151
151
  ${a.join(`
152
152
  `)}`)}return n.join(`
153
153
 
154
- `)}var x0={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Uw={components:{panel:{borderRadius:"0",shadow:"none"}}},hh={id:"shop",label:"Shopping Assistant",config:{theme:x0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Vo},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},yh={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Uw}},bh={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Uw}},vh={shop:hh,minimal:yh,fullscreen:bh};function qw(e){return vh[e]}var Re=typeof document<"u"?document.currentScript?.src??null:null;xv(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});rv(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});Ax(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});kC(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});IC(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});cw(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"history-view.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the history-view.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host history-view.js alongside it.`)):import(e)});aS(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"animations-extra.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the animations-extra.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin.`)):import(e)});FS(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"approval-ui.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the approval-ui.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host approval-ui.js alongside it.`)):import(e)});Sx(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"voice-runtime.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the voice-runtime.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host voice-runtime.js alongside it.`)):import(e)});zS(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"artifacts-ui.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the artifacts-ui.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host artifacts-ui.js alongside it.`)):import(e)});tw(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"forms-ui.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the forms-ui.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host forms-ui.js alongside it.`)):import(e)});Px(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"icons-extra.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the icons-extra.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host icons-extra.js alongside it, or register the icons they use via registerIcons().`)):import(e)});wv(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"webmcp-runtime.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the webmcp-runtime.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host webmcp-runtime.js alongside it.`)):import(e)});Mx(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"session-reconnect.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the session-reconnect.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host session-reconnect.js alongside it.`)):import(e)});$S(()=>{let e=Re?.replace(/index\.global\.js($|\?)/,"event-stream-view.js$1");return!e||e===Re?Promise.reject(new Error(`Could not derive the event-stream-view.js URL from the widget script URL (${Re??"unavailable"}). Self-hosted deployments that rename index.global.js should host event-stream-view.js alongside it.`)):import(e)});return mT(C0);})();
154
+ `)}var T0={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Vw={components:{panel:{borderRadius:"0",shadow:"none"}}},vh={id:"shop",label:"Shopping Assistant",config:{theme:T0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:zo},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},xh={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Vw}},Ch={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Vw}},Sh={shop:vh,minimal:xh,fullscreen:Ch};function jw(e){return Sh[e]}var He=typeof document<"u"?document.currentScript?.src??null:null;Av(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});lv(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});Ex(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});HC(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});WC(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});fw(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"history-view.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the history-view.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host history-view.js alongside it.`)):import(e)});dS(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"animations-extra.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the animations-extra.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin.`)):import(e)});$S(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"approval-ui.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the approval-ui.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host approval-ui.js alongside it.`)):import(e)});Mx(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"voice-runtime.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the voice-runtime.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host voice-runtime.js alongside it.`)):import(e)});GS(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"artifacts-ui.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the artifacts-ui.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host artifacts-ui.js alongside it.`)):import(e)});rw(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"forms-ui.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the forms-ui.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host forms-ui.js alongside it.`)):import(e)});Ix(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"icons-extra.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the icons-extra.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host icons-extra.js alongside it, or register the icons they use via registerIcons().`)):import(e)});Ev(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"webmcp-runtime.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the webmcp-runtime.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host webmcp-runtime.js alongside it.`)):import(e)});Px(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"session-reconnect.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the session-reconnect.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host session-reconnect.js alongside it.`)):import(e)});zS(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"event-stream-view.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the event-stream-view.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host event-stream-view.js alongside it.`)):import(e)});return yT(E0);})();
155
155
  /*! Bundled license information:
156
156
 
157
157
  lucide/dist/esm/icons/activity.mjs: