@runtypelabs/persona 4.21.0 → 4.22.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 (78) hide show
  1. package/dist/{approval-ui-RNNBR5R3.js → approval-ui-K7R5Q5OC.js} +1 -1
  2. package/dist/approval-ui.cjs +2 -2
  3. package/dist/approval-ui.d.cts +73 -2
  4. package/dist/approval-ui.d.ts +73 -2
  5. package/dist/approval-ui.js +2 -2
  6. package/dist/artifacts-ui-F4N6VMKF.js +7 -0
  7. package/dist/artifacts-ui.cjs +1 -1
  8. package/dist/artifacts-ui.d.cts +73 -2
  9. package/dist/artifacts-ui.d.ts +73 -2
  10. package/dist/artifacts-ui.js +1 -1
  11. package/dist/chunk-NQLDCJAP.js +4 -0
  12. package/dist/codegen.cjs +1 -1
  13. package/dist/codegen.js +1 -1
  14. package/dist/context-mentions.d.cts +73 -2
  15. package/dist/context-mentions.d.ts +73 -2
  16. package/dist/event-stream-view-FKWDY3UB.js +1 -0
  17. package/dist/event-stream-view.cjs +1 -1
  18. package/dist/event-stream-view.d.cts +73 -2
  19. package/dist/event-stream-view.d.ts +73 -2
  20. package/dist/event-stream-view.js +1 -1
  21. package/dist/forms-ui.d.cts +73 -2
  22. package/dist/forms-ui.d.ts +73 -2
  23. package/dist/index.cjs +66 -66
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +136 -5
  26. package/dist/index.d.ts +136 -5
  27. package/dist/index.global.js +50 -50
  28. package/dist/index.global.js.map +1 -1
  29. package/dist/index.js +67 -67
  30. package/dist/index.js.map +1 -1
  31. package/dist/launcher.global.js +2 -2
  32. package/dist/launcher.global.js.map +1 -1
  33. package/dist/session-reconnect.d.cts +73 -2
  34. package/dist/session-reconnect.d.ts +73 -2
  35. package/dist/smart-dom-reader.d.cts +73 -2
  36. package/dist/smart-dom-reader.d.ts +73 -2
  37. package/dist/theme-editor-preview.cjs +65 -65
  38. package/dist/theme-editor-preview.d.cts +73 -2
  39. package/dist/theme-editor-preview.d.ts +73 -2
  40. package/dist/theme-editor-preview.js +49 -49
  41. package/dist/theme-editor.cjs +4 -4
  42. package/dist/theme-editor.d.cts +73 -2
  43. package/dist/theme-editor.d.ts +73 -2
  44. package/dist/theme-editor.js +2 -2
  45. package/dist/theme-reference.cjs +1 -1
  46. package/dist/theme-reference.d.cts +65 -1
  47. package/dist/theme-reference.d.ts +65 -1
  48. package/dist/theme-reference.js +1 -1
  49. package/dist/webmcp-polyfill.js +1 -4
  50. package/dist/webmcp-runtime-JI7T4QYF.js +6 -0
  51. package/dist/webmcp-runtime.cjs +2 -2
  52. package/dist/webmcp-runtime.d.cts +34 -2
  53. package/dist/webmcp-runtime.d.ts +34 -2
  54. package/dist/webmcp-runtime.js +2 -2
  55. package/package.json +2 -2
  56. package/src/client-visitor-history.test.ts +131 -0
  57. package/src/components/artifact-preview.ts +5 -0
  58. package/src/components/event-stream-badge-theming.test.ts +159 -0
  59. package/src/components/event-stream-view.ts +50 -20
  60. package/src/generated/runtype-openapi-contract.ts +8 -0
  61. package/src/index-core.ts +2 -0
  62. package/src/runtime/init.registry.test.ts +56 -0
  63. package/src/runtime/init.ts +17 -0
  64. package/src/types/theme.ts +41 -1
  65. package/src/types.ts +38 -1
  66. package/src/ui.reasoning-display.test.ts +136 -2
  67. package/src/ui.ts +69 -21
  68. package/src/utils/__snapshots__/tokens-parity.test.ts.snap +1740 -0
  69. package/src/utils/formatting.ts +22 -0
  70. package/src/utils/theme.ts +16 -0
  71. package/src/utils/tokens.ts +59 -0
  72. package/src/webmcp-bridge.test.ts +132 -23
  73. package/src/webmcp-bridge.ts +26 -2
  74. package/src/webmcp-runtime-entry.ts +71 -11
  75. package/dist/artifacts-ui-J6AKUGTS.js +0 -7
  76. package/dist/chunk-HBE7LFNT.js +0 -4
  77. package/dist/event-stream-view-73NWKWVQ.js +0 -1
  78. package/dist/webmcp-runtime-P3CHZRHF.js +0 -6
@@ -1,32 +1,32 @@
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,`
1
+ "use strict";var AgentWidget=(()=>{var hT=Object.create;var ic=Object.defineProperty;var yT=Object.getOwnPropertyDescriptor;var bT=Object.getOwnPropertyNames;var vT=Object.getPrototypeOf,xT=Object.prototype.hasOwnProperty;var mo=(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 lv=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),CT=(e,t)=>{for(var o in t)ic(e,o,{get:t[o],enumerable:!0})},dv=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of bT(t))!xT.call(e,r)&&r!==o&&ic(e,r,{get:()=>t[r],enumerable:!(n=yT(t,r))||n.enumerable});return e};var eo=(e,t,o)=>(o=e!=null?hT(vT(e)):{},dv(t||!e||!e.__esModule?ic(o,"default",{value:e,enumerable:!0}):o,e)),ST=e=>dv(ic({},"__esModule",{value:!0}),e);var _f=lv(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.Allow=he.ALL=he.COLLECTION=he.ATOM=he.SPECIAL=he.INF=he._INFINITY=he.INFINITY=he.NAN=he.BOOL=he.NULL=he.OBJ=he.ARR=he.NUM=he.STR=void 0;he.STR=1;he.NUM=2;he.ARR=4;he.OBJ=8;he.NULL=16;he.BOOL=32;he.NAN=64;he.INFINITY=128;he._INFINITY=256;he.INF=he.INFINITY|he._INFINITY;he.SPECIAL=he.NULL|he.BOOL|he.INF|he.NAN;he.ATOM=he.STR|he.NUM|he.SPECIAL;he.COLLECTION=he.ARR|he.OBJ;he.ALL=he.ATOM|he.COLLECTION;he.Allow={STR:he.STR,NUM:he.NUM,ARR:he.ARR,OBJ:he.OBJ,NULL:he.NULL,BOOL:he.BOOL,NAN:he.NAN,INFINITY:he.INFINITY,_INFINITY:he._INFINITY,INF:he.INF,SPECIAL:he.SPECIAL,ATOM:he.ATOM,COLLECTION:he.COLLECTION,ALL:he.ALL};he.default=he.Allow});var mc=lv(so=>{"use strict";var NT=so&&so.__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]})),FT=so&&so.__exportStar||function(e,t){for(var o in e)o!=="default"&&!Object.prototype.hasOwnProperty.call(t,o)&&NT(t,e,o)};Object.defineProperty(so,"__esModule",{value:!0});so.Allow=so.MalformedJSON=so.PartialJSON=so.parseJSON=so.parse=void 0;var go=_f();Object.defineProperty(so,"Allow",{enumerable:!0,get:function(){return go.Allow}});FT(_f(),so);var pc=class extends Error{};so.PartialJSON=pc;var fc=class extends Error{};so.MalformedJSON=fc;function Bv(e,t=go.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return UT(e.trim(),t)}so.parseJSON=Bv;var UT=(e,t)=>{let o=e.length,n=0,r=h=>{throw new pc(`${h} at position ${n}`)},a=h=>{throw new fc(`${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"||go.Allow.NULL&t&&o-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||go.Allow.BOOL&t&&o-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||go.Allow.BOOL&t&&o-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||go.Allow.INFINITY&t&&o-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||go.Allow._INFINITY&t&&1<o-n&&o-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||go.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(go.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&&go.Allow.OBJ&t)return h;let y=d();m(),n++;try{let x=i();h[y]=x}catch(x){if(go.Allow.OBJ&t)return h;throw x}m(),e[n]===","&&n++}}catch{if(go.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(go.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(go.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&&!(go.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()},qT=Bv;so.parse=qT});var WL={};CT(WL,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Kf,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>zf,ASK_USER_QUESTION_TOOL_NAME:()=>sl,AgentWidgetClient:()=>_s,AgentWidgetSession:()=>Va,AttachmentManager:()=>qs,BrowserSpeechEngine:()=>Ns,DEFAULT_COMPONENTS:()=>pg,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>zc,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>$o,DEFAULT_PALETTE:()=>cg,DEFAULT_SEMANTIC:()=>ug,DEFAULT_WIDGET_CONFIG:()=>st,HistoryProviderError:()=>an,PRESETS:()=>Mh,PRESET_FULLSCREEN:()=>Ah,PRESET_MINIMAL:()=>wh,PRESET_SHOP:()=>Sh,ReadAloudController:()=>qa,SUGGEST_REPLIES_CLIENT_TOOL:()=>bc,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>$f,SUGGEST_REPLIES_TOOL_NAME:()=>Un,THEME_ZONES:()=>qC,VERSION:()=>qn,WEBMCP_TOOL_PREFIX:()=>ol,applyFeaturePreferences:()=>rh,applyThemeVariables:()=>Vs,attachHeaderToContainer:()=>zs,buildComposer:()=>Xs,buildDefaultHeader:()=>kg,buildHeader:()=>br,buildHeaderWithLayout:()=>oi,buildMinimalHeader:()=>Lg,builtInClientToolsForDispatch:()=>Na,canonicalArtifactDisplayMode:()=>Lo,collectEnrichedPageContext:()=>zw,componentRegistry:()=>xn,createActionManager:()=>$l,createAgentExperience:()=>zu,createAskUserQuestionBubble:()=>Gv,createBubbleWithLayout:()=>MS,createCSATFeedback:()=>Vu,createComboButton:()=>xu,createComponentMiddleware:()=>Aw,createComponentStreamParser:()=>Fu,createDefaultSanitizer:()=>Rf,createDirectivePostprocessor:()=>mv,createDropdownMenu:()=>Ks,createFlexibleJsonStreamParser:()=>ex,createIconButton:()=>Gs,createImagePart:()=>Lc,createJsonStreamParser:()=>Ec,createLabelButton:()=>Pg,createLocalStorageAdapter:()=>_u,createMarkdownProcessor:()=>el,createMarkdownProcessorFromConfig:()=>tl,createMessageActions:()=>Og,createNPSFeedback:()=>$u,createPlainTextParser:()=>Mc,createRegexJsonParser:()=>Tc,createSplitButton:()=>yS,createStandardBubble:()=>ni,createTextPart:()=>sn,createTheme:()=>Ml,createThemeObserver:()=>Ja,createToggleGroup:()=>hS,createTypingIndicator:()=>Qs,createWidgetHostLayout:()=>zl,createXmlParser:()=>Pc,defaultActionHandlers:()=>Zs,defaultJsonActionParser:()=>Vl,defaultParseRules:()=>xh,detectColorScheme:()=>Tl,directivePostprocessor:()=>gv,ensureAskUserQuestionSheet:()=>_a,escapeHtml:()=>fr,extractComponentDirectiveFromMessage:()=>qu,fileToImagePart:()=>rx,formatEnrichedContext:()=>Kw,generateAssistantMessageId:()=>$r,generateMessageId:()=>Hv,generateStableSelector:()=>Ch,generateUserMessageId:()=>Ba,getActiveTheme:()=>Yr,getAgentWidgetHandles:()=>Ww,getColorScheme:()=>cu,getDisplayText:()=>kc,getHeaderLayout:()=>Ig,getImageParts:()=>nx,getPreset:()=>Xw,hasComponentDirective:()=>jl,hasImages:()=>Ua,headerLayouts:()=>Cu,initAgentWidget:()=>Bw,isAskUserQuestionMessage:()=>mr,isComponentDirectiveType:()=>ww,isDockedMountMode:()=>wt,isHistoryProviderError:()=>Tx,isSuggestRepliesMessage:()=>Ds,isWebMcpToolName:()=>qr,isWelcomeVisible:()=>ts,latestAgentSuggestions:()=>vc,listRegisteredStreamAnimations:()=>Cg,loadMarkdownParsers:()=>dc,markdownPostprocessor:()=>If,mergeWithDefaults:()=>Qa,normalizeContent:()=>ox,normalizeMediaType:()=>Vr,onMarkdownParsersReady:()=>Wa,parseAskUserQuestionPayload:()=>gr,parseSuggestRepliesPayload:()=>jf,parseWidgetPreferenceSlice:()=>nh,pickBestVoice:()=>pl,pluginRegistry:()=>ql,registerIcons:()=>_x,registerStreamAnimationPlugin:()=>Za,removeAskUserQuestionSheet:()=>Kr,renderComponentDirective:()=>Uu,renderLoadingIndicatorWithFallback:()=>Bg,renderLucideIcon:()=>ue,resolveArtifactDisplay:()=>Df,resolveArtifactDisplayMode:()=>Fn,resolveConfigPreferences:()=>Ul,resolveDockConfig:()=>Ro,resolveSanitizer:()=>cc,resolveTokens:()=>lu,resolveWelcomeConfig:()=>vn,stripWebMcpPrefix:()=>Of,themeToCssVariables:()=>du,unregisterStreamAnimationPlugin:()=>xg,validateImageFile:()=>sx,validateTheme:()=>fg});var bt=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:wT,load:AT,provide:VL,getSync:Lf}=bt({fallbackImport:()=>import("./markdown-parsers-entry")}),lc=new Set,MT=()=>{let e=[...lc];lc.clear();for(let t of e)try{t()}catch{}},cv=wT,dc=()=>{let e=Lf();return e?Promise.resolve(e):AT().then(t=>(MT(),t))},Wa=e=>Lf()?()=>{}:(lc.add(e),()=>{lc.delete(e)});var Nn=Lf;var TT=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},el=e=>{let t=null;return o=>{let n=Nn();if(!n)return fr(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=TT(e?.renderer);i&&t.use({renderer:i})}return t.parse(o)}},tl=e=>e?el({markedOptions:e.options,renderer:e.renderer}):el(),ET=el(),If=e=>ET(e),fr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),pv=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),uv=e=>`%%FORM_PLACEHOLDER_${e}%%`,fv=(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=uv(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=uv(t.length);return t.push({token:a,type:r}),a}),o},mv=e=>{let t=tl(e);return o=>{let n=[],r=fv(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="${pv(d)}"></div>`;a=a.replace(c,p)}),a}},gv=e=>{let t=[],o=fv(e,t),n=If(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="${pv(a)}"></div>`;n=n.replace(i,c)}),n};var PT={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"]},kT=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Rf=()=>{let e=null;return t=>{let o=Nn();if(!o)return fr(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:")&&!kT.test(i)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,PT)}},cc=e=>e===!1?null:typeof e=="function"?e:Rf();var hv=/^\s*\|?[\s:|-]*-[\s:|-]*$/,yv=e=>e.includes("|"),bv=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())},LT=e=>`| ${e.join(" | ")} |`,IT=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,RT=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),vv=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(!yv(r)||hv.test(r)||!hv.test(a))continue;let i=bv(r).length;if(i<1)continue;let d=IT(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()===""||!yv(u))break;let p=LT(RT(bv(u),i));t[c]!==p&&(t[c]=p,o=!0)}n=c-1}return o?t.join(`
4
+ `):e};var xv="var(--persona-md-table-scroll-fade, 24px)",Cv=new WeakSet;function wv(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 Sv(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":xv),e.style.setProperty("--persona-fade-r",r<=1?"0px":xv)}function Hf(e){Cv.has(e)||(Cv.add(e),e.addEventListener("scroll",t=>{let o=t.target;o?.classList?.contains("persona-table-scroll")&&Sv(o)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Sv)}var ol="webmcp:",Wf=new Map,Mv=e=>{Wf.clear();for(let t of e){let o=t.title?.trim();o&&Wf.set(t.name,o)}},uc=e=>Wf.get(Of(e)),Bf=null,Tv=e=>{Bf=e};function Ev(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}:${HT(t.join(""))}`}function Av(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 HT(e){let t=Av(e,0).toString(36),o=Av(e,2654435761).toString(36);return`${t}.${o}`}var Of=e=>e.startsWith(ol)?e.slice(ol.length):e,qr=e=>e.startsWith(ol),Pv=()=>Bf?Bf():import("@mcp-b/webmcp-polyfill");var{setLoader:WT,load:BT}=bt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),kv=WT,Lv=BT;function Lo(e){return e==="card"?"collapsed":e}function Vr(e){return e.split(";",1)[0].trim().toLowerCase()}function OT(e,t){if(!e)return;let o=Object.entries(e);for(let[r,a]of o)if(Vr(r)===t)return{mode:Lo(a),selector:Vr(r)};let n=`${t.split("/",1)[0]}/*`;for(let[r,a]of o)if(Vr(r)===n)return{mode:Lo(a),selector:n}}function Df(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:Lo(n.files),matchedBy:{type:"files"}};let d=t.file.mimeType?Vr(t.file.mimeType):void 0,c=d?OT(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:Lo(n.files.default),matchedBy:{type:"files"}}}let r=n.byKind?.[t.artifactType];if(r)return{mode:Lo(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=n.byType?.[t.artifactType];if(a)return{mode:Lo(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:Lo(i),matchedBy:{type:"preferredMode"}}:n.default?{mode:Lo(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Fn(e,t){return Df(e,t).mode}function nl(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 DT="agent_",_T="flow_";function Iv(e){return e.startsWith(DT)?{kind:"agentId",agentId:e}:e.startsWith(_T)?{kind:"flowId",flowId:e}:null}function Rv(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=Iv(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=Iv(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 Hv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ba(){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 Wv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}var jr=eo(mc(),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},ho=(...e)=>e.filter(Boolean).join(" ");var sl="ask_user_question",rl=8,Oa="data-persona-ask-sheet-for",VT="Other",$T="Other\u2026",Dv="Type your own answer here",_v="Send",jT="Next",zT="Back",KT="Submit all",GT="Skip",XT=3,Nf="data-ask-current-index",Ff="data-ask-question-count",Nv="data-ask-answers",Uf="data-ask-grouped",Fv="data-ask-layout",QT=e=>e.layout==="pills"?"pills":"rows",YT=e=>e.getAttribute(Fv)==="pills"?"pills":"rows",Ov=!1,Uv=e=>e.replace(/["\\]/g,"\\$&"),mr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===sl,gc=e=>e?.features?.askUserQuestion??{},gr=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,jr.parse)(r,jr.STR|jr.OBJ|jr.ARR);if(a&&typeof a=="object")return{payload:a,complete:o}}catch{}return{payload:null,complete:o}},al=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>rl&&!Ov&&(Ov=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${rl}.`)),t.slice(0,rl)},JT=e=>al(e)[0]??null,ZT=(e,t)=>al(e)[t]??null,qv=(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))},Vv=(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},eE=(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=Vv(o,n,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},tE=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},oE=(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<XT;p++)a.appendChild(tE(n));return a}if(c.forEach((p,m)=>{a.appendChild(eE(p,m,n,i))}),e?.allowFreeText!==!1){let p=n==="rows"?VT:$T;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??Dv,y.setAttribute("data-ask-free-text-input","true"),y.setAttribute("aria-label",t.freeTextLabel??p),h.appendChild(y),m.appendChild(h);let x=Vv(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},$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??Dv,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??_v,a.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(a)}return n},nE=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??_v,o.setAttribute("data-ask-user-action","submit-multi"),o.disabled=!0,t.appendChild(o),t},rE=(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??zT,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??GT,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??KT:o.nextLabel??jT,d.setAttribute("data-ask-user-action",c?"submit-all":"next"),d.disabled=!0,a.appendChild(d),n.appendChild(a),n},Os=e=>{let t=e.getAttribute(Nv);if(!t)return{};try{let o=JSON.parse(t);return o&&typeof o=="object"?o:{}}catch{return{}}},jv=(e,t)=>{e.setAttribute(Nv,JSON.stringify(t))},rn=e=>{let t=Number(e.getAttribute(Nf)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},sE=(e,t)=>{e.setAttribute(Nf,String(Math.max(0,Math.floor(t))))},Da=e=>{let t=Number(e.getAttribute(Ff)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},zr=e=>e.getAttribute(Uf)==="true",aE=(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},iE=(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)))},hc=(e,t)=>{let{payload:o}=gr(t),n=al(o),r=Os(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},zv=e=>{let t=Os(e),o=rn(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="")},Kv=e=>{if(!zr(e))return;let t=Os(e),o=rn(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}},qf=(e,t,o)=>{let n=gc(o),r=YT(e),{payload:a,complete:i}=gr(t),d=zr(e),c=rn(e),u=Da(e),p=d?ZT(a,c):JT(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=oE(p,n,i,r);T.replaceWith(P)}if(r!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith($v(n,r))}let w=e.querySelector('[data-ask-multi-actions="true"]');!d&&m&&!w?e.appendChild(nE(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=rE(c,u,n);k?k.replaceWith(P):e.appendChild(P)}else k&&k.remove();zv(e),Kv(e)},lE=(e,t,o)=>{let n=gc(t),r=QT(n),a=e.toolCall.id,i=al(o),d=Math.max(1,i.length),c=d>1,u=aE(e,i),p=c?iE(e,d):0,m=I("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Oa,a),m.setAttribute("data-tool-call-id",a),m.setAttribute("data-message-id",e.id),m.setAttribute(Ff,String(d)),m.setAttribute(Nf,String(p)),m.setAttribute(Uf,c?"true":"false"),m.setAttribute(Fv,r),jv(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`),qv(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($v(n,r)),qf(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},dE=(e,t,o)=>{let{payload:n}=gr(t),r=Math.max(1,al(n).length);r>Da(e)&&(e.setAttribute(Ff,String(r)),r>1&&!zr(e)&&e.setAttribute(Uf,"true")),qf(e,t,o)},Gv=(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=gc(t);qv(o,n);let r=I("span","persona-ask-stub-label"),{complete:a}=gr(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",o.appendChild(r),o},_a=(e,t,o)=>{if(!o||!mr(e)||gc(t).enabled===!1)return;let r=e.toolCall.id;o.querySelectorAll(`[${Oa}]`).forEach(u=>{u.getAttribute(Oa)!==r&&u.remove()});let i=o.querySelector(`[${Oa}="${Uv(r)}"]`);if(i){dE(i,e,t);return}let{payload:d}=gr(e),c=lE(e,t,d);o.appendChild(c)},Kr=(e,t)=>{if(!e)return;let o=t?`[${Oa}="${Uv(t)}"]`:`[${Oa}]`;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)})},Vf=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),Gr=(e,t)=>{let o=Os(e),n=rn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete o[n]:o[n]=t,jv(e,o),zv(e),Kv(e)},yc=(e,t,o,n)=>{let r=Da(e),a=Math.max(0,Math.min(r-1,n));sE(e,a),qf(e,t,o)};var Un="suggest_replies";var $f={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},bc={name:Un,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:$f,origin:"sdk",annotations:{readOnlyHint:!0}},Qv=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ds=e=>e.variant==="tool"&&e.toolCall?.name===Un,jf=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},vc=e=>{for(let t=e.length-1;t>=0;t--){let o=e[t];if(o.role==="user")return null;if(!Ds(o))continue;let n=jf(o.toolCall?.args);return n.length>0?n:null}return null},Xv=new Set,cE=(e,t,o)=>{let n=`${e}:${t}:${o}`;Xv.has(n)||(Xv.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Xr=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&&cE(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 zf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:rl,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},Kf={name:sl,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:zf,origin:"sdk",annotations:{readOnlyHint:!0}},Na=e=>{let t=[],o=e?.features?.askUserQuestion;return o?.expose===!0&&o.enabled!==!1&&t.push(Kf),Xr(e).expose&&t.push(bc),t};var hr=eo(mc(),1),xc=e=>e.replace(/\\n/g,`
5
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Cc=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)}},uE=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`},Yv=e=>e.status==="complete"?uE(e):e.status==="pending"?"Waiting":"",pE=15e3,fE=1200,Jv=(e,t)=>{let o=t?.durationMs??pE,n=t?.chars??fE;return typeof e.durationMs=="number"?e.durationMs<o:(e.chunks??[]).join("").length<n},mE=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 Zv=e=>e.status==="complete"?mE(e):"Using tool...",Sc=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ll=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 Sc(t)},wc=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Sc(t)},Gf=(e,t,o)=>{if(!t)return o;let n=e.name?.trim()||"tool",r=ll(e);return t.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,r)},Ac=(e,t)=>{let o=e.replace(/\{toolName\}/g,t),n=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,i;for(;(i=r.exec(o))!==null;)i.index>a&&il(n,o.slice(a,i.index),[]),i[1]!==void 0?il(n,i[1],["bold"]):i[2]!==void 0?il(n,i[2],["italic"]):i[3]!==void 0&&il(n,i[3],["dim"]),a=i.index+i[0].length;return a<o.length&&il(n,o.slice(a),[]),n},il=(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})},gE=()=>{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=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(`
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()=>{}}},dl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Mc=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Tc=()=>{let e=gE();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)}},Ec=()=>{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,hr.parse)(o,hr.STR|hr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?xc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=xc(r.text)))}catch{}return t=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},ex=e=>{let t=null,o=0,r=e||(a=>{if(!a||typeof a!="object")return null;let i=d=>typeof d=="string"?xc(d):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?xc(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,hr.parse)(a,hr.STR|hr.OBJ),c=r(d);c!==null&&(t=c)}catch{}return o=a.length,{text:t||"",raw:a}},close:()=>{}}},Pc=()=>{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 tx="4.22.0";var qn=tx;var Fa="[Image]";function ox(e){return typeof e=="string"?[{type:"text",text:e}]:e}function kc(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ua(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function nx(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function sn(e){return{type:"text",text:e}}function Lc(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function rx(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 sx(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 ax=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],yE=["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"],yr=[...ax,...yE];function bE(e){return ax.includes(e)||e.startsWith("image/")}function Ic(e){return bE(e.type)}function ix(e,t,o){return{type:"file",data:e,mimeType:t,filename:o}}async function lx(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;Ic(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 dx(e,t=yr,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 vE(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function cx(e,t){let o=vE(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 xE=["user","assistant","system"],CE=0;function ux(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Rc(e){return typeof e=="string"?e:void 0}function SE(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?sn(t.text):null;case"image":return typeof t.image=="string"?Lc(t.image,{mimeType:Rc(t.mimeType),alt:Rc(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?ix(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...Rc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...Rc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function wE(e,t){let o=ux(t),n=e.map(i=>ux(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:CE+h;a=d+1}return r.map(i=>new Date(i).toISOString())}function px(e,t){let o=wE(e,t?.beforeCreatedAt),n=[];return e.forEach((r,a)=>{if(typeof r?.id!="string"||r.id===""||!xE.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(SE).filter(p=>p!==null),u=kc(c);n.push({id:r.id,role:i,content:u||(Ua(c)?Fa:""),createdAt:d,...c.length>0&&{contentParts:c}});return}n.push({id:r.id,role:i,content:"",createdAt:d})}),n}function cl(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 ul(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 AE="https://api.runtype.com/v1/dispatch",fx="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)}},mx=32768,Xf=49152,gx=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:""}},hx=e=>"reason"in e?e.reason:void 0,yx="The identity proof was not admitted; account history is unavailable",bx="The identity proof was rejected",vx="The request carried no visitor credential",xx="The stored visitor belongs to a different signed-in user",Qf=(e,t)=>e instanceof Fe&&e.code===t;function ME(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 Yf=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 TE(e){switch(e){case"json":return Ec;case"regex-json":return Tc;case"xml":return Pc;default:return Mc}}var Cx=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function EE(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=Cx(o);if(!Cx(n))return e;if(!r||n===o||n.startsWith(o))return t;let i=dl(e);return dl(t)!==null&&i===null?t:e}var _s=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??AE,this.headers={"Content-Type":"application/json","X-Persona-Version":qn,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??TE(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 Lv().then(o=>{let n=new o.WebMcpBridge(t,{recordToolDisplayTitles:Mv,getToolDisplayTitle:uc,loadPolyfill:Pv});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=Rv(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$/,"")||fx}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":qn,"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&&hx(o)===hx(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":qn},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":qn},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(!Qf(r,"not_found")&&!Qf(r,"visitor_required")&&!Qf(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":qn},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",yx);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",bx);if(r.includes("visitor token required"))throw new Fe("visitor_token_missing",vx);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",xx);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",yx);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",bx)):r.includes("visitor token required")?new Fe("visitor_token_missing",vx):r.includes("visitor_identity_mismatch")?new Fe("visitor_identity_mismatch",xx):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":qn,...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(gx),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:gx(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>mx)throw new Fe("payload_too_large",`displayContent exceeds the ${mx} character limit`);n+=u}if(n>Xf)throw new Fe("payload_too_large",`Display projection batch exceeds the ${Xf} 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<=Xf,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=Wv();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(Yf).map(x=>{let T=p?cl(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":qn,...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?Ev(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(/\/+$/,"")||fx}/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=[...Na(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(Yf).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=[...Na(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(Yf).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=[...Na(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=F=>{let J=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,S=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,N=F.tools?F.tools.map(q=>({...q,chunks:q.chunks?[...q.chunks]:void 0})):void 0;return{...F,reasoning:J,toolCall:S,tools:N}},h=F=>{if(F.role!=="assistant"||F.variant)return!0;let J=Array.isArray(F.contentParts)&&F.contentParts.length>0,S=typeof F.rawContent=="string"&&F.rawContent.trim()!=="";return typeof F.content=="string"&&F.content.trim()!==""||J||S||!!F.stopReason},y=F=>{h(F)&&o({type:"message",message:m(F)})},x=null,T=null,w={current:null},k={current:null},P=null,H="",b=new Map,A=new Map,C=new Map,L=new Map,U=new Map,Q={lastId:null,byStep:new Map},V={lastId:null,byCall:new Map},E=F=>{if(F==null)return null;try{return String(F)}catch{return null}},O=F=>E(F.stepId??F.step_id??F.step??F.parentId??F.flowStepId??F.flow_step_id),D=F=>E(F.callId??F.call_id??F.requestId??F.request_id??F.toolCallId??F.tool_call_id??F.stepId??F.step_id),W=n,te=!1,X=()=>{if(x)return x;let F,J="",S=P;return!te&&W?(F=W,te=!0,J=r??""):W&&S?F=`${W}_${S}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:F,role:"assistant",content:J,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},y(x),x},fe=(F,J)=>{Q.lastId=J,F&&Q.byStep.set(F,J)},le=(F,J)=>{let S=F.reasoningId??F.id,N=O(F);if(S){let $=String(S);return fe(N,$),$}if(N){let $=Q.byStep.get(N);if($)return Q.lastId=$,$}if(Q.lastId&&!J)return Q.lastId;if(!J)return null;let q=`reason-${p()}`;return fe(N,q),q},be=F=>{let J=L.get(F);if(J)return J;let S={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:F,status:"streaming",chunks:[]}};return L.set(F,S),y(S),S},He=(F,J)=>{V.lastId=J,F&&V.byCall.set(F,J)},We=new Set,Se=new Map,mt=new Set,ke=new Map,z=F=>{if(!F)return!1;let J=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return J==="emit_artifact_markdown"||J==="emit_artifact_component"},qe=(F,J)=>{let S=F.toolId??F.id,N=D(F);if(S){let $=String(S);return He(N,$),$}if(N){let $=V.byCall.get(N);if($)return V.lastId=$,$}if(V.lastId&&!J)return V.lastId;if(!J)return null;let q=`tool-${p()}`;return He(N,q),q},Ge=F=>{let J=U.get(F);if(J)return J;let S={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:F,status:"pending"}};return U.set(F,S),y(S),S},Tt=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let J=Number(F);if(!Number.isNaN(J)&&Number.isFinite(J))return J;let S=Date.parse(F);if(!Number.isNaN(S))return S}return Date.now()},Ie=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},Ee=new Map,ye=new Map,Cn=new Map,Sn=(F,J,S)=>{let N=Cn.get(F);N||(N=[],Cn.set(F,N));let q=0,$=N.length;for(;q<$;){let se=q+$>>>1;N[se].seq<J?q=se+1:$=se}N[q]?.seq===J?N[q]={seq:J,text:S}:N.splice(q,0,{seq:J,text:S});let oe="";for(let se=0;se<N.length;se++)oe+=N[se].text;return oe},ea=(F,J)=>{let S=Ie(J),N=ye.get(F.id),q=EE(N,S);F.rawContent=q;let $=Ee.get(F.id),oe=Be=>{let Wt=F.content??"";Be.trim()!==""&&(Wt.trim().length===0||Be.startsWith(Wt)||Be.trimStart().startsWith(Wt.trim()))&&(F.content=Be)},se=()=>{if($){let Be=$.close?.();Be instanceof Promise&&Be.catch(()=>{})}Ee.delete(F.id),ye.delete(F.id),F.streaming=!1,y(F)};if(!$){oe(S),se();return}let ie=dl(q);if(ie!==null&&ie.trim()!==""){oe(ie),se();return}let de=Be=>{let Wt=typeof Be=="string"?Be:Be?.text??null;if(Wt!==null&&Wt.trim()!=="")return Wt;let Et=$.getExtractedText();return Et!==null&&Et.trim()!==""?Et:S},qt;try{qt=$.processChunk(q)}catch{oe(S),se();return}if(qt instanceof Promise){qt.then(Be=>{oe(de(Be)),se()}).catch(()=>{oe(S),se()});return}oe(de(qt)),se()},Ht=null,wn=(F,J,S,N)=>{F.rawContent=J,Ee.has(F.id)||Ee.set(F.id,this.createStreamParser());let q=Ee.get(F.id),$=J.trim().startsWith("{")||J.trim().startsWith("[");if($&&ye.set(F.id,J),q.__isPlainTextParser===!0){F.content=N!==void 0?J:F.content+S,ye.delete(F.id),Ee.delete(F.id),F.rawContent=void 0,y(F);return}let se=q.processChunk(J);if(se instanceof Promise)se.then(ie=>{let de=typeof ie=="string"?ie:ie?.text??null;de!==null&&de.trim()!==""?(F.content=de,y(F)):!$&&!J.trim().startsWith("<")&&(F.content=N!==void 0?J:F.content+S,ye.delete(F.id),Ee.delete(F.id),F.rawContent=void 0,y(F))}).catch(()=>{F.content=N!==void 0?J:F.content+S,ye.delete(F.id),Ee.delete(F.id),F.rawContent=void 0,y(F)});else{let ie=typeof se=="string"?se:se?.text??null;ie!==null&&ie.trim()!==""?(F.content=ie,y(F)):!$&&!J.trim().startsWith("<")&&(F.content=N!==void 0?J:F.content+S,ye.delete(F.id),Ee.delete(F.id),F.rawContent=void 0,y(F))}},Ko=(F,J)=>{let S=J??F.content;if(S==null||S===""){F.streaming=!1,y(F);return}let q=ye.get(F.id)??Ie(S);F.rawContent=q;let $=Ee.get(F.id),oe=null,se=!1;if($&&(oe=$.getExtractedText(),oe===null&&(oe=dl(q)),oe===null)){let ie=$.processChunk(q);ie instanceof Promise?(se=!0,ie.then(de=>{let qt=typeof de=="string"?de:de?.text??null;qt!==null&&(F.content=qt,F.streaming=!1,Ee.delete(F.id),ye.delete(F.id),y(F))}).catch(()=>{})):oe=typeof ie=="string"?ie:ie?.text??null}if(!se){oe!==null&&oe.trim()!==""?F.content=oe:ye.has(F.id)||(F.content=Ie(S));let ie=Ee.get(F.id);if(ie){let de=ie.close?.();de instanceof Promise&&de.catch(()=>{}),Ee.delete(F.id)}ye.delete(F.id),F.streaming=!1,y(F)}},io=(F,J,S)=>{let N=A.get(F);if(N)return N;let q={id:`nested-${J}-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...S?{variant:S}:{},...S==="reasoning"?{reasoning:{id:F,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:J}};return A.set(F,q),y(q),q},An=[],Go,ln=new Map,ta=0,Mn="agent",Kn=!1,os=null,et=null,Ho=new Map,dn=this.config.iterationDisplay??"separate";for(Go=()=>{for(let F=0;F<An.length;F++){let J=An[F].payloadType,S=An[F].payload;if(!Kn&&Mn!=="flow"&&typeof S.stepType=="string"&&(Mn="flow"),J==="reasoning_start"){let N=typeof S.id=="string"?S.id:null,q=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(N&&q){b.set(N,q),io(N,q,"reasoning");continue}let $=le(S,!0)??`reason-${p()}`,oe=be($);oe.reasoning=oe.reasoning??{id:$,status:"streaming",chunks:[]},oe.reasoning.startedAt=oe.reasoning.startedAt??Tt(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(J==="reasoning_delta"){let N=typeof S.id=="string"?S.id:null;if(N&&b.has(N)&&A.has(N)){let se=A.get(N),ie=S.reasoningText??S.text??S.delta??"";ie&&S.hidden!==!0&&se.reasoning&&(se.reasoning.chunks.push(String(ie)),y(se));continue}let q=le(S,!1)??le(S,!0)??`reason-${p()}`,$=be(q);$.reasoning=$.reasoning??{id:q,status:"streaming",chunks:[]},$.reasoning.startedAt=$.reasoning.startedAt??Tt(S.startedAt??S.timestamp);let oe=S.reasoningText??S.text??S.delta??"";if(oe&&S.hidden!==!0){let se=typeof S.sequenceIndex=="number"?S.sequenceIndex:void 0;if(se!==void 0){let ie=Sn(q,se,String(oe));$.reasoning.chunks=[ie]}else $.reasoning.chunks.push(String(oe))}if($.reasoning.status=S.done?"complete":"streaming",S.done){$.reasoning.completedAt=Tt(S.completedAt??S.timestamp);let se=$.reasoning.startedAt??Date.now();$.reasoning.durationMs=Math.max(0,($.reasoning.completedAt??Date.now())-se)}$.streaming=$.reasoning.status!=="complete",y($)}else if(J==="reasoning_complete"){let N=typeof S.id=="string"?S.id:null;if(N&&b.has(N)&&A.has(N)){let ie=A.get(N);if(ie.reasoning){let de=typeof S.text=="string"?S.text:"";de&&ie.reasoning.chunks.length===0&&ie.reasoning.chunks.push(de),ie.reasoning.status="complete",ie.streaming=!1,y(ie)}b.delete(N),A.delete(N);continue}let q=le(S,!1)??le(S,!0)??`reason-${p()}`,$=typeof S.text=="string"?S.text:"";!L.get(q)&&($||S.scope==="loop")&&be(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=Tt(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 se=O(S);se&&Q.byStep.delete(se)}else if(J==="tool_start"){x&&(x.streaming=!1,y(x),x=null),typeof S.iteration=="number"&&(ta=S.iteration);let N=(typeof S.toolCallId=="string"?S.toolCallId:void 0)??qe(S,!0)??`tool-${p()}`,q=S.toolName??S.name;if(z(q)){We.add(N);continue}He(D(S),N);let $=Ge(N),oe=$.toolCall??{id:N,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??Tt(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(J==="tool_output_delta"){let N=qe(S,!1)??qe(S,!0)??`tool-${p()}`;if(We.has(N))continue;let q=Ge(N),$=q.toolCall??{id:N,status:"running"};$.startedAt=$.startedAt??Tt(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 se=S.agentContext;(se||S.executionId)&&(q.agentMetadata=q.agentMetadata??{executionId:se?.executionId??S.executionId,iteration:se?.iteration??S.iteration}),y(q)}else if(J==="tool_complete"){let N=qe(S,!1)??qe(S,!0)??`tool-${p()}`;if(We.has(N)){We.delete(N);continue}let q=Ge(N),$=q.toolCall??{id:N,status:"running"};$.status="complete",S.result!==void 0&&($.result=S.result),typeof S.duration=="number"&&($.duration=S.duration),$.completedAt=Tt(S.completedAt??S.timestamp);let oe=S.duration??S.executionTime;if(typeof oe=="number")$.durationMs=oe;else{let de=$.startedAt??Date.now();$.durationMs=Math.max(0,($.completedAt??Date.now())-de)}q.toolCall=$,q.streaming=!1;let se=S.agentContext;(se||S.executionId)&&(q.agentMetadata=q.agentMetadata??{executionId:se?.executionId??S.executionId,iteration:se?.iteration??S.iteration}),y(q);let ie=D(S);ie&&V.byCall.delete(ie)}else if(J==="await"&&S.toolName){let N=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:void 0,q=N??S.toolId??`local-${p()}`,$=Ge(q),oe=S.toolName,se=S.origin==="webmcp"&&!qr(oe)?`webmcp:${oe}`:oe,ie=qr(se),de=$.toolCall??{id:q,status:"pending"};de.name=se,de.args=S.parameters,de.status=ie?"running":"complete",de.chunks=de.chunks??[],de.startedAt=de.startedAt??Tt(S.startedAt??S.timestamp??S.awaitedAt),ie?(de.completedAt=void 0,de.duration=void 0,de.durationMs=void 0):de.completedAt=de.completedAt??de.startedAt,$.toolCall=de,$.streaming=!1,$.agentMetadata={...$.agentMetadata,executionId:S.executionId??$.agentMetadata?.executionId,awaitingLocalTool:!0,...N?{webMcpToolCallId:N}:{}},y($)}else if(J==="text_start"){let N=typeof S.id=="string"?S.id:null,q=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(N&&q){b.set(N,q);continue}let $=x;$&&(Mn==="flow"?(Ko($),Ht=$):($.streaming=!1,y($)),x=null),P=typeof S.id=="string"?S.id:P,H=""}else if(J==="text_delta"){let N=typeof S.id=="string"?S.id:null,q=N?b.get(N):void 0;if(N&&q){let se=typeof S.delta=="string"?S.delta:"",ie=(C.get(N)??"")+se;if(C.set(N,ie),ie.trim()==="")continue;let de=io(N,q);de.agentMetadata={...de.agentMetadata,executionId:S.executionId,parentToolId:q},wn(de,ie,se,void 0);continue}if(P=typeof S.id=="string"?S.id:P,Mn==="flow"){let se=typeof S.delta=="string"?S.delta:"";if(H+=se,H.trim()==="")continue;let ie=X();ie.agentMetadata={executionId:S.executionId,iteration:S.iteration},wn(ie,H,se,void 0),T=ie;continue}let $=typeof S.delta=="string"?S.delta:"";H+=$;let oe=X();oe.agentMetadata={executionId:S.executionId,iteration:S.iteration,turnId:os??void 0,agentName:et?.agentName},wn(oe,H,$,void 0),T=oe}else if(J==="text_complete"){let N=typeof S.id=="string"?S.id:null;if(N&&b.has(N)){let $=A.get(N);$&&Ko($),b.delete(N),C.delete(N),A.delete(N);continue}let q=x;q&&(Mn==="flow"?(Ko(q),Ht=q):((q.content??"")===""&&typeof S.text=="string"&&(q.content=S.text),q.streaming=!1,y(q)),x=null),P=null,H=""}else if(J==="step_complete"){let N=S.stepType,q=S.executionType;if(N==="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 se=x;se&&se.streaming&&(se.streaming=!1,y(se)),o({type:"status",status:"idle"});continue}{let $=Ht;Ht=null;let oe=S.stopReason,se=S.result?.response;if($)oe&&($.stopReason=oe),se!=null?ea($,se):$.streaming!==!1&&(Ee.delete($.id),ye.delete($.id),$.streaming=!1,y($));else{let ie=se!=null&&se!=="";if(ie||oe){let de=X();oe&&(de.stopReason=oe),ie?Ko(de,se):(de.streaming=!1,y(de))}}continue}}else if(J==="execution_start")Mn=S.kind==="flow"?"flow":"agent",Kn=!0,Mn==="agent"&&(et={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??"",status:"running",currentIteration:0,maxTurns:S.maxTurns??1,startedAt:Tt(S.startedAt)});else if(J==="turn_start"){let N=typeof S.iteration=="number"?S.iteration:ta;if(N!==ta){if(et&&(et.currentIteration=N),dn==="separate"&&N>1){let q=x;q&&(q.streaming=!1,y(q),Ho.set(N-1,q),x=null)}ta=N}os=typeof S.id=="string"?S.id:null,T=null}else if(J==="tool_input_delta"){let N=S.toolCallId??V.lastId;if(N){let q=U.get(N);q?.toolCall&&(q.toolCall.chunks=q.toolCall.chunks??[],q.toolCall.chunks.push(S.delta??""),y(q))}}else{if(J==="tool_input_complete")continue;if(J==="turn_complete"){let N=S.stopReason,q=x??T;if(N&&q!==null){let $=S.id;(!$||q.agentMetadata?.turnId===$)&&(q.stopReason=N,y(q))}os===S.id&&(os=null)}else if(J==="media_start"){let N=String(S.id);ln.set(N,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,role:typeof S.role=="string"?S.role:void 0,toolCallId:S.toolCallId,parts:[]})}else if(J==="media_delta"){let N=ln.get(String(S.id));N&&typeof S.delta=="string"&&N.parts.push(S.delta)}else if(J==="media_complete"){let N=String(S.id),q=ln.get(N);ln.delete(N);let $=(typeof S.mediaType=="string"?S.mediaType:void 0)??q?.mediaType??"application/octet-stream",oe=typeof S.data=="string"?S.data:void 0,se=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(se){let Wt=$.toLowerCase();ie={type:Wt==="image"||Wt.startsWith("image/")?"image-url":"file-url",url:se,mediaType:$}}let de=S.toolCallId??q?.toolCallId,qt=ie?[ie]:[],Be=[];for(let Wt of qt){if(!Wt||typeof Wt!="object")continue;let Et=Wt,Gn=typeof Et.type=="string"?Et.type:void 0,Sr=typeof Et.mediaType=="string"?Et.mediaType.toLowerCase():"",Vt=null,$t="";if(Gn==="media"){let So=typeof Et.data=="string"?Et.data:void 0;if(!So)continue;$t=Sr.length>0?Sr:"application/octet-stream",Vt=`data:${$t};base64,${So}`}else if(Gn==="image-url"){let So=typeof Et.url=="string"?Et.url:void 0;if(!So)continue;$t=Sr,Vt=So}else if(Gn==="file-url"){let So=typeof Et.url=="string"?Et.url:void 0;if(!So)continue;$t=Sr,Vt=So}else continue;if(Vt)if(Gn==="image-url"||$t.startsWith("image/"))Be.push({type:"image",image:Vt,...$t.includes("/")?{mimeType:$t}:{}});else if($t.startsWith("audio/"))Be.push({type:"audio",audio:Vt,mimeType:$t});else if($t.startsWith("video/"))Be.push({type:"video",video:Vt,mimeType:$t});else{let So=$t||"application/octet-stream";Be.push({type:"file",data:Vt,mimeType:So,filename:ME(So)})}}if(Be.length>0){let Wt=p(),Et=de,Sr={id:`agent-media-${typeof Et=="string"&&Et.length>0?`${Et}-${Wt}`:String(Wt)}`,role:"assistant",content:"",contentParts:Be,createdAt:new Date().toISOString(),streaming:!1,sequence:Wt,agentMetadata:{executionId:S.executionId,iteration:typeof S.iteration=="number"?S.iteration:ta}};y(Sr);let Vt=x;Vt&&(Vt.streaming=!1,y(Vt)),x=null,w.current=null}}else if(J==="execution_complete"){let N=S.kind??Mn;N==="agent"&&et&&(et.status=S.success?"complete":"error",et.completedAt=Tt(S.completedAt),et.stopReason=S.stopReason);let q=x;q&&(N==="flow"&&q.streaming!==!1?Ko(q):(q.streaming=!1,y(q)),x=null),P=null,H="",Ht=null,o({type:"status",status:"idle",terminal:!0})}else if(J==="execution_error"){let N=typeof S.error=="string"?S.error:S.error?.message??"Execution error";o({type:"error",error:new Error(N)})}else if(J!=="ping"){if(J==="approval_start"){let N=S.approvalId??`approval-${p()}`,q={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:N,status:"pending",agentId:et?.agentId??"virtual",executionId:S.executionId??et?.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(J==="step_await"&&S.awaitReason==="approval_required"){let N=S.approvalId??`approval-${p()}`,q={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:N,status:"pending",agentId:et?.agentId??"virtual",executionId:S.executionId??et?.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(J==="approval_complete"){let N=S.approvalId;if(N){let $={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:N,status:S.decision??"approved",agentId:et?.agentId??"virtual",executionId:S.executionId??et?.executionId??"",toolName:S.toolName??"",description:S.description??"",resolvedAt:Date.now()}};y($)}}else if(J==="artifact_start"||J==="artifact_delta"||J==="artifact_update"||J==="artifact_complete"){if(J==="artifact_start"){let N=S.artifactType,q=String(S.id),$=typeof S.title=="string"?S.title:void 0,oe=S.file,se;oe&&typeof oe=="object"&&!Array.isArray(oe)&&typeof oe.path=="string"&&typeof oe.mimeType=="string"&&(se={path:oe.path,mimeType:oe.mimeType,...typeof oe.language=="string"?{language:oe.language}:{}}),o({type:"artifact_start",id:q,artifactType:N,title:$,component:typeof S.component=="string"?S.component:void 0,...se?{file:se}:{}});let ie=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?{...S.props}:void 0;if(ke.set(q,{markdown:"",title:$,file:se,...ie?{props:ie}:{}}),!mt.has(q)){mt.add(q);let de=Fn(this.config.features?.artifacts,{artifactType:N,...se?{file:se}:{}}),qt=typeof S.component=="string"?S.component:void 0,Be={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:nl(de,{artifactId:q,title:$,artifactType:N,status:"streaming",...se?{file:se}:{},...qt?{component:qt}:{}})};Se.set(q,Be),y(Be)}}else if(J==="artifact_delta"){let N=String(S.id),q=typeof S.delta=="string"?S.delta:String(S.delta??"");o({type:"artifact_delta",id:N,artDelta:q});let $=ke.get(N);$&&($.markdown+=q)}else if(J==="artifact_update"){let N=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?S.props:{};o({type:"artifact_update",id:String(S.id),props:N,component:typeof S.component=="string"?S.component:void 0});let q=ke.get(String(S.id));q&&(q.props={...q.props??{},...N})}else if(J==="artifact_complete"){let N=String(S.id);o({type:"artifact_complete",id:N});let q=Se.get(N);if(q){q.streaming=!1;try{let $=JSON.parse(q.rawContent??"{}");if($.props){$.props.status="complete";let oe=ke.get(N);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{}ke.delete(N),y(q),Se.delete(N)}}}else if(J==="transcript_insert"){let N=S.message;if(!N||typeof N!="object")continue;let q=String(N.id??`msg-${p()}`),$=N.role,se={id:q,role:$==="user"?"user":$==="system"?"system":"assistant",content:typeof N.content=="string"?N.content:"",rawContent:typeof N.rawContent=="string"?N.rawContent:void 0,createdAt:typeof N.createdAt=="string"?N.createdAt:new Date().toISOString(),streaming:N.streaming===!0,...typeof N.variant=="string"?{variant:N.variant}:{},sequence:p()};if(y(se),se.rawContent)try{let de=JSON.parse(se.rawContent)?.props?.artifactId;typeof de=="string"&&mt.add(de)}catch{}x=null,w.current=null,Ee.delete(q),ye.delete(q)}else if(J==="error"){if(S.recoverable===!1&&S.error!=null&&S.error!==""){let N=typeof S.error=="string"?S.error:S.error?.message!=null?String(S.error.message):"Execution error";o({type:"error",error:new Error(N)});let q=x;q&&q.streaming&&(q.streaming=!1,y(q)),o({type:"status",status:"idle"})}}else if(J==="step_error"||J==="dispatch_error"||J==="flow_error"){let N=null;if(S.error instanceof Error)N=S.error;else if(J==="dispatch_error"){let q=S.message??S.error;q!=null&&q!==""&&(N=new Error(String(q)))}else{let q=S.error;typeof q=="string"&&q!==""?N=new Error(q):q!=null&&typeof q=="object"&&Reflect.has(q,"message")&&(N=new Error(String(q.message??q)))}if(N){o({type:"error",error:N});let q=x;q&&q.streaming&&(q.streaming=!1,y(q)),o({type:"status",status:"idle"})}}}}}An.length=0};;){let{done:F,value:J}=await a.read();if(F)break;d+=i.decode(J,{stream:!0});let S=d.split(`
8
8
 
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}
9
+ `);d=S.pop()??"";for(let N of S){let q=N.split(`
10
+ `),$="message",oe="",se=null;for(let Be of q)Be.startsWith("event:")?$=Be.replace("event:","").trim():Be.startsWith("data:")?oe+=Be.replace("data:","").trim():Be.startsWith("id:")&&(se=Be.slice(3).trim());let ie=()=>{se!==null&&se!==""&&o({type:"cursor",id:se})};if(!oe){ie();continue}let de;try{de=JSON.parse(oe)}catch(Be){o({type:"error",error:Be instanceof Error?Be:new Error("Failed to parse chat stream payload")});continue}let qt=$!=="message"?$:de.type??"message";if(this.onSSEEvent?.(qt,de),this.parseSSEEvent){w.current=x;let Be=await this.handleCustomSSEEvent(de,o,w,y,p,k);if(w.current&&w.current!==x&&(x=w.current),Be){ie();continue}}An.push({payloadType:qt,payload:de}),Go(),ie()}}Go()}};function PE(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 Sx(e,t){let o="`".repeat(Math.max(3,PE(t)+1));return`${o}${e}
12
12
  ${t}
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(`
13
+ ${o}`}var kE=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function LE(e){let t=e?.text?.trim()??"";return t?Sx(kE(e),t):""}function wx(e){let t=LE(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[sn(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 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,`
15
+ `)}:{}}function Hc(e,t=140){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,t-1)}\u2026`}function Ax(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 Jf(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 Mx(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 Jf(e,o.id)?o.id:null}return null}function Zf(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 an=class extends Error{constructor(t,o,n){super(o),this.name="HistoryProviderError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};function Tx(e){return e instanceof an}function pl(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 Ns=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):pl(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 qa=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 IE=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Ex(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:IE()}catch{return!1}}var{setLoader:RE,load:HE}=bt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),Px=RE,em=HE;function tm(e){if(!e)return"";let t=WE(e);return kx(t!==null?t:e)}function WE(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 kx(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 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}
17
+ `),t.trim()}var om=null,Lx=e=>{om=e},nm=()=>om?om():import("./runtype-tts-entry");var{setLoader:BE,load:OE}=bt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),Ix=BE,Rx=OE;var DE=["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 _E(e,t){return DE.some(o=>e[o]!==t[o])}var Vn=class extends Error{constructor(t,o){super(o),this.name="SessionHistoryError",this.code=t}};function rm(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 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(`
19
+ _Details: ${o.message}_`:n}var sm=e=>({isError:!0,content:[{type:"text",text:e}]}),NE=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Hx=e=>qr(e)||e===Un,Va=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 qa(()=>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&&(qr(o.name)||o.name===Un&&Xr(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 _s(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&&em().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||nm().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 Ex(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=Ns.isSupported()?new Ns({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 nm().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=em().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 Vn("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 an("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 Vn("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 Vn("superseded","A later selection won");let d=await n.prepareOpen(t,{context:r});if(a!==this.historyOpenEpoch)throw d.discard(),new Vn("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=ul(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 Vn("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 Vn("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 Vn("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 Vn("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=ul(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=cl(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=cl(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(!_E(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 _s(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"?Ba():o==="assistant"?$r():`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"?Ba():r==="assistant"?$r():`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,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(`
23
+ `),d=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(d){let u=[];a&&u.push(sn(a)),u.push(...r.contentParts),u.push(...t.contentParts),t.contentParts=u}else if(c){let u=[];i&&u.push(sn(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=Ba(),i=$r();this.activeAssistantMessageId=null;let d=o?.contentParts&&Ua(o.contentParts)?Fa:"",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=wx({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=rm(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=Ax(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=$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=rm(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!==Un?!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===Un)return{dedupeKey:m,resumeKey:y,output:Qv(),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,sm(k?"Aborted by cancel()":NE(w)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(c,sm("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===Un?{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,sm("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=Fn(this.config.features?.artifacts,t),r=nl(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=Fn(this.config.features?.artifacts,o),a=nl(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=Rx().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=>rm(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=tm(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return pl(t)}toggleReadAloud(t){let o=this.messages.find(a=>a.id===t);if(!o||o.role!=="assistant")return;let n=tm(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&&Hx(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&&Hx(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 $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 am=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var im=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var fl=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var lm=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var dm=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var cm=[["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 um=[["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 ja=[["path",{d:"M20 6 9 17l-5-5"}]];var ml=[["path",{d:"m6 9 6 6 6-6"}]];var pm=[["path",{d:"m15 18-6-6 6-6"}]];var fm=[["path",{d:"m9 18 6-6-6-6"}]];var Fs=[["path",{d:"m18 15-6-6-6 6"}]];var mm=[["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 gm=[["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 Wc=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var za=[["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 hm=[["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 Bc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Oc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var ym=[["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 bm=[["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 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"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var hl=[["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 Us=[["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 yl=[["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 vm=[["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 xm=[["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 Dc=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Cm=[["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 Sm=[["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 wm=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var bl=[["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 Am=[["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 Mm=[["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 Tm=[["path",{d:"M5 12h14"}]];var _c=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M9 3v18"}]];var Em=[["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 Pm=[["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 km=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Lm=[["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 Im=[["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 Rm=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Hm=[["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 Wm=[["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 Bm=[["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 Nc=[["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 Om=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Dm=[["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 _m=[["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 Nm=[["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 Fm=[["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 Um=[["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 qm=[["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 Vm=[["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 vl=[["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:FE,load:UE}=bt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),Wx=FE,Fc=UE;var qE={activity:$a,"arrow-down":am,"arrow-up":dm,"arrow-up-right":lm,bot:um,"chevron-down":ml,"chevron-up":Fs,"chevron-right":fm,"chevron-left":pm,check:ja,clipboard:gm,"clipboard-copy":mm,"code-xml":Wc,copy:za,file:yl,"file-code":gl,"file-spreadsheet":hl,"file-text":Us,"image-plus":xm,loader:Cm,"loader-circle":Dc,mic:Am,paperclip:Em,quote:Lm,"refresh-cw":Im,search:Rm,send:Hm,"shield-alert":Wm,"shield-check":Bm,"shield-x":Nc,square:Om,"thumbs-down":_m,"thumbs-up":Nm,upload:qm,"volume-2":Vm,x:vl,"at-sign":cm,"arrow-left":im,"arrow-right":fl,"external-link":ym,ellipsis:Oc,"ellipsis-vertical":Bc,menu:wm,"panel-left":_c,plus:km,minus:Tm,pencil:Pm,trash:Um,"trash-2":Fm,download:hm,maximize:Sm,minimize:Mm,"message-square":bl,star:Dm,eye:bm,history:vm},VE=["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"],xl=new Map(Object.entries(qE)),Ka=new Set,Uc=!1,qc=new Set,Bx=e=>{let t=[...qc];e&&qc.clear();for(let o of t)try{o()}catch{}},Ox=e=>Uc?()=>{}:(qc.add(e),()=>{qc.delete(e)}),Dx=()=>{let e=0;for(let t of[...Ka]){let o=xl.get(t.name);if(!o)continue;Ka.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},_x=e=>{for(let[t,o]of Object.entries(e))xl.set(t,o);Dx()>0&&!Uc&&Bx(!1)};var $m=!1,$E=()=>{Fc().then(e=>{if(!Uc){for(let[t,o]of Object.entries(e.EXTRA_LUCIDE_ICONS))xl.has(t)||xl.set(t,o);Uc=!0,Dx(),Bx(!0)}}).catch(e=>{$m=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},jE=(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},ue=(e,t=24,o="currentColor",n=2)=>{let r=xl.get(e);if(r)return Ft(r,t,o,n);if(VE.includes(e)){$m&&($m=!1);let a=jE(t,o,n);if(Ka.size>=500){let i=Ka.values().next().value;i&&Ka.delete(i)}return Ka.add({el:a,name:e,size:t,color:o,strokeWidth:n}),$E(),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 zE={add:e=>lx(e)},KE=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Vc={allowedTypes:yr,maxFileSize:10*1024*1024,maxFiles:4};function GE(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function XE(e){return e==="application/pdf"?Us:e.startsWith("text/")?Us:e.includes("word")?Us:e.includes("excel")||e.includes("spreadsheet")?hl:e==="application/json"?gl:yl}var qs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??Vc.allowedTypes,maxFileSize:t.maxFileSize??Vc.maxFileSize,maxFiles:t.maxFiles??Vc.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:zE}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:Vc.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=dx(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:GE(),file:n,previewUrl:Ic(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=KE(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=Ic(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=XE(t.file.type),h=Ft(m,20,"var(--persona-muted, #6b7280)",1.5);h&&p.appendChild(h);let y=I("span");y.textContent=cx(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=ue("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(vl,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 Nx=(e,t)=>e.length===t.length&&e.every((o,n)=>o===t[n]),QE=(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 Fx(){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=>{QE(e.attachments,p)||(e.attachments=[...p],u())},setMentionRefs:p=>{Nx(e.mentionRefs,p)||(e.mentionRefs=[...p],u())},setSelectedModelId:p=>{e.selectedModelId!==p&&(e.selectedModelId=p,u())},setActiveModeIds:p=>{Nx(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 Io=(e,...t)=>{for(let o of t){let n=e.querySelector(o);if(n)return n}return null},Ux=(e,t)=>{let o=I("div",e);return o.setAttribute(t,""),o.setAttribute("data-persona-composer-synthesized",""),o.style.display="contents",o};function qx(e,t={}){let o=Io(e,"[data-persona-composer-form]"),n=Io(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:Io(e,"[data-persona-composer-header]"),body:Io(e,"[data-persona-composer-body]"),actionsStart:Io(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Io(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Io(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Io(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Io(e,"[data-persona-composer-status]")},a=new Set,i=r.header;i||(a.add("header"),i=Ux("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,H,b)=>{if(k)return k;a.add(w);let A=Ux(P,H);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=Io(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:Io(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Io(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Io(e,"[data-persona-composer-submit]")??void 0,micButton:Io(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:r,addListener:(w,k,P,H)=>{w.addEventListener(k,P,H),y.push({target:w,type:k,handler:P,options:H})},removeListener:(w,k,P,H)=>{w.removeEventListener(k,P,H),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"},ao=1e5,Ga=ao+1;var YE=8,JE=8,jm=10,Vx=200,$x=300,jx=0,jc=e=>Math.max(0,e);function zx(e){e.delayMs!==void 0&&(Vx=jc(e.delayMs)),e.skipDelayMs!==void 0&&($x=jc(e.skipDelayMs))}var ZE=()=>Date.now()<jx,e0=e=>{jx=e>0?Date.now()+e:0},$c=new WeakMap,Km="data-persona-tooltip-suppressed",t0=e=>typeof e.closest=="function"&&e.closest(`[${Km}]`)!==null;function Kx(e){$c.get(e)?.hide()}var Gx=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,o0=e=>{let t=e.getRootNode?.();return Gx(t)?t:e.ownerDocument.body},zm=(e,t,o)=>Math.min(Math.max(e,t),Math.max(t,o)),n0=[...["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 to(e){$c.get(e.anchor)?.destroy();let{anchor:t,trigger:o=t,text:n,hint:r,enabled:a=!0,gap:i=YE,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(),H=()=>(typeof r=="function"?r():r??"").trim(),b=()=>jc(e.delayMs??Vx),A=()=>jc(e.skipDelayMs??$x),C=()=>{x!==void 0&&(u().clearTimeout(x),x=void 0)},L=()=>{C();let be=p!==null;y?.(),y=null,p?.remove(),p=null,m=null,h=null,be&&e0(A())},U=()=>{if(!p)return;let be=c(),He=u(),We=t.getBoundingClientRect(),Se=p.getBoundingClientRect(),mt=be.documentElement.clientWidth||He.innerWidth,ke=be.documentElement.clientHeight||He.innerHeight,z=mt-d-Se.width,qe=We.left+We.width/2-Se.width/2,Ge=zm(qe,d,z),Tt=We.top-d,Ie=ke-d-We.bottom,Ee=Se.height+i,ye=Tt>=Ee||Tt>=Ie?"top":"bottom",Cn=ye==="top"?We.top-i-Se.height:We.bottom+i,Sn=ke-d-Se.height,ea=zm(Cn,d,Sn),Ht=We.left+We.width/2,wn=Math.max(jm,Se.width-jm),Ko=zm(Ht-Ge,jm,wn);p.dataset.placement=ye,p.style.left=`${Ge}px`,p.style.top=`${ea}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${Ko}px`)},Q=()=>{if(k||!a||p||!t.isConnected||t0(t))return;let be=P(),He=o0(t);if(!be||!He)return;let We=c(),Se=u();p=We.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(Ga);let mt=Se.getComputedStyle?.(t);if(mt){for(let Ee of n0){let ye=mt.getPropertyValue(Ee).trim();ye&&p.style.setProperty(Ee,ye)}mt.fontFamily&&(p.style.fontFamily=mt.fontFamily)}m=We.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=be,p.appendChild(m);let ke=H();ke&&(h=We.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=ke,p.appendChild(h));let z=We.createElement("span");z.className="persona-control-tooltip__arrow",p.appendChild(z),He.appendChild(p),U(),p.dataset.state="open";let qe=()=>{if(!t.isConnected){L();return}m&&(m.textContent=P()),h&&(h.textContent=H()),U()};Se.addEventListener("scroll",qe,!0),Se.addEventListener("resize",qe);let Ge=t.getRootNode(),Tt=Gx(Ge)?Ge:We.documentElement,Ie=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||L()});Ie?.observe(Tt,{childList:!0,subtree:!0}),y=()=>{Se.removeEventListener("scroll",qe,!0),Se.removeEventListener("resize",qe),Ie?.disconnect()}},V=be=>{if(!(k||p)){if(C(),be||b()<=0||ZE()){Q();return}x=u().setTimeout(()=>{x=void 0,Q()},b())}},E=()=>{T||w?V(w):L()},O=()=>{let be=u();(!be.matchMedia||!be.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()},X=()=>{T=!1,w=!1,L()},fe=be=>{be.key==="Escape"&&X()};o.addEventListener("mouseenter",O),o.addEventListener("mouseleave",D),t.addEventListener("focus",W),t.addEventListener("blur",te),t.addEventListener("keydown",fe),t.addEventListener("click",X);let le={get isOpen(){return p!==null},show:Q,hide:L,reposition:U,destroy:()=>{k||(k=!0,L(),o.removeEventListener("mouseenter",O),o.removeEventListener("mouseleave",D),t.removeEventListener("focus",W),t.removeEventListener("blur",te),t.removeEventListener("keydown",fe),t.removeEventListener("click",X),$c.delete(t))}};return $c.set(t,le),le}var Xx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Xa(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];Xx(a)&&Xx(r)?o[n]=Xa(a,r):o[n]=r}return o}var $o="min(440px, calc(100vw - 24px))",zc="440px",Gm="How can I help...",r0={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:$o,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)"},st={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:r0,copy:{inputPlaceholder:Gm,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 Qx(e,t){if(!(!e&&!t))return e?t?Xa(e,t):e:t}function Qa(e){return e?{...st,...e,theme:Qx(st.theme,e.theme),darkTheme:Qx(st.darkTheme,e.darkTheme),launcher:{...st.launcher,...e.launcher,dock:{...st.launcher?.dock,...e.launcher?.dock},clearChat:{...st.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...st.tooltip,...e.tooltip},copy:{...st.copy,...e.copy},sendButton:{...st.sendButton,...e.sendButton},statusIndicator:{...st.statusIndicator,...e.statusIndicator},voiceRecognition:{...st.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=st.features?.artifacts,o=e.features?.artifacts,n=st.features?.scrollToBottom,r=e.features?.scrollToBottom,a=st.features?.scrollBehavior,i=e.features?.scrollBehavior,d=st.features?.streamAnimation,c=e.features?.streamAnimation,u=st.features?.askUserQuestion,p=e.features?.askUserQuestion,m=st.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{...st.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??st.suggestionChips,suggestionChipsConfig:{...st.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...st.layout,...e.layout,header:{...st.layout?.header,...e.layout?.header},messages:{...st.layout?.messages,...e.layout?.messages,avatar:{...st.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...st.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...st.layout?.slots,...e.layout?.slots}},markdown:{...st.markdown,...e.markdown,options:{...st.markdown?.options,...e.markdown?.options}},messageActions:{...st.messageActions,...e.messageActions}}:st}function Xm(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 Kc(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function Yx(e,t){e.style.maxHeight=`${t*Xm(e)}px`,e.style.overflowY="auto"}function wl(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 Jx(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Zx(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||!Jx(t)}function s0(e){return(e.submitKey??"enter")!=="enter"||Jx(e)?"enter":"send"}function Gc(e,t){e.setAttribute("enterkeyhint",s0(t))}function Xc(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 Qm(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 jo="persona-composer-control",bn="persona-composer-control--glyph",Jm=40,yo=24,Qc=(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)}},Yc=(e,t)=>{let o=I("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=e?.copy?.inputPlaceholder??Gm,o.dir="auto",Gc(o,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:wl(o)}),Xc(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=Kc(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*Xm(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}},i0="[data-persona-glyph-stack]",Zm=(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},Jc=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??"")||Jm,y=t.backgroundColor,x=t.textColor,T=I("div","persona-send-button-wrapper"),w=Y("button",{className:ho("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",o?`persona-flex persona-items-center persona-justify-center ${jo}`:"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,H=null;if(o){let C=parseFloat(t.iconSize??"")||Math.round(h*.5),L=t.iconStrokeWidth??2,U=x?.trim()||"currentColor";r&&(k=ue(r,C,U,L)),P=ue(a,C,U,L),k&&P?(H=Zm(k,P),w.appendChild(H)):k?w.appendChild(k):(w.textContent=n,P=null)}else w.textContent=c;w.setAttribute("aria-label",i),T.appendChild(w),to({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(i0)??H)?.setAttribute("data-mode",C):w.textContent=C==="stop"?u:c},glyphStack:H}},Ya=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??"")||yo,p=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,h=I("div","persona-send-button-wrapper"),y=Y("button",{className:ho("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",jo,!c&&bn),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=ue(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 to({anchor:y,trigger:h,text:()=>y.getAttribute("aria-label")??w,enabled:k}),{button:y,wrapper:h}},Zc=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??yr).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 ${jo} ${bn}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),d=ue(r,yo,"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 to({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:a,input:n,previewsContainer:o}},eu=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},tu=()=>Y("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function l0(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function ou(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??l0(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(),H=d?.()??null,b=H!=null?k.top+H: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,U=i?.()??null;if(U!=null){let Q=Math.max(k.left,k.right-P.width);L=Math.min(Math.max(k.left+U,k.left),Q)}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,H=()=>{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",H,!0),k.addEventListener("resize",H),y=()=>{k.clearTimeout(A),P.removeEventListener("pointerdown",b,!0),k.removeEventListener("scroll",H,!0),k.removeEventListener("resize",H)},u?.()};return{get isOpen(){return h},open:w,close:T,toggle:()=>h?T():w(),reposition:x,destroy:T}}var d0='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',c0=["--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"],eg="data-persona-menu-focus",u0=new Set(["ArrowDown","ArrowUp","Home","End"]);function eC(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(d0)??e}var p0=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function tC(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 ${jo} ${bn}`,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=ue("plus",yo,"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 X=!!W&&eC(te)===W;te.toggleAttribute(eg,X&&p)}},y=()=>c.filter(W=>W.isConnected||a.contains(W)).map(eC).filter(W=>!p0(W)),x=(W,te)=>{W.forEach((X,fe)=>{X.setAttribute("tabindex",fe===te?"0":"-1")})},T=W=>{let te=y();if(te.length===0)return;let X=(W%te.length+te.length)%te.length;u=X,x(te,X),te[X].focus(),h()},w=()=>n.ownerDocument??document,k=null,P=null,H=null,b=()=>{k&&(w().removeEventListener("focusin",k,!0),k=null)},A=()=>{P&&(a.removeEventListener("focusin",P),P=null),H&&(a.removeEventListener("pointerdown",H,!0),H=null)},C=null,L=()=>(C||(C=ou({anchor:r,content:a,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),b()}})),C),U=()=>C?.isOpen===!0,Q=(W=!1)=>{if(U()){C?.close(),r.setAttribute("aria-expanded","false"),b(),A(),u=-1,p=!1;for(let te of c)te.removeAttribute(eg);W&&r.focus()}},V=(W=0,te=!1)=>{if(o||U())return;p=te,Qc(r,a,c0),L().open(),r.setAttribute("aria-expanded","true");let X=y();x(X,-1),T(W<0?X.length-1:W),k=fe=>{let le=typeof fe.composedPath=="function"?fe.composedPath():[];le.includes(a)||le.includes(n)||Q()},w().addEventListener("focusin",k,!0),P=()=>h(),a.addEventListener("focusin",P),H=()=>{p=!1},a.addEventListener("pointerdown",H,!0)},E=W=>{W.preventDefault(),W.stopPropagation(),U()?Q(!0):V(0)},O=W=>{if(W.key==="ArrowDown"||W.key==="Enter"||W.key===" "){W.preventDefault(),p=!0,U()?T(0):V(0,!0);return}W.key==="ArrowUp"&&(W.preventDefault(),p=!0,U()?T(-1):V(-1,!0))},D=W=>{switch(u0.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(),Q(!0);return;case"Tab":Q(!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 X of c)W.includes(X)||X.removeAttribute(eg);if(c=[...W],!U())return;let te=y();x(te,Math.min(u,te.length-1)),h()},isOpen:U,open:()=>V(0),close:Q,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},oC="data-persona-composer-action",tg="data-persona-composer-disable-when-streaming",f0="core:overflow",m0=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function g0(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 og(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 nC=(e,t)=>{!e||typeof console>"u"||console.warn(t)},h0=(e,t)=>t.includes(":")?t:`${e}:${t}`;function y0(e){let{debug:t}=e,o=[],n=new Map,r=0,a=d=>{let c=n.get(d.id);if(c){nC(t,`[Persona] composer action "${d.id}" is already contributed by ${rC(c)}; the ${rC(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?h0(u,d.id):d.id,m=d.order??$n.custom;d.placement==="end"&&m>=$n.send&&(nC(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 rC=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",sC=(e,t,o)=>e===void 0?o:typeof e=="function"?e(t)===!0:e===!0,b0=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function v0(e,t){if(!e||e==="always")return!0;let o=b0(t);return e==="when-text"?o:!o}var Qr=e=>e.kind==="custom",ng=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,x0=e=>{let t=ng(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},C0='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function S0(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(C0)||n.childNodes.forEach(o)};return o(e),t.trim()}var w0=e=>S0(e).length===0;function aC(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 X of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])D.style[X]="";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 X=ue(O.iconName,16,"currentColor",1.5);X&&W.appendChild(X)}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(tg,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=ho("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",jo,bn,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 X=ue(O.iconName,yo,"currentColor",1.5);X&&D.appendChild(X)}if(te){let X=I("span","persona-composer-action-button__label");X.textContent=O.shortLabel,D.appendChild(X)}else D.firstChild||(D.textContent=O.label);E.tooltip?.destroy(),E.tooltip=to({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 le=I("div","persona-send-button-wrapper");le.appendChild(W),te=le}te.setAttribute(oC,E.id);let X={resolved:E,element:te,button:W,owned:!0,managed:!0,busy:!1,visible:!0,mode:O},fe=le=>{if(le.preventDefault(),le.stopPropagation(),X.busy||W.disabled)return;let be=X.resolved.action;X.mode==="menu"&&y?.close(!0);let He;try{He=be.onSelect(e.actionContext,le)}catch(We){e.reportError(We,{actionId:X.resolved.id});return}!He||typeof He.then!="function"||(X.busy=!0,W.setAttribute("aria-busy","true"),He.catch(We=>{e.reportError(We,{actionId:X.resolved.id})}).finally(()=>{X.busy=!1,W.removeAttribute("aria-busy")}))};return W.addEventListener("click",fe),X.detach=()=>W.removeEventListener("click",fe),i(X,D),X},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(oC,E.id),D.element.toggleAttribute(tg,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?Qr(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 X=D+1;X<O.length;X++){let fe=O[X];if(!fe.managed&&fe.element.parentElement===E){te=fe.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=tC({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),y),H=E=>{x!==E&&(T?.disconnect(),x=E,w=og(E),!(typeof ResizeObserver>"u")&&(T=new ResizeObserver(O=>{let W=O[O.length-1]?.contentRect?.width??og(E);W!==w&&(w=W,Q())}),T.observe(E)))},b=(E,O)=>{let D=g0(E.collapseAutoActionsBelow,O);if(D===null)return!1;let W=w||og(O);return W>0&&W<D},A=(E,O,D)=>{if(!O)return"bar";if(E.resolved.builtIn){let te=m0(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(!w0(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let D=x0(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&&!Qr(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",[Km]:""}});W.appendChild(E.element),Kx(ng(E.element)),E.menuSlot=W;let te=X=>{let fe=ng(E.element);if(fe.disabled)return;let le=X.target===fe||fe.contains(X.target);y?.close(!0),le||fe.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},U=(E,O)=>{let D=O.map(W=>W.menuSlot??W.element);for(D.forEach((W,te)=>{let X=E.children[te];X!==W&&(X?E.insertBefore(W,X):E.appendChild(W))});E.children.length>D.length;)E.lastElementChild?.remove()},Q=()=>{if(n)return;let E=e.getBindings();if(!E)return;let O=e.getState(),D=O.phase==="streaming",W=k();W&&H(E.footer);let te=W?b(W,E.footer):!1,X={start:[],end:[]},fe=[];for(let le of o){let be=t.get(le.id);if(!be)continue;let He=le.action,We=He?sC(He.visible,O,!0)&&v0(He.visibility,O):!0;if(be.visible!==We&&(be.visible=We,!We&&be.managed&&(be.menuSlot??be.element).remove()),!!We){if(be=L(be,A(be,W,te)),He){let Se=sC(He.disabled,O,!1)||He.disableWhenStreaming===!0&&D;h(be,Se),!Qr(He)&&He.pressed!==void 0&&be.button?.setAttribute("aria-pressed",He.pressed?"true":"false")}be.mode==="menu"?(C(be),fe.push(be)):X[le.placement].push(be)}}if(fe.length>0){let le=P();U(le.panel,fe),le.setItems(fe.map(Se=>Se.menuSlot??Se.element)),le.applyButtonSize();let be=Number.isFinite(W?.order)?W?.order:$n.overflow,He=X.start.findIndex(Se=>Se.resolved.order>be),We={resolved:{id:f0,placement:"start",presentation:"bar",order:be,sequence:-1,source:"core"},element:le.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};X.start.splice(He<0?X.start.length:He,0,We)}else y&&(y.close(),y.trigger.remove(),y.setItems([]));m(E.actionsStart,X.start),m(E.actionsEnd,X.end)};return{resolve:()=>{if(n)return;let E=y0(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 le=u(D,"bar");le&&t.set(D.id,le);continue}let te=W.resolved.action,X=D.action;if(!!te!=!!X||te&&X&&Qr(te)!==Qr(X)||te&&X&&Qr(te)&&Qr(X)&&te.render!==X.render){p(W),t.delete(D.id);let le=u(D,W.mode);le&&t.set(D.id,le);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)):X&&!Qr(X)?i(W,X):X&&W.element.toggleAttribute(tg,X.disableWhenStreaming===!0)}o=E,Q()},sync:Q,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 A0="core:model",M0=700,iC=16,T0=["--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"],lC=()=>{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 dC(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}=lC();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=ou({anchor:c,content:m,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Qc(c,m,T0),x.open(),c.setAttribute("aria-expanded","true");let W=[...h.keys()].indexOf(r(e.getModels())?.id??"");k(O??(W>=0?W:0))},H=O=>{w(!0),e.onSelect(O)},b=O=>{O.preventDefault(),O.stopPropagation();let D=O.currentTarget.getAttribute("data-persona-model-option");D&&H(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 le=ue(O.icon,iC,"currentColor",1.5);if(le){let be=I("span","persona-composer-model-option-icon");be.appendChild(le),D.appendChild(be)}}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 le=I("span","persona-composer-model-option-description");le.textContent=O.description,W.appendChild(le)}D.appendChild(W);let X=I("span","persona-composer-model-option-check");X.setAttribute("aria-hidden","true");let fe=ue("check",iC,"currentColor",2);return fe&&X.appendChild(fe),D.appendChild(X),D.addEventListener("click",b),D},C=()=>{let O=e.getModels(),D=O.map(X=>`${X.id}:${X.label}:${X.icon??""}:${X.description??""}`).join("|");if(D!==y){y=D;for(let X of h.values())X.removeEventListener("click",b);h.clear(),m.replaceChildren(...O.map(X=>{let fe=A(X);return h.set(X.id,fe),fe}))}let W=r(O);for(let[X,fe]of h)fe.setAttribute("aria-selected",String(X===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()},U=O=>{if(O.key==="ArrowDown"){O.preventDefault(),T()?k(0):P(0);return}O.key==="ArrowUp"&&(O.preventDefault(),T()?k(-1):P(-1))},Q=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",U),m.addEventListener("keydown",Q);let{wrapper:V,chevron:E}=lC();return V.append(c,E),{element:V,destroy:()=>{n===C&&(n=null),c.removeEventListener("click",L),c.removeEventListener("keydown",U),m.removeEventListener("keydown",Q);for(let O of h.values())O.removeEventListener("click",b);h.clear(),x?.destroy(),x=null,m.remove()}}};return{action:{id:A0,kind:"custom",placement:"end",order:M0,presentation:o==="popover"?"bar":"auto",label:t,render:()=>o==="popover"?i():a()},repaint:()=>n?.()}}var rg="[data-persona-composer-chip-row]";function nu(e){e.style.display=e.childElementCount>0?"flex":"none"}function sg(e){let t=e.querySelector(rg);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 E0=":scope > [data-persona-composer-mode]";function cC(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=ue(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=ue("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(E0)),d=u=>{u.setAttribute("data-persona-chip-exit",""),u.setAttribute("aria-hidden","true"),u.style.pointerEvents="none";let p=()=>{u.remove(),nu(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}nu(t)},destroy:()=>{n=!0,c(),nu(t)}}}var uC=e=>`core:mode:${e}`;var ag=e=>Math.min(300+e,499),pC=e=>`core:mode-group:${e}`;function ru(e,t){return e?t?.find(o=>o.id===e)?.presentation==="segmented":!1}function P0(e,t){return e?t?.find(o=>o.id===e)?.chipVisibility==="hidden":!1}function fC(e,t){return e?.length?e.filter(o=>!ru(o.groupId,t)&&!P0(o.groupId,t)):[]}var k0=(e,t)=>e.groupId?t?.find(o=>o.id===e.groupId)?.selection??null:null;function mC(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(k0(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 su(e,t){return t?.length?t.filter(o=>e.includes(o.id)).map(o=>o.id):[]}function gC(e,t){return t?.length?t.filter(o=>e.includes(o.id)&&(o.persistence??"sticky")!=="once").map(o=>o.id):[]}function hC(e,t){if(!(!t?.length||e.length===0))return t.find(o=>e.includes(o.id)&&o.placeholder)?.placeholder}var L0=16;function yC(e){let t=null;return{action:{id:pC(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=ue(u.iconName,L0,"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 bC(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=Hc(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=ue("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 vC(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=ue(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=Hc(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 xC(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 CC(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 SC(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 wC(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 AC(e){return e.wrapped||e.text.includes(`
24
+ `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission||e.dictationActive)}function MC(){let e=!1;return{observe:(t,o)=>o?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function TC(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 EC(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function ig(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 kC(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var I0=e=>typeof e?.then=="function";function PC(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 LC(e,t,o){let n;try{n=e(ig(t),{signal:o})}catch(r){return{status:"error",error:r}}return I0(n)?Promise.resolve(n).then(r=>o.aborted?{status:"aborted"}:PC(t,r),r=>o.aborted?{status:"aborted"}:{status:"error",error:r}):PC(t,n)}var IC=/\s/;function R0(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===""||IC.test(n)}function H0(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 R0(e,a,n)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(i===`
26
+ `||i==="\uFFFC"||!r&&IC.test(i))return null;a--}return null}function RC(e,t,o){for(let n of o){let r=H0(e,t,n.trigger,n.position??"anywhere",n.allowSpaces??!1);if(r)return{channel:n,match:r}}return null}function HC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function WC(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 BC(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 ${jo} ${bn}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),d=ue(n,yo,"currentColor",1.5);return d?i.appendChild(d):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),o()}),a.appendChild(i),to({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:a}}var{setLoader:W0,load:B0}=bt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),OC=W0,lg=B0;var{setLoader:O0,load:D0}=bt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),DC=O0,_C=D0;function Al(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let o=Y("span",{className:ho("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=ue(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 NC(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let o=WC(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
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=`
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=lg().then(A=>(A.setMentionIconRenderer(ue),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:H,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=()=>{_C().then(b=>{let A=b.mountInlineComposer({textarea:e.textarea,renderToken:L=>Al(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=BC({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 H=(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(!HC(b))return;let A=p,C=A.selectionStart??0;RC(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:()=>{lg().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 au="16px",iu="transparent",_0=(()=>{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})(),cg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:_0,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"}},ug={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"}},pg={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:$o,maxWidth:zc,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:au,canvasBackground:iu},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function bo(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."))?bo(e,n):n}function lu(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=bo(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 fg(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 UC(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]=UC(a,r):o[n]=r}return o}function N0(e,t){return t?UC(e,t):e}function Ml(e,t={}){let o={palette:cg,semantic:ug,components:pg},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:N0(o.components,e?.components)};if(t.validate!==!1){let r=fg(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 dg=e=>e.trim()==="0"?"0px":e,FC="--persona-",F0=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},U0=.179,oo=(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[FC+a],r!==void 0)break;r!==void 0&&(e[FC+o]=r)}};function du(e){let t=lu(e),o={};for(let[z,qe]of Object.entries(t)){let Ge=z.replace(/\./g,"-");o[`--persona-${Ge}`]=qe.value}oo(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"],oo(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"]]),oo(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"]}`,oo(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"]??au,o["--persona-panel-canvas-bg"]=o["--persona-components-panel-canvasBackground"]??iu,oo(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"]]),oo(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"],oo(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"],oo(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[z,qe]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ge=o[`--persona-components-history-overlay-${z}`];Ge&&(o[`--persona-history-overlay-${qe}`]=Ge)}for(let[z,qe]of[["background","bg"],["borderRadius","radius"]]){let Ge=o[`--persona-components-history-menu-${z}`];Ge&&(o[`--persona-history-menu-${qe}`]=Ge)}let m=e.components?.history?.motion;if(m){let z=Tt=>{if(Tt===void 0)return;let Ie=String(Tt).trim();return/^\d+(\.\d+)?$/.test(Ie)?`${Ie}ms`:Ie},qe=z(m.enterDurationMs);qe!==void 0&&(o["--persona-history-enter-ms"]=qe);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 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 z of["scrim","shadow"]){let qe=o[`--persona-components-history-confirm-${z}`];qe&&(o[`--persona-history-confirm-${z}`]=qe)}for(let[z,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-${z}`];Ge&&(o[`--persona-tooltip-${qe}`]=Ge)}e.components?.tooltip?.arrow===!1&&(o["--persona-tooltip-arrow-display"]="none");for(let[z,qe]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-${qe}`]=Ge)}oo(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,oo(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"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),oo(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 H=o["--persona-components-markdown-heading-h2-fontSize"];H&&(o["--persona-md-h2-size"]=H);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),oo(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"]]),oo(o,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),oo(o,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),oo(o,[["md-hr-color","components-markdown-hr-color","divider"]]),oo(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"],oo(o,[["message-border","components-message-border","border"]]),oo(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 U=C?.labelButton;U&&(U.background&&(o["--persona-label-btn-bg"]=U.background),U.border&&(o["--persona-label-btn-border"]=U.border),U.color&&(o["--persona-label-btn-color"]=U.color),U.padding&&(o["--persona-label-btn-padding"]=U.padding),U.borderRadius&&(o["--persona-label-btn-radius"]=U.borderRadius),U.hoverBackground&&(o["--persona-label-btn-hover-bg"]=U.hoverBackground),U.fontSize&&(o["--persona-label-btn-font-size"]=U.fontSize),U.gap&&(o["--persona-label-btn-gap"]=U.gap));let Q=C?.toggleGroup;Q&&(Q.gap&&(o["--persona-toggle-group-gap"]=Q.gap),Q.borderRadius&&(o["--persona-toggle-group-radius"]=Q.borderRadius));let V=C?.artifact;if(V?.toolbar){let z=V.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"]=dg(z.toggleGroupGap)),z.toggleBorderRadius&&(o["--persona-artifact-toolbar-toggle-radius"]=z.toggleBorderRadius),z.toggleGroupPadding&&(o["--persona-artifact-toolbar-toggle-group-padding"]=dg(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"]=bo(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"]=dg(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(V?.tab){let z=V.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(V?.pane){let z=V.pane;if(z.toolbarBackground){let qe=bo(e,z.toolbarBackground)??z.toolbarBackground;o["--persona-artifact-toolbar-bg"]=qe}}if(V?.card){let z=V.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(V?.inline){let z=V.inline;z.background&&(o["--persona-artifact-inline-bg"]=bo(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"]=bo(e,z.chromeBackground)??z.chromeBackground),z.chromeBorder&&(o["--persona-artifact-inline-chrome-border"]=bo(e,z.chromeBorder)??z.chromeBorder),z.titleColor&&(o["--persona-artifact-inline-title-color"]=bo(e,z.titleColor)??z.titleColor),z.mutedColor&&(o["--persona-artifact-inline-muted-color"]=bo(e,z.mutedColor)??z.mutedColor),z.frameHeight&&(o["--persona-artifact-inline-frame-height"]=z.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"]=bo(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",X=o["--persona-palette-colors-gray-300"]??"#d1d5db",fe=!D||D===O,le=F0(O??o["--persona-background"]),be=fe&&le!==void 0&&le<U0,He=be?"rgba(255, 255, 255, 0.08)":W,We=be?"rgba(255, 255, 255, 0.12)":te,Se=be?"rgba(255, 255, 255, 0.16)":X,mt=fe?He:D,ke=fe?We:D;return o["--persona-icon-btn-hover-bg"]=o["--persona-icon-btn-hover-bg"]??mt,o["--persona-icon-btn-active-bg"]=o["--persona-icon-btn-active-bg"]??ke,fe&&(o["--persona-icon-btn-active-border"]=o["--persona-icon-btn-active-border"]??Se),o["--persona-label-btn-hover-bg"]=o["--persona-label-btn-hover-bg"]??mt,o["--persona-artifact-tab-hover-bg"]=o["--persona-artifact-tab-hover-bg"]??mt,o["--persona-artifact-card-hover-bg"]=o["--persona-artifact-card-hover-bg"]??mt,o}var qC={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 q0={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"}}},V0={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},VC=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Tl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",$0=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Tl()},cu=e=>$0(e),j0=e=>Ml(e),z0=e=>{let t=Xa(V0,e??{})??{};return Ml({...t,palette:{...t.palette,colors:{...q0.colors,...t.palette?.colors}}},{validate:!1})},Yr=e=>{let t=cu(e),o=VC(e?.theme),n=VC(e?.darkTheme);return t==="dark"?z0(Xa(o??{},n??{})):j0(o)},K0=e=>du(e),Vs=(e,t)=>{let o=Yr(t),n=K0(o);for(let[r,a]of Object.entries(n))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",cu(t))},Ja=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let o=new MutationObserver(()=>{e(Tl())});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(Tl());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 Jr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var uu="24px",mg=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",El=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 jC=null;var gg=()=>{if(jC!==null)return jC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},G0="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",pu=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},fu=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 pu("unknown modifier in",e),null;return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(o)||!/^([^+\s]|[a-z]{2,12})$/.test(o)?(pu("unsupported",e),null):(o==="space"&&(n.key=" "),n)},X0=e=>G0.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),zC=(e,t)=>{let o=fu(e);if(!o)return"";let n=gg(),r=X0(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("+")},mu=e=>zC(e,!1),Pl=e=>zC(e,!0),Q0=(e,t)=>t.key?.toLowerCase()===e.key&&(gg()?t.metaKey:t.ctrlKey)===e.mod&&!(gg()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Y0=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},KC=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(Q0(d.parsed,a)&&d.when?.()!==!1&&n(d,a)&&!(!d.allowInInput&&Y0(i))){a.preventDefault();try{d.run(a)}catch(c){pu(`${d.id} threw on`,d.combo),console.warn(c)}return}};return o?.addEventListener("keydown",r),{register(a){let i=fu(a.combo);if(!i)return()=>{};let d=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(d);return c?(pu(`${c.id} already owns`,a.combo),()=>{}):(t.set(d,{...a,parsed:i}),a.element?.setAttribute("aria-keyshortcuts",Pl(a.combo)),()=>{t.get(d)?.id===a.id&&t.delete(d),a.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),o?.removeEventListener("keydown",r)}}};var GC=(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,U=null){A instanceof HTMLTemplateElement&&C instanceof HTMLTemplateElement&&(A=A.content,C=C.content),L||(L=A.firstChild);for(let Q of C.childNodes){if(L&&L!=U){let E=x(b,Q,L,U);if(E){E!==L&&w(b,L,E),i(E,Q,b),L=E.nextSibling;continue}}if(Q instanceof Element){let E=Q.getAttribute("id");if(b.persistentIds.has(E)){let O=k(A,E,L,b);i(O,Q,b),L=O.nextSibling;continue}}let V=y(A,Q,L,b);V&&(L=V.nextSibling)}for(;L&&L!=U;){let Q=L;L=L.nextSibling,T(b,Q)}}function y(b,A,C,L){if(L.callbacks.beforeNodeAdded(A)===!1)return null;if(L.idMap.has(A)){let U=document.createElement(A.tagName);return b.insertBefore(U,C),i(U,A,L),L.callbacks.afterNodeAdded(U),U}else{let U=document.importNode(A,!0);return b.insertBefore(U,C),L.callbacks.afterNodeAdded(U),U}}let x=(function(){function b(L,U,Q,V){let E=null,O=U.nextSibling,D=0,W=Q;for(;W&&W!=V;){if(C(W,U)){if(A(L,W,U))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,U,Q){let V=L.idMap.get(U),E=L.idMap.get(Q);if(!E||!V)return!1;for(let O of V)if(E.has(O))return!0;return!1}function C(L,U){let Q=L,V=U;return Q.nodeType===V.nodeType&&Q.tagName===V.tagName&&(!Q.getAttribute?.("id")||Q.getAttribute?.("id")===V.getAttribute?.("id"))}return b})();function T(b,A){if(b.idMap.has(A))H(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 U=L;L=L.nextSibling,T(b,U)}return L}function k(b,A,C,L){let U=L.target.getAttribute?.("id")===A&&L.target||L.target.querySelector(`[id="${A}"]`)||L.pantry.querySelector(`[id="${A}"]`);return P(U,L),H(b,U,C),U}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 H(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,H,b){return b.ignoreActive&&P===document.activeElement?null:(b.callbacks.beforeNodeMorphed(P,H)===!1||(P instanceof HTMLHeadElement&&b.head.ignore||(P instanceof HTMLHeadElement&&b.head.style!=="morph"?c(P,H,b):(y(P,H,b),k(P,b)||a(b,P,H))),b.callbacks.afterNodeMorphed(P,H)),P)}function y(P,H,b){let A=H.nodeType;if(A===1){let C=P,L=H,U=C.attributes,Q=L.attributes;for(let V of Q)w(V.name,C,"update",b)||C.getAttribute(V.name)!==V.value&&C.setAttribute(V.name,V.value);for(let V=U.length-1;0<=V;V--){let E=U[V];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!==H.nodeValue&&(P.nodeValue=H.nodeValue)}function x(P,H,b){if(P instanceof HTMLInputElement&&H instanceof HTMLInputElement&&H.type!=="file"){let A=H.value,C=P.value;T(P,H,"checked",b),T(P,H,"disabled",b),H.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&&H instanceof HTMLOptionElement)T(P,H,"selected",b);else if(P instanceof HTMLTextAreaElement&&H instanceof HTMLTextAreaElement){let A=H.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,H,b,A){let C=H[b],L=P[b];if(C!==L){let U=w(b,P,"update",A);U||(P[b]=H[b]),C?U||P.setAttribute(b,""):w(b,P,"remove",A)||P.removeAttribute(b)}}function w(P,H,b,A){return P==="value"&&A.ignoreActiveValue&&H===document.activeElement?!0:A.callbacks.beforeAttributeUpdated(P,H,b)===!1}function k(P,H){return!!H.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 H=Object.assign(h,{head:{block:!1,ignore:!0}});return T(H)})}}return T(h)}function c(h,y,x){let T=[],w=[],k=[],P=[],H=new Map;for(let A of y.children)H.set(A.outerHTML,A);for(let A of h.children){let C=H.has(A.outerHTML),L=x.head.shouldReAppend(A),U=x.head.shouldPreserve(A);C||U?L?w.push(A):(H.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(...H.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,U=new Promise(function(Q){L=Q});C.addEventListener("load",function(){L()}),b.push(U)}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:U}=P(b,A),Q=y(C),V=Q.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(V))throw`Do not understand how to morph style ${V}`;return{target:b,newContent:A,config:Q,morphStyle:V,ignoreActive:Q.ignoreActive,ignoreActiveValue:Q.ignoreActiveValue,restoreFocus:Q.restoreFocus,idMap:U,persistentIds:L,pantry:x(),activeElementAndParents:T(b),callbacks:Q.callbacks,head:Q.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 U of L){let Q=U.getAttribute("id");if(A.has(Q)){let V=U;for(;V;){let E=b.get(V);if(E==null&&(E=new Set,b.set(V,E)),E.add(Q),V===C)break;V=V.parentElement}}}}function P(b,A){let C=w(b),L=w(A),U=H(C,L),Q=new Map;k(Q,U,b,C);let V=A.__idiomorphRoot||A;return k(Q,U,V,L),{persistentIds:U,idMap:Q}}function H(b,A){let C=new Set,L=new Map;for(let{id:Q,tagName:V}of b)L.has(Q)?C.add(Q):L.set(Q,V);let U=new Set;for(let{id:Q,tagName:V}of A)U.has(Q)?C.add(Q):L.get(Q)===V&&U.add(Q);for(let Q of C)U.delete(Q);return U}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 H of[...k])P.append(H);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=[],H=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;H&&H!=this.nextSibling;)P.push(H),H=H.nextSibling;return P}querySelectorAll(P){return this.childNodes.reduce((H,b)=>{if(b instanceof Element){b.matches(P)&&H.push(b);let A=b.querySelectorAll(P);for(let C=0;C<A.length;C++)H.push(A[C])}return H},[])}insertBefore(P,H){return this.realParentNode.insertBefore(P,H)}moveBefore(P,H){return this.realParentNode.moveBefore(P,H)}get __idiomorphRoot(){return this.originalNode}}function w(k){let P=new DOMParser,H=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(H.match(/<\/html>/)||H.match(/<\/head>/)||H.match(/<\/body>/)){let b=P.parseFromString(k,"text/html");if(H.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 gu=(e,t,o={})=>{let{preserveTypingAnimation:n=!0}=o;GC.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 XC=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var hg={index:-1,draft:""};function QC(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 YC(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 JC(){return new Map}function ZC(e,t,o){let n=e.get(t);return n&&n.fingerprint===o?n.wrapper:null}function eS(e,t,o,n){e.set(t,{fingerprint:o,wrapper:n})}function tS(e,t){for(let o of e.keys())t.has(o)||e.delete(o)}function oS(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 nS(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function jn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function $s(e,t){return jn(e)-e.scrollTop<=t}function rS(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 sS(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 aS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function yg(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 iS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var kl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},J0=["pre","code","a","script","style"],hu=e=>({type:e?.type??kl.type,placeholder:e?.placeholder??kl.placeholder,speed:e?.speed??kl.speed,duration:e?.duration??kl.duration,buffer:e?.buffer??kl.buffer}),dS=[{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"}],Ll=new Map;for(let e of dS)Ll.set(e.name,e);var cS=["wipe","glyph-cycle"],Za=e=>{Ll.set(e.name,e)},xg=e=>{dS.some(t=>t.name===e)||Ll.delete(e)},Cg=()=>Array.from(Ll.keys()),Il=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Ll.get(e)??null,yu=(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},Z0=(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},eP=(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},bg=/\s/,tP=(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},oP=(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(bg.test(a[d])){let c=d;for(;c<a.length&&bg.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&&!bg.test(a[u]);)c.appendChild(Z0(n,a[u],t,o.value)),o.value+=1,u+=1;i.appendChild(c),d=u}r.replaceChild(i,e)},nP=(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(eP(n,c,t,o.value)),o.value+=1));r.replaceChild(i,e)},Rl=(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??J0).map(m=>m.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),d=[],c=i.nextNode();for(;c;)tP(c,a)||d.push(c),c=i.nextNode();let u={value:n?.startIndex??0},p=t==="char"?oP:nP;for(let m of d)p(m,o,u);return r.innerHTML},bu=(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},Hl=(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},lS=new WeakMap,rP=(e,t)=>{if(!e.styles)return;let o=lS.get(t);if(o||(o=new Set,lS.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)},vg=new WeakMap,sP=(e,t)=>{if(!e.onAttach)return;let o=vg.get(t);if(o||(o=new Map,vg.set(t,o)),o.has(e.name))return;let n=e.onAttach(t);o.set(e.name,n)},uS=e=>{let t=vg.get(e);if(t){for(let o of t.values())typeof o=="function"&&o();t.clear()}},Wl=(e,t)=>{rP(e,t),sP(e,t)};var{setLoader:aP,load:iP}=bt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),pS=aP,fS=iP;function Sg(e,t=ao){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 Bl=0,Zr=null;function wg(e=document){if(Bl++,Bl===1){let o=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Zr={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,Bl=Math.max(0,Bl-1),Bl===0&&Zr)){let o=e.body,n=e.defaultView??window;o.style.overflow=Zr.originalOverflow,o.style.position=Zr.originalPosition,o.style.top=Zr.originalTop,o.style.width=Zr.originalWidth,n.scrollTo(0,Zr.scrollY),Zr=null}}}var Ol={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},wt=e=>(e?.launcher?.mountMode??"floating")==="docked",es=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Ro=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ol.side,width:t?.width??Ol.width,animate:t?.animate??Ol.animate,reveal:t?.reveal??Ol.reveal,maxHeight:t?.maxHeight??Ol.maxHeight}};var Ag=e=>e==="followUp"?"follow-up":e,Mg=(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"}},lP=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'}},mS=new WeakSet,dP=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,cP=e=>{dP()||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"})})},Tg=e=>{var H,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 Q of c)if(Q.onSuggestionSelect?.({suggestion:{...t},surface:n,source:r,variant:a,config:d})===!1)return;let U=m();if(T==="fill"){U.value=t.prompt,U.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),U.focus();return}if(y){y(t.prompt);return}U.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=lP(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 U=ue(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);U&&(U.classList.add("persona-suggestion__icon"),t.iconColor&&(U.style.color=t.iconColor),C.appendChild(U))}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 U=Ft(fl,16,"currentColor",1.8);U&&(U.classList.add("persona-suggestion__arrow"),C.appendChild(U))}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()),(H=P.dataset).suggestionId||(H.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},Dl=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",H=T?.variant??"chip",b=T?.behavior??"send",A=T?.overflow??"wrap",C=T?.config??{},L=T?.plugins??[],U=typeof T?.maxItems=="number"?Math.max(0,Math.floor(T.maxItems)):void 0,Q=P?"followUps":"starters";!mS.has(C)&&C.debug===!0&&H!=="chip"&&C.suggestions?.[Q]?.overflow!==void 0&&(mS.add(C),console.info(`[persona] suggestions.${Q}.overflow applies to the "chip" variant only; the "${H}" variant manages its own stacking.`));let V=X=>X.map(Mg).filter(fe=>fe!==null).map(fe=>({...fe,behavior:fe.behavior??b})),E=V(p??[]);L.forEach(X=>{X.transformSuggestions&&(E=V(X.transformSuggestions({suggestions:E.map(fe=>({...fe})),surface:k,source:w,config:C})))});let O=U===void 0?E:E.slice(0,U);if(!O.length){e.hidden=!0,n=null,a();return}if(!P&&(y??m.getMessages()).some(fe=>fe.role==="user")){e.hidden=!0,n=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Ag(k),e.dataset.variant=H,e.dataset.overflow=A;let D=document.createDocumentFragment(),W=m.isStreaming();O.forEach((X,fe)=>{let le=Tg({item:X,index:fe,surface:k,source:w,variant:H,streaming:W,config:C,plugins:L,chipsConfig:x,session:m,getTextarea:()=>h,eventTarget:e,submitPrompt:T?.submitPrompt});D.appendChild(le),o.push(le),[...le instanceof HTMLButtonElement?[le]:[],...Array.from(le.querySelectorAll("button"))].forEach(He=>{t.includes(He)||(He.disabled=W,t.push(He))})}),e.appendChild(D),i(),d();let te=JSON.stringify({normalized:O,surface:k,variant:H,source:w});te!==n&&(n=te,cP(o),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:O.map(X=>({...X})),surface:k,source:w,variant:H},bubbles:!0,composed:!0})),P&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:O.map(X=>X.prompt)},bubbles:!0,composed:!0})))}}};var zo={"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 uP="persona-header-control",pP="persona-header-control--glyph",fP="persona-header-control--sparse",mP=20,gP={x:[1.4,1.05]},gS="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",hP="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vu=(e,t,o={})=>{let{iconSize:n,iconText:r}=o,[a,i]=gP[t]??[1,1.5],d=!n;e.classList.toggle(pP,d),e.classList.toggle(fP,d&&a!==1);let c=parseFloat(n??"")||mP,u=ue(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)},js=e=>{let{ariaLabel:t,tooltip:o=!0,tooltipHint:n,iconName:r,iconText:a,wrapperClassName:i=gS,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,H=I("div",i),b=!!(m||h),A=Y("button",{className:ho(uP,"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||vo.actionIconColor,backgroundColor:p,border:b?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:y,paddingLeft:x,paddingRight:x,paddingTop:T,paddingBottom:T}});return r?vu(A,r,{iconSize:c,iconText:a}):a&&(A.textContent=a),H.appendChild(A),to({anchor:A,trigger:H,text:()=>A.getAttribute("aria-label")??t,hint:n,enabled:o}),{button:A,wrapper:H}},ei=(e,t={})=>{let{showClose:o=!0,wrapperClassName:n=gS,buttonSize:r,iconSize:a}=t,i=e?.launcher??{},d=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:u,wrapper:p}=js({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}},ti=(e,t={})=>{let{wrapperClassName:o=hP,buttonSize:n,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},d=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:u,wrapper:p}=js({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 vo={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)"},Eg={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)"},yP={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)"},br=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:vo.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=ue(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:vo.titleColor,...Eg}}),h=Y("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:vo.subtitleColor,...yP}});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=ti(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:H,wrapper:b}=ei(t,{showClose:o,wrapperClassName:P});return i!=="top-right"&&n.appendChild(b),{header:n,iconHolder:u,headerTitle:m,headerSubtitle:h,closeButton:H,closeButtonWrapper:b,clearChatButton:w,clearChatButtonWrapper:k}},zs=(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 Ks(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(Ga)):(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=ue(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 Gs(e){let{icon:t,label:o,size:n,strokeWidth:r,className:a,chromeless:i,onClick:d,aria:c}=e,u=I("button",ho(!i&&"persona-icon-btn",a));u.type="button",u.setAttribute("aria-label",o),u.title=o;let p=ue(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 Pg(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=ue(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 hS(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=Gs({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 yS(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?Gs({...w,icon:o,size:n??14}):Pg({...w,icon:o,iconSize:n??14}),P=Gs({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 H=null,b=()=>{if(H)return H;let A=(typeof u=="function"?u():u)??void 0;return H=Ks({items:a,onSelect:i,anchor:T,position:c,portal:A,onOpenChange:C=>{P.setAttribute("aria-expanded",C?"true":"false")}}),A||T.appendChild(H.element),H};return T.isConnected?b():requestAnimationFrame(()=>{H||b()}),P.addEventListener("click",A=>{A.stopPropagation(),b().toggle()}),{element:T,primaryButton:k,chevronButton:P,openMenu:()=>b().show(),closeMenu:()=>H?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{H?.destroy(),T.remove()}}}function xu(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=ue(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=Ks({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 kg=e=>{let t=br({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 bP(e,t,o){if(t?.length)for(let n of t){let{button:r,wrapper:a}=js({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?mu(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=Pl(n.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(n.menuItems?.length){let i=Ks({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 Lg=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=vo.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=xu({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:A=>{let C=U=>{U===!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=vo.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=vo.titleColor,Object.assign(p.style,Eg),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}=ei(t,{showClose:o,wrapperClassName:m});n&&h.addEventListener("click",n);let x=I("div","persona-flex persona-items-center persona-gap-1");c||bP(x,r?.trailingActions,r?.onAction??a);let T=i.clearChat??{},w=null,k=null;if(T.enabled??!0){let b=T.placement??"inline",A=ti(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 H=I("span");return H.style.display="none",{header:d,iconHolder:P,headerTitle:p,headerSubtitle:H,closeButton:h,closeButtonWrapper:y,clearChatButton:w,clearChatButtonWrapper:k}},Cu={default:kg,minimal:Lg},Ig=e=>Cu[e]??Cu.default,oi=(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=Ig(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 Xs=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=tu(),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}=Yc(t);i();let d=Jc(t),c=Ya(t),u=Zc(t),p=eu(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 bS=()=>{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(bl,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(Fs,16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,n,r),{root:e,textNode:n}},Su=e=>{let{config:t}=e,o=Y("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=tu(),r=eu(t);r.style.display="none";let{textarea:a,attachAutoResize:i}=Yc(t,{defaultMaxLines:5});i();let d=Jc(t),c=Ya(t),u=Zc(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 vP=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}},xP=(e,t)=>{if(!e)return null;let o=vP(e);if(o===null)return null;let n=t?.[e],r=n!==void 0?n:o;return r||null},CP=(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},SP=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Hg=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(":"))},Wg=320,wS=320,wP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),AP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),MP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),TP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),EP=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=ue(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},PP=(e,t)=>{let o=document.createDocumentFragment();for(let n of e){if(n.kind==="text"){o.appendChild(document.createTextNode(n.text));continue}o.appendChild(Al(n.ref,{readonly:!0,render:t}))}return o},vS="\uE000",xS="\uE001",kP=(e,t,o,n)=>{let r=Math.random().toString(36).slice(2,8),a=h=>`${vS}${r}:${h}${xS}`,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(PP(t,n));return}e.innerHTML=d;let u=new RegExp(`${vS}${r}:(\\d+)${xS}`),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(Al(T.ref,{readonly:!0,render:n}),w),y=w}}},LP=(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=`${Wg}px`,u.style.maxHeight=`${wS}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}),SP(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}},IP=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(!Hg(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=`${Wg}px`,t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},RP=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(!Hg(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=`${Wg}px`,r.style.maxHeight=`${wS}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}},HP=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(!Hg(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}},Qs=()=>{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},Bg=(e,t,o)=>{let n={config:o??{},streaming:!0,location:e,defaultRenderer:Qs};if(t){let r=t(n);if(r!==null)return r}return Qs()},WP=(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},CS=(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},_l=(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},SS={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"}},BP=(e,t,o="bubble",n)=>{if(!n)return;let r=t==="user"?"user":"assistant",a=SS[o??"bubble"]??SS.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)`)},wu="custom:",OP=e=>`${wu}${e}`,AS=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(o=>(o.roles??["assistant"]).includes(t)),Og=(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=AS(t,e.role);if(!r&&!a&&!i&&!d&&!c&&!u&&!p&&m.length===0){let H=I("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}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=(H,b,A)=>{let C=Gs({icon:H,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 H of m)k.appendChild(P(H.iconName??"ellipsis",H.label,OP(H.id)));return k},ni=(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=_l(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;BP(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=wP(e),P=e.content?.trim()??"",b=k.length>0&&P===Fa,A=hu(a?.widgetConfig?.features?.streamAnimation),C=a?.widgetConfig?.features?.streamAnimation?.plugins,L=e.role==="assistant"&&A.type!=="none"?Il(A.type,C):null,U=e.role==="assistant"&&L?.isAnimating?.(e)===!0,Q=e.role==="assistant"&&L!==null&&(!!e.streaming||U);Q&&L?.bubbleClass&&T.classList.add(L.bubbleClass);let V=document.createElement("div");V.classList.add("persona-message-content"),e.streaming&&V.classList.add("persona-content-streaming"),Q&&L&&(L.containerClass&&V.classList.add(L.containerClass),V.style.setProperty("--persona-stream-step",`${A.speed}ms`),V.style.setProperty("--persona-stream-duration",`${A.duration}ms`));let E=Q?yu(e.content??"",A.buffer,L,e,!!e.streaming):e.content??"",O=()=>{let ke=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent});return Q&&L?.wrap==="char"?Rl(ke,"char",e.id,{skipTags:L.skipTags}):Q&&L?.wrap==="word"?Rl(ke,"word",e.id,{skipTags:L.skipTags}):ke},D=null;if(b?(D=document.createElement("div"),D.innerHTML=O(),D.style.display="none",V.appendChild(D)):e.contentSegments?.length?kP(V,e.contentSegments,ke=>t({text:ke,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):V.innerHTML=O(),Q&&L?.useCaret&&!b&&P){let ke=bu(),z=V.querySelectorAll(".persona-stream-char, .persona-stream-word"),qe=z[z.length-1];if(qe?.parentNode)qe.parentNode.insertBefore(ke,qe.nextSibling);else{let Ge=V.lastElementChild;Ge?Ge.appendChild(ke):V.appendChild(ke)}}if(m&&y==="inline"&&e.createdAt){let ke=CS(e,u,"span");ke.classList.add("persona-timestamp-inline");let z=V.lastElementChild;z?z.appendChild(ke):V.appendChild(ke)}if(k.length>0){let ke=LP(k,!b&&!!P,()=>{b&&D&&(D.style.display="")});ke?T.appendChild(ke):b&&D&&(D.style.display="")}let W=AP(e);if(W.length>0){let ke=IP(W);ke&&T.appendChild(ke)}let te=MP(e);if(te.length>0){let ke=RP(te);ke&&T.appendChild(ke)}let X=TP(e);if(X.length>0){let ke=HP(X);ke&&T.appendChild(ke)}let fe=e.contentSegments?.length?null:EP(e.contextMentions);if(fe&&T.appendChild(fe),T.appendChild(V),m&&y==="below"&&e.createdAt){let ke=CS(e,u);ke.classList.add("persona-mt-1"),T.appendChild(ke)}let le=e.role==="assistant"?xP(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ke=!!(E&&E.trim()),z=A.placeholder==="skeleton",qe=z&&A.buffer==="line"&&ke;if(ke)qe&&T.appendChild(Hl());else if(z)T.appendChild(Hl());else{let Ge=Bg("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);Ge&&T.appendChild(Ge)}}le&&e.stopReason&&!e.streaming&&(P||(V.style.display="none"),T.appendChild(CP(e.stopReason,le)));let be=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&n?.enabled!==!1,He=a?.actionEligibility,We=e.role==="user"&&!e.streaming&&n?.enabled!==!1&&(n?.showEdit===!0&&He?.canEdit===!0||n?.showQuote===!0&&He?.canQuote===!0||AS(n,"user").length>0);if((be||We)&&n){let ke=Og(e,We?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,r,He);T.appendChild(ke)}if(!p||e.role==="system")return T;let Se=I("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),mt=WP(c,e.role);return h==="right"||h==="left"&&e.role==="user"?Se.append(T,mt):Se.append(mt,T),Se},MS=(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}):ni(e,t,o,n,r,a)};var DP=40,_P=(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=ue(t.name,DP);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},TS=(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}},ri=(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)},Mu=(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==="",_P(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")},NP="data-persona-welcome-plugin",ES="data-persona-welcome-overlay",Au="persona-welcome-overlay-active",Dg=new WeakMap,_g=(e,t,o)=>{o.setAttribute(NP,""),t.appendChild(o),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(ES,""),e.classList.contains(Au)||(Dg.set(e,e.scrollTop),e.classList.add(Au),e.scrollTop=0)},Ng=(e,t,o)=>{o&&o!==t&&o.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(ES),e.classList.contains(Au)&&(e.classList.remove(Au),e.scrollTop=Dg.get(e)??e.scrollTop,Dg.delete(e))},PS=()=>{let e=Y("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Tu=(e,t,o)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let n=o?.layout?.messages?.layout??"bubble",r=Y("div",{className:_l("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},kS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,LS=(e,t)=>{if(kS()||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},IS=(e,t,o)=>{if(t<=1||kS()||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 FP="Hello \u{1F44B}",UP="I can answer questions and help you get things done here.",RS=new WeakSet,xo=(e,t)=>!!e&&e[t]!==void 0,qP=(e,t)=>{!e||e.debug!==!0||!t.length||RS.has(e)||(RS.add(e),t.forEach(o=>console.warn(`[persona] ${o}`)))},vn=e=>{let t=e?.welcome,o=e?.copy,n=xo(t,"variant")?t.variant:o?.showWelcomeCard===!1?"none":"card",r=n==="hero"?"on-first-message":xo(t,"dismiss")?t.dismiss:"never",a=[];xo(t,"title")&&xo(o,"welcomeTitle")&&a.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),xo(t,"subtitle")&&xo(o,"welcomeSubtitle")&&a.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),xo(t,"variant")&&xo(o,"showWelcomeCard")&&a.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),n==="hero"&&xo(t,"message")&&a.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),n==="hero"&&xo(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=El(t?.anchorComposerTop)!==null;return xo(t,"anchorComposerTop")&&!d&&a.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),i!=="center"&&(xo(t,"anchorComposerTop")||xo(t,"composerGap"))&&a.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),qP(e,a),{title:xo(t,"title")?t.title:o?.welcomeTitle??FP,kicker:t?.kicker??"",subtitle:xo(t,"subtitle")?t.subtitle:o?.welcomeSubtitle??UP,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()||uu}},HS=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",ts=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(o=>o.role==="user");var WS="16px",Ug="10px",qg="14px",BS=e=>{let t=e?.launcher?.enabled??!0,o=wt(e);if(es(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??ao);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??ao),{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&&zo[r.position]?zo[r.position]:zo["bottom-right"],i=I("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??ao);let d=I("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=e?.launcher?.width??e?.launcherWidth??$o;return d.style.width=u,d.style.maxWidth=u,i.appendChild(d),{wrapper:i,panel:d}},Vg=e=>{let t=Y("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Ag(e)}});return t.hidden=!0,t},OS=(e,t)=>{let o=Vg("starter"),n=TS(e,o,{flatShadow:wt(e)}),r=vn(e);Mu(n,r),ri(t,n.host,ts(r,e?.initialMessages));let a=PS();return Tu(a,r.message,e),{welcome:n,greetingHost:a}},VP=(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}=ei(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:WS,iconSize:Ug});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=ti(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:WS,iconSize:qg});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}=OS(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=Vg("followUp"),P=Jr(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 H=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=Su({config:e}),{root:A,textNode:C}=bS();return o.append(c,r,u,H),d&&o.appendChild(d),{container:o,body:u,messagesWrapper:w,starterSuggestions:T,transcriptSuggestions:k,composerOverlay:H,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}},DS=(e,t=!0)=>{if(es(e))return VP(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?oi(e,n,{showClose:t}):br({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}=OS(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=Vg("followUp"),T=Jr(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=Xs({config:e}),k=e?.layout?.showFooter!==!1;r?zs(o,a,e):(a.header.style.display="none",zs(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 $g=(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 om=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),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
- `);let r=vc(o.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
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=`
37
+ `,o.addEventListener("click",t);let n=a=>{let i=a.launcher??{},d=wt(a),c=o.querySelector("[data-role='launcher-title']");if(c){let H=i.title??"Chat Assistant";c.textContent=H,c.setAttribute("title",H)}let u=o.querySelector("[data-role='launcher-subtitle']");if(u){let H=i.subtitle??"Here to help you get answers fast";u.textContent=H,u.setAttribute("title",H)}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 H=i.agentIconSize??"40px";if(m.style.height=H,m.style.width=H,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(H)||24,A=ue(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 H=i.agentIconSize??"40px";h.style.height=H,h.style.width=H,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 H=i.callToActionIconSize??"32px";y.style.height=H,y.style.width=H,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(H)||24,C=Math.max(A-b,8),L=ue(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&&zo[i.position]?zo[i.position]:zo["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??ao));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}},$P="teaser-dismissed",NS=new Set,_S=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${$P}`},jP=(e,t)=>{if(NS.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},zP=(e,t)=>{if(NS.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},KP=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,GP=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||wt(e??{})?null:t},FS=(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(),zP(_S(n),te&&y())},k=te=>{!r||m||w(te==="user"&&u)},P=()=>{c=null,!(!a||m||h)&&(p=!0,u=!0,a.hidden=!1,!(KP()||typeof a.animate!="function")&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},H=()=>{!r||!a||m||p||h||jP(_S(n),y())||(x(),c=setTimeout(P,Math.max(0,r.delayMs??0)))},b=()=>{w(y()),t()},A=te=>{te.stopPropagation(),w(y())},L=$g(e,()=>{k("user"),t()}),U=()=>{x(),d?.removeEventListener("click",b),i?.removeEventListener("click",A),a?.remove(),a=null,d=null,i=null,u=!1},Q=()=>{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)},V=()=>{let te=n.launcher?.position??"bottom-right",X=zo[te]??zo["bottom-right"];if(!a){o.className="persona-launcher-surface",o.removeAttribute("data-teaser"),o.style.zIndex="",L.element.style.position="";return}o.className=ho("persona-launcher-surface",X),o.setAttribute("data-teaser",te),o.style.zIndex=String(n.launcher?.zIndex??ao),L.element.style.position="static"},E=te=>{let X=GP(te);if(r=X,!X){U();return}a||Q(),d.textContent=X.text,i.hidden=X.dismissible===!1,i.setAttribute("aria-label",X.dismissLabel??"Dismiss message"),H()},O=te=>{n=te,L.update(te),E(te),V()},D=(te,X="user")=>{h=te,te&&k(X)},W=()=>{U(),L.destroy(),o.remove()};return o.appendChild(L.element),e&&(E(e),V()),{element:o,launcher:L,get teaser(){return a?{element:a,show:P,dismiss:w}:null},setPanelOpen:D,update:O,destroy:W}};var US=({config:e,showClose:t})=>{let{wrapper:o,panel:n,pillRoot:r}=BS(e),a=DS(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}}},jg=({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=FS(e,o);return{instance:r,element:r.element}};var XP=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},QP=(e,t,o)=>`${XP(e)}plugin:${t}:${o}`,qS=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=>QP(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 si=(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 YP=["persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"],JP="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",ZP="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",ek=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Eu=(e,t)=>{let o=I("div",["persona-message-bubble",e,...YP].join(" "));return o.id=`bubble-${t}`,o.setAttribute("data-message-id",t),o},Pu=e=>{let t=I("button",e.expandable?JP:ZP);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},zg=(e,t,o)=>{e.innerHTML="";let n=Ft(t?Fs:ml,16,o,2);n?e.appendChild(n):e.textContent=t?"Hide":"Show"},ku=(e,t,o)=>{if(!o.expandable)return e.append(t),null;let n=I("div","persona-flex persona-items-center");zg(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},Lu=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?.();ek(t,o)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Iu=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&zg(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"},Ru=(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&&zg(c,n,o.iconColor),a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")};var ai=new Set,tk=(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
+ `):""},VS=(e,t)=>{Ru(e,t,{stateSet:ai,previewKind:"reasoning",iconColor:"currentColor"})},Kg=(e,t)=>{let o=e.reasoning,n=Eu("persona-reasoning-bubble",e.id);if(!o)return n;let r=t?.features?.reasoningDisplay??{},a=r.expandable!==!1,i=a&&ai.has(e.id),d=o.status!=="complete",c=tk(e,r.previewMaxLines??3),u=Pu({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=wc(o),W},w=y.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:h,previewText:c,isActive:d,config:t??{},elapsed:wc(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=Yv(o),p.appendChild(k);let P=r.loadingAnimation??"none",H=y.activeTextTemplate,b=y.completeTextTemplate,A=d?H:b,C=w instanceof HTMLElement,L=(W,te)=>{m.textContent="";let X=Ac(W,""),fe=0;for(let le of X){let be=le.styles.length>0?(()=>{let He=I("span",le.styles.map(We=>`persona-tool-text-${We}`).join(" "));return m.appendChild(He),He})():m;if(le.isDuration&&d)be.appendChild(T());else{let He=le.isDuration?wc(o):le.text;te?fe=si(be,He,fe):be.appendChild(document.createTextNode(He))}}};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="",si(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=ue(r.iconName,16,"currentColor",2);te&&(W.appendChild(te),u.appendChild(W))}let U="currentColor",Q=ku(u,p,{expandable:a,expanded:i,iconColor:U,metaGap:!1}),V=Lu({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,V),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),Iu({expanded:i,header:u,toggleIcon:Q,content:E,collapsedPreview:V,iconColor:U}),n.append(u,V,E),n};var ii=new Set,$S=e=>e.toggleTextColor||e.headerTextColor||"var(--persona-primary, #171717)",ok=(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
+ `);let r=Cc(o.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
40
+ `):""},Gg=(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)"},nk=(e,t)=>{let o=e.toolCall,n=t?.features?.toolCallDisplay,r=n?.collapsedMode??"tool-call",a=ok(e,n?.previewMaxLines??3),i=o?Zv(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=Gf(o,c.activeTextTemplate,u):!d&&c.completeTextTemplate&&(u=Gf(o,c.completeTextTemplate,u)),{summary:u,previewText:a,isActive:d}},jS=(e,t,o)=>{Ru(e,t,{stateSet:ii,previewKind:"tool",iconColor:$S(o?.toolCall??{})})},Xg=(e,t)=>{let o=e.toolCall,n=t?.toolCall??{},r=Eu("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&&ii.has(e.id),{summary:c,previewText:u,isActive:p}=nk(e,t),m=Pu({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=ll(o),E},w=n.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:c,previewText:u,collapsedMode:a.collapsedMode??"tool-call",isActive:p,config:t??{},elapsed:ll(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,H=n.completeTextTemplate,b=p?P:H,A=w instanceof HTMLElement,C=(E,O)=>{y.textContent="";let D=o.name?.trim()||"tool",W=Ac(E,D),te=0;for(let X of W){let fe=X.styles.length>0?(()=>{let le=I("span",X.styles.map(be=>`persona-tool-text-${be}`).join(" "));return y.appendChild(le),le})():y;if(X.isDuration&&p)fe.appendChild(T());else{let le=X.isDuration?ll(o):X.text;O?te=si(fe,le,te):fe.appendChild(document.createTextNode(le))}}};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="",si(y,O,0)}}else b&&C(b,!1);let L=$S(n),U=ku(m,h,{expandable:i,expanded:d,iconColor:L,metaGap:!0}),Q=Lu({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,Q),r;let V=I("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(V.style.display=d?"":"none",n.contentBackgroundColor&&(V.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(V.style.color=n.contentTextColor),n.contentPaddingX&&(V.style.paddingLeft=n.contentPaddingX,V.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(V.style.paddingTop=n.contentPaddingY,V.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,V.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",Gg(D,n),D.textContent=Cc(o.args),E.append(O,D),V.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",Gg(D,n),D.textContent=o.chunks.join(""),E.append(O,D),V.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",Gg(D,n),D.textContent=Cc(o.result),E.append(O,D),V.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`,V.appendChild(E)}return Iu({expanded:d,header:m,toggleIcon:U,content:V,collapsedPreview:Q,iconColor:L}),r.append(m,Q,V),r};var{setLoader:rk,load:sk,provide:xD,getSync:ak}=bt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),zS=rk,KS=sk;var GS=ak;var{setLoader:ik,load:lk}=bt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),XS=ik,Qg=lk;var Yg=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)})}},xn=new Yg;var Jg=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:dk,load:ck,provide:kD,getSync:uk}=bt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),li=null,Hu=new Set,QS=e=>{if(li)return li;li=e,e.initArtifactsUi({componentRegistry:xn});for(let n of Jg)xn.has(n)||xn.register(n,n==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Nn();t?e.__provideMarkdownParsers(t):Wa(()=>{let n=Nn();n&&e.__provideMarkdownParsers(n)}),e.__setIconsExtraLoader(()=>Fc());let o=[...Hu];Hu.clear();for(let n of o)try{n()}catch{}return e},YS=dk,Wu=()=>ck().then(QS);var vr=()=>{if(li)return li;let e=uk();return e?QS(e):null},Zg=e=>li?()=>{}:(Hu.add(e),()=>{Hu.delete(e)});function Co(e){return e?.features?.artifacts?.enabled===!0}function JS(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"),!Co(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 pk(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 ZS=["panel","seamless","detached"];function eh(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&ZS.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function th(e){return!e||!Co(e)?!1:eh(e)==="detached"}function Nl(e,t){if(!Co(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"),pk(e),JS(e,t);return}let o=t.features?.artifacts?.layout,n=eh(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)}JS(e,t)}function Fl(e,t){for(let d of ZS)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"),!Co(t))return;let o=t.features?.artifacts?.layout,n=eh(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 ew(e,t){return!t||!Co(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var fk=new Set(["__proto__","prototype","constructor"]),mk=new Set(["collapsed","card","panel","inline"]),tw=new Set(["markdown","component"]),gk=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ys=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ou=e=>!fk.has(e),oh=e=>typeof e=="string"&&mk.has(e),Js=e=>Object.keys(e).length>0;function zn(e,t,o,n){e.push({path:t,code:o,message:n})}var hk="Ignored because this key is not part of the persisted preference schema.",Bu="Ignored an unsupported value.",yk="Expected collapsed, panel, or inline.",bk='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',ow={kind:"mode",message:Bu},di={kind:"string",message:"Expected a CSS length string."},xr={kind:"boolean"},vk={paneWidth:di,paneMaxWidth:di,paneMinWidth:di,expandedPanelWidth:di,resizableMinWidth:di,resizableMaxWidth:di,expandLauncherPanelWhenOpen:xr,resizable:xr},xk={kind:"object",message:"Expected a preference object.",children:{showToolCalls:xr,showReasoning:xr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Bu},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Bu},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Bu},expandable:xr,grouped:xr}},reasoningDisplay:{kind:"object",children:{expandable:xr,activePreview:xr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:ow,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:ow,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:tw,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:tw}}},filePreview:{kind:"object",children:{enabled:xr}},layout:{kind:"object",children:vk}}}}};function nw(e,t,o,n){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:zn(n,o,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:zn(n,o,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:zn(n,o,"invalid_value",t.message);case"mode":return oh(e)?Lo(e):zn(n,o,"invalid_value",t.message);case"modeMap":{if(!Ys(e))return zn(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:Vr(i);Ou(i)&&(r?r.has(i):gk.test(c))?oh(d)?a[c]=Lo(d):zn(n,`${o}.${i}`,"invalid_value",yk):zn(n,`${o}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":bk)}return Js(a)?a:void 0}case"object":{if(t.bareMode&&oh(e))return Lo(e);if(!Ys(e))return zn(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))(!Ou(d)||!r.includes(d))&&zn(n,a(d),"unknown_key",hk);let i={};for(let d of r){let c=t.children[d],u=nw(e[d],c,a(d),n);if(c.deprecated&&e[d]!==void 0&&zn(n,a(d),"deprecated_key",c.deprecated),u===void 0)continue;let p=c.alias??d,m=i[p];i[p]=Ys(m)&&Ys(u)?{...m,...u}:u}return Js(i)?i:void 0}}}function nh(e){let t=[];return{preferences:(e===null?void 0:nw(e,xk,"",t))??{},issues:t}}function ci(e){if(Array.isArray(e))return e.map(ci);if(!Ys(e))return e;let t={};for(let[o,n]of Object.entries(e))Ou(o)&&n!==void 0&&(t[o]=ci(n));return t}function rw(e,t){let o=ci(e);for(let[n,r]of Object.entries(t)){if(!Ou(n)||r===void 0)continue;let a=o[n];o[n]=Ys(a)&&Ys(r)?rw(a,r):ci(r)}return o}function Ck(e){let t={},o;for(let r of e){let a=nh(r).preferences;o=sw(o,a.artifacts?.display),t=rw(t,a)}let n=t;return n.artifacts&&(o!==void 0?n.artifacts.display=o:delete n.artifacts.display),n}function Sk(e,t){if(t===void 0)return e===void 0?void 0:ci(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}:{},...Js(r)?{byMediaType:r}:{}};return Js(a)?a:void 0}function sw(e,t){if(t===void 0)return e===void 0?void 0:ci(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=Sk(o.files,t.files),i={...n?{default:n}:{},...Js(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return Js(i)?i:void 0}function rh(e={},t){let o=Ck(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=sw(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 Ul(e){let t=e.preferences;return!t||!Js(t)?e:{...e,features:rh(e.features??{},[t])}}function wk(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 Ak(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 Mk(e,t,o){return o<t?t:Math.min(o,Math.max(t,e))}function Tk(e,t,o,n){let r=e-n-2*t-o;return Math.max(0,r)}function sh(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 aw(e,t,o,n,r,a,i=200){let d=wk(r,200),c=Tk(t,o,n,i);c=Math.max(d,c);let u=Ak(a);return u!==null&&(c=Math.min(c,u)),Mk(e,d,c)}var{setLoader:Ek,load:Pk,provide:OD,getSync:kk}=bt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),iw=Ek,lw=Pk;var dw=kk;var ah=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()}},ql=new ah;var cw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Lk=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),uw=(e,t,o)=>{if(!cw(e)||!cw(t)||Lk.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]=uw(e[r],t[r],a)}return n};function Du(e,t){let o=uw(e,t,"");return Qa(o)}var pw=()=>{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 Ik=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Rk=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},Vl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Ik(e),o=Rk(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}},ih=e=>typeof e=="string"?e:e==null?"":String(e),Zs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ih(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let o=e.payload,n=ih(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:ih(o.text)}}},fw=e=>Array.isArray(e)?e.map(t=>String(t)):[],$l=e=>{let t=new Set(fw(e.getSessionMetadata().processedActionMessageIds)),o=()=>{t=new Set(fw(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 Hk=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}},Wk=e=>e.map(t=>({...t,streaming:!1})),Bk=e=>e.map(t=>({...t,status:"complete"})),_u=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=t();return o?Hk(o.getItem(e)):null},save:o=>{let n=t();if(n)try{let r={...o,messages:o.messages?Wk(o.messages):void 0,artifacts:o.artifacts?Bk(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 Ok=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")},mw=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 Ok(e)},Dk=async(e,t)=>{let o=await mw(e);return{storageKey:`${t}visitor:${o}`,leaseKey:`${t}visitor-init-lock:${o}`,lockName:`persona-visitor-init:${await mw(`${e}\0${t}`)}`}};var gw=(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 U=u;u=C,c+=1;let Q={previousToken:U,token:C,source:L,revision:c};for(let V of m)V(Q)},T=C=>{d||C.key!==null&&C.key!==n||x(C.key===null?null:C.newValue??null,"external")},w=(async()=>{let C=await Dk(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 U=JSON.parse(L);return typeof U?.expiresAt=="number"&&typeof U?.ownerNonce=="string"?U:null}catch{return null}},H=C=>{let L=h();if(L)try{P()?.ownerNonce===C&&L.removeItem(r)}catch{}},b=C=>new Promise(L=>{let U=setTimeout(Q,C);function Q(){clearTimeout(U),window.removeEventListener("storage",V),L()}function V(E){(E.key===null||E.key===r)&&Q()}window.addEventListener("storage",V)}),A=async C=>{let L=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U=Date.now()+15e3;for(;Date.now()<U;){let Q=h();if(!Q)break;let V=Date.now(),E=P();if(E&&E.expiresAt>V&&E.ownerNonce!==L){await b(Math.min(E.expiresAt-V,500));continue}try{Q.setItem(r,JSON.stringify({ownerNonce:L,expiresAt:V+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,H(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,U){return C===e&&L===t&&U===o},destroy(){d=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",T),p&&H(p)}}};var{setLoader:_k,load:Nk}=bt({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),hw=_k,lh=Nk;var dh=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Cr=e=>Object.freeze({...e}),yw=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),bw=e=>e?Cr(e):null;function vw(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){dh("renderHistoryView cleanup",A)}},p=(b,A)=>{for(let C of t){let L=C[b];if(L)try{let U=L(A);if(U)return U}catch(U){dh(b,U)}}return null},m=()=>({presentation:e.getPresentation(),config:o}),h={header:b=>i?p("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:Cr(b.identityStatus),pendingAction:bw(b.pendingAction),copy:Cr(b.copy),actions:Object.freeze({close:T.close,startNewConversation:T.startNewConversation}),defaultRenderer:b.defaultRenderer})):null,conversation:b=>i?p("renderHistoryConversation",Object.freeze({...m(),conversation:yw(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:Cr(b.state),identityStatus:Cr(b.identityStatus),copy:Cr(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:()=>H(),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(yw)),activeConversationId:b.activeConversationId,state:Cr(b.state),pendingAction:bw(b.pendingAction),identityStatus:Cr(b.identityStatus),nextCursor:b.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:o,copy:Cr(x.copy),actions:T,defaultRenderer:w,requestRender:()=>H(),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){dh("renderHistoryView",L),b=null}if(b)break}let A=!b||b.contains(x.element);return i=A,x.setDomRenderEnabled(A),b??x.element};function H(){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,H(),{view:x,get element(){return d??x.element},requestRender:H,dispose:()=>{n=!0,u()}}}var Fk=null;function xw(){return Fk}var Uk=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"]]),qk=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."]]),ch=e=>qk.get(e)??"Conversation history is unavailable right now.";function Vk(e){if(e instanceof an)return e;if(e instanceof Fe){let t=Uk.get(e.code)??"unavailable";return new an(t,ch(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new an("unavailable",ch("unavailable"))}function Cw(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 an("unsupported_scope",ch("unsupported_scope"))},a=async(d,c)=>{r(d);try{return await c()}catch(u){throw Vk(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=px(u.messages,{...c.beforeCreatedAt?{beforeCreatedAt:c.beforeCreatedAt}:{}});return{summary:u.summary,messages:ul([],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 $k=["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"],Sw={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 uh(e){if(!e)return Sw;let t={...Sw};for(let o of $k){let n=e[o];typeof n=="string"&&n.length>0&&(t[o]=n)}return t}var jk="button:not([disabled])";function Nu(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(jk));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 ui=eo(mc(),1);function zk(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Kk(e,t){if(!zk(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 Fu(){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,ui.parse)(o,ui.STR|ui.OBJ),a=Kk(r,o);a&&(e=a)}catch{}return t=o.length,e},reset:()=>{e=null,t=0}}}function ww(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Uu(e,t){let{config:o,message:n,onPropsUpdate:r}=t,a=xn.get(e.component);if(!a){if(Jg.includes(e.component)){Wu().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 Aw(){let e=Fu();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Mw(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 jl(e){let t=Mw(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 qu(e){let t=Mw(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 Gk=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Vu(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=Gk}=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=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=`
44
+ `,L.addEventListener("click",()=>{m=C,k.forEach((U,Q)=>{let V=Q<C;U.classList.toggle("selected",V),U.setAttribute("aria-checked",Q===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 H=document.createElement("div");H.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)}}),H.appendChild(b),H.appendChild(A),h.appendChild(H),p.appendChild(h),p}function $u(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 H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=u;let b=document.createElement("span");b.className="persona-feedback-label-high",b.textContent=p,P.appendChild(H),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 U=document.createElement("div");U.className="persona-feedback-actions";let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-skip",Q.textContent=d,Q.addEventListener("click",()=>{o?.(),m.remove()});let V=document.createElement("button");return V.type="button",V.className="persona-feedback-btn persona-feedback-btn-submit",V.textContent=i,V.addEventListener("click",async()=>{if(h===null){A.classList.add("persona-feedback-shake"),setTimeout(()=>A.classList.remove("persona-feedback-shake"),500);return}V.disabled=!0,V.textContent="Submitting...";try{let E=L?.value.trim()||void 0;await t(h,E),m.remove()}catch(E){V.disabled=!1,V.textContent=i,console.error("[NPS Feedback] Failed to submit:",E)}}),U.appendChild(Q),U.appendChild(V),y.appendChild(U),m.appendChild(y),m}var pi="persona-chat-history",Yk=30*1e3,Jk=641,fi="data-persona-composer-reason",Zk={"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 eL(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=Zk[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 ju(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 tL(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 oL(e){try{let t=e==="local"?localStorage:sessionStorage,o="__persist_test__";return t.setItem(o,"1"),t.removeItem(o),t}catch{return null}}var ph=e=>!e||typeof e!="object"?{}:{...e},Tw=e=>e.map(t=>({...t,streaming:!1})),Ew=(e,t,o)=>{let n=e?.markdown?tl(e.markdown):null,r=cc(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=Nn()!==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?vv(c):c,y=n(h);m=r&&p?r(y):y}else m=fr(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)),fr(d.text??"")}}};function Pw(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=ue(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 nL=(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},rL=e=>e.reduce((t,o)=>({blocks:[...t.blocks,...o.blocks],contentParts:[...t.contentParts,...o.contentParts],context:nL(t.context,o.context)}),{blocks:[],contentParts:[],context:{}}),zu=(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=Qa(t),r=()=>{zx({delayMs:n.tooltip?.delayMs??200,skipDelayMs:n.tooltip?.skipDelayMs??300})};r();let a=n.features;n=Ul(n);let i=ql.getForInstance(n.plugins),d=KC(e),c=[],u=!1,p=qS(()=>n),m=null,h=null,y=null,x=!1,T=null,w=s=>{m=s,s.initApprovalUi({webMcpToolTitle:uc});let l=s.createBuiltInApprovalPlugin();h=l.plugin,y=l.teardown},k=()=>{if(m)return m;let s=GS();return s?(w(s),s):(KS().then(l=>{x||m||(w(l),T?.())}).catch(()=>{}),null)},P=!1,H=!1,b=null,A=(s,l,f,g)=>{if(!s.querySelector("[data-tv-form]"))return;let v=dw();if(v){v.enhanceWithForms(s,l,f,g);return}lw().then(()=>{P||H||!b||(H=!0,b())}).catch(()=>{})};n.components&&xn.registerAll(n.components);let C=pw(),U=n.persistState===!1?null:n.storageAdapter??_u(),Q=!!n.clientToken&&typeof n.reconnectStream!="function",V={},E=null,O,D=new Promise(s=>{O=s}),W,te=!1,X=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&&(te=!0),f}return l}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}return s};if(U?.load)try{let s=U.load();if(s&&typeof s.then=="function")E=s.then(l=>X(l??{messages:[],metadata:{}}));else{let f=X(s??{messages:[],metadata:{}});f.metadata&&(V=ph(f.metadata)),f.messages?.length&&(n={...n,initialMessages:f.messages}),f.artifacts?.length&&(n={...n,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),W=f.draft}}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",s)}else if(n.onStateLoaded)try{let s=X({messages:[],metadata:{}});s.messages?.length&&(n={...n,initialMessages:s.messages})}catch(s){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",s)}E||O();let fe=()=>V,le=s=>{V=s({...V})??{},ma()},be=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Vl],He=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Zs.message,Zs.messageAndClick],We=$l({parsers:be,handlers:He,getSessionMetadata:fe,updateSessionMetadata:le,emit:C.emit,documentRef:typeof document<"u"?document:null});We.syncFromMetadata();let Se=n.launcher?.enabled??!0,mt=n.launcher?.autoExpand??!1,ke=n.autoFocusInput??!1,z=mt,qe=Se,Ge=n.layout?.header?.layout,Tt=!1,Ie=()=>es(n),Ee=()=>Se||Ie(),ye=Ie()?!1:Se?mt:!0,Cn=!1,Sn=null,ea=()=>{Cn=!0,Sn&&clearTimeout(Sn),Sn=setTimeout(()=>{Cn&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Cn=!1)},1e4)},Ht=Ew(n,We,ea),wn=n.features?.showReasoning??!0,Ko=n.features?.showToolCalls??!0,io=n.features?.showEventStreamToggle??!1,An=n.features?.scrollToBottom??{},Go=n.features?.scrollBehavior??{},ln=()=>(typeof n.persistState=="object"?n.persistState?.keyPrefix:void 0)??"persona-",Mn=`${ln()}event-stream`,Kn=null,os=n.features?.eventStream?.maxEvents??2e3,et=null,Ho=null,dn=null,F=!1,J=null,S=!1,N=null,q=0,$=(s,l)=>{et?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:s,timestamp:Date.now(),payload:JSON.stringify(l)})},oe=(s,l)=>{Ho?.processEvent(s,l),et?$(s,l):dn&&(dn.length>=os&&dn.shift(),dn.push({type:s,payload:l}))},se=()=>{et||!io||(dn??(dn=[]),Qg().then(s=>{if(F||et||!io)return;Kn=new s.EventStreamStore(Mn),et=new s.EventStreamBuffer(os,Kn),Ho=Ho??new s.ThroughputTracker,Kn.open().then(()=>et?.restore()).catch(f=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let l=dn??[];dn=null;for(let f of l)Ho?.processEvent(f.type,f.payload),$(f.type,f.payload)}).catch(()=>{}))};io&&se();let ie=!1,de=null,qt=()=>{},Be=()=>{},Wt=()=>{},Et=()=>{},Gn=()=>{},Sr=()=>S||ie&&de==="panel",Vt={onCopy:s=>{C.emit("message:copy",s),R?.isClientTokenMode()&&R.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),R?.isClientTokenMode()&&R.submitMessageFeedback(s.messageId,s.type).catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",l)}),n.messageActions?.onFeedback?.(s)}},$t=n.statusIndicator??{},So=s=>s==="idle"?$t.idleText??Ut.idle:s==="connecting"?$t.connectingText??Ut.connecting:s==="connected"?$t.connectedText??Ut.connected:s==="error"?$t.errorText??Ut.error:s==="paused"?$t.pausedText??Ut.paused:s==="resuming"?$t.resumingText??Ut.resuming:Ut[s];function Kl(s,l,f,g){if(!s.hasAttribute(fi))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 Wo=US({config:n,showClose:Ee()}),{wrapper:Ke,panel:Ce,pillRoot:Xt}=Wo.shell,_e=Wo.panelElements,{container:pe,body:ne,messagesWrapper:Me,starterSuggestions:Qu,transcriptSuggestions:mi,suggestions:wr,textarea:ce,sendButton:we,composerForm:cn,statusText:at,welcomeHost:wo,welcomeIconHolder:Qw,greetingHost:Bo,introKicker:Yw,introTitle:Jw,introSubtitle:Zw,closeButton:Ue,iconHolder:Pt,headerTitle:Ar,headerSubtitle:ns,header:Ae,footer:Le,actionsRow:eA}=_e,Yu=_e.leftActions,Gl=_e.rightActions,Tn=_e.sendButtonWrapper,Th=_e.setSendButtonMode,re=_e.micButton,Oo=_e.micButtonWrapper,At=_e.attachmentButton,Ao=_e.attachmentButtonWrapper,vt=_e.attachmentInput,Mo=_e.attachmentPreviewsContainer;pe.classList.add("persona-relative"),ne.classList.add("persona-relative");let tA=12,gi=()=>An.label??"",oA=()=>An.iconName??"arrow-down",nA=()=>An.enabled!==!1,Do=()=>Go.mode??"anchor-top",Mr=()=>Do()==="follow"||Do()==="anchor-top"&&Mi,hi=()=>Go.anchorTopOffset??16,rA=()=>Go.restorePosition??"bottom",Eh=()=>Go.pauseOnInteraction===!0,Ph=()=>Go.showActivityWhilePinned!==!1,kh=()=>Go.announce===!0,Ju=()=>Go.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 yi=I("span","persona-flex persona-items-center"),Zu=I("span",""),rs=I("span","");rs.setAttribute("data-persona-scroll-to-bottom-count",""),rs.style.display="none",Ot.append(yi,Zu,rs),pe.appendChild(Ot);let Xo=I("div","persona-stream-anchor-spacer");Xo.setAttribute("aria-hidden","true"),Xo.setAttribute("data-persona-anchor-spacer",""),Xo.style.flexShrink="0",Xo.style.pointerEvents="none",Xo.style.height="0px",Xo.style.display="none",ne.appendChild(Xo);let Xn=I("div","persona-sr-only");Xn.setAttribute("aria-live","polite"),Xn.setAttribute("aria-atomic","true"),Xn.setAttribute("role","status"),Xn.setAttribute("data-persona-live-region",""),Object.assign(Xn.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),pe.appendChild(Xn);let bi=null,Xl=null,Ql=s=>{!kh()||!s||(Xl=s,bi===null&&(bi=setTimeout(()=>{bi=null,Xl&&kh()&&(Xn.textContent=Xl),Xl=null},400)))},Yl="empty",Jl=0,ep=()=>Jl||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,ss=()=>{let l=Le.style.display==="none"?0:Le.offsetHeight;Ot.style.bottom=`${l+ep()+tA}px`};ss();let tp=()=>{aa||(Le.style.marginBottom=Jl>0?`${Jl}px`:"")},Zl=()=>{let s=mg(n,Ie()),l=vn(n),g=Le.style.display==="none"?0:Le.offsetHeight,v=l.anchor==="center"&&Yl==="empty"?El(l.anchorComposerTop)??El("44%"):null,M=v===null||Ie()?0:$C({columnHeight:pe.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`),Jl=s==="block"?M:0,tp(),ss()},Lh=()=>{let s=!!gi();Ot.setAttribute("aria-label",gi()||"Jump to latest"),Ot.title=gi(),Ot.setAttribute("data-persona-scroll-to-bottom-has-label",s?"true":"false"),yi.innerHTML="";let l=ue(oA(),"14px","currentColor",2);l?(yi.appendChild(l),yi.style.display=""):yi.style.display="none",Zu.textContent=gi(),Zu.style.display=s?"":"none"};Lh();let Je=null,Bt=null,ve=Fx(),sA=s=>{try{pe.dispatchEvent(new CustomEvent("persona:composer:state",{detail:s,bubbles:!0,composed:!0}))}catch{}};ve.subscribe(sA);let En=()=>{ve.setText(ce?.value??"")},as=()=>{ve.setMentionRefs(Bt?.getMentionRefs()??[])},aA=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}),Ih=s=>{let l=Object.freeze(s.map(aA));ve.setAttachments(l);try{n.attachments?.onChange?.(l)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}Ep()};ve.setSelectedModelId(n.composer?.selectedModelId);let vi=()=>n.composer?.modes??[],oa=()=>fC(vi(),n.composer?.modeGroups);{let s=su(n.composer?.defaultActiveModeIds??[],vi());s.length&&ve.setActiveModeIds(s)}function Rh(s){if(ve.getState().selectedModelId!==s){ve.setSelectedModelId(s),Tr?.repaint();try{n.composer?.onModelChange?.(s)}catch(l){console.error("[AgentWidget] composer.onModelChange failed:",l)}}}function ed(s){ve.setActiveModeIds(s),Qn?.render(s,oa()),na.forEach(l=>l.repaint()),kn?.resolve(),Md(),un()}function op(s){ed(mC(ve.getState().activeModeIds,s,vi(),n.composer?.modeGroups))}let Tr=null,np=null,Qn=null,na=new Map,Er=null;function Pn(s){ve.setQuote(s),Er?.render(ve.getState().quote),un(),Ay()}let Hh=!1;function rp(){let s=n.composer?.streamingSubmitBehavior??"block";return s!=="interrupt"?s:n.clientToken?"interrupt":(!Hh&&n.debug===!0&&(Hh=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Pr=null;function ra(s){ve.setPendingSubmission(s),Pr?.render(ve.getState().pendingSubmission),un()}let iA=s=>{let l=na.get(s);if(l)return l;let f=yC({groupId:s,getGroup:()=>n.composer?.modeGroups?.find(g=>g.id===s),getModes:()=>vi().filter(g=>g.groupId===s),getActiveIds:()=>ve.getState().activeModeIds,onSelect:g=>op(g)});return na.set(s,f),f},lA=()=>{let s=[],l=ve.getState().activeModeIds,f=new Set;if(vi().forEach((g,v)=>{if(ru(g.groupId,n.composer?.modeGroups)){let M=g.groupId;if(f.has(M))return;f.add(M);let _=iA(M);_.action.order=ag(v),_.action.label=n.composer?.modeGroups?.find(K=>K.id===M)?.label??M,s.push(_.action);return}s.push({id:uC(g.id),kind:"button",placement:"start",order:ag(v),presentation:g.presentation??"auto",label:g.label,shortLabel:g.shortLabel,iconName:g.iconName,pressed:l.includes(g.id),onSelect:()=>op(g.id)})}),n.composer?.models?.length&&!i.some(g=>g.renderComposer)){let g=n.composer?.modelPicker?.presentation??"native";(!Tr||np!==g)&&(np=g,Tr=dC({getModels:()=>n.composer?.models??[],getSelectedModelId:()=>ve.getState().selectedModelId,onSelect:v=>Rh(v),presentation:g,getSuffix:()=>n.composer?.modelPicker?.suffix})),s.push(Tr.action)}return s},sp=null,Wh=i.find(s=>s.renderHeader);if(Wh?.renderHeader){let s=Wh.renderHeader({config:n,defaultRenderer:()=>{let l=br({config:n,showClose:Ee()});return zs(pe,l,n),l.header},onClose:()=>pt(!1,"user")});if(s){let l=Ae;l&&(l.replaceWith(s),Ae=s,Wo.header.element=s)}}let Bh=()=>{J&&(ne.style.display="none",Le.parentNode?.insertBefore(J.element,Le),J.update())},ap=()=>{if(!et){se();return}if(S=!0,J?Bh():Qg().then(l=>{J||!S||!et||(J=l.createEventStreamView({buffer:et,getFullHistory:()=>et.getAllFromStore(),onClose:()=>sa(),config:n,plugins:i,getThroughput:()=>Ho?.getMetric()??{status:"idle"},renderIconByName:ue}),Bh())}).catch(()=>{sa()}),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${vo.actionIconColor}`;let l=n.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(f=>f&&tt.classList.add(f))}let s=()=>{if(!S)return;let l=Date.now();l-q>=200&&(J?.update(),q=l),N=requestAnimationFrame(s)};q=0,N=requestAnimationFrame(s),zt(),C.emit("eventStream:opened",{timestamp:Date.now()})},sa=()=>{if(S){if(S=!1,J&&J.element.remove(),ne.style.display="",tt){tt.style.boxShadow="";let s=n.features?.eventStream?.classNames?.toggleButtonActive;s&&s.split(/\s+/).forEach(l=>l&&tt.classList.remove(l))}N!==null&&(cancelAnimationFrame(N),N=null),zt(),C.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(io){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=vo.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===Ae?Ae.insertBefore(tt,M):Ae.appendChild(tt),tt.addEventListener("click",()=>{S?sa():ap()})}let Oh=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??yr).join(","),v.multiple=(l.maxFiles??4)>1,v.style.display="none",v.setAttribute("aria-label",l.buttonTooltipText??"Attach files"),s.appendChild(v)}},aa=!1,Dh=s=>{let l=i.find(v=>v.renderComposer);if(!l?.renderComposer)return null;let f=n.composer,g=u?R.isStreaming():!1;return l.renderComposer({config:n,defaultRenderer:s,requestRender:()=>Qb(),storage:p(l.id),onSubmit:v=>{!R||R.isStreaming()||Jd(v.trim(),{consumeDraft:!1})},streaming:g,disabled:g,openAttachmentPicker:()=>{Br()||vt?.click()},models:f?.models,selectedModelId:ve.getState().selectedModelId??f?.selectedModelId,onModelChange:v=>Rh(v),onVoiceToggle:n.voiceRecognition?.enabled===!0?()=>{sp?.()}:void 0})},_h=Dh(()=>Xs({config:n}).footer);_h&&(Wo.replaceComposer(_h),Le=Wo.composer.footer,aa=!0);let ot=null,dA=s=>{cn=s.form,ce=s.input,Tn=s.sendButton?s.sendButton.parentElement:null,s.sendButton&&(we=s.sendButton),s.micButton&&(re=s.micButton,Oo=s.micButton.parentElement),s.found.status&&(at=s.found.status),s.found.suggestions&&(wr=s.found.suggestions),s.attachmentButton&&(At=s.attachmentButton,Ao=s.attachmentButton.parentElement),vt=s.attachmentInput??null,Mo=s.attachmentPreviews??null,s.found.actionsRow&&(eA=s.found.actionsRow),Yu=s.found.actionsStart,Gl=s.found.actionsEnd};function ip(){let s=ce;if(!s)return;let l=n.composer?.inputAttributes,f=!l?.ariaLabel&&!(s instanceof HTMLTextAreaElement)?s.getAttribute("aria-label"):null;Xc(s,l),f&&s.setAttribute("aria-label",f),Gc(s,{submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:wl(s)}),Yx(s,Kc(n.composer?.maxLines,Ie()?5:3))}let Nh=s=>{ot=qx(s,{debug:n.debug===!0}),ot&&dA(ot),ip()};Oh(Le),Nh(Le),En();let xi=Jr(n,Ie());xi&&(Me.style.maxWidth=xi,Me.style.marginLeft="auto",Me.style.marginRight="auto",Me.style.width="100%",Bo.style.maxWidth=xi,Bo.style.marginLeft="auto",Bo.style.marginRight="auto",Bo.style.width="100%",Qu.style.maxWidth=xi,mi.style.maxWidth=xi,mi.style.marginLeft="auto",mi.style.marginRight="auto",mi.style.width="100%");let Fh=()=>{let s=Jr(n,Ie());if(!(!s||Ie()))for(let l of[cn,wr,Mo,at])l&&(l.style.maxWidth=s,l.style.marginLeft="auto",l.style.marginRight="auto",l.style.width="100%")};Fh();let Uh=()=>{!n.attachments?.enabled||!vt||!Mo||(Je?Je.remountPreviews(Mo):(Je=qs.fromConfig(n.attachments,Ih),Je.setPreviewsContainer(Mo)),ot?.addListener(vt,"change",s=>{let l=s.target;Je?.handleFileSelect(l.files),l.value=""}),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(Pw(n.attachments.dropOverlay)))};Uh();let cA=()=>Bt?.prefetch(),qh=()=>{if(!n.contextMentions?.enabled||!ce)return;let s=ot?.header??null,l=s?sg(s):void 0;if(Bt=NC({config:n,textarea:ce,anchor:cn??ce,getMessages:()=>R.getMessages(),liveRegionHost:pe,chipRow:l}),Bt&&!l){let f=ce;f.parentElement?.insertBefore(Bt.contextRow,f)}};qh();let kn=null,uA={getState:()=>ve.getState(),getValue:()=>ce?.value??"",setValue:s=>{ce&&(ce.value=s,ce.dispatchEvent(new Event("input",{bubbles:!0})),En())},submit:()=>{EC(ot?.form??null)},openAttachmentPicker:()=>{Br()||vt?.click()},toggleVoice:()=>{sp?.()},requestRender:()=>kn?.resolve()},pA=()=>{let s=[];return(Bt?.affordanceButtons??[]).forEach((f,g)=>{s.push({id:`core:mention-${g}`,placement:"start",order:$n.mention+g,element:f,managed:!0})}),Ao&&s.push({id:"core:attachment",placement:"start",order:$n.attachment,element:Ao}),Oo&&s.push({id:"core:mic",placement:"end",order:$n.mic,element:Oo}),Tn&&s.push({id:"core:send",placement:"end",order:$n.send,element:Tn}),s},Vh=()=>{kn?.destroy(),kn=aC({getBindings:()=>ot,collect:()=>({builtIns:pA(),configActions:[...lA(),...n.composer?.actions??[]],plugins:i,contributionContext:{config:n,getState:()=>ve.getState(),requestRender:()=>kn?.resolve()},debug:n.debug===!0}),actionContext:uA,getState:()=>ve.getState(),getOverflow:()=>n.composer?.actionOverflow,reportError:(s,l)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${l.actionId}" failed:`,s)}}),kn.resolve()};Vh();let lp=()=>{if(Qn?.destroy(),Qn=null,!oa().length)return;let s=ot?.header;s&&(Qn=cC({row:sg(s),onRemove:l=>op(l),initialIds:ve.getState().activeModeIds}),Qn.render(ve.getState().activeModeIds,oa()))};lp();let $h=()=>{Er?.destroy(),Er=null,Pr?.destroy(),Pr=null;let s=ot?.header;s&&(Er=bC({onDismiss:()=>Pn(void 0)}),s.appendChild(Er.element),Er.render(ve.getState().quote),rp()==="defer-one"&&(Pr=vC({onEdit:()=>FM(),onRemove:()=>ra(void 0)}),s.appendChild(Pr.element),Pr.render(ve.getState().pendingSubmission)))};$h();let dp=MC(),fA=()=>{let s=ot?.header?.querySelector(rg);if(s)return s.childElementCount>0;let l=ve.getState();return l.mentionRefs.length>0||su(l.activeModeIds,oa()).length>0},jh=()=>!1;function un(){let s=ve.getState(),l=dp.observe(TC(ce),s.text);Le.toggleAttribute("data-persona-composer-compact",AC({text:s.text,wrapped:l,hasAttachments:s.attachments.length>0,hasChips:fA(),hasQuote:s.quote!==void 0,hasPendingSubmission:s.pendingSubmission!==void 0,dictationActive:jh()}))}function zh(){n.composer?.layout==="single-row"&&!Ie()?Le.setAttribute("data-persona-composer-layout","single-row"):Le.removeAttribute("data-persona-composer-layout")}zh(),ve.subscribe(()=>{kn?.sync(),Ep(),wd(),un(),Ay()}),wd();let Kh=!1,mA=s=>{if(Kh||n.debug!==!0)return;let l=["messages","composer"].filter(f=>s[f]);l.length&&(Kh=!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??{};mA(s);let l=g=>{switch(g){case"body-top":return ne.querySelector("[data-persona-intro-card]");case"messages":return Me;case"footer-top":return wr;case"composer":return cn;case"footer-bottom":return at;default:return null}},f=(g,v)=>{switch(g){case"header-left":case"header-center":case"header-right":if(g==="header-left")Ae.insertBefore(v,Ae.firstChild);else if(g==="header-right")Ae.appendChild(v);else{let M=Ae.querySelector(".persona-flex-col");M?M.parentNode?.insertBefore(v,M.nextSibling):Ae.appendChild(v)}break;case"body-top":{let M=ne.querySelector("[data-persona-intro-card]");M?M.replaceWith(v):ne.insertBefore(v,ne.firstChild);break}case"body-bottom":ne.appendChild(v);break;case"footer-top":wr.replaceWith(v);break;case"footer-bottom":at.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 Gh=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")ai.has(v)?ai.delete(v):ai.add(v),VS(v,g);else if(M==="tool")ii.has(v)?ii.delete(v):ii.add(v),jS(v,g,n);else if(M==="approval"&&m){let K=((n.approval!==!1?n.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",j=m.approvalDetailsExpansionState.get(v)??K;m.approvalDetailsExpansionState.set(v,!j),m.updateApprovalDetailsUI(v,g,n)}Dt.delete(v)};Me.addEventListener("pointerdown",s=>{s.target.closest('button[data-expand-header="true"]')&&(s.preventDefault(),Gh(s))}),Me.addEventListener("keydown",s=>{let l=s.target;(s.key==="Enter"||s.key===" ")&&l.closest('button[data-expand-header="true"]')&&(s.preventDefault(),Gh(s))}),Me.addEventListener("copy",s=>{let{clipboardData:l}=s;if(!l)return;let f=Me.getRootNode(),g=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!g||g.isCollapsed)return;let v=g.toString(),M=XC(v);!M||M===v||(l.setData("text/plain",M),s.preventDefault())});let cp=new Map,Xh=null,Qh="idle",gA={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},hA=(s,l)=>{let{icon:f,label:g}=gA[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=ue(f,14,"currentColor",2);v&&(s.innerHTML="",s.appendChild(v))},Yh=()=>{Me.querySelectorAll('[data-action="read-aloud"]').forEach(l=>{let g=l.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;hA(l,g&&g===Xh?Qh:"idle")})};Me.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 K=R.getMessages().find(j=>j.id===v);if(K&&Vt.onCopy){let j=K.content||"";navigator.clipboard.writeText(j).then(()=>{f.classList.add("persona-message-action-success");let G=Ft(ja,14,"currentColor",2);G&&(f.innerHTML="",f.appendChild(G)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let Z=Ft(za,14,"currentColor",2);Z&&(f.innerHTML="",f.appendChild(Z))},2e3)}).catch(G=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",G)}),Vt.onCopy(K)}}else if(M==="read-aloud")R.toggleReadAloud(v);else if(M==="upvote"||M==="downvote"){let K=(cp.get(v)??null)===M,j=M==="upvote"?"thumbs-up":"thumbs-down";if(K){cp.delete(v),f.classList.remove("persona-message-action-active");let G=ue(j,14,"currentColor",2);G&&(f.innerHTML="",f.appendChild(G))}else{let G=M==="upvote"?"downvote":"upvote",Z=g.querySelector(`[data-action="${G}"]`);if(Z){Z.classList.remove("persona-message-action-active");let ft=ue(G==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ft&&(Z.innerHTML="",Z.appendChild(ft))}cp.set(v,M),f.classList.add("persona-message-action-active");let ae=ue(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 Ye=R.getMessages().find(ct=>ct.id===v);Ye&&Vt.onFeedback&&Vt.onFeedback({type:M,messageId:Ye.id,message:Ye})}}else if(M==="regenerate")td?.regenerate(v);else if(M==="edit")td?.edit(v);else if(M==="quote")td?.quote(v);else if(M?.startsWith(wu)){let _=M.slice(wu.length),K=n.messageActions?.custom?.find(G=>G.id===_),j=R.getMessages().find(G=>G.id===v);if(!K||!j)return;try{K.onSelect(j)}catch(G){console.error(`[AgentWidget] messageActions.custom "${_}" onSelect failed:`,G)}}});let td=null;Me.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 _=M==="approve"?"approved":"denied",j=R.getMessages().find(Z=>Z.id===v);if(!j?.approval)return;let G=g.querySelector("[data-approval-buttons]");G&&G.querySelectorAll("button").forEach(ae=>{ae.disabled=!0,ae.style.opacity="0.5",ae.style.cursor="not-allowed"}),j.approval.toolType==="webmcp"?R.resolveWebMcpApproval(v,_):R.resolveApproval(j.approval,_)});let $e=null,Jh=!1,Ci=null,is=()=>{},Si="none",od=null,Qo={artifacts:[],selectedId:null},Yn=!1,pn=!1,wi=!1,ia=!1,Zh=()=>ia||Qo.artifacts.some(s=>Fn(n.features?.artifacts,s)==="panel"),nd=()=>Qo.artifacts.length>0&&!Yn&&Zh(),dt={current:null},up=(s,l)=>{let f=R.getArtifactById(l),g=f?.markdown,v=f?.title||"artifact",M=f?.file,_=f?.artifactType??"markdown";if(!g){let G=s.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(G){let ae=R.getMessages().find(me=>me.id===G);if(ae?.rawContent)try{let me=JSON.parse(ae.rawContent);g=me?.props?.markdown,v=me?.props?.title||v,me?.props?.file&&typeof me.props.file=="object"&&(M=me.props.file),!f&&typeof me?.props?.artifactType=="string"&&(_=me.props.artifactType)}catch{}}}return{markdown:g,title:v,file:M,artifactType:_}};Me.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:_,file:K}=up(f,g);if(!M)return;let j=vr();j&&j.triggerArtifactDownload(j.downloadInfoFor({title:_,markdown:M,file:K}))}),Me.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]"),_=v?v.getAttribute("data-artifact-inline"):M?.getAttribute("data-open-artifact")??null,j=(v?n.features?.artifacts?.inlineActions:n.features?.artifacts?.cardActions)?.find(ct=>ct.id===g);if(!j)return;let{markdown:G,title:Z,file:ae,artifactType:me}=up(f,_??""),Ye={artifactId:_,title:Z,artifactType:me,markdown:G,file:ae};try{Promise.resolve(j.onClick(Ye)).catch(()=>{})}catch{}}),Me.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=R.getArtifactById(g),M=vr();if(!M)return;let _="";if(v)_=M.artifactCopyText(v);else{let{markdown:K,file:j,artifactType:G}=up(f,g);G==="markdown"&&(_=M.artifactCopyText({id:g,artifactType:"markdown",status:"complete",markdown:K??"",...j?{file:j}:{}}))}_&&navigator.clipboard.writeText(_).then(()=>{let K=Ft(ja,16,"currentColor",2);K&&(f.replaceChildren(K),setTimeout(()=>{let j=Ft(za,16,"currentColor",2);j&&f.replaceChildren(j)},1500))}).catch(()=>{})}),Me.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||(Yn=!1,ia=!0,pn=!0,wi=!0,R.selectArtifact(g),fn())}),Me.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(),Yn=!1,ia=!0,R.selectArtifact(g),fn())}),Me.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 la=_e.composerOverlay,da=(s,l,f)=>{let g=l.trim();if(!g||!dt.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})),Kr(la,v);let _=dt.current.getMessages().find(K=>K.toolCall?.id===v);_?.agentMetadata?.awaitingLocalTool?dt.current.resolveAskUserQuestion(_,f.structured??g):dt.current.sendMessage(g)},ls=s=>{let l=dt.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:hc(s,g),currentIndex:rn(s)})},ey=s=>Object.entries(s).map(([l,f])=>`${l}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),pp=s=>{if(n.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let l=rn(s),f=Da(s);if(l>=f-1)return;let g=dt.current?.getMessages().find(v=>v.toolCall?.id===s.getAttribute("data-tool-call-id"));g&&(yc(s,g,n,l+1),ls(s))};la.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})),Kr(la,M);let _=dt.current?.getMessages().find(K=>K.toolCall?.id===M);_?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(_),dt.current?.resolveAskUserQuestion(_,"(dismissed)"));return}if(v==="pick"){let M=f.getAttribute("data-option-label");if(!M)return;let _=g.getAttribute("data-multi-select")==="true",K=zr(g);if(K&&_){let j=Os(g)[rn(g)],G=new Set(Array.isArray(j)?j:[]);G.has(M)?G.delete(M):G.add(M),Gr(g,Array.from(G)),ls(g);return}if(K){Gr(g,M),ls(g),pp(g);return}if(_){let j=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",j?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!j);let G=g.querySelector('[data-ask-user-action="submit-multi"]');G&&(G.disabled=Vf(g).length===0);return}da(g,M,{source:"pick",values:[M]});return}if(v==="submit-multi"){let M=Vf(g);if(M.length===0)return;da(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 _=g.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!_.trim())return;if(zr(g)){Gr(g,_.trim()),ls(g),pp(g);return}da(g,_,{source:"free-text"});return}if(v==="next"||v==="back"){if(!dt.current)return;let M=g.getAttribute("data-tool-call-id")??"",_=dt.current.getMessages().find(ae=>ae.toolCall?.id===M);if(!_)return;let j=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(j){let ae=Os(g)[rn(g)];(typeof ae!="string"||ae!==j)&&Gr(g,j)}let G=v==="next"?1:-1,Z=rn(g)+G;yc(g,_,n,Z),ls(g);return}if(v==="submit-all"){if(!dt.current)return;let M=g.getAttribute("data-tool-call-id")??"",_=dt.current.getMessages().find(ae=>ae.toolCall?.id===M);if(!_)return;let j=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";j&&Gr(g,j);let G=hc(g,_);dt.current.persistAskUserQuestionProgress(_,{answers:G,currentIndex:rn(g)});let Z=ey(G);da(g,Z||"(submitted)",{source:"submit-all",structured:G});return}if(v==="skip"){if(!dt.current)return;let M=g.getAttribute("data-tool-call-id")??"",_=dt.current.getMessages().find(me=>me.toolCall?.id===M);if(!_)return;let K=zr(g),j=rn(g),G=Da(g),Z=j>=G-1;if(!K){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:M},bubbles:!0,composed:!0})),Kr(la,M),_.agentMetadata?.awaitingLocalTool&&(dt.current.markAskUserQuestionResolved(_),dt.current.resolveAskUserQuestion(_,"(dismissed)"));return}Gr(g,"");let ae=g.querySelector('[data-ask-free-text-input="true"]');if(ae&&(ae.value=""),Z){let me=hc(g,_),Ye=ey(me);da(g,Ye||"(skipped)",{source:"submit-all",structured:me});return}yc(g,_,n,j+1),ls(g);return}}),la.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(zr(g)){Gr(g,v.trim()),ls(g),pp(g);return}da(g,v,{source:"free-text"})}});let ty=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=la.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",ty);let Ln=null,xt=null,Ai=null,rd=null,sd=()=>{},oy=!1,ad="",id="";function fp(){rd?.(),rd=null}let yA=()=>{let s=Sa&&Ps?.isConnected?Ps:null,l=s?s.getBoundingClientRect().width:0;return l<=0?200:l+360},ny=()=>{if(!Ln||!xt)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){xt.style.removeProperty("position"),xt.style.removeProperty("left"),xt.style.removeProperty("top"),xt.style.removeProperty("bottom"),xt.style.removeProperty("width"),xt.style.removeProperty("z-index");return}let g=Ln.firstElementChild;if(!g||g===xt)return;let v=10;xt.style.position="absolute",xt.style.top="0",xt.style.bottom="0",xt.style.width=`${v}px`,xt.style.zIndex="5";let M=sh(Ln,l),_=g.offsetWidth+M/2-v/2;xt.style.left=`${Math.max(0,_)}px`},ld=()=>{},bA=()=>{let s=e.ownerDocument.defaultView??window,l=n.launcher?.mobileFullscreen??!0,f=n.launcher?.mobileBreakpoint??640;return!l||s.innerWidth>f?!1:Se||wt(n)},dd=()=>!Co(n)||!nd()||e.classList.contains("persona-artifact-narrow-host")||bA()||(e.ownerDocument.defaultView??window).innerWidth<Jk?"none":th(n)?"detached":"welded",fn=()=>{if(!$e||!Co(n))return;Nl(e,n),Fl(e,n),ld();let s=n.features?.artifacts?.layout?.narrowHostMaxWidth??520,l=Ce.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",l>0&&l<=s);let f=nd();$e.setVisible(f),$e.update(Qo),Yn?($e.setMobileOpen(!1),$e.element.classList.add("persona-hidden"),$e.backdrop?.classList.add("persona-hidden"),pn=!1,wi=!1):Qo.artifacts.length>0&&Zh()?($e.element.classList.remove("persona-hidden"),$e.setMobileOpen(!0)):($e.setMobileOpen(!1),$e.element.classList.add("persona-hidden"),$e.backdrop?.classList.add("persona-hidden"),pn=!1,wi=!1);let g=n.features?.artifacts?.layout?.showExpandToggle===!0;if($e.setExpandToggleVisible(g),$e.setCopyButtonVisible(n.features?.artifacts?.layout?.showCopyButton===!0),$e.setRefreshButtonVisible(typeof n.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),$e.setCustomActions(n.features?.artifacts?.toolbarActions??[]),$e.setTabFade(n.features?.artifacts?.layout?.tabFade),$e.setRenderTabBar(n.features?.artifacts?.renderTabBar),!g&&!wi&&(pn=!1),pn!==oy){let M=$e.element;pn?(ad=M.style.width,id=M.style.maxWidth,M.style.removeProperty("width"),M.style.removeProperty("max-width")):(ad&&(M.style.width=ad),id&&(M.style.maxWidth=id),ad="",id=""),oy=pn}e.classList.toggle("persona-artifact-expanded",pn),$e.setExpanded(pn);let v=dd();v!==Si&&(Si=v,is()),sd()};if(Co(n)){Ce.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(pe),Ln=l,l.appendChild(s),Ce.appendChild(l);let f=v=>{Jh||$e||($e=v.createArtifactPane(n,{onSelect:M=>dt.current?.selectArtifact(M),onDismiss:()=>{Yn=!0,fn()},onToggleExpand:()=>{let M=!pn,_=Qo.selectedId??Qo.artifacts[Qo.artifacts.length-1]?.id??null;n.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:_,expanded:M})!==!0&&(pn=M,M||(wi=!1),fn())}}),$e.element.classList.add("persona-hidden"),l.appendChild($e.element),$e.backdrop&&Ce.appendChild($e.backdrop),sd(),fn())},g=vr();g?f(g):(Zg(()=>{let v=vr();v&&f(v)}),Wu().catch(()=>{})),sd=()=>{if(!Ln||!$e)return;if(!(n.features?.artifacts?.layout?.resizable===!0)){Ai?.(),Ai=null,fp(),xt&&(xt.remove(),xt=null),$e.element.style.removeProperty("width"),$e.element.style.removeProperty("maxWidth");return}if(!xt){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 _=e.ownerDocument,K=_.defaultView??window,j=G=>{if(!$e||G.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||K.innerWidth<=640)return;G.preventDefault(),fp();let Z=G.clientX,ae=$e.element.getBoundingClientRect().width,me=n.features?.artifacts?.layout,Ye=ft=>{let Qt=Ln.getBoundingClientRect().width,Nt=e.classList.contains("persona-artifact-welded-split"),It=sh(Ln,K),lo=Nt?0:M.getBoundingClientRect().width||6,Ze=ae-(ft.clientX-Z),co=aw(Ze,Qt,It,lo,me?.resizableMinWidth,me?.resizableMaxWidth,yA());$e.element.style.width=`${co}px`,$e.element.style.maxWidth="none",ny()},ct=()=>{_.removeEventListener("pointermove",Ye),_.removeEventListener("pointerup",ct),_.removeEventListener("pointercancel",ct),rd=null;try{M.releasePointerCapture(G.pointerId)}catch{}};rd=ct,_.addEventListener("pointermove",Ye),_.addEventListener("pointerup",ct),_.addEventListener("pointercancel",ct);try{M.setPointerCapture(G.pointerId)}catch{}};M.addEventListener("pointerdown",j),xt=M,Ln.insertBefore(M,$e.element),Ai=()=>{M.removeEventListener("pointerdown",j)}}if(xt){let M=nd();xt.classList.toggle("persona-hidden",!M),ny()}},ld=()=>{if(!Se||!$e||(n.launcher?.sidebarMode??!1)||wt(n)&&Ro(n).reveal==="emerge")return;let M=e.ownerDocument.defaultView??window,_=n.launcher?.mobileFullscreen??!0,K=n.launcher?.mobileBreakpoint??640;if(_&&M.innerWidth<=K||!ew(n,Se))return;let j=n.launcher?.width??n.launcherWidth??$o,G=n.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";nd()?(Ce.style.width=G,Ce.style.maxWidth=G):(Ce.style.width=j,Ce.style.maxWidth=j)},typeof ResizeObserver<"u"&&(Ci=new ResizeObserver(()=>{fn()}),Ci.observe(Ce))}else Ce.appendChild(pe);Ie()&&Xt&&(_e.peekBanner&&Xt.appendChild(_e.peekBanner),Xt.appendChild(Le)),e.appendChild(Ke),Xt&&e.appendChild(Xt);let mp=()=>{if(Ie()){Ce.style.width="100%",Ce.style.maxWidth="100%";let Ne=n.launcher?.composerBar??{},gt=Ke.dataset.state==="expanded",nt=Ne.expandedSize??"anchored";if(!(gt&&nt!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let ht=n.theme?.components?.panel,pr=Yr(n),Yt=(Bs,rc)=>Bs==null||Bs===""?rc:bo(pr,Bs)??Bs,nn="1px solid var(--persona-border)",yt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",kf="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=Yt(ht?.border,nn),pe.style.borderRadius=Yt(ht?.borderRadius,kf),pe.style.boxShadow=Yt(ht?.shadow,yt),pe.style.overflow="hidden";return}let s=wt(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,_=Yr(n),K=(Ne,gt)=>Ne==null||Ne===""?gt:bo(_,Ne)??Ne,j=e.ownerDocument.defaultView??window,G=n.launcher?.mobileFullscreen??!0,Z=n.launcher?.mobileBreakpoint??640,ae=j.innerWidth<=Z,me=G&&ae&&Se,Ye=s&&G&&ae,ct=n.launcher?.position??"bottom-left",ft=ct==="bottom-left"||ct==="top-left",Qt=n.launcher?.zIndex??ao,Nt="var(--persona-panel-border, 1px solid var(--persona-border))",It="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",lo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ze=v&&!me&&!Ye;Ze?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let co=Ze?Nt:l||me?"none":Nt,On=Ze?It:me?"none":l?ft?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":g?"none":It;s&&!me&&!Ze&&(On="none",co="none");let ur=Ze?lo:l||me?"0":lo,Dn=K(M?.border,co),Ha=K(M?.shadow,On),Ws=K(M?.borderRadius,ur),B=dd(),Te=B==="detached",Re=B==="welded";e.classList.toggle("persona-artifact-detached-split",Te),e.classList.toggle("persona-artifact-welded-split",Re);let xe="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)))))",lt=(n.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Co(n)&&th(n)&&g&&!s;e.classList.toggle("persona-artifact-chat-flush",lt);let Pe=Te||lt?"none":Ha,hn=Te?Nt:Re?"none":Dn,Mt=Te?lo:Ws;lt&&(hn="none",Mt="0");let no=M?.borderRadius!=null&&M.borderRadius!=="",Gt=lt&&!no?"0":Ws,Rt=ne.scrollTop;e.style.cssText="",Ke.style.cssText="",Ce.style.cssText="",pe.style.cssText="",ne.style.cssText="",aa||(Le.style.cssText=""),S&&(ne.style.display="none"),(f||g)&&(e.style.minWidth="0");let Oe=()=>{if(Rt<=0)return;(ne.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ne.scrollTop===Rt)return;let gt=ne.scrollHeight-ne.clientHeight;gt<=0||(ne.scrollTop=Math.min(Rt,gt))})};if(me){Ke.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"),Ke.style.cssText=`
45
45
  position: fixed !important;
46
46
  inset: 0 !important;
47
47
  width: 100% !important;
@@ -53,7 +53,7 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
53
53
  flex-direction: column !important;
54
54
  z-index: ${Qt} !important;
55
55
  background-color: var(--persona-surface, #ffffff) !important;
56
- `,we.style.cssText=`
56
+ `,Ce.style.cssText=`
57
57
  position: relative !important;
58
58
  display: flex !important;
59
59
  flex-direction: column !important;
@@ -66,7 +66,7 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
66
66
  padding: 0 !important;
67
67
  box-shadow: none !important;
68
68
  border-radius: 0 !important;
69
- `,ue.style.cssText=`
69
+ `,pe.style.cssText=`
70
70
  display: flex !important;
71
71
  flex-direction: column !important;
72
72
  flex: 1 1 0% !important;
@@ -77,11 +77,11 @@ _Details: ${o.message}_`:n}var om=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",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=`
80
+ `,ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.overflowY="auto",Le.style.flexShrink="0",tp(),Tt=!0,Oe();return}let Ve=n?.launcher?.width??n?.launcherWidth??$o;if(!l&&!s)g&&f?(Ce.style.width="100%",Ce.style.maxWidth="100%"):(Ce.style.width=Ve,Ce.style.maxWidth=Ve);else if(s)if(Ro(n).reveal==="emerge"&&!v){let gt=Ro(n).width;Ce.style.width=gt,Ce.style.maxWidth=gt}else Ce.style.width="100%",Ce.style.maxWidth="100%";if(ld(),Ce.style.boxShadow=Pe,Ce.style.borderRadius=Gt,Te?Ce.style.border="none":Re&&(Ce.style.border=Dn),pe.style.border=hn,pe.style.borderRadius=Mt,pe.style.boxShadow=Te&&!lt?xe:"",lt&&(pe.style.background="transparent",ne.style.background="transparent",Le.style.background="transparent",Le.style.borderTop="none"),Re){let Ne=n.features?.artifacts?.layout;od=Ne?.unifiedSplitOuterRadius?.trim()||Ne?.paneBorderRadius?.trim()||Ws}else od=null;if(s&&!me&&!Ze&&!Te&&!Re&&M?.border===void 0&&(pe.style.border="none",Ro(n).side==="right"?pe.style.borderLeft="1px solid var(--persona-border)":pe.style.borderRight="1px solid var(--persona-border)"),s&&!me&&Re&&M?.border===void 0&&(Ro(n).side==="right"?Ce.style.borderLeft="1px solid var(--persona-border)":Ce.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%"),Ke.style.display="flex",Ke.style.flexDirection="column",Ke.style.flex="1 1 0%",Ke.style.minHeight="0",Ke.style.maxHeight="100%",Ke.style.height="100%",g&&(Ke.style.overflow="hidden"),Ce.style.display="flex",Ce.style.flexDirection="column",Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.maxHeight="100%",Ce.style.height="100%",Te||(Ce.style.overflow="hidden"),pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.overflow="hidden",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.overflowY="auto",Le.style.flexShrink="0"),g&&(Ze||Te||lt)&&!s&&(lt||(Ke.style.padding="var(--persona-panel-inset)"),Ke.style.background="var(--persona-panel-canvas-bg)"),Ke.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&&(zo[ct]??zo["bottom-right"]).split(" ").forEach(gt=>Ke.classList.add(gt)),l){let Ne=n.launcher?.sidebarWidth??"420px";v?Ke.style.cssText=`
81
81
  position: fixed !important;
82
82
  top: var(--persona-panel-inset) !important;
83
83
  bottom: var(--persona-panel-inset) !important;
84
- width: ${ve} !important;
84
+ width: ${Ne} !important;
85
85
  height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
86
86
  max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
87
87
  margin: 0 !important;
@@ -89,12 +89,12 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
89
89
  display: flex !important;
90
90
  flex-direction: column !important;
91
91
  z-index: ${Qt} !important;
92
- ${ct?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
93
- `:Xe.style.cssText=`
92
+ ${ft?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
93
+ `:Ke.style.cssText=`
94
94
  position: fixed !important;
95
95
  top: 0 !important;
96
96
  bottom: 0 !important;
97
- width: ${ve} !important;
97
+ width: ${Ne} !important;
98
98
  height: 100vh !important;
99
99
  max-height: 100vh !important;
100
100
  margin: 0 !important;
@@ -102,8 +102,8 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
102
102
  display: flex !important;
103
103
  flex-direction: column !important;
104
104
  z-index: ${Qt} !important;
105
- ${ct?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
106
- `,we.style.cssText=`
105
+ ${ft?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
106
+ `,Ce.style.cssText=`
107
107
  position: relative !important;
108
108
  display: flex !important;
109
109
  flex-direction: column !important;
@@ -115,9 +115,9 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
115
115
  margin: 0 !important;
116
116
  padding: 0 !important;
117
117
  box-shadow: ${Pe} !important;
118
- border-radius: ${Re} !important;
119
- ${me?"border: none !important;":pt?`border: ${Bn} !important;`:""}
120
- `,we.style.setProperty("width","100%","important"),we.style.setProperty("max-width","100%","important"),ue.style.cssText=`
118
+ border-radius: ${Gt} !important;
119
+ ${Te?"border: none !important;":Re?`border: ${Dn} !important;`:""}
120
+ `,Ce.style.setProperty("width","100%","important"),Ce.style.setProperty("max-width","100%","important"),pe.style.cssText=`
121
121
  display: flex !important;
122
122
  flex-direction: column !important;
123
123
  flex: 1 1 0% !important;
@@ -126,32 +126,32 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
126
126
  min-height: 0 !important;
127
127
  max-height: 100% !important;
128
128
  overflow: hidden !important;
129
- border-radius: ${Kt} !important;
130
- border: ${zt} !important;
131
- ${me&&!It?`box-shadow: ${jt} !important;`:""}
132
- ${It?"background: transparent !important;":""}
133
- `,na||(Ie.style.cssText=`
129
+ border-radius: ${Mt} !important;
130
+ border: ${hn} !important;
131
+ ${Te&&!lt?`box-shadow: ${xe} !important;`:""}
132
+ ${lt?"background: transparent !important;":""}
133
+ `,aa||(Le.style.cssText=`
134
134
  flex-shrink: 0 !important;
135
135
  border-top: none !important;
136
136
  padding: 8px 16px 12px 16px !important;
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}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:
137
+ ${lt?"background: transparent !important;":""}
138
+ `)}if(!g&&!s){let Ne="max-height: -moz-available !important; max-height: stretch !important;",gt=l?"":"padding-top: 1.25em !important;",nt=l?"":`z-index: ${n.launcher?.zIndex??ao} !important;`;Ke.style.cssText+=Ne+gt+nt}tp(),Oe()},gp=()=>{e.style.setProperty("--persona-content-max-width",Jr(n,Ie()))},ry=!1,sy=()=>{let s=mg(n,Ie());Ie()&&n.composer?.placement&&n.debug===!0&&!ry&&(ry=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let l=vn(n);e.setAttribute("data-persona-composer-placement",s),e.setAttribute("data-persona-conversation-state",Yl),e.setAttribute("data-persona-welcome-anchor",l.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",l.composerGap??uu),Zl()},ay=()=>{if(Ie())return;let s=wt(n),l=n.launcher?.sidebarMode??!1;if(s||l||(n.launcher?.fullHeight??!1)||!Se)return;let g=e.ownerDocument.defaultView??window,v=n.launcher?.mobileFullscreen??!0,M=n.launcher?.mobileBreakpoint??640;if(v&&g.innerWidth<=M)return;let _=g.innerHeight,K=64,j=n.launcher?.heightOffset??0,G=Math.max(200,_-K),Z=Math.min(640,G);Ce.style.height=`${Math.max(200,Z-j)}px`};mp(),Vs(e,n),Nl(e,n),Fl(e,n),gp(),sy(),is=()=>{mp(),ay(),Vs(e,n),Nl(e,n),Fl(e,n),gp(),sy(),od?e.style.setProperty("--persona-artifact-welded-outer-radius",od):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Be(),qt()};let ge=[];ge.push(()=>{Jh=!0}),ge.push(()=>{c.forEach(s=>s()),d.destroy()}),ge.push(()=>{document.removeEventListener("keydown",ty)}),ge.push(()=>{bi!==null&&clearTimeout(bi)});let In=null,Rn=null;ge.push(()=>{In?.(),In=null,Rn?.(),Rn=null}),Ci&&ge.push(()=>{Ci?.disconnect(),Ci=null}),ge.push(()=>{Ai?.(),Ai=null,fp(),xt&&(xt.remove(),xt=null),$e?.element.style.removeProperty("width"),$e?.element.style.removeProperty("maxWidth"),$e?.destroy()}),io&&ge.push(()=>{F=!0,dn=null,N!==null&&(cancelAnimationFrame(N),N=null),J?.destroy(),J=null,et?.destroy(),et=null,Kn=null});let ds=null,iy=()=>{ds&&(ds(),ds=null),n.colorScheme==="auto"&&(ds=Ja(()=>{Vs(e,n)}))};iy(),ge.push(()=>{ds&&(ds(),ds=null)}),ge.push(()=>{x=!0,y?.()}),ge.push(()=>{P=!0});let ly=!1;ge.push(()=>{ly=!0});let hp=(s,l)=>{let f=Il(s,l);return f||!cS.includes(s)?f:(fS().then(g=>{if(ly)return;Za(g.wipe),Za(g.glyphCycle);let v=Il(s,l);v&&Wl(v,e)}).catch(()=>{}),null)},cd=n.features?.streamAnimation;if(cd?.type&&cd.type!=="none"){let s=hp(cd.type,cd.plugins);s&&Wl(s,e),ge.push(()=>uS(e))}let Jn=Dl(wr),dy=Dl(Qu),cy=Dl(mi),cs=[Jn,dy,cy];ge.push(()=>{cs.forEach(s=>s.destroy())});let us=null,R,ps=null,uy=!1,py=0,fy=null,my=s=>s.reduce((l,f)=>f.role==="user"?l+1:l,0),gy=s=>{for(let l=s.length-1;l>=0;l--)if(Ds(s[l]))return s[l].id??null;return null},hy=!1,vA=()=>{hy||n.debug!==!0||(hy=!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".'))},yy=!1,by=!1,vy=(s,l)=>{yy||n.debug!==!0||!l.enabled||l.expose||uy||by&&(R.isStreaming()||s.some(Ds)||(yy=!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.")))},ca=s=>{if(!R)return;let l=s??R.getMessages(),f=G=>{G.render([],R,ce,l)},g=G=>{cs.forEach(Z=>{Z!==G&&f(Z)})};ps&&(my(l)>py||gy(l)!==fy)&&(ps=null);let v=Xr(n);vy(l,v);let M=v.enabled?vc(l):null,_=ps??M,K=ps?"host":"agent";if(_){let G=n.suggestions?.followUps,Z=G?.placement??(G?"auto":"composer"),me=(Z==="auto"?Ie()?"composer":"after-message":Z)==="after-message"?cy:Jn;g(me),me.render(_,R,ce,l,n.suggestionChipsConfig,{source:K,surface:"followUp",variant:G?.variant??"chip",behavior:G?.behavior??"send",overflow:G?.overflow??"wrap",maxItems:G?.maxItems??4,config:n,plugins:i,submitPrompt:Yd});return}if(l.some(G=>G.role==="user")){cs.forEach(f);return}let j=n.suggestions?.starters;if(j){let G=ts(vn(n),l),Z=j.placement??"auto",ae=Z==="auto"?G?"welcome":"composer":Z;if(ae==="welcome"&&!G){vA(),cs.forEach(f);return}let me=ae==="welcome"?dy:Jn;g(me),me.render(j.items??n.suggestionChips,R,ce,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:Yd});return}g(Jn),Jn.render(n.suggestionChips,R,ce,l,n.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:n,plugins:i,submitPrompt:Yd})},xy=()=>{ps&&(ps=null,ca())},xA=s=>{let l=Array.isArray(s)?[...s]:[];if(!l.length){xy();return}let f=R?R.getMessages():[];ps=l,uy=!0,py=my(f),fy=gy(f),ca(f)},_o=!1,Dt=JC(),ua=new Map,fs=new Map,kr=new Map,ms=null,Lr=null;function gs(){if(!ms)return;let s=ms;ms=null,Lr?.destroy(),Lr=null,Dt.delete(s),pe.querySelector(`#wrapper-${s}`)?.removeAttribute("data-preserve-runtime"),R&&Yo(Me,R.getMessages(),Ht)}let hs=0,CA=Nn()!==null,No=nS(),Fo=0,Ir=null,To=!1,ud=!1,Rr=0,jt=null,ys=null,yp=!1,pa=!1,bs=null,Mi=!0,pd=!1,fa=null,fd=!1,vs=()=>{fd=!0,MA()},bp=null,SA=4,Zn=24,wA=80,AA=1e3,er=null,Cy=()=>{e.setAttribute("data-persona-scrollbar",Ju()),Ju()!=="on-scroll"&&(er!==null&&clearTimeout(er),er=null,ne.removeAttribute("data-persona-scrollbar-visible"))},MA=()=>{Ju()==="on-scroll"&&(ne.setAttribute("data-persona-scrollbar-visible",""),er!==null&&clearTimeout(er),er=setTimeout(()=>{er=null,$s(ne,Zn)&&ne.removeAttribute("data-persona-scrollbar-visible")},AA))};Cy(),ge.push(()=>{er!==null&&clearTimeout(er)});let vp=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};jh=()=>je.active,un();let Sy=n.voiceRecognition?.autoResume??!1,tr=s=>{C.emit("voice:state",{active:je.active,source:s,timestamp:Date.now()})},mn=()=>{le(s=>({...s,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},TA=()=>{if(n.voiceRecognition?.enabled===!1)return;let s=ph(V.voiceState),l=!!s.active,f=Number(s.timestamp??0);je.manuallyDeactivated=!!s.manuallyDeactivated,l&&Date.now()-f<Yk&&setTimeout(()=>{je.active||(je.manuallyDeactivated=!1,n.voiceRecognition?.provider?.type==="runtype"?R.toggleVoice().then(()=>{je.active=R.isVoiceActive(),tr("restore"),R.isVoiceActive()&&Ia()}):ec("restore"))},1e3)},EA=()=>R?Tw(R.getMessages()).filter(s=>!s.__skipPersist):[],md=null,wy=(s,l)=>{typeof console<"u"&&console.error(s,l)},gd=(s,l)=>{let f=()=>{try{let _=s();return!_||typeof _.then!="function"?null:Promise.resolve(_).catch(K=>{wy(l,K)})}catch(_){return wy(l,_),null}},g=md,v=g?g.then(()=>f()??void 0):f();if(!v)return;let M=v.finally(()=>{md===M&&(md=null)});md=M};function ma(s){if(!U?.save)return;let l=s?Tw(s):R?EA():[],f=Q&&R?.getResumableHandle();f&&(V={...V,durableResume:{executionId:f.executionId,after:f.lastEventId}});let g={messages:l,metadata:V,artifacts:Qo.artifacts,selectedArtifactId:Qo.selectedId,...xs?{draft:xs}:{}};gd(()=>U.save(g),"[AgentWidget] Failed to persist state:")}let xs,hd=()=>!U?.save||n.persistState===!1?!1:typeof n.persistState=="object"?n.persistState.persist?.draft!==!1:!0,Ti=wC({write:()=>{if(!hd())return;let s=ve.getState(),l=CC({text:s.text,mentionRefs:s.mentionRefs,contentSegments:gf(),selectedModelId:s.selectedModelId,activeModeIds:s.activeModeIds,quote:s.quote});JSON.stringify(l)!==JSON.stringify(xs)&&(xs=l,ma())}});function Ay(){hd()&&Ti.schedule()}function xp(){Ti.flush()}function My(s){if(!hd())return;let l=SC(s,{mentionSourceIds:(n.contextMentions?.sources??[]).map(f=>f.id),modelIds:(n.composer?.models??[]).map(f=>f.id),modes:n.composer?.modes??[]});l&&(xs=s,ce&&!ce.value&&(ce.value=l.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),En()),l.selectedModelId&&(ve.setSelectedModelId(l.selectedModelId),Tr?.repaint()),ed(l.activeModeIds??[]),l.quote&&Pn(l.quote),Ti.cancel())}function yd(){Ti.cancel(),xs&&(xs=void 0,hd()&&ma())}let ga=null,Ty=()=>Ke.querySelector("#persona-scroll-container")||ne,ha=()=>{ga!==null&&(cancelAnimationFrame(ga),ga=null),To=!1},Ey=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),ud=!1,ha()},PA=()=>_o&&Sp()&&(Do()!=="anchor-top"||Ph()),Cp=()=>{let s=gi()||"Jump to latest",l=PA();Ot.toggleAttribute("data-persona-scroll-to-bottom-streaming",l),Rr>0?(rs.textContent=String(Rr),rs.style.display="",Ot.setAttribute("aria-label",`${s} (${Rr} new)`)):(rs.textContent="",rs.style.display="none",Ot.setAttribute("aria-label",l?`${s} (response streaming below)`:s))},Py=()=>{Rr!==0&&(Rr=0,Cp())},kA=()=>{let s=jt?.spacerHeight??0;return s<=0?$s(ne,Zn):Cd(s)-ne.scrollTop-ne.clientHeight<=Zn},Sp=()=>Mr()?!No.isFollowing():!kA(),wp=()=>!!R&&R.getMessages().length>0,zt=()=>{if(!nA()||Sr()){Ot.parentNode&&Ot.remove(),Ot.style.display="none";return}Ot.parentNode!==pe&&pe.appendChild(Ot),ss();let l=jn(ne)>0&&Sp()&&wp();l?Cp():Py(),Ot.style.display=l?"":"none"},Ei=()=>{No.pause()&&(Ey(),zt())},Eo=()=>{No.resume(),Py(),zt()},Hr=(s=!1)=>{Mr()&&wp()&&No.isFollowing()&&(!s&&!_o||(Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),ud=!0,Ir=requestAnimationFrame(()=>{Ir=null,ud=!1,No.isFollowing()&&LA(Ty(),s?220:140)})))},ky=(s,l,f,g=()=>!0)=>{let v=s.scrollTop,M=l(),_=M-v;if(ha(),Math.abs(_)<1){To=!0,s.scrollTop=M,Fo=s.scrollTop,To=!1;return}let K=performance.now();To=!0;let j=Z=>1-Math.pow(1-Z,3),G=Z=>{if(!g()){ha();return}let ae=l();ae!==M&&(M=ae,_=M-v);let me=Z-K,Ye=Math.min(me/f,1),ct=j(Ye),ft=v+_*ct;s.scrollTop=ft,Fo=s.scrollTop,Ye<1?ga=requestAnimationFrame(G):(s.scrollTop=M,Fo=s.scrollTop,ga=null,To=!1)};ga=requestAnimationFrame(G)},LA=(s,l=500)=>{let f=jn(s)-s.scrollTop;if(Math.abs(f)<1){Fo=s.scrollTop;return}if(Math.abs(f)>=wA){ha(),To=!0,s.scrollTop=jn(s),Fo=s.scrollTop,To=!1;return}ky(s,()=>jn(s),l,()=>No.isFollowing())},bd=()=>{if(!wp()){zt();return}let s=Ty();To=!0,s.scrollTop=jn(s),Fo=s.scrollTop,To=!1,zt()},Cs=s=>{let l=0,f=s;for(;f&&f!==ne;)l+=f.offsetTop,f=f.offsetParent;return l},IA=()=>{let s=ne.getRootNode();return(typeof s.getSelection=="function"?s.getSelection():null)??ne.ownerDocument.getSelection()},vd=()=>aS(IA(),ne),Ap=()=>{if(rA()!=="last-user-turn")return!1;let s=R?.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=ne.querySelector(`[data-message-id="${f}"]`);if(!g)return!1;let v=Math.min(Math.max(0,Cs(g)-hi()),jn(ne));return To=!0,ne.scrollTop=v,Fo=ne.scrollTop,To=!1,Do()==="follow"&&!$s(ne,Zn)&&No.pause(),zt(),!0},xd=s=>{let l=Math.max(0,Math.round(s));Xo.style.height=`${l}px`,Xo.style.display=l>0?"":"none",jt&&(jt.spacerHeight=Math.max(0,s))},Cd=s=>{let l=parseFloat(getComputedStyle(ne).paddingBottom)||0,f=0;for(let v of Array.from(ne.children)){if(v===Xo||v.offsetHeight===0)continue;let M=Cs(v)+v.offsetHeight;M>f&&(f=M)}let g=ne.scrollHeight-s;return f>0?Math.min(f+l,g):g},RA=()=>{if(!jt||jt.spacerHeight<=0)return;let s=Cd(jt.spacerHeight),l=Math.max(0,Math.round(ne.scrollTop)+ne.clientHeight-s+Zn);l<jt.spacerHeight&&(xd(l),zt())},gn=()=>{ys!==null&&(cancelAnimationFrame(ys),ys=null),ha(),jt=null,Xo.style.height="0px",Xo.style.display="none"},Ly=s=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Mp=s=>ne.querySelector(`[data-message-id="${Ly(s)}"]`),Iy=s=>{ys!==null&&cancelAnimationFrame(ys),ys=requestAnimationFrame(()=>{ys=null;let l=Ly(s),f=ne.querySelector(`[data-message-id="${l}"]`);if(!f)return;let g=Cs(f),v=jt?.spacerHeight??0,M=Cd(v),{targetScrollTop:_,spacerHeight:K}=yg({anchorOffsetTop:g,topOffset:hi(),viewportHeight:ne.clientHeight,contentHeight:M,slack:Zn});jt={initialSpacerHeight:K,contentHeightAtAnchor:M,spacerHeight:K},xd(K),ky(ne,()=>f.isConnected?Math.max(0,Cs(f)-hi()):_,220)})},Po=()=>{if(Do()!=="anchor-top"||!jt||!fa)return;let s=Mp(fa);if(!s)return;ha();let l=jt.spacerHeight,f=Cd(l),{targetScrollTop:g,spacerHeight:v}=yg({anchorOffsetTop:Cs(s),topOffset:hi(),viewportHeight:ne.clientHeight,contentHeight:f,slack:Zn});jt={initialSpacerHeight:v,contentHeightAtAnchor:f,spacerHeight:v},xd(v),To=!0,ne.scrollTop=g,Fo=ne.scrollTop,To=!1,zt()},HA=()=>{if(Mr()){if(!No.isFollowing()||$s(ne,1))return;Hr(!_o);return}if(jt&&jt.initialSpacerHeight>0){let s=ne.scrollHeight-jt.spacerHeight,l=iS({initialSpacerHeight:jt.initialSpacerHeight,contentHeightAtAnchor:jt.contentHeightAtAnchor,currentContentHeight:s});l!==jt.spacerHeight&&xd(l)}zt()},WA=s=>{let l=Do();l==="follow"?(Eo(),Hr(!0)):l==="anchor-top"&&(Mi=!1,pd=!0,fd=!1,fa=s,Iy(s))},BA=()=>{if(Do()==="anchor-top"){if(pd){Mi=!1;return}Mi=!0,gn(),Eo(),Hr(!0)}},OA=96,DA=s=>{if(bs===null)return!0;let l=Mp(bs),f=Mp(s);if(!l||!f)return!0;let g=Cs(f)-Cs(l);return hi()+g>ne.clientHeight-OA},_A=s=>{if(Do()!=="anchor-top"||!pd||fd||vd())return;let l=bs===null;for(let f of s){if(!l){f.id===bs&&(l=!0);continue}if(oS(f)){if(f.id===fa||!DA(f.id))return;fa=f.id,Iy(f.id);return}}},NA=s=>{let l=new Map;s.forEach(f=>{let g=vp.get(f.id);l.set(f.id,{streaming:f.streaming,role:f.role}),!g&&f.role==="assistant"&&(C.emit("assistant:message",f),!pa&&(Do()!=="anchor-top"||Ph())&&Sp()&&(Rr+=1,Cp(),zt(),Ql(Rr===1?"1 new message below.":`${Rr} 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}))}),vp.clear(),l.forEach((f,g)=>{vp.set(g,f)})},Pi=(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")},or=(s,l)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${s}`,f.setAttribute("data-wrapper-id",s),Pi(f,l),f},FA=(s,l,f)=>{let g=document.createElement("div"),M=(()=>{let B=i.find(Te=>Te.renderLoadingIndicator);if(B?.renderLoadingIndicator)return B.renderLoadingIndicator;if(n.loadingIndicator?.render)return n.loadingIndicator.render})(),_=(B,Te)=>Te==null?!1:typeof Te=="string"?(B.textContent=Te,!0):(B.appendChild(Te),!0),K=new Set,j=new Map,G=new Set,Z=i.some(B=>B.renderAskUserQuestion),ae=[],me=[],Ye=n.enableComponentStreaming!==!1,ct=n.approval!==!1,ft=[],Qt=n.messageActions,Nt=Qt?.showRegenerate===!0&&Qt.enabled!==!1&&dt.current?.isStreaming()!==!0?Mx(l):null,It=Qt?.showEdit===!0&&Qt.enabled!==!1,lo=Qt?.showQuote===!0&&Qt.enabled!==!1,Ze=null,co=n.features?.reasoningDisplay?.completedVisibility,On=B=>co==="removed"?!0:co==="removed-when-short"?Jv(B,n.features?.reasoningDisplay?.shortThinkThreshold):!1,ur=n.features?.toolCallDisplay?.completedVisibility==="removed";if(l.forEach(B=>{if(B.variant==="reasoning"&&B.reasoning?.status==="complete"&&On(B.reasoning)||ur&&B.variant==="tool"&&B.toolCall?.status==="complete")return;if(K.add(B.id),j.set(B.id,B.role),ms===B.id&&Lr){let Oe=or(B.id,B.role);Oe.setAttribute("data-persona-message-edit-stub","true"),Oe.setAttribute("data-preserve-runtime","true"),g.appendChild(Oe),Ze={messageId:B.id,element:Lr.element};return}let Te=Z&&mr(B),Re=ct&&B.variant==="approval"&&!!B.approval,xe=!Te&&B.role==="assistant"&&!B.variant&&Ye&&jl(B);!Re&&kr.has(B.id)&&(s.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),kr.delete(B.id)),!xe&&fs.has(B.id)&&(s.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),fs.delete(B.id));let Kt=mr(B)?`:${B.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${B.agentMetadata?.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",uo={canRegenerate:Nt===B.id,canEdit:It&&Zf(B),canQuote:lo&&!B.variant&&(B.content?.trim().length??0)>0},lt=`${uo.canRegenerate?"r":""}${uo.canEdit?"e":""}${uo.canQuote?"q":""}`,Pe=YC(B,hs)+Kt+`:${lt}`,hn=Te||Re||xe?null:ZC(Dt,B.id,Pe);if(hn){g.appendChild(hn.cloneNode(!0)),mr(B)&&B.toolCall?.id&&B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(G.add(B.toolCall.id),_a(B,n,_e.composerOverlay));return}let Mt=null,no=i.find(Oe=>!!(B.variant==="reasoning"&&Oe.renderReasoning||B.variant==="tool"&&Oe.renderToolCall||!B.variant&&Oe.renderMessage)),Gt=n.layout?.messages;if(mr(B)&&B.agentMetadata?.askUserQuestionAnswered===!0){ua.delete(B.id),s.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ds(B)&&Xr(n).enabled)return;if(mr(B)&&n.features?.askUserQuestion?.enabled!==!1){let Oe=i.find(Vo=>typeof Vo.renderAskUserQuestion=="function");if(Oe&&dt.current){let Vo=ua.get(B.id),Ve=Vo!==Pe,Ne=null;if(Ve){let{payload:ut,complete:ht}=gr(B),pr=B.id,Yt=()=>dt.current?.getMessages().find(nn=>nn.id===pr);Ne=Oe.renderAskUserQuestion({message:B,payload:ut,complete:ht,resolve:nn=>{let yt=Yt();yt&&dt.current?.resolveAskUserQuestion(yt,nn)},dismiss:()=>{let nn=Yt();nn?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(nn),dt.current?.resolveAskUserQuestion(nn,"(dismissed)"))},config:n})}let gt=Vo!=null;if(Ve&&Ne===null&&!gt){B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(G.add(B.toolCall.id),_a(B,n,_e.composerOverlay));return}let nt=or(B.id,B.role);nt.setAttribute("data-ask-plugin-stub","true"),nt.setAttribute("data-preserve-runtime","true"),g.appendChild(nt),ae.push({messageId:B.id,fingerprint:Pe,bubble:Ne});return}else{B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(G.add(B.toolCall.id),_a(B,n,_e.composerOverlay));return}}else if(Re){let Oe=k();if(!Oe){g.appendChild(or(B.id,B.role));return}let Vo=i.find(nt=>typeof nt.renderApproval=="function")??h,Ne=kr.get(B.id)!==Pe,gt=null;if(Ne&&Vo?.renderApproval){let nt=B.id,ut=(ht,pr)=>{let Yt=dt.current?.getMessages().find(nn=>nn.id===nt);Yt?.approval&&(Yt.approval.toolType==="webmcp"?dt.current?.resolveWebMcpApproval(Yt.id,ht):dt.current?.resolveApproval(Yt.approval,ht,pr))};gt=Vo.renderApproval({message:B,defaultRenderer:()=>Oe.createApprovalBubble(B,n),config:n,approve:ht=>ut("approved",ht),deny:ht=>ut("denied",ht)})}if(Ne&&gt===null)s.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),kr.delete(B.id),Mt=Oe.createApprovalBubble(B,n);else{let nt=or(B.id,B.role);nt.setAttribute("data-approval-plugin-stub","true"),nt.setAttribute("data-preserve-runtime","true"),g.appendChild(nt),ft.push({messageId:B.id,fingerprint:Pe,bubble:gt});return}}else if(no)if(B.variant==="reasoning"&&B.reasoning&&no.renderReasoning){if(!wn)return;Mt=no.renderReasoning({message:B,defaultRenderer:()=>Kg(B,n),config:n})}else if(B.variant==="tool"&&B.toolCall&&no.renderToolCall){if(!Ko)return;Mt=no.renderToolCall({message:B,defaultRenderer:()=>Xg(B,n),config:n})}else no.renderMessage&&(Mt=no.renderMessage({message:B,defaultRenderer:()=>{let Oe=ni(B,f,Gt,n.messageActions,Vt,{loadingIndicatorRenderer:M,widgetConfig:n,actionEligibility:uo});return B.role!=="user"&&A(Oe,B,n,R),Oe},config:n}));if(!Mt&&xe){let Oe=qu(B);if(Oe){let Vo=fs.get(B.id),Ve=Vo!==Pe,Ne=n.wrapComponentDirectiveInBubble!==!1&&xn.getOptions(Oe.component)?.bubbleChrome!==!1,gt=null;if(Ve){let nt=Uu(Oe,{config:n,message:B,transform:f});if(nt&&Oe.component==="PersonaArtifactInline"){let ut=nt.hasAttribute("data-artifact-inline")?nt:nt.querySelector("[data-artifact-inline]"),ht=ut?.getAttribute("data-artifact-inline")??"",pr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(ht):ht,Yt=ht?s.querySelector(`#wrapper-${B.id}`)?.querySelector(`[data-artifact-inline="${pr}"]`)??null:null;ut&&Yt&&Yt!==ut&&vr()?.hasLiveInlineArtifactBlock(Yt)&&(ut===nt?nt=Yt:ut.replaceWith(Yt))}if(nt)if(Ne){let ut=document.createElement("div");if(ut.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ut.id=`bubble-${B.id}`,ut.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let ht=document.createElement("div");ht.className="persona-mb-3 persona-text-sm persona-leading-relaxed",ht.innerHTML=f({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),ut.appendChild(ht)}ut.appendChild(nt),gt=ut}else{let ut=document.createElement("div");if(ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ut.id=`bubble-${B.id}`,ut.setAttribute("data-message-id",B.id),ut.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let ht=document.createElement("div");ht.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",ht.innerHTML=f({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),ut.appendChild(ht)}ut.appendChild(nt),gt=ut}}if(gt||Vo!=null){let nt=or(B.id,B.role);nt.setAttribute("data-component-directive-stub","true"),nt.setAttribute("data-preserve-runtime","true"),g.appendChild(nt),me.push({messageId:B.id,fingerprint:Pe,bubble:gt});return}}}if(!Mt)if(B.variant==="reasoning"&&B.reasoning){if(!wn)return;Mt=Kg(B,n)}else if(B.variant==="tool"&&B.toolCall){if(!Ko)return;Mt=Xg(B,n)}else if(B.variant==="approval"&&B.approval){if(n.approval===!1)return;let Oe=k();if(!Oe)return;Mt=Oe.createApprovalBubble(B,n)}else{let Oe=n.layout?.messages;Oe?.renderUserMessage&&B.role==="user"?Mt=Oe.renderUserMessage({message:B,config:n,streaming:!!B.streaming}):Oe?.renderAssistantMessage&&B.role==="assistant"?Mt=Oe.renderAssistantMessage({message:B,config:n,streaming:!!B.streaming}):Mt=ni(B,f,Oe,n.messageActions,Vt,{loadingIndicatorRenderer:M,widgetConfig:n,actionEligibility:uo}),B.role!=="user"&&Mt&&A(Mt,B,n,R)}let Rt=or(B.id,B.role);Rt.appendChild(Mt),eS(Dt,B.id,Pe,Rt),g.appendChild(Rt)}),_e.composerOverlay&&_e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Te=>{let Re=Te.getAttribute("data-persona-ask-sheet-for");Re&&!G.has(Re)&&Kr(_e.composerOverlay,Re)}),n.features?.toolCallDisplay?.grouped){let B=[],Te=[],Re=n.features.toolCallDisplay.groupedMode==="summary";l.forEach(xe=>{if(xe.variant==="tool"&&xe.toolCall&&Ko){if(ur&&xe.toolCall.status==="complete")return;Te.push(xe);return}xe.variant==="reasoning"&&(!wn||xe.reasoning?.status==="complete"&&On(xe.reasoning))||((Te.length>1||Re&&Te.length>0)&&B.push(Te),Te=[])}),(Te.length>1||Re&&Te.length>0)&&B.push(Te),B.forEach(xe=>{let Kt=xe.map(Gt=>Array.from(g.children).find(Rt=>Rt instanceof HTMLElement&&Rt.getAttribute("data-wrapper-id")===Gt.id)).filter(Gt=>!!Gt);if(Kt.length<(Re?1:2))return;let uo=or(`tool-group-${xe[0].id}`,"assistant");uo.setAttribute("data-persona-tool-group-row","true");let lt=document.createElement("div");lt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",lt.setAttribute("data-persona-tool-group","true");let Pe=document.createElement("div");Pe.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",Pe.id=`tool-group-summary-${xe[0].id}`;let hn=`Called ${xe.length} ${xe.length===1?"tool":"tools"}`,Mt=n.toolCall?.renderGroupedSummary?.({messages:xe,toolCalls:xe.map(Gt=>Gt.toolCall).filter(Gt=>!!Gt),defaultSummary:hn,config:n});_(Pe,Mt)||(Pe.textContent=hn);let no=document.createElement("div");no.className="persona-tool-group-stack persona-flex persona-flex-col",no.id=`tool-group-stack-${xe[0].id}`,no.setAttribute("data-persona-tool-group-stack","true"),lt.appendChild(Pe),Re||lt.appendChild(no),uo.appendChild(lt),Kt[0].before(uo),Kt.forEach((Gt,Rt)=>{if(Re){Gt.remove();return}Gt.style.setProperty("--persona-message-row-max-width","100%");let Oe=document.createElement("div");Oe.className="persona-tool-group-item persona-relative",Oe.setAttribute("data-persona-tool-group-item","true"),Rt<Kt.length-1&&Oe.setAttribute("data-persona-tool-group-connector","true"),Oe.appendChild(Gt),no.appendChild(Oe)})})}tS(Dt,K);let Dn=l.some(B=>B.role==="assistant"&&B.streaming),Ha=l[l.length-1],Ws=Ha?.role==="assistant"&&!Ha.streaming&&Ha.variant!=="approval";if(_o&&l.some(B=>B.role==="user")&&!Dn&&!Ws){let B={config:n,streaming:!0,location:"standalone",defaultRenderer:Qs},Te=i.find(xe=>xe.renderLoadingIndicator),Re=null;if(Te?.renderLoadingIndicator&&(Re=Te.renderLoadingIndicator(B)),Re===null&&n.loadingIndicator?.render&&(Re=n.loadingIndicator.render(B)),Re===null&&(Re=Qs()),Re){let xe=document.createElement("div"),Kt=n.loadingIndicator?.showBubble!==!1,uo=n.layout?.messages?.layout??"bubble";xe.className=Kt?_l("assistant",uo).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),xe.setAttribute("data-typing-indicator","true"),Kt&&(xe.style.color="var(--persona-message-assistant-text, var(--persona-text))",uo!=="flat"&&(xe.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",xe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),xe.appendChild(Re);let lt=or("typing-indicator","assistant");lt.appendChild(xe),g.appendChild(lt)}}if(!_o&&l.length>0){let B=l[l.length-1],Te={config:n,lastMessage:B,messageCount:l.length},Re=i.find(Kt=>Kt.renderIdleIndicator),xe=null;if(Re?.renderIdleIndicator&&(xe=Re.renderIdleIndicator(Te)),xe===null&&n.loadingIndicator?.renderIdle&&(xe=n.loadingIndicator.renderIdle(Te)),xe){let Kt=document.createElement("div"),uo=n.loadingIndicator?.showBubble!==!1;Kt.className=uo?["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(" "),Kt.setAttribute("data-idle-indicator","true"),Kt.appendChild(xe);let lt=or("idle-indicator","assistant");lt.appendChild(Kt),g.appendChild(lt)}}if(wv(g),gu(s,g),Hf(s),Ze){let{messageId:B,element:Te}=Ze,Re=s.querySelector(`#wrapper-${B}`);Re&&Te.parentElement!==Re&&(Pi(Re,j.get(B)??"user"),Re.replaceChildren(Te))}if(ae.length>0)for(let{messageId:B,fingerprint:Te,bubble:Re}of ae){let xe=s.querySelector(`#wrapper-${B}`);xe&&(Pi(xe,j.get(B)??"assistant"),Re!==null&&(xe.replaceChildren(Re),xe.setAttribute("data-bubble-fp",Te),ua.set(B,Te)))}if(ua.size>0)for(let B of ua.keys())K.has(B)||ua.delete(B);if(me.length>0)for(let{messageId:B,fingerprint:Te,bubble:Re}of me){let xe=s.querySelector(`#wrapper-${B}`);xe&&(Pi(xe,j.get(B)??"assistant"),Re!==null&&(xe.replaceChildren(Re),xe.setAttribute("data-bubble-fp",Te),fs.set(B,Te)))}if(fs.size>0)for(let B of fs.keys())K.has(B)||fs.delete(B);if(ft.length>0)for(let{messageId:B,fingerprint:Te,bubble:Re}of ft){let xe=s.querySelector(`#wrapper-${B}`);xe&&(Pi(xe,j.get(B)??"assistant"),Re!==null&&(xe.replaceChildren(Re),xe.setAttribute("data-bubble-fp",Te),kr.set(B,Te)))}if(kr.size>0)for(let B of kr.keys())K.has(B)||kr.delete(B)},Tp=!1,Sd=()=>{Tp||(Tp=!0,dc().catch(()=>{Tp=!1}))},Yo=(s,l,f)=>{l.length>0&&Sd(),FA(s,l,f),Yh()},ki=null,UA=()=>{if(ki)return;let s=f=>{let g=f.composedPath();g.includes(Ke)||Xt&&g.includes(Xt)||pt(!1,"user")};ki=s,(e.ownerDocument??document).addEventListener("pointerdown",s,!0)},Ry=()=>{if(!ki)return;(e.ownerDocument??document).removeEventListener("pointerdown",ki,!0),ki=null};ge.push(()=>Ry());let Li=null,qA=()=>{if(Li)return;let s=f=>{f.key==="Escape"&&(f.isComposing||pt(!1,"user"))};Li=s,(e.ownerDocument??document).addEventListener("keydown",s,!0)},Hy=()=>{if(!Li)return;(e.ownerDocument??document).removeEventListener("keydown",Li,!0),Li=null};ge.push(()=>Hy());let Ii=!1,Wy=new Set,VA=()=>{let s=n.launcher?.composerBar?.peek?.streamAnimation;return s||n.features?.streamAnimation},ya=()=>{if(!Ie())return;let s=_e.peekBanner,l=_e.peekTextNode;if(!s||!l)return;if(ye){s.classList.remove("persona-pill-peek--visible");return}let f=R?.getMessages()??[],g;for(let Nt=f.length-1;Nt>=0;Nt--){let It=f[Nt];if(It.role==="assistant"&&It.content){g=It;break}}if(!g){s.classList.remove("persona-pill-peek--visible");return}let v=g.content,M=!!g.streaming,_=VA(),K=hu(_),j=K.type!=="none"?hp(K.type,_?.plugins):null,G=j?.isAnimating?.(g)===!0,Z=j!==null&&(M||G);Z&&j&&!Wy.has(j.name)&&(Wl(j,e),Wy.add(j.name));let ae=Z&&j?.containerClass?j.containerClass:null,me=l.dataset.personaPeekStreamClass??null;me&&me!==ae&&(l.classList.remove(me),delete l.dataset.personaPeekStreamClass),ae&&me!==ae&&(l.classList.add(ae),l.dataset.personaPeekStreamClass=ae),Z?(l.style.setProperty("--persona-stream-step",`${K.speed}ms`),l.style.setProperty("--persona-stream-duration",`${K.duration}ms`)):(l.style.removeProperty("--persona-stream-step"),l.style.removeProperty("--persona-stream-duration"));let Ye=Z?yu(v,K.buffer,j,g,M):v;if(Z&&K.placeholder==="skeleton"&&M&&(!Ye||!Ye.trim())){let Nt=document.createElement("div"),It=Hl();It.classList.add("persona-pill-peek__skeleton"),Nt.appendChild(It),gu(l,Nt)}else{let Nt=Math.max(0,Ye.length-100),It=Ye.length>100?Ye.slice(-100):Ye,lo=fr(It);if(!Z||!j){let Ze=Ye.length>100?`\u2026${It}`:It;l.textContent!==Ze&&(l.textContent=Ze)}else{let Ze=lo;(j.wrap==="char"||j.wrap==="word")&&(Ze=Rl(lo,j.wrap,`peek-${g.id}`,{skipTags:j.skipTags,startIndex:Nt}));let co=document.createElement("div");if(co.innerHTML=Ze,j.useCaret&&It.length>0){let On=bu(),ur=co.querySelectorAll(".persona-stream-char, .persona-stream-word"),Dn=ur[ur.length-1];Dn?.parentNode?Dn.parentNode.insertBefore(On,Dn.nextSibling):co.appendChild(On)}gu(l,co),j.onAfterRender?.({container:l,bubble:s,messageId:g.id,message:g,speed:K.speed,duration:K.duration})}}let Qt=_o||Ii;s.classList.toggle("persona-pill-peek--visible",Qt)};if(Ie()){let s=_e.peekBanner;if(s){let g=v=>{v.preventDefault(),v.stopPropagation(),pt(!0,"user")};s.addEventListener("pointerdown",g),ge.push(()=>{s.removeEventListener("pointerdown",g)})}let l=()=>{Ii||(Ii=!0,ya())},f=()=>{Ii&&(Ii=!1,ya())};Ce.addEventListener("pointerenter",l),Ce.addEventListener("pointerleave",f),ge.push(()=>{Ce.removeEventListener("pointerenter",l),Ce.removeEventListener("pointerleave",f)}),Xt&&(Xt.addEventListener("pointerenter",l),Xt.addEventListener("pointerleave",f),ge.push(()=>{Xt.removeEventListener("pointerenter",l),Xt.removeEventListener("pointerleave",f)}))}let $A=s=>{let l=n.launcher?.composerBar??{},f=l.expandedSize??"anchored",g=l.bottomOffset??"16px",v=l.collapsedMaxWidth,M=l.expandedMaxWidth??"880px",_=l.expandedTopOffset??"5vh",K=l.modalMaxWidth??"880px",j=l.modalMaxHeight??"min(90vh, 800px)",G="calc(100vw - 32px)",Z="var(--persona-pill-area-height, 80px)",ae=Ke.style;if(ae.left="",ae.right="",ae.top="",ae.bottom="",ae.transform="",ae.width="",ae.maxWidth="",ae.height="",ae.maxHeight="",Xt){let me=Xt.style;me.bottom=g,me.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=K,ae.maxWidth=G,ae.maxHeight=j,ae.height=j;return}ae.left="50%",ae.transform="translateX(-50%)",ae.bottom=`calc(${g} + ${Z})`,ae.top=_,ae.width=M,ae.maxWidth=G}},Ri=()=>{if(ye&&Sd(),!Ee())return;if(Ie()){let G=(n.launcher?.composerBar??{}).expandedSize??"anchored",Z=ye?"expanded":"collapsed";Ke.dataset.state=Z,Ke.dataset.expandedSize=G,Xt&&(Xt.dataset.state=Z,Xt.dataset.expandedSize=G),Ke.style.removeProperty("display"),Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),$A(ye),pe.style.display=ye?"flex":"none",is(),ye?(UA(),qA()):(Ry(),Hy()),ya();return}let s=wt(n),l=e.ownerDocument.defaultView??window,f=n.launcher?.mobileBreakpoint??640,g=n.launcher?.mobileFullscreen??!0,v=l.innerWidth<=f,M=g&&v&&Se,_=Ro(n).reveal;ye?(Ke.style.removeProperty("display"),Ke.style.display=s?"flex":"",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-95","persona-opacity-0"),Ce.classList.add("persona-scale-100","persona-opacity-100"),kt?(kt.setPanelOpen(!0),kt.element.style.display="none"):fo&&(fo.style.display="none")):(s?s&&(_==="overlay"||_==="push")&&!M?(Ke.style.removeProperty("display"),Ke.style.display="flex",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ke.style.setProperty("display","none","important"),Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ke.style.display="",Ke.classList.add("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100"),Ce.classList.add("persona-scale-95","persona-opacity-0")),kt?(kt.setPanelOpen(!1),kt.element.style.display=s?"none":""):fo&&(fo.style.display=s?"none":""))},pt=(s,l="user")=>{if(!Ee()||ye===s)return;let f=ye;ye=s,Ri();let g=(()=>{let M=n.launcher?.sidebarMode??!1,_=e.ownerDocument.defaultView??window,K=n.launcher?.mobileFullscreen??!0,j=n.launcher?.mobileBreakpoint??640,G=_.innerWidth<=j,Z=wt(n)&&K&&G,ae=Ie()&&(n.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return M||K&&G&&Se||Z||ae})();if(ye&&g){if(!In){let M=e.getRootNode(),_=M instanceof ShadowRoot?M.host:e.closest(".persona-host");_&&(In=Sg(_,n.launcher?.zIndex??ao))}Rn||(Rn=wg(e.ownerDocument))}else ye||(In?.(),In=null,Rn?.(),Rn=null);ye&&(Xi(),Ap()||(Do()==="follow"?Hr(!0):bd()));let v={open:ye,source:l,timestamp:Date.now()};ye&&!f?C.emit("widget:opened",v):!ye&&f&&C.emit("widget:closed",v),C.emit("widget:state",{open:ye,launcherEnabled:Se,voiceActive:je.active,streaming:R.isStreaming()})},Wr={inputDisabled:!1,sendDisabled:!1},Br=()=>Wr.inputDisabled,Ss=()=>Wr.inputDisabled||Wr.sendDisabled,jA=()=>(Wr.inputDisabled?Wr.inputReason:void 0)??(Wr.sendDisabled?Wr.sendReason:void 0);function Ep(){if(!we)return;if(ve.getState().phase==="streaming"){we.disabled=!1;return}let s=Je?!Je.isReady():!1;we.disabled=Ss()||s}function wd(){if(!Tn)return;let s=ve.getState(),l=n.sendButton?.visibility==="when-text"&&s.phase!=="streaming"&&s.text.trim().length===0&&s.attachments.length===0;Tn.toggleAttribute("data-persona-send-hidden",l)}function zA(){let s=jA();if(Ie()){let l=cn??Le;s?l.setAttribute("title",s):l.removeAttribute("title"),Le.toggleAttribute(fi,!!s);return}if(s){at.setAttribute("role","status"),at.setAttribute("aria-live","polite"),at.setAttribute(fi,""),at.textContent=s;return}if(at.hasAttribute(fi)&&(at.removeAttribute("role"),at.removeAttribute("aria-live"),at.removeAttribute(fi),u)){let l=R.getStatus();Kl(at,So(l),n.statusIndicator??{},l)}}function Pp(){let s=Qm(n.composer?.inputDisabled),l=Qm(n.composer?.sendDisabled);Wr={inputDisabled:s.disabled,inputReason:s.reason,sendDisabled:l.disabled,sendReason:l.reason},ve.setInputDisabled(s.disabled),ve.setSendDisabled(l.disabled);let f=ve.getState().phase==="streaming",g=s.disabled,v=f||g;ce&&(ce instanceof HTMLTextAreaElement?ce.disabled=g:ce.setAttribute("contenteditable",g?"false":"true"),ce.setAttribute("aria-disabled",g?"true":"false")),At&&(At.disabled=g),vt&&(vt.disabled=g);for(let M of Bt?.affordanceButtons??[])M.querySelectorAll("button").forEach(_=>{_.disabled=g});re&&(re.disabled=v),cs.forEach(M=>{M.elements.forEach(_=>{_.toggleAttribute("data-disabled",v),_ instanceof HTMLButtonElement||_.setAttribute("aria-disabled",v?"true":"false")}),M.buttons.forEach(_=>{_.disabled=v})}),Hp.forEach(M=>{M.toggleAttribute("data-disabled",v),M instanceof HTMLButtonElement?M.disabled=v:M.setAttribute("aria-disabled",v?"true":"false"),M.querySelectorAll("button").forEach(_=>{_.disabled=v})}),Le.dataset.personaComposerStreaming=f?"true":"false",Le.dataset.personaComposerInputDisabled=g?"true":"false",Le.dataset.personaComposerSendDisabled=Ss()?"true":"false",Le.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(M=>{(M instanceof HTMLButtonElement||M instanceof HTMLInputElement||M instanceof HTMLTextAreaElement||M instanceof HTMLSelectElement)&&(M.disabled=f)}),Ep(),zA()}let Hi=s=>{ve.setStreaming(s),Th(s?"stop":"send"),Pp()},ws=()=>{je.active||ce&&ce.focus()};C.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>ws(),200)});let As=null,Wi=!1,kp=!wo.hidden,Or=null,Lp=!E,Ad=null;ge.push(()=>{Ad?.cancel(),Ad=null});let KA=s=>{let l=HS(s);if(l===Yl)return;Yl=l,e.setAttribute("data-persona-conversation-state",l);let f=ep();Zl(),Lp&&(Ad?.cancel(),Ad=IS(Le,l==="active"?f:ep(),l==="active"?"drop":"rise")),Po()},By=null,Oy,Dy=null,ba=null,Ip=!1,Bi=s=>{let l=vn(n),f=`${l.variant}|${l.dismiss}|${l.anchor??"bottom"}|${l.align??""}|${l.iconPlacement}|${l.kicker??""}|${l.title}|${l.subtitle}`;(f!==By||l.icon!==Oy)&&(By=f,Oy=l.icon,Mu({host:wo,iconHolder:Qw,kicker:Yw,title:Jw,subtitle:Zw,starterSuggestions:Qu},l));let g=l.message===void 0?null:`${n.layout?.messages?.layout??"bubble"}|${l.message}`;g!==Dy&&(Dy=g,Tu(Bo,l.message,n));let v=s??(R?R.getMessages():n.initialMessages);KA(v);let M=Wi,_=!M&&ts(l,v),K=_!==kp;if(kp=_,ba){Or?.cancel(),Or=null,M!==Ip&&(Ip=M,M?Ng(ne,wo,null):_g(ne,wo,ba)),ri(ne,wo,!M);return}if(K&&!_&&!M&&l.dismiss==="on-first-message"&&Lp){Or=LS(wo,G=>{Or===G&&(Or=null),!kp&&!ba&&(ri(ne,wo,!1),Po()),G?.cancel()});return}if(Or){if(!_&&!M)return;Or.cancel(),Or=null}let j=!wo.hidden;ri(ne,wo,_),!_&&j&&Po()},Rp=[],Hp=[],Wp=!1,_y=null,Ny,Fy=()=>{Hp.length=0;let s=Rp.splice(0,Rp.length);for(let l of s)try{l()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};ge.push(Fy);let GA=(s,l)=>{let f=Mg(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=Tg({item:{...f,behavior:f.behavior??g?.behavior??"send"},index:l,surface:"starter",source:"config",variant:g?.variant??"card",streaming:u?R.isStreaming():!1,config:n,plugins:i,chipsConfig:n.suggestionChipsConfig,session:R,getTextarea:()=>ce,eventTarget:wo,submitPrompt:Yd});return Hp.push(v),v},Bp=()=>{if(Wp)return;Wp=!0;let s=vn(n);_y=`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`,Ny=s.icon;try{Fy(),Ng(ne,wo,ba),ba=null,Ip=!1;let l=R?R.getMessages():n.initialMessages,f=ts(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:()=>wo,sendMessage:_=>{if(!R||R.isStreaming())return;let K=_.trim();K&&R.sendMessage(K)},requestRender:()=>Bp(),renderStarter:_=>GA(_,g++),storage:p(M.id),onCleanup:_=>{Rp.push(_)}}),v))break;v&&v!==wo&&(ba=v,_g(ne,wo,v))}finally{Wp=!1}Bi()},XA=()=>{let s=vn(n);`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`===_y&&s.icon===Ny||Bp()},Md=()=>{Bi(),aa||(ce.placeholder=hC(ve.getState().activeModeIds,n.composer?.modes)??n.copy?.inputPlaceholder??"How can I help...",!(n.sendButton?.useIcon??!1)&&!R?.isStreaming()&&(we.textContent=n.copy?.sendButtonLabel??"Send")),ce.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ce.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},QA=!!n.setStoredConversationId,va=s=>le(l=>{let f={...l};return delete f[s],f}),Td=s=>{let l=V[s];return typeof l=="string"?l:null},Uy=()=>{let s=V.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};n.clientToken&&(n={...n,getStoredSessionId:()=>Td("sessionId"),setStoredSessionId:s=>{le(l=>({...l,sessionId:s}))},clearStoredSessionId:n.clearStoredSessionId??(()=>va("sessionId")),getStoredConversationId:n.getStoredConversationId??(()=>Td("conversationId")),setStoredConversationId:n.setStoredConversationId??(s=>{le(l=>({...l,conversationId:s}))}),clearStoredConversationId:n.clearStoredConversationId??(()=>va("conversationId"))});let qy=()=>n.clientToken??null,Vy=s=>gw(s,ln(),n.persistState===!1),$y=qy(),nr=$y?Vy($y):null,rr={...nr?{visitorStore:nr}:{},historyBootstrapReady:D,getStoredMessageCursor:()=>Td("historyMessageCursor"),setStoredMessageCursor:s=>{if(s===null){va("historyMessageCursor");return}le(l=>({...l,historyMessageCursor:s}))},getPendingDisplayProjections:()=>{let s=V.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){va("pendingDisplayProjections");return}le(l=>({...l,pendingDisplayProjections:s}))},getStoredResumableHandle:Uy,setStoredResumableHandle:s=>{if(!s){va("durableResume");return}le(l=>({...l,durableResume:s}))},shouldResumeDurableConversation:()=>Q&&Uy()!==null,...QA?{}:{getStoredConversationRevision:()=>Td("conversationRevision"),setStoredConversationRevision:s=>{if(s===null){va("conversationRevision");return}le(l=>({...l,conversationRevision:s}))}}};if(Q){let s=n.onExecutionState,l=e.ownerDocument.defaultView,f=!1,g=()=>f=!0,v=()=>f=!1;l?.addEventListener("pagehide",g),l?.addEventListener("pageshow",v),ge.push(()=>{l?.removeEventListener("pagehide",g),l?.removeEventListener("pageshow",v)}),n={...n,reconnectStream:n.reconnectStream??(M=>R.getClient().reconnectClientTokenStream(M)),onExecutionState:M=>{(M||!f)&&rr.setStoredResumableHandle?.(M?{executionId:M.executionId,after:M.lastEventId}:null),s?.(M)}}}let YA=()=>{let s=qy();if(s&&nr?.matches(s,ln(),n.persistState===!1)||!s&&!nr)return;nr?.destroy(),nr=s?Vy(s):null;let l={...rr};nr?l.visitorStore=nr:delete l.visitorStore,rr=l,R.setHistoryInternals(rr)},Ms=null,JA=()=>{Ms==null&&(Ms=setInterval(()=>{let s=Me.querySelectorAll("[data-tool-elapsed]");if(s.length===0){clearInterval(Ms),Ms=null;return}let l=Date.now();s.forEach(f=>{let g=Number(f.getAttribute("data-tool-elapsed"));g&&(f.textContent=Sc(l-g))})},100))},Op=(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((_,K)=>Op(_,l[K]));let f=s,g=l,v=Object.keys(f),M=Object.keys(g);return v.length===M.length&&v.every(_=>Object.prototype.hasOwnProperty.call(g,_)&&Op(f[_],g[_]))},jy=s=>{let{content:l,rawContent:f,llmContent:g,...v}=s;return v},Dp=s=>s.role==="assistant"&&s.streaming===!0&&!s.variant&&!s.toolCall&&!s.tools&&!s.approval&&!s.reasoning&&!s.contentParts&&!s.stopReason&&!jl(s),ZA=(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))&&Dp(g)&&Dp(v)&&Op(jy(g),jy(v))},_p=null,xa=null,Ts=null,sr=null,Np=null,eM=s=>{if(!Q)return ma(s);Np=s,queueMicrotask(()=>{Np===s&&(Np=null,ma(s))})},Ed=s=>{_p=s;let l,f;xa=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),!xa&&Dp(M)&&(xa={index:v,id:M.id}),l&&f&&xa)break}Yo(Me,s,Ht),vr()?.updateInlineArtifactBlocks(Me,Qo.artifacts,{suppressTransition:_o}),JA(),Bi(s),ca(s),Hr(!_o),NA(s),s.length===0&&(gn(),Mi=!0,pd=!1,fa=null,fd=!1),!yp||pa?(yp=!0,bs=l?.id??null,bp=f?.id??null):l&&l.id!==bs?(bs=l.id,WA(l.id)):f&&f.id!==bp&&BA(),f&&(bp=f.id),_A(s);let g=je.lastUserMessageId;l&&l.id!==g&&(je.lastUserMessageId=l.id,C.emit("user:message",l)),je.lastUserMessageWasVoice=!!l?.viaVoice,eM(s),ya()},Fp=()=>{sr!==null&&(cancelAnimationFrame(sr),sr=null);let s=Ts;Ts=null,s&&Ed(s)},zy=()=>{sr!==null&&cancelAnimationFrame(sr),sr=null,Ts=null},tM=s=>{let l=Ts??_p;if(_o&&l&&xa&&ZA(l,s,xa)){Ts=s,sr===null&&(sr=requestAnimationFrame(()=>{sr=null;let f=Ts;Ts=null,f&&Ed(f)}));return}if(s.length===0){zy(),Ed(s);return}Fp(),Ed(s)};R=new Va(n,{onMessagesChanged(s){tM(s)},onStatusChanged(s){let l=n.statusIndicator??{};Kl(at,(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),Gn()},onStreamingChanged(s){s||(R?.getMessages().length===0?zy():Fp()),_o=s,Hi(s),Gn(),R&&Yo(Me,R.getMessages(),Ht),s||(Hr(!0),RA(),by=!0,R&&vy(R.getMessages(),Xr(n))),zt(),Ql(s?"Responding\u2026":"Response complete."),ya()},onVoiceStatusChanged(s){if(C.emit("voice:status",{status:s,timestamp:Date.now()}),n.voiceRecognition?.provider?.type==="runtype")switch(s){case"listening":cr(),Ia();break;case"processing":cr(),nT();break;case"speaking":cr(),rT();break;default:s==="idle"&&R.isBargeInActive()?(cr(),Ia(),re?.setAttribute("aria-label","End voice session")):(je.active=!1,cr(),tr("system"),mn());break}},onArtifactsState(s){Qo=s,s.artifacts.length===0&&(ia=!1),vr()?.updateInlineArtifactBlocks(Me,s.artifacts,{suppressTransition:_o}),fn(),ma()},onHistoryStateChanged(s){Wt(s)},onHistoryNotice(s){Et(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})}},rr),dt.current=R,ge.push(()=>R.cancel()),ge.push(()=>{R.destroy(),nr?.destroy()});let Up=null;if(R.onReadAloudChange((s,l)=>{Xh=s,Qh=l,Yh();let f=s??Up;s&&(Up=s);let g=f?R.getMessages().find(v=>v.id===f)??null:null;C.emit("message:read-aloud",{messageId:f,message:g,state:l,timestamp:Date.now()}),l==="idle"&&(Up=null)}),u=!0,yp=!0,n.voiceRecognition?.provider?.type==="runtype")try{R.setupVoice()}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",s)}let oM=720,nM=250,Qe=uh(n.features?.history?.copy),Uo=null,qp=!1,it=null,Pd=null,kd="conversation",Vp=null,po=null,Hn=null,Ld=R.getHistoryState(),$p=null,Oi=0,jp=null,Id=null,Rd=null,zp=`persona-history-${Math.random().toString(36).slice(2,8)}`,Kp=()=>n.features?.history?.enabled===!0,Wn=()=>Kp()&&!!Uo&&!qp,Ky=()=>{let s=R.getStatus();return _o||s==="paused"||s==="resuming"},Gp=()=>{let s=n.features?.history?.scope;if(s)return s;let l=n.getIdentityProof?"verified-user":"browser",f=Uo?.capabilities.scopes;return!f||f.includes(l)?l:f[0]??l},Ca=()=>Pd?.scope??Gp(),Gy=()=>R.getClientSession()?.targetId??null,Xy=s=>`${s.state}:${"reason"in s?s.reason:""}`,rM=s=>{let l=Xy(s);l!==$p&&($p=l,C.emit("history:identityStatusChanged",{status:s,timestamp:Date.now()}))},Hd=s=>{s&&(Xn.textContent="",Xn.textContent=s)},Qy=null,Yy=null,sM=()=>{if(!Kp())return null;let s=xw();if(s)return s();let l=n.features?.history?.provider;return l?typeof l!="function"?l:(Qy!==l&&(Qy=l,Yy=l()),Yy):R.isClientTokenMode()?Cw({client:R.getClient(),getIdentityProofConfigured:()=>typeof n.getIdentityProof=="function",onActivationCommitted:f=>R.bindActivatedSession(f),getClient:()=>R.getClient()}):null},Jy=()=>{Id?.(),Id=null,Rd?.(),Rd=null,qp=!1,Uo=sM();let s={...rr};Uo?s.historyProvider=Uo:delete s.historyProvider,rr=s,R.setHistoryInternals(rr),Uo&&(Id=Uo.subscribeAvailability?.(l=>{qp=!l,l||ko({restoreFocus:!1}),_r()})??null,Rd=Uo.subscribeIdentityStatus(l=>rM(l)),$p=Xy(Uo.getIdentityStatus()))},Xp=()=>{let s=n.features?.history?.presentation??"panel";if(s==="panel"||s==="auto"&&!(!Se||wt(n)))return"panel";let l=Ln??pe;return(l.getBoundingClientRect().width||l.clientWidth)>=oM?"rail":"panel"},Jo=(s,l)=>{l?(s.setAttribute("aria-hidden","true"),s.setAttribute("inert","")):(s.removeAttribute("aria-hidden"),s.removeAttribute("inert"))},Wd="data-persona-history-suppressed",qo=null,Dr=null,Es=null,Di=null,Qp=null,Zy="",eb=()=>Ae===Qp?Zy:n.layout?.showHeader===!1?"none":"",aM=()=>de==="panel"&&!!Es&&Di===Es.element&&n.layout?.showHeader!==!1&&eb()!=="none",iM=()=>{for(let s of Array.from(Ae.children))s!==qo&&s.setAttribute(Wd,"")},lM=()=>{for(let s of Array.from(pe.querySelectorAll(`[${Wd}]`)))s.removeAttribute(Wd)},dM=()=>{let s=Es;if(!s)return;if(Array.from(Ae.children).some(g=>g!==qo&&!g.hasAttribute(Wd))){Dr&&Dr!==Ae&&(Dr.style.removeProperty("min-height"),Dr=null);let g=Ae.offsetHeight;g>0&&(Ae.style.minHeight=`${g}px`,Dr=Ae)}qo||(qo=I("div","persona-history-header-host")),s.setHeaderPlacement("external");let f=s.getHeaderElement();f.parentNode!==qo&&qo.replaceChildren(f),qo.parentNode!==Ae&&Ae.appendChild(qo),iM()},tb=()=>{Dr&&(Dr.style.removeProperty("min-height"),Dr=null),qo&&(Es?.setHeaderPlacement("inline"),qo.remove(),qo=null,lM())},Bd=null,Yp=()=>{if(Bd){if(ne.style.display="none",Jo(ne,!0),Le.hidden=!0,Jo(Le,!0),aM()){dM(),Ae.style.display=eb(),Jo(Ae,!1);return}tb(),Ae.style.display="none",Jo(Ae,!0)}};qt=Yp;let cM=s=>{let l=ne.style.display,f=Le.hidden,g=Le,v=Ae,M=Ae.style.display;Qp=v,Zy=M,Bd=()=>{Bd=null,tb(),Qp=null,ne.style.display=l,Jo(ne,!1),g.hidden=f,Jo(g,!1),Le!==g&&(Le.hidden=!1,Jo(Le,!1)),v.style.display=M,Jo(v,!1),Ae!==v&&(Ae.style.display=n.layout?.showHeader===!1?"none":"",Jo(Ae,!1))},Le.parentNode?.insertBefore(s,Le),Yp()},Sa=null,Ps=null,_i=null,wa=null,ob=()=>[Ae,_e.closeButtonWrapper,_e.clearChatButtonWrapper,ne,Le],uM=52,Od=()=>n.features?.history?.rail?.collapsible!==!1,Aa=()=>n.features?.history?.rail?.side==="right"?"right":"left",Jp=200,Zp=400,ef=s=>Math.min(Zp,Math.max(Jp,Math.round(s))),pM=()=>n.features?.history?.rail?.resizable===!0,Ni,fM=()=>{if(Ni===void 0&&(Ni=null,n.persistState!==!1))try{let s=Number(window.localStorage.getItem(`${ln()}rail-width`));s&&(Ni=s)}catch{}return Ni},Fi=()=>ef(fM()??n.features?.history?.rail?.width??260),mM=s=>{if(Ni=s,n.persistState!==!1)try{window.localStorage.setItem(`${ln()}rail-width`,String(s))}catch{}},Dd=()=>Od()&&n.features?.history?.rail?.collapsedBehavior==="overlay",_t=!1,nb=s=>{let l=I("img");return l.src=s,l.alt="",l.setAttribute("aria-hidden","true"),l},gM=()=>{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=nb(s.iconUrl):f=s.icon?ue(s.icon,20):null),f?f.cloneNode(!0):null}},hM=()=>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=nb(g.iconUrl):v=g.icon?ue(g.icon,20):null}catch(M){f(M),v=null}return v},onSelect:()=>{try{g.onSelect()}catch(M){f(M)}}}})}})??[],yM=s=>{let l=hM();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},Ui=null,rb=()=>`${ln()}rail-collapsed`,tf=()=>{if(Ui===null&&(Ui=n.features?.history?.rail?.defaultCollapsed===!0,n.persistState!==!1))try{let s=window.localStorage.getItem(rb());s&&(Ui=s==="1")}catch{}return Ui},of=s=>{if(Ui=s,n.persistState!==!1)try{window.localStorage.setItem(rb(),s?"1":"0")}catch{}},qi=()=>de==="rail"&&Od()&&!Dd()&&tf(),nf=()=>{},sb=()=>{if(Dd()){nf();return}of(!tf()),it?.view.setCollapsed(qi()),Be(),Po()},rf=()=>{let s=n.features?.history?.rail?.collapseShortcut;return!s||!fu(s)?null:{combo:s,hint:mu(s),aria:Pl(s)}},ab=()=>{c.forEach(l=>l()),c=[];let s=rf();s&&c.push(d.register({id:"history-rail-collapse",combo:s.combo,scope:n.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>ie&&de==="rail"&&Od()||Ta(),run:()=>Dd()?nf():sb()}));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}`}))};ab();let bM=300,_d="var(--persona-history-overlay-margin,8px)",Zo=null,ar=null,Nd=0,ir=null,Ma=null,ks=!1,sf=0,ib=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Ta=()=>Wn()&&Dd()&&(de??Xp())==="rail",vM=()=>ie&&!_t,Vi=()=>{Ma!==null&&clearTimeout(Ma),Ma=null},xM=()=>{lh().catch(()=>{})},lb=()=>{Vi(),_t&&(Ma=setTimeout(()=>{Ma=null,!(ks||!_t)&&(ir?.contains(document.activeElement)||ko({restoreFocus:!1}))},bM))},CM=(s,l)=>{let f=ir?.getBoundingClientRect();if(!f)return!1;let g=Zo?.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},af=s=>{_t&&(ks=CM(s.clientX,s.clientY),ks?Vi():Ma===null&&lb())},db=s=>{ie||!Ta()||(_t=!0,ji({invoker:Zo,keyboard:s?.keyboard===!0}).then(()=>{ie?!ks&&document.activeElement!==Zo&&ko():_t=!1}))},cb=()=>{let s=Di?.querySelector('[data-persona-history-focus="collapse"]');s&&(s.setAttribute("aria-label",_t?Qe.expandLabel:Qe.collapseLabel),s.setAttribute("aria-expanded",_t?"false":"true"))},ub=()=>{of(!1);let s=it;if(!_t||!s){ji({invoker:Zo});return}let l=document.activeElement===Zo;_t=!1,Fd(),s.element.remove(),df(s.element),cb(),l&&qd(),Po(),_r()},SM=()=>{of(!0),ko()};nf=()=>{!ie||_t?ub():SM()};let wM=()=>{let s=rf(),l=js({ariaLabel:Qe.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":zp,...s?{"aria-keyshortcuts":s.aria}:{}}}),f=l.button;f.addEventListener("mouseenter",()=>{ks=!0,Vi(),!(ib()||Date.now()<sf)&&db()}),f.addEventListener("mouseleave",()=>{ks=!1,sf=0,lb()}),f.addEventListener("focus",()=>{ie||xM()}),f.addEventListener("click",g=>{Wn()&&(g.detail!==0&&ib()&&!ie?db():ub())}),Zo=f,ar=l.wrapper},$i=()=>{if(ar&&!ar.isConnected&&(ar=null,Zo=null),!Ta()){ar?.remove(),ar=null,Zo=null;return}Zo||wM();let s=ar,l=Zo;if(!s||!l)return;let f=Aa()!=="right"?Ae.firstChild:null;(f??Ae.lastChild)!==s&&Ae.insertBefore(s,f),s.style.display=vM()||Nd>0?"none":"",l.setAttribute("aria-label",Qe.expandLabel),l.setAttribute("aria-expanded",ie?"true":"false"),ir&&Be()},pb=s=>{if(!_t)return;let l=s.target;l instanceof Node&&(ir?.contains(l)||ar?.contains(l)||l instanceof Element&&l.closest('.persona-dropdown-menu,[role="alertdialog"]')||ko({restoreFocus:!1}))};document.addEventListener("pointerdown",pb,!0),ge.push(()=>{document.removeEventListener("pointerdown",pb,!0),document.removeEventListener("pointermove",af),Ea?.(),Vi()});let lf=null,Ea=null,fb=16,mb=s=>{mM(ef(s)),Be(),Po()},AM=()=>{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(Jp)),s.setAttribute("aria-valuemax",String(Zp)),s.addEventListener("pointerdown",l=>{let f=Ps;if(!f||l.button!==0)return;l.preventDefault(),Ea?.();let g=l.clientX,v=f.getBoundingClientRect().width||Fi(),M=Aa()==="right"?-1:1,_=v,K=e.ownerDocument;f.style.transition="none";let j=Z=>{_=ef(v+M*(Z.clientX-g)),f.style.flex=`0 0 ${_}px`,s.setAttribute("aria-valuenow",String(_))},G=()=>{Ea=null,K.removeEventListener("pointermove",j),K.removeEventListener("pointerup",G),K.removeEventListener("pointercancel",G),f.style.removeProperty("transition");try{s.releasePointerCapture(l.pointerId)}catch{}mb(_)};Ea=G,K.addEventListener("pointermove",j),K.addEventListener("pointerup",G),K.addEventListener("pointercancel",G);try{s.setPointerCapture(l.pointerId)}catch{}}),s.addEventListener("keydown",l=>{let f=Aa()==="right"?-fb:fb,g=Fi(),v=l.key==="ArrowRight"?g+f:l.key==="ArrowLeft"?g-f:l.key==="Home"?Jp:l.key==="End"?Zp:null;v!==null&&(l.preventDefault(),mb(v))}),s},MM=(s,l)=>{if(!pM()||qi()){Ea?.(),lf?.remove();return}let f=lf??AM();lf=f,f.setAttribute("aria-label",Qe.resizeLabel),f.setAttribute("aria-valuenow",String(Fi())),f.nextElementSibling!==l&&s.insertBefore(f,l)};Be=()=>{it?.view.setRailSide(Aa());let s=Aa()==="right",l=ir;if(l){let K=Zo?Zo.getBoundingClientRect().bottom-pe.getBoundingClientRect().top:0;l.style.top=`calc(${Math.max(0,Math.round(K))}px + ${_d})`,l.style.width=`${Fi()}px`,l.style.left=s?"":_d,l.style.right=s?_d:""}let f=Ps,g=Sa,v=_i;if(!f||!g||!v)return;f.style.flex=`0 0 ${qi()?uM:Fi()}px`;let M="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=s?"":M,f.style.borderLeft=s?M:"";let _=s?v:f;g.firstElementChild!==_&&g.append(_,s?f:v),MM(g,s?f:v)};let gb=s=>{if(wa&&Ps){wa.replaceWith(s),wa=null,Be();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",pe.insertBefore(l,Ae.parentNode===pe?Ae:ne);for(let v of ob())v?.parentNode===pe&&f.appendChild(v);l.append(g,f),g.appendChild(s),Sa=l,Ps=g,_i=f,Be()},TM=()=>{if(Sa)return;let s=I("div","persona-history-rail-placeholder");s.style.cssText="flex:1 1 auto;min-height:0",wa=s,gb(s),Po()},hb=()=>{wa&&(Fd(),Po())},EM=s=>{let l=I("div","persona-history-rail-overlay");l.style.cssText=`position:absolute;bottom:${_d};display:flex;overflow:hidden;z-index:${Ga-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,pe.style.position="relative",pe.appendChild(l),l.appendChild(s),document.addEventListener("pointermove",af),ir=l,Be(),cb()},Fd=()=>{Bd?.(),ir&&(ks&&(sf=Date.now()+150),document.removeEventListener("pointermove",af),ir.remove(),ir=null);let s=Sa;if(s){Ea?.();for(let l of ob())l&&s.contains(l)&&pe.insertBefore(l,s);s.remove(),Sa=null,Ps=null,_i=null,wa=null}},yb=s=>{Di=s,s.id=zp,s.style.flex="1 1 auto",s.style.minHeight="0"},df=s=>{yb(s),(de!=="rail"||_t)&&hb(),de!=="rail"?cM(s):_t?EM(s):gb(s)},Ud=()=>{if($i(),Pb(),!ie||!it)return;let s=Xp();if(s===de)return;let l=document.activeElement,f=l instanceof HTMLElement&&(it.element.contains(l)||qo?.contains(l)===!0)?l:null;Fd(),it.element.remove(),it.view.setHeaderPlacement("inline"),de=s,it.view.setPresentation(s),it.view.setCollapsed(qi()),it.requestRender(),it.element.isConnected||df(it.element),f?.isConnected?f.focus():qd(),zt(),Po(),_r()},bb=(s,l)=>qo?.querySelector(l)??s.querySelector(l),qd=()=>{let s=it?.element??Di;if(!s)return;let l=bb(s,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(l){l.focus();return}let f=bb(s,".persona-history-title")??s;f.tabIndex=-1,f.focus()},ji=async s=>{if(!Wn()||ie)return;let l=Uo;if(!l)return;if(!_t&&Ta()&&tf()){$i();return}Vd();let f=++Oi;kd=s?.returnSurface??"conversation",Vp=s?.invoker??po;let g=Ta()&&!_t;g&&(Nd+=1,$i(),TM());let v;try{v=await lh()}catch{Hd(Qe.openHistoryLabel),g&&(Nd-=1,f===Oi&&(hb(),$i()));return}if(g&&(Nd-=1),f!==Oi||ie)return;Pd={scope:Gp()},de=Xp(),ie=!0;let M=de==="panel"&&n.layout?.showHeader!==!1&&Ae.style.display!=="none"?"external":"inline",_=n.features?.history?.rowAvatar,K=rf(),j=K?{hint:K.hint,aria:K.aria}:null,G={provider:l,context:Pd,targetId:Gy(),presentation:de,collapsible:Od(),collapsed:qi(),railSide:Aa(),renderRailHeader:n.features?.history?.rail?.renderHeader,railBrand:gM(),onToggleCollapse:sb,...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:_===!1?!1:typeof _=="string"?_:n.launcher?.iconUrl,activeConversationId:R.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:Z=>uf(Z,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Z=>Ls(Z),attachTooltip:to,onStartNew:()=>pf({focusComposer:!0}),onClose:()=>ko(),onRequestDeleteConversation:Z=>Eb(Z),onRequestClearHistory:()=>HM(),...l.resetDevice?{onRequestResetIdentity:()=>WM()}:{}};it=vw({plugins:i,config:n,getPresentation:()=>de??"panel",getReturnSurface:()=>kd,close:()=>ko(),createView:({slots:Z,renderDom:ae,onModelChange:me,railSections:Ye})=>(Es=v.createHistoryView({...G,railSections:yM(Ye),slots:Z,renderDom:ae,onModelChange:me,onAnnounce:Hd}),Es),onElementChanged:(Z,ae)=>{if(!ae?.isConnected)return df(Z);yb(Z),ae.replaceWith(Z),Yp()}}),it.view.setNewConversationRequired(Ld.recovery==="new_conversation_required"),s?.focus!==!1&&(de!=="rail"||s?.keyboard===!0)&&qd(),zt(),Po(),_r(),C.emit("history:opened",{presentation:de,returnSurface:kd,timestamp:Date.now()})},Vd=()=>{},ko=s=>{if(!ie)return;Oi+=1;let l=kd,f=Vp,g=it,v=s?.restoreFocus!==!1;ie=!1;let M=!1,_=null,K=()=>{if(!M){if(M=!0,Vd=()=>{},_!==null&&clearTimeout(_),_t=!1,Vi(),Fd(),g?.dispose(),g?.view.destroy(),g?.element.remove(),it===g&&(it=null,Es=null,Di=null,de=null,Pd=null,Vp=null),zt(),Po(),_r(),v){let G=f??po;G?.isConnected?G.focus():ws()}C.emit("history:closed",{returnSurface:l,timestamp:Date.now()})}},j=g&&g.element===g.view.element?g.view.playExit():null;if(!j){K();return}Vd=K,_=setTimeout(K,nM),j.then(K)},vb=s=>{if(!(s.key!=="Escape"||!ie||!it)){if(de==="rail"){let l=s.target;if(!(l instanceof Node)||!(it.element.contains(l)||_t&&ar?.contains(l)===!0))return}s.preventDefault(),s.stopPropagation(),ko()}};pe.addEventListener("keydown",vb),ge.push(()=>pe.removeEventListener("keydown",vb));let $d=null,xb=!1,zi=()=>{if(!Ar)return;let s=n.layout?.header?.titleSource==="conversation",l=s&&$d?.trim()||null;Ar.textContent=l??n.launcher?.title??"Chat Assistant";let f=Ar.closest(".persona-combo-btn");if(!f)return;let g=!s||R.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")},PM=s=>{s!==$d&&($d=s,zi())},Ls=s=>{xb=s?.starred===!0,PM(s&&s.title.trim()||null),zi()};zi(),pe.addEventListener("persona:title-menu-builtin",s=>{let l=s.detail?.actionId,f=R.getActiveConversationId();f&&(l==="delete"?Eb(f):l==="star"&&R.canUpdateConversations()&&ff(f,{starred:!xb}).catch(()=>{}))});let jd=0,kM=250,zd=null,Kd=()=>{zd&&clearTimeout(zd),zd=null};ge.push(Kd);let Cb=()=>{Kd();let s=As;s&&(Wi=!0,s.hidden=!1,Me.style.display="none",Bi())},Gd=()=>{jd+=1,Kd(),As&&(As.remove(),As=null,Wi=!1,Me.style.removeProperty("display"),Jo(Le,!1),Bi())},LM=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Me.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},cf=(s,l)=>Y("div",{className:ho("persona-conversation-loading-bubble",l&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:s}}),Sb=()=>Y("div",{className:"persona-conversation-loading-body"},cf("58%",!1),cf("72%",!0),cf("44%",!1)),wb=s=>{As?.remove(),As=s,s.hidden=!Wi,ne.insertBefore(s,Me),Kd(),Wi||(zd=setTimeout(Cb,kM)),Jo(Le,!0)},IM=()=>{let s={config:n,streaming:!1,location:"conversation-open",defaultRenderer:Sb},l=null,f=i.find(g=>g.renderLoadingIndicator);f?.renderLoadingIndicator&&(l=f.renderLoadingIndicator(s)),l===null&&n.loadingIndicator?.render&&(l=n.loadingIndicator.render(s)),wb(Y("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Qe.openConversationLoadingLabel}},l??Sb()))},RM=s=>{let l=()=>{uf(s,{focusComposer:!0}).catch(()=>{})},f=Wn()?()=>{Gd(),ji()}:void 0,g=(K,j)=>{let G=Y("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:K});return G.addEventListener("click",j),G},v=()=>Y("div",{className:"persona-conversation-loading-error-body"},Y("p",{className:"persona-conversation-loading-error-title",text:Qe.openConversationErrorTitle}),Y("div",{className:"persona-conversation-loading-error-actions"},g(Qe.openConversationRetryLabel,l),f?g(Qe.openConversationBackLabel,f):null)),M=Object.freeze({conversationId:s,config:n,copy:Object.freeze({title:Qe.openConversationErrorTitle,retryLabel:Qe.openConversationRetryLabel,backLabel:Qe.openConversationBackLabel}),retry:l,...f?{back:f}:{},defaultRenderer:v}),_=null;for(let K of i)if(K.renderHistoryOpenError){try{_=K.renderHistoryOpenError(M)}catch(j){console.warn("[persona] renderHistoryOpenError threw",j),_=null}if(_)break}wb(Y("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},_??v())),Cb()};C.on("history:closed",()=>{As&&Jo(Le,!0)});let uf=async(s,{focusComposer:l=!1}={})=>{let f=Ca(),g=!!it;it?.view.setActiveConversationId(s),Gd();let v=jd;IM(),ie&&(de==="panel"||_t)&&ko({restoreFocus:!1}),pa=!0;try{await R.openConversation(s,{scope:f})}catch(M){throw v===jd&&RM(s),M}finally{pa=!1}v===jd&&(Gd(),Dt.clear(),gn(),Eo(),Ap()||bd(),LM(),lr(),g||Ls(null),C.emit("history:conversationOpened",{conversationId:s,title:$d,scope:f,timestamp:Date.now()}),l&&ws())},pf=async({focusComposer:s=!1}={})=>{Gd(),await R.startNewConversation({scope:Ca()}),Ls(null),Dt.clear(),gn(),Eo(),bd(),lr();let l=R.getActiveConversationId();it?.view.setActiveConversationId(l),C.emit("history:conversationStarted",{conversationId:l,timestamp:Date.now()}),ie&&(de==="panel"||_t)&&ko({restoreFocus:!1}),s&&ws()},ff=async(s,l)=>{let f=await R.updateConversation(s,{...l,...l.title!==void 0?{title:l.title.trim()}:{}});return it?.view.applyConversationSummary(f),!it&&s===R.getActiveConversationId()&&Ls(f),f},Ab=async s=>{let l=Ca(),f=R.getActiveConversationId()===s;await R.deleteConversation(s,{scope:l}),it?.view.removeConversationSummary(s),f&&(Ls(null),Dt.clear(),gn(),Eo(),lr()),C.emit("history:conversationDeleted",{conversationId:s,scope:l,wasActive:f,timestamp:Date.now()})},Mb=async s=>{let l=s?.scope??Ca(),f=s?.allTargets?null:s?.targetId??Gy(),g=await R.clearConversationHistory({...f?{targetId:f}:{},scope:l});return Ls(null),Dt.clear(),gn(),Eo(),lr(),C.emit("history:cleared",{deleted:g.deleted,scope:l,targetId:f,timestamp:Date.now()}),g},Tb=async()=>{if(!Uo?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let s=!1;try{s=(await R.resetHistoryDevice()).remoteRevocationConfirmed}finally{Ls(null),R.clearArtifacts(),Dt.clear(),_p=null,n.clearStoredSessionId?.(),n.clearStoredConversationId?.(),V={},We.syncFromMetadata(),U?.clear&&gd(()=>U.clear(),"[AgentWidget] Failed to clear storage adapter:"),gn(),Eo(),lr(),ko({restoreFocus:!1}),ws(),ye||kt?.launcher.element.focus()}return Hd(s?Qe.identityResetNotice:Qe.identityResetUnconfirmedNotice),C.emit("history:identityReset",{remoteRevocationConfirmed:s,timestamp:Date.now()}),{remoteRevocationConfirmed:s}},mf=()=>Ln?Ce:pe,Eb=async s=>await Nu({host:mf(),title:Qe.deleteConversationConfirmTitle,description:Qe.deleteConversationConfirm,confirmLabel:Qe.deleteConversationConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await Ab(s),"deleted"):"cancelled",HM=async()=>{let s=Ca()==="verified-user";return await Nu({host:mf(),title:Qe.clearHistoryConfirmTitle,description:s?Qe.clearHistoryVerifiedConfirm:Qe.clearHistoryConfirm,confirmLabel:Qe.clearHistoryConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await Mb(),"cleared"):"cancelled"},WM=async()=>{if(!await Nu({host:mf(),title:Qe.resetIdentityConfirmTitle,description:Qe.resetIdentityConfirm,confirmLabel:Qe.resetIdentityConfirmLabel,cancelLabel:Qe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:l}=await Tb();return{outcome:"reset",remoteRevocationConfirmed:l}},en=I("button","persona-history-earlier");en.type="button",en.textContent=Qe.showEarlierMessagesLabel,en.setAttribute("data-persona-history-earlier",""),Object.assign(en.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 lr=()=>{if(!(Wn()&&!!Ld.nextMessageCursor&&!!R.getActiveConversationId())){en.remove();return}en.textContent=Qe.showEarlierMessagesLabel,en.parentNode!==ne&&ne.insertBefore(en,ne.firstChild)};en.addEventListener("click",()=>{let s=R.getActiveConversationId(),l=Ld.nextMessageCursor;if(!s||!l||en.disabled)return;en.disabled=!0;let f=ne.scrollHeight,g=ne.scrollTop;R.loadOlderMessages(s,l,{scope:Ca()}).then(()=>{ne.scrollTop=g+(ne.scrollHeight-f),Po()}).catch(()=>{}).finally(()=>{en.disabled=!1,lr()})});let BM=()=>{let s=js({ariaLabel:Qe.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(!(!Wn()||Ky())){if(ie){ko();return}ji({invoker:s.button,keyboard:l.detail===0})}}),s},Pb=()=>{if(!Wn()){Hn?.remove(),po=null,Hn=null;return}if(Hn&&!Hn.isConnected&&(po=null,Hn=null),!po&&Ae){let g=BM();po=g.button,Hn=g.wrapper;let v=_e.clearChatButtonWrapper||_e.closeButtonWrapper;v?.parentNode&&Ae.contains(v)?v.parentNode.insertBefore(Hn,v):Ae.appendChild(Hn)}if(!po||!Hn)return;let s=Ta()||ie&&de==="rail";if(Hn.style.display=s?"none":"",s){document.activeElement===po&&qd();return}let l=Ky();po.disabled=l,po.setAttribute("aria-disabled",l?"true":"false");let f=l?Qe.openHistoryBusyLabel:Qe.openHistoryLabel;po.setAttribute("aria-label",f),(n.features?.history?.presentation??"panel")==="panel"?(po.removeAttribute("aria-expanded"),po.removeAttribute("aria-controls")):(po.setAttribute("aria-expanded",ie?"true":"false"),po.setAttribute("aria-controls",zp))},Xd=!1,OM=()=>{let s=_e.clearChatButton;if(s){if(Wn()){Xd||(jp=s.getAttribute("aria-label")??"",Xd=!0),s.setAttribute("aria-label",Qe.newConversationLabel),s.removeAttribute("title");return}Xd&&(Xd=!1,jp&&s.setAttribute("aria-label",jp))}},_r=()=>{Qe=uh(n.features?.history?.copy),Pb(),$i(),OM(),lr()};Gn=_r,Wt=s=>{Ld=s,it?.view.setNewConversationRequired(s.recovery==="new_conversation_required"),Hi(s.sendBlocked||_o),lr()},Et=s=>{(s.code==="history_continuity_reset"||s.code==="conversation_deleted_recovered")&&(Dt.clear(),gn(),Eo()),Hd(s.message),it?.view.refresh()},Jy(),_r(),ge.push(()=>{Id?.(),Rd?.(),Oi+=1,Vd(),it?.dispose(),it?.view.destroy(),it=null}),n.clientToken&&R.initClientSession().then(()=>{if(Wn())return R.reconcileBootConversation({scope:Gp()})}).then(()=>{lr()}).catch(s=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",s)}),(io||n.onSSEEvent)&&R.setSSEEventCallback((s,l)=>{n.onSSEEvent?.(s,l),oe(s,l)});let kb=()=>{let s=n.resume??(Q?rr.getStoredResumableHandle?.():null);s&&typeof n.reconnectStream=="function"&&R.resumeFromHandle(s)};E?E.then(s=>{if(s){if(s.metadata&&(V=ph(s.metadata),We.syncFromMetadata()),s.messages?.length){pa=!0;try{R.hydrateMessages(s.messages)}finally{pa=!1}Sd()}s.artifacts?.length&&R.hydrateArtifacts(s.artifacts,s.selectedArtifactId??null),My(s.draft)}}).catch(s=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",s)}).finally(()=>{Lp=!0,O(),kb()}):(My(W),kb());let DM=()=>{!Ie()||ye||!(n.launcher?.composerBar?.expandOnSubmit??!0)||pt(!0,"auto")},_M=(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),rL(v)}}:s:l,gf=()=>{let l=ce.getInlineMessageFields?.();return l&&l.contentSegments.some(g=>g.kind==="mention")?l.contentSegments:void 0},dr=!1,Is=null,Qd=()=>{ce.value="",ce.style.height="auto",En(),Gi()},hf="data-persona-composer-notice",Pa=null;function NM(s){Ql(s),!(Ie()||!at)&&(at.hasAttribute(fi)||(at.setAttribute(hf,""),at.setAttribute("role","status"),at.setAttribute("aria-live","polite"),at.textContent=s,Pa&&clearTimeout(Pa),Pa=setTimeout(()=>{if(Pa=null,!!at?.hasAttribute(hf)&&(at.removeAttribute(hf),at.removeAttribute("role"),at.removeAttribute("aria-live"),u)){let l=R.getStatus();Kl(at,So(l),n.statusIndicator??{},l)}},4e3)))}function FM(){let s=ve.getState().pendingSubmission;s&&(ra(void 0),ce&&(ce.value=s.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),En()),s.options.selectedModelId&&(ve.setSelectedModelId(s.options.selectedModelId),Tr?.repaint()),s.options.activeModeIds?.length&&ed(s.options.activeModeIds),s.options.quote&&Pn(s.options.quote),ce?.focus())}let UM=s=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",s)},Lb=(s={})=>{let l=(s.overrideText??ce?.value??"").trim();return s.resolveInlineCommand&&l?(Bt?.takeInlineCommand(l)??Promise.resolve(null)).then(f=>Ib(s,l,f)):Ib(s,l,null)},Ib=(s,l,f)=>{if(f?.kind==="action"){Qd(),Bt?.clear(),as();return}let g=f?.kind==="server"?f.mentions:null,v=f?.kind==="prompt"?f.sendText:l,M=s.pending?.contentParts,_=(Je?.hasAttachments()??!1)||(M?.length??0)>0;if(!kC({text:v,hasAttachments:_,attachmentsReady:Je?.isReady()??!0,hasMentions:Bt?.hasMentions()??!1,hasServerMentions:!!g,inputDisabled:Br(),sendDisabled:Ss()}))return;let K=R.isStreaming()?rp():"block";if(K==="defer-one"&&!s.pending){if(ve.getState().pendingSubmission){NM("One message is already queued. Edit or remove it first.");return}qM({intent:s,sendText:v,serverMentions:g});return}let j={text:v,mentionRefs:[...Bt?.getMentionRefs()??[],...g?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:gf(),options:{...ve.getState().selectedModelId&&{selectedModelId:ve.getState().selectedModelId},...ve.getState().activeModeIds.length>0&&{activeModeIds:[...ve.getState().activeModeIds]},...ve.getState().quote&&{quote:{...ve.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 G=()=>{if(M?.length)return[...M];if(!Je?.hasAttachments())return;let ft=[...Je.getContentParts()];return j.text&&ft.push(sn(j.text)),ft};j.contentParts=G();let Z=()=>{gs(),DM();let ft=Bt?.collectForSubmit()??null,Qt=_M(ft,g),Nt=G();s.consumeDraft!==!1&&Qd();let It={selectedModelId:j.options.selectedModelId,activeModeIds:j.options.activeModeIds},lo=K==="interrupt";lo&&R.cancel(),R.sendMessage(j.text,{contentParts:Nt,mentions:Qt??void 0,contentSegments:j.contentSegments,viaVoice:j.viaVoice,composerOptions:It,...j.options.quote&&{quote:j.options.quote},...lo&&{interrupt:!0}}),Je?.hasAttachments()&&Je.clearAttachments(),ft&&Bt?.clear(),as();let Ze=ve.getState().activeModeIds,co=gC(Ze,n.composer?.modes);co.length!==Ze.length&&ed(co),ve.getState().quote&&Pn(void 0),yd(),dp.release(),un()},ae=n.composer?.onBeforeSend;if(!ae){Z();return}let me=new AbortController;Is=me;let Ye=ft=>{if(Is=null,ft.status==="error"){UM(ft.error);return}ft.status==="proceed"&&Z()},ct=LC(ae,j,me.signal);if(!(ct instanceof Promise)){Ye(ct);return}return ve.setPreparing(!0),ct.then(Ye).finally(()=>ve.setPreparing(!1))};function qM(s){let l=ve.getState(),f=Je?.hasAttachments()??!1,g=f?[...Je.getContentParts()]:[];f&&s.sendText&&g.push(sn(s.sendText));let v=ig({text:s.sendText,contentParts:g.length?g:void 0,mentionRefs:[...Bt?.getMentionRefs()??[],...s.serverMentions?.refs??[]],contentSegments:gf(),options:{...l.selectedModelId&&{selectedModelId:l.selectedModelId},...l.activeModeIds.length>0&&{activeModeIds:[...l.activeModeIds]},...l.quote&&{quote:{...l.quote}}},viaVoice:s.intent.viaVoice});ra(v),s.intent.consumeDraft!==!1&&Qd(),f&&Je.clearAttachments(),Bt?.clear(),as(),l.quote&&Pn(void 0),yd(),dp.release(),un(),Ql("Message queued. It sends when the response finishes.")}function VM(){let s=ve.getState().pendingSubmission;s&&(ra(void 0),Jd(s.text,{consumeDraft:!1,pending:s}))}function $M(s){if(n.messageActions?.showEdit!==!0)return;let l=R.getMessages().find(f=>f.id===s);!l||!Zf(l)||ms!==s&&(gs(),ms=s,Lr=xC({messageId:s,initialText:l.content,onSave:f=>jM(s,f),onCancel:()=>gs()}),Dt.delete(s),Yo(Me,R.getMessages(),Ht),Lr.focus())}function jM(s,l){let f=Lr;if(ms=null,Lr=null,f?.destroy(),Dt.delete(s),!R.resubmitFrom(s,{reason:"edit",replacement:{text:l,mentionRefs:[],options:{}}})){Yo(Me,R.getMessages(),Ht);return}Po()}function zM(s){if(R.isStreaming())return;let l=Jf(R.getMessages(),s);l&&(gs(),R.resubmitFrom(l,{reason:"retry"})&&Po())}td={regenerate:zM,edit:$M,quote:s=>{let f=R.getMessages().find(g=>g.id===s)?.content?.trim();f&&(Pn({text:f,messageId:s}),ce?.focus())}};let Ki=async s=>{if(!dr){dr=!0;try{await Lb({resolveInlineCommand:!0,...s})}finally{dr=!1}}};function Yd(s){Ss()||(Qd(),Jd(s,{consumeDraft:!1}))}let Jd=(s,l)=>{if(dr)return;dr=!0;let f=()=>{dr=!1};try{let g=Lb({...l,overrideText:s});g instanceof Promise?g.finally(f):f()}catch(g){throw f(),g}},KM=s=>{if(s.preventDefault(),R.isStreaming()){R.cancel(),Ho?.reset(),J?.update();return}dr||Ki()},GM=()=>n.features?.composerHistory!==!1,yf={...hg},bf=!1,Gi=()=>{yf={...hg}},XM=()=>R.getMessages().filter(s=>s.role==="user").map(s=>s.content??"").filter(s=>s.length>0),QM=s=>{if(!ce)return;bf=!0,ce.value=s,ce.dispatchEvent(new Event("input",{bubbles:!0})),bf=!1;let l=ce.value.length;ce.setSelectionRange(l,l)},YM=s=>{bf||(s.isComposing||Bt?.handleInput(s.inputType??void 0),Gi())},JM=()=>({submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:wl(ce)}),ZM=s=>{if(ce&&!Br()&&!(!s.isComposing&&Bt?.handleKeydown(s))){if(GM()&&(s.key==="ArrowUp"||s.key==="ArrowDown")&&!s.shiftKey&&!s.metaKey&&!s.ctrlKey&&!s.altKey&&!s.isComposing){let l=ce.selectionStart===0&&ce.selectionEnd===0,f=QC({direction:s.key==="ArrowUp"?"up":"down",history:XM(),currentValue:ce.value,atStart:l,state:yf});if(yf=f.state,f.handled){s.preventDefault(),f.value!==void 0&&QM(f.value);return}}if(Zx(s,JM())){if(R.isStreaming()){if(s.preventDefault(),rp()==="block"||dr||Ss())return;Gi(),Ki();return}if(dr){s.preventDefault();return}if(Ss()){s.preventDefault();return}Gi(),s.preventDefault(),we.click()}}},Rb=s=>{if(!(s.key!=="Escape"||s.isComposing)&&s.composedPath().includes(pe)){if(Is){Is.abort(),Is=null,s.preventDefault(),s.stopImmediatePropagation();return}R.isStreaming()&&(R.cancel(),Ho?.reset(),J?.update(),Gi(),s.preventDefault(),s.stopImmediatePropagation())}},eT=async s=>{if(n.attachments?.enabled!==!0||!Je||Br())return;let l=eL(s.clipboardData);l.length!==0&&(s.preventDefault(),await Je.handleFiles(l))},tn=null,Bn=!1,ka=null,Ct=null,vf=()=>n.voiceRecognition?.completionBehavior==="review";function Rs(s){re?.setAttribute("data-state",s),s==="recording"?oT():wf()}let Hb="--persona-voice-level",xf=.5,La=null,Cf=-1,Zd=0,Wb=()=>{let s=[],l=Oo??re?.parentElement??null;return l&&s.push(l),Le&&s.push(Le),s},Sf=s=>{let l=Math.round(Math.max(0,Math.min(1,s))*100)/100;if(l!==Cf){Cf=l;for(let f of Wb())f.style.setProperty(Hb,String(l))}},tT=()=>{Cf=-1,Zd=0;for(let s of Wb())s.style.removeProperty(Hb)};function oT(){if(La!==null)return;if(typeof requestAnimationFrame!="function"){Sf(u?R.getVoiceLevel()??xf:xf);return}let s=()=>{La=requestAnimationFrame(s);let l=u?R.getVoiceLevel():null;if(l===null){Sf(xf);return}Zd+=(l-Zd)*.3,Sf(Zd)};La=requestAnimationFrame(s)}function wf(){La!==null&&(cancelAnimationFrame(La),La=null),tT()}let Bb=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ec=(s="user")=>{if(Bn||R.isStreaming())return;let l=Bb();if(!l)return;tn=new l;let f=n.voiceRecognition??{},g=f.pauseDuration??2e3;tn.continuous=f.provider?.browser?.continuous??!0,tn.interimResults=!0,tn.lang=f.provider?.browser?.language??"en-US";let v=ce.value;tn.onresult=M=>{let _="",K="";for(let G=0;G<M.results.length;G++){let Z=M.results[G],ae=Z[0].transcript;Z.isFinal?_+=ae+" ":K=ae}let j=v+_+K;ce.value=j,En(),ka&&clearTimeout(ka),(_||K)&&(ka=window.setTimeout(()=>{if(ce.value.trim()&&tn&&Bn){if(Nr(),vf())return;Ki({viaVoice:!0})}},g))},tn.onerror=M=>{M.error!=="no-speech"&&Nr()},tn.onend=()=>{if(Bn){let M=ce.value.trim();!vf()&&M&&M!==v.trim()&&Ki({viaVoice:!0}),Nr()}};try{if(tn.start(),Bn=!0,je.active=!0,s!=="system"&&(je.manuallyDeactivated=!1),tr(s),mn(),un(),re){let M=n.voiceRecognition??{};Ct={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:M.iconName??"mic",iconSize:parseFloat(M.iconSize??"")||yo};let _=M.recordingBackgroundColor,K=M.recordingIconColor,j=M.recordingBorderColor;if(re.classList.add("persona-voice-recording"),Rs("recording"),re.style.backgroundColor=_??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=K??"var(--persona-voice-recording-indicator, #ffffff)",K){let G=re.querySelector("svg");G&&G.setAttribute("stroke",K)}j&&(re.style.borderColor=j),re.setAttribute("aria-label","Stop voice recognition")}}catch{Nr("system")}},Nr=(s="user")=>{if(Bn){if(Bn=!1,ka&&(clearTimeout(ka),ka=null),tn){try{tn.stop()}catch{}tn=null}if(je.active=!1,tr(s),mn(),un(),re){if(re.classList.remove("persona-voice-recording"),Rs("idle"),Ct){re.style.backgroundColor=Ct.backgroundColor,re.style.color=Ct.color,re.style.borderColor=Ct.borderColor;let l=re.querySelector("svg");l&&l.setAttribute("stroke",Ct.color||"currentColor"),Ct=null}re.setAttribute("aria-label","Start voice recognition")}}},Af=()=>{if(!re||Ct)return;let s=n.voiceRecognition??{};Ct={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:s.iconName??"mic",iconSize:parseFloat(s.iconSize??"")||yo}},Mf=(s,l)=>{if(!re)return;let f=re.querySelector("svg");f&&f.remove();let g=Ct?.iconSize??(parseFloat(n.voiceRecognition?.iconSize??"")||yo),v=ue(s,g,l,1.5);v&&re.appendChild(v)},tc=()=>{re&&re.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ia=()=>{if(!re)return;Af();let s=n.voiceRecognition??{},l=s.recordingBackgroundColor,f=s.recordingIconColor,g=s.recordingBorderColor;if(tc(),re.classList.add("persona-voice-recording"),Rs("recording"),re.style.backgroundColor=l??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let v=re.querySelector("svg");v&&v.setAttribute("stroke",f)}g&&(re.style.borderColor=g),re.setAttribute("aria-label","Stop voice recognition")},nT=()=>{if(!re)return;Af();let s=n.voiceRecognition??{},l=R.getVoiceInterruptionMode(),f=s.processingIconName??"loader",g=s.processingIconColor??Ct?.color??"",v=s.processingBackgroundColor??Ct?.backgroundColor??"",M=s.processingBorderColor??Ct?.borderColor??"";tc(),re.classList.add("persona-voice-processing"),Rs("processing"),re.style.backgroundColor=v,re.style.borderColor=M;let _=g||"currentColor";re.style.color=_,Mf(f,_),re.setAttribute("aria-label","Processing voice input"),l==="none"&&(re.style.cursor="default")},rT=()=>{if(!re)return;Af();let s=n.voiceRecognition??{},l=R.getVoiceInterruptionMode(),f=l==="cancel"?"square":l==="barge-in"?"mic":"volume-2",g=s.speakingIconName??f,v=s.speakingIconColor??(l==="barge-in"?s.recordingIconColor??Ct?.color??"":Ct?.color??""),M=s.speakingBackgroundColor??(l==="barge-in"?s.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Ct?.backgroundColor??""),_=s.speakingBorderColor??(l==="barge-in"?s.recordingBorderColor??"":Ct?.borderColor??"");tc(),re.classList.add("persona-voice-speaking"),Rs("speaking"),re.style.backgroundColor=M,re.style.borderColor=_;let K=v||"currentColor";re.style.color=K,Mf(g,K);let j=l==="cancel"?"Stop playback and re-record":l==="barge-in"?"Speak to interrupt":"Agent is speaking";re.setAttribute("aria-label",j),l==="none"&&(re.style.cursor="default"),l==="barge-in"&&re.classList.add("persona-voice-recording")},cr=()=>{re&&(tc(),Rs("idle"),Ct&&(re.style.backgroundColor=Ct.backgroundColor??"",re.style.color=Ct.color??"",re.style.borderColor=Ct.borderColor??"",Mf(Ct.iconName,Ct.color||"currentColor"),Ct=null),re.style.cursor="",re.setAttribute("aria-label","Start voice recognition"))},Tf=()=>{if(!Br()){if(n.voiceRecognition?.provider?.type==="runtype"){let s=R.getVoiceStatus(),l=R.getVoiceInterruptionMode();if(l==="none"&&(s==="processing"||s==="speaking"))return;if(l==="cancel"&&(s==="processing"||s==="speaking")){R.stopVoicePlayback();return}if(R.isBargeInActive()){R.stopVoicePlayback(),R.deactivateBargeIn().then(()=>{je.active=!1,je.manuallyDeactivated=!0,mn(),tr("user"),cr()});return}R.toggleVoice().then(()=>{je.active=R.isVoiceActive(),je.manuallyDeactivated=!R.isVoiceActive(),mn(),tr("user"),R.isVoiceActive()?Ia():cr()});return}if(Bn){let s=ce.value.trim();je.manuallyDeactivated=!0,mn(),Nr("user"),s&&!vf()&&Ki()}else je.manuallyDeactivated=!1,mn(),ec("user")}};sp=Tf,re&&ge.push(()=>{n.voiceRecognition?.provider?.type==="runtype"?(R.isVoiceActive()&&R.toggleVoice(),cr()):Nr("system")});let sT=C.on("assistant:complete",()=>{ve.getState().pendingSubmission&&setTimeout(()=>{R.isStreaming()||VM()},0)});ge.push(sT);let aT=C.on("assistant:complete",()=>{Sy&&(je.active||je.manuallyDeactivated||Sy==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{!je.active&&!je.manuallyDeactivated&&(n.voiceRecognition?.provider?.type==="runtype"?R.toggleVoice().then(()=>{je.active=R.isVoiceActive(),tr("auto"),R.isVoiceActive()&&Ia()}):ec("auto"))},600))});ge.push(aT);let iT=C.on("action:resubmit",()=>{setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)});ge.push(iT);let Ob=()=>{pt(!ye,"user")},kt=null,fo=null;if(Se&&!Ie()){let{instance:s,element:l}=jg({config:n,plugins:i,onToggle:Ob});kt=s,s||(fo=l)}kt?e.appendChild(kt.element):fo&&e.appendChild(fo),Ri(),ca(),Md(),Bp(),Hi(R.isStreaming()),Ap()||(Do()==="follow"?Hr(!0):bd()),TA(),ke&&(!Se||Ie()?setTimeout(()=>ws(),0):ye&&setTimeout(()=>ws(),200));let Hs=null,Db=()=>{Hs&&(Hs.disconnect(),Hs.observe(Le),Hs.observe(pe))},Xi=()=>{if(Ie()){ss(),Ri();return}let s=wt(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,_=g&&M&&Se;try{if(_){is(),Si=dd();return}let K=!1;Tt&&(Tt=!1,is(),K=!0);let j=dd();if(!K&&j!==Si&&(is(),K=!0),Si=j,K&&sd(),!Se&&!s){Ce.style.height="",Ce.style.width="";return}if(!l&&!s){let Z=n?.launcher?.width??n?.launcherWidth??$o;Ce.style.width=Z,Ce.style.maxWidth=Z}ld(),ay()}finally{if(ss(),Zl(),Ri(),ye&&Se){let j=(e.ownerDocument.defaultView??window).innerWidth<=(n.launcher?.mobileBreakpoint??640),G=n.launcher?.sidebarMode??!1,Z=n.launcher?.mobileFullscreen??!0,ae=wt(n)&&Z&&j,me=G||Z&&j&&Se||ae;if(me&&!Rn){let Ye=e.getRootNode(),ct=Ye instanceof ShadowRoot?Ye.host:e.closest(".persona-host");ct&&!In&&(In=Sg(ct,n.launcher?.zIndex??ao)),Rn=wg(e.ownerDocument)}else me||(In?.(),In=null,Rn?.(),Rn=null)}}};Xi();let oc=e.ownerDocument.defaultView??window;if(oc.addEventListener("resize",Xi),ge.push(()=>oc.removeEventListener("resize",Xi)),typeof ResizeObserver<"u"){Hs=new ResizeObserver(()=>{Zl()}),Db(),ge.push(()=>{Hs?.disconnect(),Hs=null});let s=new ResizeObserver(()=>{Ud()});s.observe(pe),ge.push(()=>s.disconnect())}oc.addEventListener("resize",Ud),ge.push(()=>oc.removeEventListener("resize",Ud)),Fo=ne.scrollTop;let _b=jn(ne),Nb=()=>{let s=ne.scrollTop,l=jn(ne),f=l<_b;if(_b=l,!Mr()){Fo=s,zt();return}let{action:g,nextLastScrollTop:v}=rS({following:No.isFollowing(),currentScrollTop:s,lastScrollTop:Fo,nearBottom:$s(ne,Zn),userScrollThreshold:SA,isAutoScrolling:To||ud||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Fo=v,g==="resume"){vd()||Eo();return}g==="pause"&&Ei()};if(ne.addEventListener("scroll",Nb,{passive:!0}),ge.push(()=>ne.removeEventListener("scroll",Nb)),typeof ResizeObserver<"u"){let s=new ResizeObserver(()=>{HA(),Hf(Me)});s.observe(Me),s.observe(ne),ge.push(()=>s.disconnect())}let Fb=()=>{Mr()&&No.isFollowing()&&vd()&&Ei()},Ub=ne.ownerDocument;Ub.addEventListener("selectionchange",Fb),ge.push(()=>{Ub.removeEventListener("selectionchange",Fb)});let lT=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),qb=s=>{lT.has(s.key)&&(vs(),Eh()&&Mr()&&No.isFollowing()&&Ei())},Vb=s=>{s.target?.closest("a, button, [tabindex], input, textarea, select")&&(vs(),Eh()&&Mr()&&No.isFollowing()&&Ei())};ne.addEventListener("keydown",qb),ne.addEventListener("focusin",Vb),ge.push(()=>{ne.removeEventListener("keydown",qb),ne.removeEventListener("focusin",Vb)});let $b=s=>{if(s.deltaY!==0&&vs(),!Mr())return;let l=sS({following:No.isFollowing(),deltaY:s.deltaY,nearBottom:$s(ne,Zn),resumeWhenNearBottom:!0});l==="pause"?Ei():l==="resume"&&!vd()&&Eo()};ne.addEventListener("wheel",$b,{passive:!0}),ne.addEventListener("touchmove",vs,{passive:!0}),ne.addEventListener("pointerdown",vs,{passive:!0}),ge.push(()=>{ne.removeEventListener("touchmove",vs),ne.removeEventListener("pointerdown",vs)}),ge.push(()=>ne.removeEventListener("wheel",$b)),Ot.addEventListener("click",()=>{gn(),ne.scrollTop=ne.scrollHeight,Fo=ne.scrollTop,Eo(),Hr(!0),zt()}),ge.push(()=>Ot.remove()),ge.push(()=>{Ey(),gn()});let jb=()=>{Ue&&(us&&(Ue.removeEventListener("click",us),us=null),Ee()?(Ue.style.display="",us=()=>{pt(!1,"user")},Ue.addEventListener("click",us)):Ue.style.display="none")};jb(),(()=>{let{clearChatButton:s}=_e;s&&s.addEventListener("click",()=>{if(Wn()){pf({focusComposer:!0}).catch(f=>{n.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}R.clearMessages(),Dt.clear(),Eo(),Kr(_e.composerOverlay);try{localStorage.removeItem(pi),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${pi}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==pi)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),U?.clear&&gd(()=>U.clear(),"[AgentWidget] Failed to clear storage adapter:"),V={},We.syncFromMetadata(),Je?.clearAttachments(),yd(),ra(void 0),Pn(void 0),gs(),et?.clear(),Ho?.reset(),J?.update()})})();let zb=[["keydown",ZM],["input",YM],["input",En],["input",as],["keyup",as],["paste",eT],["focus",cA]],Kb=s=>{if(s)for(let[l,f]of zb)ot?.addListener(s,l,f)},dT=s=>{if(s)for(let[l,f]of zb)ot?.removeListener(s,l,f)},Gb=()=>{ot&&(ot.addListener(ot.form,"submit",KM),ot.addListener(ot.footer,"click",as),Kb(ce),re&&ot.addListener(re,"click",Tf))};Gb();let Xb=()=>{Bt?.onComposerSwap((s,l)=>{dT(l),ce=s,ot&&(ot.input=s),Kb(s),ip(),Pp(),En()})};Xb();let Ef=!1;function Qb(){if(!Ef){Ef=!0;try{let s=ce?.value??"",l=Le.ownerDocument??document,f=ce?l.activeElement===ce:!1;wf(),ot?.destroy(),ot=null,Bt?.destroy(),Bt=null;let g=null,v=()=>(g=Ie()?Su({config:n}):Xs({config:n}),g.footer),M=Dh(v)??v();Wo.replaceComposer(M),Le=Wo.composer.footer;let _=g!==null&&M===g.footer;aa=!_,Th=_?g.setSendButtonMode:()=>{},Oh(Le),Nh(Le),Fh(),Uh(),qh(),Xb(),Vh(),lp(),$h(),Gb();let K=cs.indexOf(Jn);Jn.destroy(),Jn=Dl(wr),K>=0&&(cs[K]=Jn),ce&&(ce.value=s),En(),as(),Md(),ca(),Hi(R.isStreaming()),je.active&&Rs("recording"),is(),Db(),ss(),un(),wd(),f&&ce?.focus()}finally{Ef=!1}}}let Qi=e.ownerDocument??document;Qi.addEventListener("keydown",Rb,!0);let Yb=()=>{xp()},Jb=()=>{Qi.visibilityState==="hidden"&&xp()};typeof window<"u"&&(window.addEventListener("pagehide",Yb),Qi.addEventListener("visibilitychange",Jb),ge.push(()=>{window.removeEventListener("pagehide",Yb),Qi.removeEventListener("visibilitychange",Jb)}));let Zb="persona-attachment-drop-active",Yi=0,Pf=()=>{Yi=0,pe.classList.remove(Zb)},Ra=()=>n.attachments?.enabled===!0&&Je!==null&&!Br(),ev=s=>{!ju(s.dataTransfer)||!Ra()||(Yi++,Yi===1&&pe.classList.add(Zb))},tv=s=>{!ju(s.dataTransfer)||!Ra()||(Yi--,Yi<=0&&Pf())},ov=s=>{!ju(s.dataTransfer)||!Ra()||(s.preventDefault(),s.dataTransfer.dropEffect="copy")},nv=s=>{if(!ju(s.dataTransfer)||!Ra())return;s.preventDefault(),s.stopPropagation(),Pf();let l=Array.from(s.dataTransfer.files??[]);l.length!==0&&Je.handleFiles(l)},Fr=!0;pe.addEventListener("dragenter",ev,Fr),pe.addEventListener("dragleave",tv,Fr),e.addEventListener("dragover",ov,Fr),e.addEventListener("drop",nv,Fr);let nc=e.ownerDocument,rv=s=>{Ra()&&s.preventDefault()},sv=s=>{Ra()&&s.preventDefault()};nc.addEventListener("dragover",rv),nc.addEventListener("drop",sv),ge.push(()=>{ot?.destroy(),ot=null,wf(),kn?.destroy(),kn=null,Qn?.destroy(),Qn=null,Er?.destroy(),Er=null,Pr?.destroy(),Pr=null,Tr=null,np=null,xp(),Ti.destroy(),Pa&&clearTimeout(Pa),gs(),Is?.abort(),Is=null,Je?.destroy(),Je=null,ve.destroy(),Qi.removeEventListener("keydown",Rb,!0),Bt?.destroy()}),ge.push(()=>{pe.removeEventListener("dragenter",ev,Fr),pe.removeEventListener("dragleave",tv,Fr),e.removeEventListener("dragover",ov,Fr),e.removeEventListener("drop",nv,Fr),nc.removeEventListener("dragover",rv),nc.removeEventListener("drop",sv),Pf()}),ge.push(()=>{R.cancel()}),kt?ge.push(()=>{kt?.destroy()}):fo&&ge.push(()=>{fo?.remove()});let Lt={update(s){let l=n.toolCall,f=n.messageActions,g=n.layout?.messages,v=n.colorScheme,M=n.loadingIndicator,_=n.iterationDisplay,K=n.features?.showReasoning,j=n.features?.showToolCalls,G=n.features?.toolCallDisplay,Z=n.features?.reasoningDisplay,ae=n.features?.streamAnimation?.type,me=n.features?.history?.enabled===!0,Ye=n.features?.history?.provider,ct=n.getIdentityProof,ft=n.clientToken,Qt=n.contextMentions;n=Du({...n,features:a},s),a=n.features,n=Ul(n),r(),mp(),Vs(e,n),Nl(e,n),Fl(e,n),Be(),fn(),n.colorScheme!==v&&iy();let Nt=ql.getForInstance(n.plugins);i.length=0,i.push(...Nt),ab(),Se=n.launcher?.enabled??!0,mt=n.launcher?.autoExpand??!1,wn=n.features?.showReasoning??!0,Ko=n.features?.showToolCalls??!0,An=n.features?.scrollToBottom??{};let It=Do();Go=n.features?.scrollBehavior??{},It!==Do()&&(gn(),Eo()),Cy(),Lh(),zt();let lo=io;if(io=n.features?.showEventStreamToggle??!1,io&&!lo){if(et||(se(),R.setSSEEventCallback((ee,ze)=>{n.onSSEEvent?.(ee,ze),oe(ee,ze)})),!tt&&Ae){let ee=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"+(ee?.toggleButton?" "+ee.toggleButton:"");tt=I("button",ze),tt.style.width="28px",tt.style.height="28px",tt.style.color=vo.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let Xe=Ft($a,"18px","currentColor",1.5);Xe&&tt.appendChild(Xe);let rt=_e.clearChatButtonWrapper,St=_e.closeButtonWrapper,ro=rt||St;ro&&ro.parentNode===Ae?Ae.insertBefore(tt,ro):Ae.appendChild(tt),tt.addEventListener("click",()=>{S?sa():ap()})}}else!io&&lo&&(sa(),tt&&(tt.remove(),tt=null),et?.clear(),Kn?.destroy(),et=null,Kn=null,Ho?.reset(),Ho=null,dn=null);if(n.launcher?.enabled===!1&&kt&&(kt.destroy(),kt=null),n.launcher?.enabled===!1&&fo&&(fo.remove(),fo=null),n.launcher?.enabled!==!1&&!kt&&!fo){let{instance:ee,element:ze}=jg({config:n,plugins:i,onToggle:Ob});kt=ee,ee||(fo=ze),e.appendChild(ze)}kt&&kt.update(n),zi(),ns&&n.launcher?.subtitle!==void 0&&(ns.textContent=n.launcher.subtitle);let Ze=n.layout?.header;if(Ze?.layout!==Ge&&Ae){let ee=Ze?oi(n,Ze,{showClose:Ee(),onClose:()=>pt(!1,"user")}):br({config:n,showClose:Ee(),onClose:()=>pt(!1,"user")});Wo.replaceHeader(ee),Ae=Wo.header.element,Pt=Wo.header.iconHolder,Ar=Wo.header.headerTitle,ns=Wo.header.headerSubtitle,Ue=Wo.header.closeButton,Ge=Ze?.layout,zi()}else if(Ze){if(Pt&&(Pt.style.display=Ze.showIcon===!1?"none":""),Ar&&(Ar.style.display=Ze.showTitle===!1?"none":""),ns&&(ns.style.display=Ze.showSubtitle===!1?"none":""),Ue){let ee=Ee()&&Ze.showCloseButton!==!1;Ue.style.display=ee?"":"none"}if(_e.clearChatButtonWrapper){let ee=Ze.showClearChat;if(ee!==void 0){_e.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:ze}=_e;ze&&!ze.classList.contains("persona-absolute")&&(ee?ze.classList.remove("persona-ml-auto"):ze.classList.add("persona-ml-auto"))}}}let On=n.layout?.showHeader!==!1;Ae&&(Ae.style.display=On?"":"none");let ur=n.layout?.showFooter!==!1;Le&&(Le.style.display=ur?"":"none"),ss(),zt(),Se!==qe?Se?pt(mt,"auto"):(ye=!0,Ri()):mt!==z&&pt(mt,"auto"),z=mt,qe=Se,Xi(),jb();let Ws=JSON.stringify(n.toolCall)!==JSON.stringify(l),B=JSON.stringify(n.messageActions)!==JSON.stringify(f),Te=JSON.stringify(n.layout?.messages)!==JSON.stringify(g),Re=n.loadingIndicator?.render!==M?.render||n.loadingIndicator?.renderIdle!==M?.renderIdle||n.loadingIndicator?.showBubble!==M?.showBubble,xe=n.iterationDisplay!==_,Kt=(n.features?.showReasoning??!0)!==(K??!0)||(n.features?.showToolCalls??!0)!==(j??!0)||JSON.stringify(n.features?.toolCallDisplay)!==JSON.stringify(G)||JSON.stringify(n.features?.reasoningDisplay)!==JSON.stringify(Z);(Ws||B||Te||Re||xe||Kt)&&R&&(hs++,Yo(Me,R.getMessages(),Ht));let lt=n.features?.streamAnimation?.type;if(lt!==ae&&lt&&lt!=="none"){let ee=hp(lt,n.features?.streamAnimation?.plugins);ee&&Wl(ee,e)}let Pe=n.launcher??{},hn=Pe.headerIconHidden??!1,Mt=n.layout?.header?.showIcon,no=hn||Mt===!1,Gt=Pe.headerIconName,Rt=Pe.headerIconSize??"48px";if(Pt){let ee=Ae,ze=ee?.querySelector(".persona-flex-col");if(no)Pt.style.display="none",ee&&ze&&!ee.contains(ze)&&ee.insertBefore(ze,ee.firstChild);else{if(Pt.style.display="",Pt.style.height=Rt,Pt.style.width=Rt,ee&&ze&&(ee.contains(Pt)?Pt.nextSibling!==ze&&(Pt.remove(),ee.insertBefore(Pt,ze)):ee.insertBefore(Pt,ze)),Gt){let rt=parseFloat(Rt)||24,St=ue(Gt,rt*.6,"currentColor",1);St?Pt.replaceChildren(St):Pt.textContent=Pe.agentIconText??"\u{1F4AC}"}else if(Pe.iconUrl){let rt=Pt.querySelector("img");if(rt)rt.src=Pe.iconUrl,rt.style.height=Rt,rt.style.width=Rt;else{let St=document.createElement("img");St.src=Pe.iconUrl,St.alt="",St.className="persona-rounded-xl persona-object-cover",St.style.height=Rt,St.style.width=Rt,Pt.replaceChildren(St)}}else{let rt=Pt.querySelector("svg"),St=Pt.querySelector("img");(rt||St)&&Pt.replaceChildren(),Pt.textContent=Pe.agentIconText??"\u{1F4AC}"}let Xe=Pt.querySelector("img");Xe&&(Xe.style.height=Rt,Xe.style.width=Rt)}}let Oe=n.layout?.header?.showTitle,Vo=n.layout?.header?.showSubtitle;if(Ar&&(Ar.style.display=Oe===!1?"none":""),ns&&(ns.style.display=Vo===!1?"none":""),Ue){let ee=Ee()&&n.layout?.header?.showCloseButton!==!1;if(Ue.style.display=ee?"":"none",!Ie()){let Jt=Pe.closeButtonSize??"";Ue.style.height=Jt,Ue.style.width=Jt,Ue.style.minWidth=Jt,Ue.style.minHeight=Jt}let ze=Pe.closeButtonPlacement??"inline",{closeButtonWrapper:Xe}=_e,rt=ze==="top-right",St=Xe?.classList.contains("persona-absolute");if(Xe&&rt!==St)if(Xe.remove(),rt){Xe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Jt=_i??pe;Jt.style.position="relative",Jt.appendChild(Xe)}else{let Jt=Pe.clearChat?.placement??"inline",Zt=Pe.clearChat?.enabled??!0;Xe.className=Zt&&Jt==="inline"?"":"persona-ml-auto",Ae&&Ae.appendChild(Xe)}if(Ue.style.color=Pe.closeButtonColor||vo.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 Jt=Pe.closeButtonBorderWidth||"0px",Zt=Pe.closeButtonBorderColor||"transparent";Ue.style.border=`${Jt} solid ${Zt}`,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=""),vu(Ue,Pe.closeButtonIconName??"x",{iconSize:Ie()?Ug:void 0,iconText:Pe.closeButtonIconText??"\xD7"});let ro=Pe.closeButtonTooltipText??"Close chat",yn=Pe.closeButtonShowTooltip??!0;Ue.setAttribute("aria-label",ro),Xe&&to({anchor:Ue,trigger:Xe,text:()=>Ue?.getAttribute("aria-label")??ro,enabled:yn})}let{clearChatButton:Ve,clearChatButtonWrapper:Ne}=_e;if(Ve){let ee=Pe.clearChat??{},ze=ee.enabled??!0,Xe=n.layout?.header?.showClearChat,rt=Xe!==void 0?Xe:ze,St=ee.placement??"inline";if(Ne){Ne.style.display=rt?"":"none";let{closeButtonWrapper:ro}=_e;!Ie()&&ro&&!ro.classList.contains("persona-absolute")&&(rt?ro.classList.remove("persona-ml-auto"):ro.classList.add("persona-ml-auto"));let yn=St==="top-right",Jt=Ne.classList.contains("persona-absolute");if(!Ie()&&yn!==Jt&&rt){if(Ne.remove(),yn){Ne.className="persona-absolute persona-top-4 persona-z-50",Ne.style.right="48px";let _n=_i??pe;_n.style.position="relative",_n.appendChild(Ne)}else{Ne.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ne.style.right="";let _n=_e.closeButtonWrapper;Ae&&_n&&_n.parentElement===Ae?Ae.insertBefore(Ne,_n):Ae&&Ae.appendChild(Ne)}let Zt=_e.closeButtonWrapper;Zt&&!Zt.classList.contains("persona-absolute")&&(yn?Zt.classList.add("persona-ml-auto"):Zt.classList.remove("persona-ml-auto"))}}if(rt){if(!Ie()){let Zt=ee.size??"";Ve.style.height=Zt,Ve.style.width=Zt,Ve.style.minWidth=Zt,Ve.style.minHeight=Zt}let ro=ee.iconColor??"";if(Ve.style.color=ro||vo.actionIconColor,vu(Ve,ee.iconName??"refresh-cw",{iconSize:Ie()?qg:void 0}),ee.backgroundColor?(Ve.style.backgroundColor=ee.backgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let Zt=ee.borderWidth||"0px",_n=ee.borderColor||"transparent";Ve.style.border=`${Zt} solid ${_n}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");ee.borderRadius?(Ve.style.borderRadius=ee.borderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),ee.paddingX?(Ve.style.paddingLeft=ee.paddingX,Ve.style.paddingRight=ee.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),ee.paddingY?(Ve.style.paddingTop=ee.paddingY,Ve.style.paddingBottom=ee.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let yn=ee.tooltipText??"Clear chat",Jt=ee.showTooltip??!0;Ve.setAttribute("aria-label",yn),Ne&&to({anchor:Ve,trigger:Ne,text:()=>Ve?.getAttribute("aria-label")??yn,enabled:Jt})}}let gt=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Vl],nt=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Zs.message,Zs.messageAndClick];We=$l({parsers:gt,handlers:nt,getSessionMetadata:fe,updateSessionMetadata:le,emit:C.emit,documentRef:typeof document<"u"?document:null}),Ht=Ew(n,We,ea),YA(),R.updateConfig(n),(n.features?.history?.enabled===!0!==me||n.features?.history?.provider!==Ye||n.getIdentityProof!==ct||n.clientToken!==ft)&&(ko({restoreFocus:!1}),Jy()),_r(),Ud(),Yo(Me,R.getMessages(),Ht),ca(),Md(),XA(),Hi(R.isStreaming()),Qt!==n.contextMentions&&Qb();let ut=n.voiceRecognition?.enabled===!0,ht=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),pr=n.voiceRecognition?.provider?.type==="runtype";if(ut&&(ht||pr))if(!re||!Oo){let ee=Ya(n);if(ee){re=ee.button,Oo=ee.wrapper;let ze=Tn&&Tn.parentElement===Gl?Tn:null;Gl?Gl.insertBefore(Oo,ze):cn?.appendChild(Oo),ot&&(ot.micButton=re),ot?.addListener(re,"click",Tf),re.disabled=R.isStreaming()}}else{let ee=n.voiceRecognition??{},ze=n.sendButton??{},Xe=ee.iconName??"mic",rt=ee.iconSize,St=parseFloat(rt??"")||yo;re.classList.add(jo),re.classList.toggle(bn,!rt),re.style.width=rt??"",re.style.height=rt??"",re.style.minWidth=rt??"",re.style.minHeight=rt??"";let ro=ee.iconColor??ze.textColor;re.innerHTML="";let yn=ue(Xe,St,ro||"currentColor",1.5);yn?re.appendChild(yn):re.textContent="\u{1F3A4}";let Jt=ee.backgroundColor??ze.backgroundColor;Jt?re.style.backgroundColor=Jt:re.style.backgroundColor="",ro?re.style.color=ro:re.style.color="var(--persona-text, #111827)",ee.borderWidth?(re.style.borderWidth=ee.borderWidth,re.style.borderStyle="solid"):(re.style.borderWidth="",re.style.borderStyle=""),ee.borderColor?re.style.borderColor=ee.borderColor:re.style.borderColor="",ee.paddingX?(re.style.paddingLeft=ee.paddingX,re.style.paddingRight=ee.paddingX):(re.style.paddingLeft="",re.style.paddingRight=""),ee.paddingY?(re.style.paddingTop=ee.paddingY,re.style.paddingBottom=ee.paddingY):(re.style.paddingTop="",re.style.paddingBottom="");let Zt=ee.tooltipText??"Start voice recognition",_n=ee.showTooltip??!1;re.setAttribute("aria-label",Zt),Oo&&to({anchor:re,trigger:Oo,text:()=>re?.getAttribute("aria-label")??Zt,enabled:_n}),Oo.style.display="",re.disabled=R.isStreaming()}else re&&Oo&&(Oo.style.display="none",n.voiceRecognition?.provider?.type==="runtype"?R.isVoiceActive()&&R.toggleVoice():Bn&&Nr());if(n.attachments?.enabled===!0){if(!Ao||!At){let ee=n.attachments??{};Mo||(Mo=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Mo.style.display="none",(ce.parentElement??cn).insertBefore(Mo,ce)),vt||(vt=document.createElement("input"),vt.type="file",vt.accept=(ee.allowedTypes??yr).join(","),vt.multiple=(ee.maxFiles??4)>1,vt.style.display="none",vt.setAttribute("aria-label","Attach files"),(ce.parentElement??cn).insertBefore(vt,ce)),Ao=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 ${jo} ${bn}`),At.type="button",At.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let ze=ee.buttonIconName??"paperclip";At.style.fontSize="18px",At.style.lineHeight="1";let Xe=ue(ze,yo,"currentColor",1.5);Xe?At.appendChild(Xe):At.textContent="\u{1F4CE}",At.addEventListener("click",St=>{St.preventDefault(),vt?.click()}),Ao.appendChild(At);let rt=ee.buttonTooltipText??"Attach file";to({anchor:At,trigger:Ao,text:()=>At?.getAttribute("aria-label")??rt}),Yu?Yu.append(Ao):cn.appendChild(Ao),ot&&(ot.attachmentButton=At,ot.attachmentInput=vt??void 0,ot.attachmentPreviews=Mo??void 0),!Je&&vt&&Mo&&(Je=qs.fromConfig(ee,Ih),Je.setPreviewsContainer(Mo),ot?.addListener(vt,"change",async()=>{Je&&vt?.files&&(await Je.handleFileSelect(vt.files),vt.value="")}))}else{Ao.style.display="";let ee=n.attachments??{};vt&&(vt.accept=(ee.allowedTypes??yr).join(","),vt.multiple=(ee.maxFiles??4)>1),Je&&Je.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles,adapter:ee.adapter})}if(pe.querySelector(".persona-attachment-drop-overlay")?.remove(),pe.appendChild(Pw(n.attachments?.dropOverlay)),At){let ee=n.attachments??{},ze=ee.buttonTooltipText??"Attach file";At.setAttribute("aria-label",ze),At.textContent="";let Xe=ue(ee.buttonIconName??"paperclip",yo,"currentColor",1.5);Xe?At.appendChild(Xe):At.textContent="\u{1F4CE}",Ao&&to({anchor:At,trigger:Ao,text:()=>At?.getAttribute("aria-label")??ze})}}else Ao&&(Ao.style.display="none"),Je&&Je.clearAttachments(),pe.querySelector(".persona-attachment-drop-overlay")?.remove();let yt=n.sendButton??{},kf=yt.useIcon??!1,Bs=yt.iconText??"\u2191",rc=yt.iconName,av=yt.tooltipText??"Send message",pT=yt.showTooltip??!1,Ji=yt.size,fT=parseFloat(Ji??"")||Jm,sc=yt.backgroundColor,Zi=yt.textColor;if(kf){if(we.style.width=Ji??"",we.style.height=Ji??"",we.style.minWidth=Ji??"",we.style.minHeight=Ji??"",we.style.fontSize="18px",we.style.lineHeight="1",Zi?we.style.color=Zi:we.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!R.isStreaming())if(we.innerHTML="",rc){let ee=parseFloat(yt.iconSize??"")||Math.round(fT*.5),ze=Zi?.trim()||"currentColor",Xe=yt.iconStrokeWidth??2,rt=ue(rc,ee,ze,Xe),St=ue(yt.stopIconName??"square",ee,ze,Xe);rt&&St?we.appendChild(Zm(rt,St)):rt?we.appendChild(rt):we.textContent=Bs}else we.textContent=Bs;we.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${jo}`,sc?(we.style.backgroundColor=sc,we.classList.remove("persona-bg-persona-primary")):(we.style.backgroundColor="",we.classList.add("persona-bg-persona-primary"))}else we.textContent=n.copy?.sendButtonLabel??"Send",we.style.width="",we.style.height="",we.style.minWidth="",we.style.minHeight="",we.style.fontSize="",we.style.lineHeight="",we.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",sc?(we.style.backgroundColor=sc,we.classList.remove("persona-bg-persona-accent")):we.classList.add("persona-bg-persona-accent"),Zi?we.style.color=Zi:we.classList.add("persona-text-white");yt.borderWidth?(we.style.borderWidth=yt.borderWidth,we.style.borderStyle="solid"):(we.style.borderWidth="",we.style.borderStyle=""),yt.borderColor?we.style.borderColor=yt.borderColor:we.style.borderColor="",yt.paddingX?(we.style.paddingLeft=yt.paddingX,we.style.paddingRight=yt.paddingX):(we.style.paddingLeft="",we.style.paddingRight=""),yt.paddingY?(we.style.paddingTop=yt.paddingY,we.style.paddingBottom=yt.paddingY):(we.style.paddingTop="",we.style.paddingBottom=""),R.isStreaming()||we.setAttribute("aria-label",av),wd(),Tn&&to({anchor:we,trigger:Tn,text:()=>we.getAttribute("aria-label")??av,enabled:pT}),zh();let iv=su(ve.getState().activeModeIds,n.composer?.modes);ve.setActiveModeIds(iv),oa().length>0!==!!Qn&&lp(),Qn?.render(iv,oa());for(let ee of[...na.keys()])ru(ee,n.composer?.modeGroups)||na.delete(ee);na.forEach(ee=>ee.repaint()),Tr?.repaint(),kn?.resolve();let ac=Jr(n,Ie());if(gp(),ac){Me.style.maxWidth=ac,Me.style.marginLeft="auto",Me.style.marginRight="auto",Me.style.width="100%",Bo.style.maxWidth=ac,Bo.style.marginLeft="auto",Bo.style.marginRight="auto",Bo.style.width="100%";for(let ee of[cn,wr,Mo,at])ee&&(ee.style.maxWidth=ac,ee.style.marginLeft="auto",ee.style.marginRight="auto",ee.style.width="100%")}else{Me.style.maxWidth="",Me.style.marginLeft="",Me.style.marginRight="",Me.style.width="",Bo.style.maxWidth="",Bo.style.marginLeft="",Bo.style.marginRight="",Bo.style.width="";for(let ee of[cn,wr,Mo,at])ee&&(ee.style.maxWidth="",ee.style.marginLeft="",ee.style.marginRight="",ee.style.width="")}let Ur=n.statusIndicator??{},mT=Ur.visible??!0;if(at.style.display=mT?"":"none",R){let ee=R.getStatus();Kl(at,(Xe=>Xe==="idle"?Ur.idleText??Ut.idle:Xe==="connecting"?Ur.connectingText??Ut.connecting:Xe==="connected"?Ur.connectedText??Ut.connected:Xe==="error"?Ur.errorText??Ut.error:Ut[Xe])(ee),Ur,ee)}at.classList.remove("persona-text-left","persona-text-center","persona-text-right");let gT=Ur.align==="left"?"persona-text-left":Ur.align==="center"?"persona-text-center":"persona-text-right";at.classList.add(gT),ip(),Pp(),un(),qt()},open(){Ee()&&pt(!0,"api")},close(){Ee()&&pt(!1,"api")},toggle(){Ee()&&pt(!ye,"api")},reconnect(){R.reconnectNow()},clearChat(){Yn=!1,R.clearMessages(),Dt.clear(),Eo();try{localStorage.removeItem(pi),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${pi}`)}catch(l){console.error("[AgentWidget] Failed to clear default localStorage:",l)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==pi)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),U?.clear&&gd(()=>U.clear(),"[AgentWidget] Failed to clear storage adapter:"),V={},We.syncFromMetadata(),Je?.clearAttachments(),yd(),ra(void 0),Pn(void 0),gs(),et?.clear(),Ho?.reset(),J?.update()},setMessage(s){return!ce||R.isStreaming()||Br()?!1:(!ye&&Ee()&&pt(!0,"system"),ce.value=s,ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(s){if(R.isStreaming()||Ss())return!1;let l=s?.trim()||ce.value.trim();return l?(!ye&&Ee()&&pt(!0,"system"),ce.value="",ce.style.height="auto",En(),Jd(l,{consumeDraft:!1}),!0):!1},getComposerState(){return ve.getState()},setQuote(s){let l=s?.text?.trim();l&&Pn({...s,text:l})},clearQuote(){Pn(void 0)},startVoiceRecognition(){return R.isStreaming()?!1:n.voiceRecognition?.provider?.type==="runtype"?(R.isVoiceActive()||(!ye&&Ee()&&pt(!0,"system"),je.manuallyDeactivated=!1,mn(),R.toggleVoice().then(()=>{je.active=R.isVoiceActive(),tr("user"),R.isVoiceActive()&&Ia()})),!0):Bn?!0:Bb()?(!ye&&Ee()&&pt(!0,"system"),je.manuallyDeactivated=!1,mn(),ec("user"),!0):!1},stopVoiceRecognition(){return n.voiceRecognition?.provider?.type==="runtype"?R.isVoiceActive()?(R.toggleVoice().then(()=>{je.active=!1,je.manuallyDeactivated=!0,mn(),tr("user"),cr()}),!0):!1:Bn?(je.manuallyDeactivated=!0,mn(),Nr("user"),!0):!1},injectMessage(s){return!ye&&Ee()&&pt(!0,"system"),R.injectMessage(s)},injectAssistantMessage(s){!ye&&Ee()&&pt(!0,"system");let l=R.injectAssistantMessage(s);return Cn&&(Cn=!1,Sn&&(clearTimeout(Sn),Sn=null),setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)),l},injectUserMessage(s){return!ye&&Ee()&&pt(!0,"system"),R.injectUserMessage(s)},injectSystemMessage(s){return!ye&&Ee()&&pt(!0,"system"),R.injectSystemMessage(s)},injectMessageBatch(s){return!ye&&Ee()&&pt(!0,"system"),R.injectMessageBatch(s)},injectComponentDirective(s){return!ye&&Ee()&&pt(!0,"system"),R.injectComponentDirective(s)},injectTestMessage(s){!ye&&Ee()&&pt(!0,"system"),R.injectTestEvent(s)},async connectStream(s,l){return R.connectStream(s,l)},__pushEventStreamEvent(s){io&&(se(),oe(s.type,s.payload))},showEventStream(){io&&ap()},hideEventStream(){S&&sa()},isEventStreamVisible(){return S},listConversations(s){return R.listConversations(s)},getActiveConversationId(){return R.getActiveConversationId()},openConversation(s,l){return uf(s,{focusComposer:l?.focus===!0})},startNewConversation(s){return pf({focusComposer:s?.focus===!0})},deleteConversation(s){return Ab(s)},renameConversation(s,l){return ff(s,{title:l})},setConversationStarred(s,l){return ff(s,{starred:l})},clearConversationHistory(s){return Mb(s)},resetHistoryIdentity(){return Tb()},getHistoryIdentityStatus(){return Uo?Uo.getIdentityStatus():Kp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(s){return ji({...s?.returnSurface?{returnSurface:s.returnSurface}:{},...s?.focus!==void 0?{focus:s.focus}:{}})},hideHistory(s){ko(s?.restoreFocus!==void 0?{restoreFocus:s.restoreFocus}:void 0)},isHistoryVisible(){return ie},showArtifacts(){Co(n)&&(Yn=!1,ia=!0,fn(),$e?.setMobileOpen(!0))},hideArtifacts(){Co(n)&&(Yn=!0,fn())},upsertArtifact(s){return Co(n)?(Fn(n.features?.artifacts,{artifactType:s.artifactType,...s.artifactType==="markdown"&&s.file?{file:s.file}:{},...s.presentation?{presentation:s.presentation}:{}})==="panel"&&(Yn=!1,ia=!0),R.upsertArtifact(s)):null},selectArtifact(s){Co(n)&&R.selectArtifact(s)},clearArtifacts(){Co(n)&&R.clearArtifacts()},getArtifacts(){return R?.getArtifacts()??[]},getSelectedArtifactId(){return R?.getSelectedArtifactId()??null},focusInput(){return Se&&!ye&&!Ie()||!ce?!1:(ce.focus(),!0)},async resolveApproval(s,l,f){let v=R.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"){R.resolveWebMcpApproval(v.id,l);return}return R.resolveApproval(v.approval,l,f)},setFollowUpSuggestions(s){xA(s)},clearFollowUpSuggestions(){xy()},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...V}},updatePersistentMetadata(s){le(s)},on(s,l){return C.on(s,l)},off(s,l){C.off(s,l)},isOpen(){return Ee()&&ye},isVoiceActive(){return je.active},toggleReadAloud(s){R.toggleReadAloud(s)},stopReadAloud(){R.stopSpeaking()},getReadAloudState(s){return R.getReadAloudState(s)},onReadAloudChange(s){return R.onReadAloudChange(s)},getState(){return{open:Ee()&&ye,launcherEnabled:Se,voiceActive:je.active,streaming:R.isStreaming()}},showCSATFeedback(s){!ye&&Ee()&&pt(!0,"system");let l=Me.querySelector(".persona-feedback-container");l&&l.remove();let f=Vu({onSubmit:async(g,v)=>{R.isClientTokenMode()&&await R.submitCSATFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});Me.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(s){!ye&&Ee()&&pt(!0,"system");let l=Me.querySelector(".persona-feedback-container");l&&l.remove();let f=$u({onSubmit:async(g,v)=>{R.isClientTokenMode()&&await R.submitNPSFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});Me.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(s,l){return R.submitCSATFeedback(s,l)},async submitNPSFeedback(s,l){return R.submitNPSFeedback(s,l)},destroy(){Fp(),Ms!=null&&(clearInterval(Ms),Ms=null),ge.forEach(s=>s()),Ke.remove(),Xt?.remove(),kt?.destroy(),fo?.remove(),us&&Ue.removeEventListener("click",us)}};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,ge.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=G=>{let Z=G.detail;(!Z?.instanceId||Z.instanceId===s)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",l),ge.push(()=>{window.removeEventListener("persona:focusInput",l)}),io){let G=ae=>{let me=ae.detail;(!me?.instanceId||me.instanceId===s)&&Lt.showEventStream()},Z=ae=>{let me=ae.detail;(!me?.instanceId||me.instanceId===s)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",G),window.addEventListener("persona:hideEventStream",Z),ge.push(()=>{window.removeEventListener("persona:showEventStream",G),window.removeEventListener("persona:hideEventStream",Z)})}let f=G=>{let Z=G.detail;(!Z?.instanceId||Z.instanceId===s)&&Lt.showHistory()},g=G=>{let Z=G.detail;(!Z?.instanceId||Z.instanceId===s)&&Lt.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",g),ge.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",g)});let v=G=>{let Z=G.detail;(!Z?.instanceId||Z.instanceId===s)&&Lt.showArtifacts()},M=G=>{let Z=G.detail;(!Z?.instanceId||Z.instanceId===s)&&Lt.hideArtifacts()},_=G=>{let Z=G.detail;Z?.instanceId&&Z.instanceId!==s||Z?.artifact&&Lt.upsertArtifact(Z.artifact)},K=G=>{let Z=G.detail;Z?.instanceId&&Z.instanceId!==s||typeof Z?.id=="string"&&Lt.selectArtifact(Z.id)},j=G=>{let Z=G.detail;(!Z?.instanceId||Z.instanceId===s)&&Lt.clearArtifacts()};window.addEventListener("persona:showArtifacts",v),window.addEventListener("persona:hideArtifacts",M),window.addEventListener("persona:upsertArtifact",_),window.addEventListener("persona:selectArtifact",K),window.addEventListener("persona:clearArtifacts",j),ge.push(()=>{window.removeEventListener("persona:showArtifacts",v),window.removeEventListener("persona:hideArtifacts",M),window.removeEventListener("persona:upsertArtifact",_),window.removeEventListener("persona:selectArtifact",K),window.removeEventListener("persona:clearArtifacts",j)})}let on=tL(n.persistState);if(on&&Ee()){let s=oL(on.storage),l=`${on.keyPrefix}widget-open`,f=`${on.keyPrefix}widget-voice`,g=`${on.keyPrefix}widget-voice-mode`;if(s){let v=on.persist?.openState&&s.getItem(l)==="true",M=on.persist?.voiceState&&s.getItem(f)==="true",_=on.persist?.voiceState&&s.getItem(g)==="true";if(v&&(kt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Lt.open(),setTimeout(()=>{if(M||_)Lt.startVoiceRecognition();else if(on.persist?.focusInput){let K=e.querySelector("textarea");K&&K.focus()}},100)},0)),on.persist?.openState&&(C.on("widget:opened",()=>{s.setItem(l,"true")}),C.on("widget:closed",()=>{s.setItem(l,"false")})),on.persist?.voiceState&&(C.on("voice:state",K=>{s.setItem(f,K.active?"true":"false")}),C.on("user:message",K=>{s.setItem(g,K.viaVoice?"true":"false")})),on.clearOnChatClear){let K=()=>{s.removeItem(l),s.removeItem(f),s.removeItem(g)},j=()=>K();window.addEventListener("persona:clear-chat",j),ge.push(()=>{window.removeEventListener("persona:clear-chat",j)})}}}if(te&&Ee()&&(kt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Lt.open()},0)),ya(),!CA){let s=Wa(()=>{R&&(hs++,Dt.clear(),Yo(Me,R.getMessages(),Ht))});ge.push(s)}T=()=>{R&&(hs++,Dt.clear(),Yo(Me,R.getMessages(),Ht))},R.getMessages().length>0&&Sd(),b=()=>{R&&(hs++,Dt.clear(),Yo(Me,R.getMessages(),Ht))};let cT=Ox(()=>{R&&(hs++,Dt.clear(),Yo(Me,R.getMessages(),Ht))});ge.push(cT);let uT=Zg(()=>{R&&(hs++,Dt.clear(),Yo(Me,R.getMessages(),Ht),vr()?.updateInlineArtifactBlocks(Me,Qo.artifacts,{suppressTransition:!0}),fn())});return ge.push(uT),Lt};var kw=(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},sL=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},aL=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},iL=(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.")},Lw=(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"},hh=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=""},Iw=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",hh(e)},fh=e=>{e.style.transition=""},mh=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=""},gh=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ku=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},lL=(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))},dL=(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)},cL=e=>{let t=Yr(e),o=t.components?.panel,n=(r,a)=>r==null||r===""?a:bo(t,r)??r;return{inset:n(o?.inset,au),canvasBackground:n(o?.canvasBackground,iu)}},Rw=(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},uL=(e,t,o,n,r,a,i,d)=>{let c=Ro(a),u=c.reveal==="push",p=d!=null,m=d?.inset??"",h=d?.canvasBackground??"";lL(e,t,o,n,u),dL(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"),mh(t),fh(n),Iw(n),gh(o),Ku(r,n),Rw(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??ao),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"),Iw(n),sL(n,c.maxHeight),Rw(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",mh(t),fh(n),gh(o),Ku(r,n);let P=c.animate?"transform 180ms ease":"none",H=c.side==="right"?"translateX(100%)":"translateX(-100%)",b=i?"translateX(0)":H;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",fh(n),hh(n),Ku(r,n);let P=kw(c.width,e.clientWidth),H=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=`${H+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=`${H}px`,o.style.maxWidth=`${H}px`,o.style.minWidth=`${H}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="",mh(t),hh(n),gh(o),Ku(r,n);let P=c.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let H=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 ${H}`,n.style.width=H,n.style.maxWidth=H,n.style.minWidth=H,n.style.minHeight="0",aL(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(${kw(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"}}},pL=(e,t)=>{let o=e.ownerDocument.createElement("div");return Lw(o,t),e.appendChild(o),{mode:"direct",host:o,shell:null,syncWidgetState:()=>{},updateConfig(n){Lw(o,n)},destroy(){o.remove()}}},fL=(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?cL(t):null};T();let w=()=>{uL(i,d,c,u,p,t,m,x)},k=null,P=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=Ja(()=>{T(),w()}))},H=()=>{y(),Ro(t).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{w()}),h.observe(i)))},b=!1,A=()=>{w(),H(),m&&!b&&i.dataset.personaDockMobileFullscreen!=="true"&&(b=!0,iL(i,Ro(t)))},C=i.ownerDocument.defaultView,L=()=>{A()};return C?.addEventListener("resize",L),Ro(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(U){let Q=U.launcherEnabled?U.open:!0;m!==Q&&(m=Q,A())},updateConfig(U){t=U,(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()}}},zl=(e,t)=>wt(t)?fL(e,t):pL(e,t);var mL=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},Hw=(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)},Gu=[],Ww=()=>[...Gu],Bw=e=>{let t=mL(e.target),o=e.useShadowDom===!0,n=t.ownerDocument,r=e.config,a=zl(t,r),i,d=[],c=(w,k)=>{let H=!(k?.launcher?.enabled??!0)||wt(k),b=n.createElement("div");if(b.setAttribute("data-persona-root","true"),H&&(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),Hw(A,n)}else w.appendChild(b),Hw(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=zu(w,r,{debugTools:e.debugTools}),p()},h=()=>{d.forEach(w=>w()),d=[],i.destroy()};m(),e.onChatReady?.();let y=w=>{h(),a.destroy(),a=zl(t,w),r=w,m()},x={update(w){let k=Du(r??{},w),P=wt(r),H=wt(k),b=es(r),A=es(k);if(P!==H||b!==A){y(k);return}r=k,a.updateConfig(r),i.update(w),u()},destroy(){h(),a.destroy();let w=Gu.indexOf(T);w!==-1&&Gu.splice(w,1),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 H=i[k];return typeof H=="function"?H.bind(i):H}});return Gu.push(T),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=T),T};var Fw=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),gL=new Set(["button","a","input","select","textarea","details","summary"]),hL=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),yh=/\b(product|card|item|listing|result)\b/i,vh=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,yL=3e3,bL=100;function Uw(e){let t=typeof e.className=="string"?e.className:"";if(yh.test(t)||e.id&&yh.test(e.id))return!0;for(let o=0;o<e.attributes.length;o++){let n=e.attributes[o];if(n.name.startsWith("data-")&&yh.test(n.value))return!0}return!1}function qw(e){return vh.test((e.textContent??"").trim())}function Vw(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 vL(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Ow(e){let t=e.match(vh);return t?t[0]:null}function Dw(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 xL(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 CL="commerce-card",SL="result-card";function _w(e){return!Uw(e)||!qw(e)||!Vw(e)&&!vL(e)?0:5200}function Nw(e){return!Uw(e)||qw(e)||!Vw(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var xh=[{id:CL,scoreElement(e){return _w(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||vh.test(n)&&n.length<32)}return!0},formatSummary(e,t){if(_w(e)===0)return null;let{title:o,href:n}=Dw(e),r=Ow((e.textContent??"").trim())??Ow(t.text)??"",a=xL(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:SL,scoreElement(e){return Nw(e)},formatSummary(e,t){if(Nw(e)===0)return null;let{title:o,href:n}=Dw(e);return[n&&o?`[${o}](${n})`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
140
+ `)}}];function wL(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function AL(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??xh;return d==="simple"&&e.rules&&e.rules.length>0?(wL(),u=[]):d==="simple"&&(u=[]),{mode:d,maxElements:o,maxCandidates:c,excludeSelector:n,maxTextLength:r,visibleOnly:a,root:i,rules:u}}function bh(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var ML=["data-testid","data-product","data-action","data-id","data-name","data-type"];function TL(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"||gL.has(t)||o&&hL.has(o)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function $w(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 EL(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 Ch(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${bh(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of ML){let a=e.getAttribute(r);if(a){let i=`${t}[${r}="${bh(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=>bh(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 PL(e){return e==="static"?bL:yL}function jw(e,t){let o=e.tagName.toLowerCase(),n=(e.textContent??"").trim().substring(0,t);return{selector:Ch(e),tagName:o,text:n,role:e.getAttribute("role"),interactivity:TL(e),attributes:EL(e)}}function kL(e,t,o,n){let r=PL(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 LL(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 IL(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(Fw.has(p)){d=i.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){d=i.nextNode();continue}}catch{}if(e.visibleOnly&&!$w(u)){d=i.nextNode();continue}let m=jw(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}=kL(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;LL(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 RL(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(Fw.has(u)){a=r.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!$w(c)){a=r.nextNode();continue}let p=jw(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 zw(e={}){let t=AL(e),o=t.root??document.body;return o?t.mode==="simple"?RL(t,o):IL(t,o):[]}var Xu=100;function Kw(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(`
144
- `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let a of e)o==="structured"&&a.formattedSummary||r[a.interactivity].push(a);if(r.clickable.length>0){let a=r.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,zu)}" (clickable)`);n.push(`Interactive elements:
144
+ `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let a of e)o==="structured"&&a.formattedSummary||r[a.interactivity].push(a);if(r.clickable.length>0){let a=r.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Xu)}" (clickable)`);n.push(`Interactive elements:
145
145
  ${a.join(`
146
- `)}`)}if(r.navigable.length>0){let a=r.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,zu)}" (navigable)`);n.push(`Navigation links:
146
+ `)}`)}if(r.navigable.length>0){let a=r.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Xu)}" (navigable)`);n.push(`Navigation links:
147
147
  ${a.join(`
148
- `)}`)}if(r.input.length>0){let a=r.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,zu)}" (input)`);n.push(`Form inputs:
148
+ `)}`)}if(r.input.length>0){let a=r.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Xu)}" (input)`);n.push(`Form inputs:
149
149
  ${a.join(`
150
- `)}`)}if(r.static.length>0){let a=r.static.map(i=>`- ${i.selector}: "${i.text.substring(0,zu)}"`);n.push(`Content:
150
+ `)}`)}if(r.static.length>0){let a=r.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Xu)}"`);n.push(`Content:
151
151
  ${a.join(`
152
152
  `)}`)}return n.join(`
153
153
 
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);})();
154
+ `)}var HL={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"}}},Gw={components:{panel:{borderRadius:"0",shadow:"none"}}},Sh={id:"shop",label:"Shopping Assistant",config:{theme:HL,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:$o},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"]}},wh={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Gw}},Ah={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Gw}},Mh={shop:Sh,minimal:wh,fullscreen:Ah};function Xw(e){return Mh[e]}var De=typeof document<"u"?document.currentScript?.src??null:null;Tv(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${De??"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)});cv(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${De??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});Lx(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${De??"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)});OC(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${De??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});DC(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${De??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});hw(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"history-view.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the history-view.js URL from the widget script URL (${De??"unavailable"}). Self-hosted deployments that rename index.global.js should host history-view.js alongside it.`)):import(e)});pS(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"animations-extra.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the animations-extra.js URL from the widget script URL (${De??"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)});zS(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"approval-ui.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the approval-ui.js URL from the widget script URL (${De??"unavailable"}). Self-hosted deployments that rename index.global.js should host approval-ui.js alongside it.`)):import(e)});Px(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"voice-runtime.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the voice-runtime.js URL from the widget script URL (${De??"unavailable"}). Self-hosted deployments that rename index.global.js should host voice-runtime.js alongside it.`)):import(e)});YS(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"artifacts-ui.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the artifacts-ui.js URL from the widget script URL (${De??"unavailable"}). Self-hosted deployments that rename index.global.js should host artifacts-ui.js alongside it.`)):import(e)});iw(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"forms-ui.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the forms-ui.js URL from the widget script URL (${De??"unavailable"}). Self-hosted deployments that rename index.global.js should host forms-ui.js alongside it.`)):import(e)});Wx(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"icons-extra.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the icons-extra.js URL from the widget script URL (${De??"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)});kv(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"webmcp-runtime.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the webmcp-runtime.js URL from the widget script URL (${De??"unavailable"}). Self-hosted deployments that rename index.global.js should host webmcp-runtime.js alongside it.`)):import(e)});Ix(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"session-reconnect.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the session-reconnect.js URL from the widget script URL (${De??"unavailable"}). Self-hosted deployments that rename index.global.js should host session-reconnect.js alongside it.`)):import(e)});XS(()=>{let e=De?.replace(/index\.global\.js($|\?)/,"event-stream-view.js$1");return!e||e===De?Promise.reject(new Error(`Could not derive the event-stream-view.js URL from the widget script URL (${De??"unavailable"}). Self-hosted deployments that rename index.global.js should host event-stream-view.js alongside it.`)):import(e)});return ST(WL);})();
155
155
  /*! Bundled license information:
156
156
 
157
157
  lucide/dist/esm/icons/activity.mjs: