@runtypelabs/persona 4.10.1 → 4.11.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.
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-Bx_rvjff.d.cts → types-DveIaNx6.d.cts} +2 -0
- package/dist/animations/{types-Bx_rvjff.d.ts → types-DveIaNx6.d.ts} +2 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/chunk-MMUPR2JW.js +1 -0
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/{context-mentions-7S5KVUTG.js → context-mentions-ONG7A7M6.js} +1 -1
- package/dist/context-mentions.d.cts +26 -0
- package/dist/context-mentions.d.ts +26 -0
- package/dist/index.cjs +67 -67
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +27 -1
- package/dist/index.d.ts +27 -1
- package/dist/index.global.js +55 -55
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +78 -78
- package/dist/index.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +26 -0
- package/dist/smart-dom-reader.d.ts +26 -0
- package/dist/theme-editor-preview.cjs +66 -66
- package/dist/theme-editor-preview.d.cts +26 -0
- package/dist/theme-editor-preview.d.ts +26 -0
- package/dist/theme-editor-preview.js +55 -55
- package/dist/theme-editor.cjs +5 -5
- package/dist/theme-editor.d.cts +26 -0
- package/dist/theme-editor.d.ts +26 -0
- package/dist/theme-editor.js +9 -9
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/components/approval-bubble.ts +0 -1
- package/src/components/composer-parts.ts +19 -19
- package/src/components/context-mention-button.test.ts +5 -1
- package/src/components/context-mention-button.ts +6 -4
- package/src/components/header-builder.test.ts +3 -3
- package/src/components/header-parts.ts +14 -108
- package/src/components/message-bubble.test.ts +49 -0
- package/src/components/message-bubble.ts +8 -7
- package/src/components/reasoning-bubble.ts +0 -2
- package/src/components/tool-bubble.ts +0 -2
- package/src/generated/runtype-openapi-contract.ts +2 -0
- package/src/index-core.ts +1 -0
- package/src/styles/widget.css +118 -58
- package/src/theme-editor/sections.test.ts +33 -0
- package/src/theme-editor/sections.ts +10 -1
- package/src/types.ts +25 -0
- package/src/ui.attachments-drop.test.ts +2 -1
- package/src/ui.message-width.test.ts +407 -0
- package/src/ui.ts +145 -238
- package/src/utils/table-scroll-fade.test.ts +123 -0
- package/src/utils/table-scroll-fade.ts +75 -0
- package/src/utils/tooltip.test.ts +226 -0
- package/src/utils/tooltip.ts +245 -0
- package/dist/chunk-IPVK3KOM.js +0 -1
package/dist/index.global.js
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var
|
|
2
|
-
\r `.includes(e[o]);)o++};return s()},
|
|
3
|
-
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],a=t[o+1];if(!
|
|
4
|
-
`):e};var
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var By=Object.create;var Ls=Object.defineProperty;var Dy=Object.getOwnPropertyDescriptor;var Fy=Object.getOwnPropertyNames;var Oy=Object.getPrototypeOf,Ny=Object.prototype.hasOwnProperty;var ya=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var _y=(e,t)=>()=>(e&&(t=e(e=0)),t);var yf=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),xf=(e,t)=>{for(var n in t)Ls(e,n,{get:t[n],enumerable:!0})},bf=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Fy(t))!Ny.call(e,r)&&r!==n&&Ls(e,r,{get:()=>t[r],enumerable:!(o=Dy(t,r))||o.enumerable});return e};var po=(e,t,n)=>(n=e!=null?By(Oy(e)):{},bf(t||!e||!e.__esModule?Ls(n,"default",{value:e,enumerable:!0}):n,e)),Uy=e=>bf(Ls({},"__esModule",{value:!0}),e);var $l=yf(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Allow=ye.ALL=ye.COLLECTION=ye.ATOM=ye.SPECIAL=ye.INF=ye._INFINITY=ye.INFINITY=ye.NAN=ye.BOOL=ye.NULL=ye.OBJ=ye.ARR=ye.NUM=ye.STR=void 0;ye.STR=1;ye.NUM=2;ye.ARR=4;ye.OBJ=8;ye.NULL=16;ye.BOOL=32;ye.NAN=64;ye.INFINITY=128;ye._INFINITY=256;ye.INF=ye.INFINITY|ye._INFINITY;ye.SPECIAL=ye.NULL|ye.BOOL|ye.INF|ye.NAN;ye.ATOM=ye.STR|ye.NUM|ye.SPECIAL;ye.COLLECTION=ye.ARR|ye.OBJ;ye.ALL=ye.ATOM|ye.COLLECTION;ye.Allow={STR:ye.STR,NUM:ye.NUM,ARR:ye.ARR,OBJ:ye.OBJ,NULL:ye.NULL,BOOL:ye.BOOL,NAN:ye.NAN,INFINITY:ye.INFINITY,_INFINITY:ye._INFINITY,INF:ye.INF,SPECIAL:ye.SPECIAL,ATOM:ye.ATOM,COLLECTION:ye.COLLECTION,ALL:ye.ALL};ye.default=ye.Allow});var Ds=yf(Ot=>{"use strict";var lx=Ot&&Ot.__createBinding||(Object.create?(function(e,t,n,o){o===void 0&&(o=n);var r=Object.getOwnPropertyDescriptor(t,n);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,r)}):(function(e,t,n,o){o===void 0&&(o=n),e[o]=t[n]})),dx=Ot&&Ot.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&lx(t,e,n)};Object.defineProperty(Ot,"__esModule",{value:!0});Ot.Allow=Ot.MalformedJSON=Ot.PartialJSON=Ot.parseJSON=Ot.parse=void 0;var Gt=$l();Object.defineProperty(Ot,"Allow",{enumerable:!0,get:function(){return Gt.Allow}});dx($l(),Ot);var Hs=class extends Error{};Ot.PartialJSON=Hs;var Bs=class extends Error{};Ot.MalformedJSON=Bs;function _f(e,t=Gt.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return cx(e.trim(),t)}Ot.parseJSON=_f;var cx=(e,t)=>{let n=e.length,o=0,r=g=>{throw new Hs(`${g} at position ${o}`)},a=g=>{throw new Bs(`${g} at position ${o}`)},s=()=>(u(),o>=n&&r("Unexpected end of input"),e[o]==='"'?l():e[o]==="{"?p():e[o]==="["?d():e.substring(o,o+4)==="null"||Gt.Allow.NULL&t&&n-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Gt.Allow.BOOL&t&&n-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Gt.Allow.BOOL&t&&n-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Gt.Allow.INFINITY&t&&n-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Gt.Allow._INFINITY&t&&1<n-o&&n-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Gt.Allow.NAN&t&&n-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):c()),l=()=>{let g=o,f=!1;for(o++;o<n&&(e[o]!=='"'||f&&e[o-1]==="\\");)f=e[o]==="\\"?!f:!1,o++;if(e.charAt(o)=='"')try{return JSON.parse(e.substring(g,++o-Number(f)))}catch(h){a(String(h))}else if(Gt.Allow.STR&t)try{return JSON.parse(e.substring(g,o-Number(f))+'"')}catch{return JSON.parse(e.substring(g,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},p=()=>{o++,u();let g={};try{for(;e[o]!=="}";){if(u(),o>=n&&Gt.Allow.OBJ&t)return g;let f=l();u(),o++;try{let h=s();g[f]=h}catch(h){if(Gt.Allow.OBJ&t)return g;throw h}u(),e[o]===","&&o++}}catch{if(Gt.Allow.OBJ&t)return g;r("Expected '}' at end of object")}return o++,g},d=()=>{o++;let g=[];try{for(;e[o]!=="]";)g.push(s()),u(),e[o]===","&&o++}catch{if(Gt.Allow.ARR&t)return g;r("Expected ']' at end of array")}return o++,g},c=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(f){if(Gt.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(f))}}let g=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==n&&!(Gt.Allow.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(g,o))}catch{e.substring(g,o)==="-"&&r("Not sure what '-' is");try{return JSON.parse(e.substring(g,e.lastIndexOf("e")))}catch(h){a(String(h))}}},u=()=>{for(;o<n&&`
|
|
2
|
+
\r `.includes(e[o]);)o++};return s()},px=_f;Ot.parse=px});var Cm={};xf(Cm,{createReconnectController:()=>Qx});function Qx(e){let t=0,n=null,o=null,r=!1,a=()=>{if(o&&(clearTimeout(o),o=null),n){let h=n;n=null,h()}},s=()=>{let h=e.getStatus();h!=="resuming"&&h!=="paused"||a()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||s()},p=()=>{s()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",p),r=!0)},c=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},u=h=>new Promise(S=>{n=S,o=setTimeout(()=>{o=null,n=null,S()},h)}),g=()=>{let h=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let S=!1;for(let E of e.getMessages())E.streaming&&(E.streaming=!1,S=!0);let L=e.buildErrorContent("Connection lost and the response could not be resumed.");L?e.appendMessage({id:`reconnect-failed-${h?.executionId??e.nextSequence()}`,role:"assistant",content:L,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):S&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},f=async()=>{let h=e.config.reconnect?.backoffMs??Jx,S=e.config.reconnect?.maxAttempts??h.length,L=e.config.reconnectStream;if(!L){e.setReconnecting(!1);return}for(;e.getResumable()&&t<S;){t+=1,e.setStatus("resuming");let E=e.getResumable(),M=E.lastEventId,A=new AbortController;e.setAbortController(A),e.emitReconnect({phase:"resuming",handle:E,attempt:t});let w=null;try{let T=await L({executionId:E.executionId,after:E.lastEventId,signal:A.signal});T&&T.ok&&T.body&&(w=T.body)}catch{w=null}if(A.signal.aborted)return;if(w){let T=e.getMessages().find(C=>C.id===E.assistantMessageId)?.content,H=typeof T=="string"?T:"";try{await e.resumeConnect(w,E.assistantMessageId,H)}catch{}if(A.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:E});return}e.getResumable().lastEventId!==M&&(t=0)}if(e.getResumable()&&t<S&&(e.setStatus("paused"),await u(h[Math.min(t-1,h.length-1)]??1e3),A.signal.aborted))return}e.getResumable()&&g()};return{begin(){t=0,d(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:a}}var Jx,wm=_y(()=>{"use strict";Jx=[1e3,2e3,4e3,8e3,8e3]});var kw={};xf(kw,{ASK_USER_QUESTION_CLIENT_TOOL:()=>td,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>ed,ASK_USER_QUESTION_TOOL_NAME:()=>wa,AgentWidgetClient:()=>Xo,AgentWidgetSession:()=>Pr,AttachmentManager:()=>Yo,BrowserSpeechEngine:()=>Co,DEFAULT_COMPONENTS:()=>dp,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>gi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>ln,DEFAULT_PALETTE:()=>ip,DEFAULT_SEMANTIC:()=>lp,DEFAULT_WIDGET_CONFIG:()=>lt,PRESETS:()=>ru,PRESET_FULLSCREEN:()=>ou,PRESET_MINIMAL:()=>nu,PRESET_SHOP:()=>tu,ReadAloudController:()=>Qo,SUGGEST_REPLIES_CLIENT_TOOL:()=>_s,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Ql,SUGGEST_REPLIES_TOOL_NAME:()=>Tn,THEME_ZONES:()=>Om,VERSION:()=>Ko,WEBMCP_TOOL_PREFIX:()=>Mn,WebMcpBridge:()=>Ar,accessibilityPlugin:()=>Eh,animationsPlugin:()=>kh,applyThemeVariables:()=>Zo,attachHeaderToContainer:()=>nr,brandPlugin:()=>Lh,buildComposer:()=>Nr,buildDefaultHeader:()=>Sp,buildHeader:()=>Jn,buildHeaderWithLayout:()=>Or,buildMinimalHeader:()=>Mp,builtInClientToolsForDispatch:()=>Er,collectEnrichedPageContext:()=>Mh,componentRegistry:()=>En,createActionManager:()=>Ya,createAgentExperience:()=>nl,createAskUserQuestionBubble:()=>em,createBestAvailableVoiceProvider:()=>ti,createBubbleWithLayout:()=>Eg,createCSATFeedback:()=>Zi,createComboButton:()=>Si,createComponentMiddleware:()=>th,createComponentStreamParser:()=>Ji,createDefaultSanitizer:()=>Ul,createDirectivePostprocessor:()=>Sf,createDropdownMenu:()=>Mo,createFlexibleJsonStreamParser:()=>rm,createIconButton:()=>Tt,createImagePart:()=>pm,createJsonStreamParser:()=>Ks,createLabelButton:()=>Xn,createLocalStorageAdapter:()=>Xi,createMarkdownProcessor:()=>ba,createMarkdownProcessorFromConfig:()=>$o,createMessageActions:()=>Ip,createNPSFeedback:()=>el,createPlainTextParser:()=>js,createPlugin:()=>Ih,createRegexJsonParser:()=>Gs,createSlashCommandsSource:()=>mh,createStandardBubble:()=>_r,createStaticMentionSource:()=>fh,createTextPart:()=>bo,createTheme:()=>Wa,createThemeObserver:()=>Ir,createToggleGroup:()=>Br,createTypingIndicator:()=>or,createVoiceProvider:()=>vo,createWidgetHostLayout:()=>es,createXmlParser:()=>Xs,defaultActionHandlers:()=>ir,defaultJsonActionParser:()=>Qa,defaultMentionFilter:()=>rl,defaultParseRules:()=>Zp,detectColorScheme:()=>Ha,directivePostprocessor:()=>Mf,ensureAskUserQuestionSheet:()=>Tr,escapeHtml:()=>In,extractComponentDirectiveFromMessage:()=>Yi,fileToImagePart:()=>um,formatEnrichedContext:()=>Th,generateAssistantMessageId:()=>xo,generateMessageId:()=>im,generateStableSelector:()=>eu,generateUserMessageId:()=>kr,getActiveTheme:()=>wo,getColorScheme:()=>vi,getDisplayText:()=>dm,getHeaderLayout:()=>Tp,getImageParts:()=>cm,getPreset:()=>Hh,hasComponentDirective:()=>Za,hasImages:()=>Ys,headerLayouts:()=>Oi,highContrastPlugin:()=>Rh,initAgentWidget:()=>ph,isAskUserQuestionMessage:()=>$n,isComponentDirectiveType:()=>eh,isDockedMountMode:()=>Lt,isSuggestRepliesMessage:()=>Sa,isVoiceSupported:()=>La,isWebMcpToolName:()=>uo,latestAgentSuggestions:()=>Us,listRegisteredStreamAnimations:()=>Cp,loadMarkdownParsers:()=>xa,markdownPostprocessor:()=>_l,mergeWithDefaults:()=>Rr,normalizeContent:()=>lm,onMarkdownParsersReady:()=>Cr,parseAskUserQuestionPayload:()=>jn,parseSuggestRepliesPayload:()=>Zl,pickBestVoice:()=>Lr,pluginRegistry:()=>Ja,reducedMotionPlugin:()=>Ph,registerStreamAnimationPlugin:()=>tr,removeAskUserQuestionSheet:()=>go,renderComponentDirective:()=>Qi,renderLoadingIndicatorWithFallback:()=>Rp,renderLucideIcon:()=>te,resolveDockConfig:()=>tn,resolveSanitizer:()=>wr,resolveTokens:()=>xi,stripWebMcpPrefix:()=>Is,themeToCssVariables:()=>bi,unregisterStreamAnimationPlugin:()=>vp,validateImageFile:()=>fm,validateTheme:()=>cp});var vr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,a=null;return{setLoader:c=>{o=c,n&&(r=null,a=null)},load:()=>r?Promise.resolve(r):a||(a=(o??t)().then(u=>(r=u,u)).catch(u=>{throw a=null,u}),a),provide:c=>{r=c},getSync:()=>r}};var{setLoader:qy,load:Vy,provide:Bw,getSync:Nl}=vr({fallbackImport:()=>import("./markdown-parsers-entry")}),Ps=new Set,zy=()=>{let e=[...Ps];Ps.clear();for(let t of e)try{t()}catch{}},vf=qy,xa=()=>{let e=Nl();return e?Promise.resolve(e):Vy().then(t=>(zy(),t))},Cr=e=>Nl()?()=>{}:(Ps.add(e),xa().catch(()=>{}),()=>{Ps.delete(e)});var Vn=Nl;var $y=e=>{if(e)return e},ba=e=>{let t=null;return n=>{let o=Vn();if(!o)return In(n);if(!t){let{Marked:r}=o,a=e?.markedOptions;t=new r({gfm:a?.gfm??!0,breaks:a?.breaks??!0,pedantic:a?.pedantic,silent:a?.silent});let s=$y(e?.renderer);s&&t.use({renderer:s})}return t.parse(n)}},$o=e=>e?ba({markedOptions:e.options,renderer:e.renderer}):ba(),jy=ba(),_l=e=>jy(e),In=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),wf=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Cf=e=>`%%FORM_PLACEHOLDER_${e}%%`,Af=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let a=JSON.parse(r.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=Cf(t.length);return t.push({token:s,type:String(a.type)}),s}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let a=Cf(t.length);return t.push({token:a,type:r}),a}),n},Sf=e=>{let t=$o(e);return n=>{let o=[],r=Af(n,o),a=t(r);return o.forEach(({token:s,type:l})=>{let p=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${wf(l)}"></div>`;a=a.replace(p,c)}),a}},Mf=e=>{let t=[],n=Af(e,t),o=_l(n);return t.forEach(({token:r,type:a})=>{let s=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${wf(a)}"></div>`;o=o.replace(s,p)}),o};var Gy={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"]},Ky=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ul=()=>{let e=null;return t=>{let n=Vn();if(!n)return In(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,a)=>{if(a.attrName==="src"||a.attrName==="href"){let s=a.attrValue;s.toLowerCase().startsWith("data:")&&!Ky.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,Gy)}},wr=e=>e===!1?null:typeof e=="function"?e:Ul();var Tf=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Ef=e=>e.includes("|"),kf=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},Xy=e=>`| ${e.join(" | ")} |`,Jy=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Qy=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Lf=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
3
|
+
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],a=t[o+1];if(!Ef(r)||Tf.test(r)||!Tf.test(a))continue;let s=kf(r).length;if(s<1)continue;let l=Jy(s);t[o+1]!==l&&(t[o+1]=l,n=!0);let p=o+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!Ef(d))break;let c=Xy(Qy(kf(d),s));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
|
|
4
|
+
`):e};var Pf="var(--persona-md-table-scroll-fade, 24px)",Rf=new WeakSet;function Wf(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function If(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":Pf),e.style.setProperty("--persona-fade-r",r<=1?"0px":Pf)}function ql(e){Rf.has(e)||(Rf.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&If(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(If)}var Mn="webmcp:",Vl=new Map,Hf=e=>{Vl.clear();for(let t of e){let n=t.title?.trim();n&&Vl.set(t.name,n)}},va=e=>Vl.get(Is(e)),Rs={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},zl=null,Df=e=>{zl=e};function Ff(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${Yy(t.join(""))}`}function Bf(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);n=Math.imul(n^a,2654435761),o=Math.imul(o^a,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Yy(e){let t=Bf(e,0).toString(36),n=Bf(e,2654435761).toString(36);return`${t}.${n}`}var Ar=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return Rs.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Hf(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let a={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},s=ex(r.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Sn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let h=typeof document<"u"&&!!document.modelContext;return Sn(h?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let a=Is(t),s;try{s=await r.getTools()}catch(h){let S=h instanceof Error?h.message:String(h);return Sn(`Failed to read WebMCP registry: ${S}`)}Hf(s);let l=s.find(h=>h.name===a);if(!l)return Sn(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return Sn(`WebMCP tool not allowed by client allowlist: ${a}`);if(o?.aborted)return Sn("Aborted by cancel()");let p=va(a),d={toolName:a,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return Sn("User declined the tool call.");if(o?.aborted)return Sn("Aborted by cancel()");let c=new AbortController,u=!1,g=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),f=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",f,{once:!0}));try{let h=await r.executeTool(l,rx(n),{signal:c.signal});return tx(h)}catch(h){if(u)return Sn(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Sn("Aborted by cancel()");let S=h instanceof Error?h.message:String(h);return Sn(S)}finally{clearTimeout(g),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(zl?await zl():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Rs.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Rs.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){let n=this.confirmHandler??nx;try{return await n(t)}catch(o){return Rs.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Zy(t,o))}},Is=e=>e.startsWith(Mn)?e.slice(Mn.length):e,uo=e=>e.startsWith(Mn),Zy=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},ex=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},tx=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:ax(t)}]}},Sn=e=>({isError:!0,content:[{type:"text",text:e}]}),nx=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=ox(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
5
5
|
|
|
6
6
|
Arguments:
|
|
7
7
|
${t}`:"")+(e.description?`
|
|
8
8
|
|
|
9
|
-
${e.description}`:"");return window.confirm(n)},Qy=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Yy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Zy=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function Jo(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function Fs(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}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var ex="agent_",tx="flow_";function Wf(e){return e.startsWith(ex)?{kind:"agentId",agentId:e}:e.startsWith(tx)?{kind:"flowId",flowId:e}:null}function Hf(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let s=n.slice(0,o),l=n.slice(o+1);if(s==="runtype"){let c=Wf(l);if(c)return c;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[s];if(!p)throw new Error(`[Persona] No target provider registered for "${s}". Add a \`targetProviders.${s}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=Wf(n);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var fo=po(_s(),1);var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Hn=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o},Df=()=>document.createDocumentFragment(),Be=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let l of Object.keys(s)){let p=s[l];p!=null&&(a[l]=p)}}let r=n.filter(a=>a!=null);return r.length>0&&o.append(...r),o},$n=(...e)=>e.filter(Boolean).join(" ");var ka="ask_user_question",Ea=8,kr="data-persona-ask-sheet-for",sx="Other",ix="Other\u2026",Nf="Type your own answer here",Of="Send",lx="Next",dx="Back",cx="Submit all",px="Skip",ux=3,Kl="data-ask-current-index",Xl="data-ask-question-count",_f="data-ask-answers",Jl="data-ask-grouped",Uf="data-ask-layout",fx=e=>e.layout==="pills"?"pills":"rows",mx=e=>e.getAttribute(Uf)==="pills"?"pills":"rows",Ff=!1,qf=e=>e.replace(/["\\]/g,"\\$&"),jn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ka,Us=e=>e?.features?.askUserQuestion??{},Gn=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),a=(0,fo.parse)(r,fo.STR|fo.OBJ|fo.ARR);if(a&&typeof a=="object")return{payload:a,complete:n}}catch{}return{payload:null,complete:n}},La=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ea&&!Ff&&(Ff=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ea}.`)),t.slice(0,Ea)},gx=e=>La(e)[0]??null,hx=(e,t)=>La(e)[t]??null,Vf=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},zf=(e,t,n)=>{if(e!=="rows")return null;let o=y("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=y("span","persona-ask-row-check");o.appendChild(r)}else{let r=y("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},yx=(e,t,n,o)=>{let a=y("button",n==="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",o?"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),n==="rows"){let s=y("span","persona-ask-row-content"),l=y("span","persona-ask-row-label");if(l.textContent=e.label,s.appendChild(l),e.description){let c=y("span","persona-ask-row-description");c.textContent=e.description,s.appendChild(c)}a.appendChild(s);let p=zf(n,o,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},xx=e=>{let n=y("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 n.setAttribute("aria-hidden","true"),n},bx=(e,t,n,o)=>{let a=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(d=>d&&typeof d.label=="string"&&d.label.length>0);if(p.length===0&&!n){for(let d=0;d<ux;d++)a.appendChild(xx(o));return a}if(p.forEach((d,u)=>{a.appendChild(yx(d,u,o,s))}),e?.allowFreeText!==!1){let d=o==="rows"?sx:ix;if(o==="rows"){let u=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let g=y("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??Nf,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??d),g.appendChild(f),u.appendChild(g);let h=zf(o,s,p.length);h&&u.appendChild(h),a.appendChild(u)}else{let u=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??d,a.appendChild(u)}}return a},$f=(e,t)=>{let o=y("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");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Nf,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let a=y("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??Of,a.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(a)}return o},Cx=e=>{let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Of,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},vx=(e,t,n)=>{let o=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=y("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??dx,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let a=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=y("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=n.skipLabel??px,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let l=y("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??cx:n.nextLabel??lx,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,a.appendChild(l),o.appendChild(a),o},Qo=e=>{let t=e.getAttribute(_f);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},jf=(e,t)=>{e.setAttribute(_f,JSON.stringify(t))},yn=e=>{let t=Number(e.getAttribute(Kl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},wx=(e,t)=>{e.setAttribute(Kl,String(Math.max(0,Math.floor(t))))},Lr=e=>{let t=Number(e.getAttribute(Xl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},mo=e=>e.getAttribute(Jl)==="true",Ax=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,a)=>{let s=typeof r?.question=="string"?r.question:"";if(s&&Object.prototype.hasOwnProperty.call(n,s)){let l=n[s];(typeof l=="string"||Array.isArray(l))&&(o[a]=l)}}),o},Sx=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},qs=(e,t)=>{let{payload:n}=Gn(t),o=La(n),r=Qo(e),a={},s=new Set;return o.forEach((l,p)=>{let c=typeof l?.question=="string"?l.question:"";c&&(s.has(c)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),s.add(c),Object.prototype.hasOwnProperty.call(r,p)&&(a[c]=r[p]))}),a},Gf=e=>{let t=Qo(e),n=yn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(p=>{let c=p.getAttribute("data-option-label")??"",d=r.has(c);p.setAttribute("aria-pressed",d?"true":"false"),p.classList.toggle("persona-ask-pill-selected",d)});let s=new Set(Array.from(a).map(p=>p.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!s.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},Kf=e=>{if(!mo(e))return;let t=Qo(e),n=yn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!r);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=l.length===0}},Ql=(e,t,n)=>{let o=Us(n),r=mx(e),{payload:a,complete:s}=Gn(t),l=mo(e),p=yn(e),c=Lr(e),d=l?hx(a,p):gx(a),u=!!d?.multiSelect,g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=l?`${p+1}/${c}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let M=typeof d?.question=="string"?d.question:"";h.textContent=M,h.classList.toggle("persona-ask-question-skeleton",!M&&!s)}let S=e.querySelector('[data-ask-pill-list="true"]');if(S){let M=bx(d,o,s,r);S.replaceWith(M)}if(r!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith($f(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!E?e.appendChild(Cx(o)):(!u||l)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(l){let M=vx(p,c,o);k?k.replaceWith(M):e.appendChild(M)}else k&&k.remove();Gf(e),Kf(e)},Mx=(e,t,n)=>{let o=Us(t),r=fx(o),a=e.toolCall.id,s=La(n),l=Math.max(1,s.length),p=l>1,c=Ax(e,s),d=p?Sx(e,l):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(kr,a),u.setAttribute("data-tool-call-id",a),u.setAttribute("data-message-id",e.id),u.setAttribute(Xl,String(l)),u.setAttribute(Kl,String(d)),u.setAttribute(Jl,p?"true":"false"),u.setAttribute(Uf,r),jf(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Vf(u,o);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let h=y("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",g.appendChild(h),u.appendChild(g);let E=y("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 E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),r!=="rows"&&u.appendChild($f(o,r)),Ql(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Tx=(e,t,n)=>{let{payload:o}=Gn(t),r=Math.max(1,La(o).length);r>Lr(e)&&(e.setAttribute(Xl,String(r)),r>1&&!mo(e)&&e.setAttribute(Jl,"true")),Ql(e,t,n)},Xf=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=Us(t);Vf(n,o);let r=y("span","persona-ask-stub-label"),{complete:a}=Gn(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Pr=(e,t,n)=>{if(!n||!jn(e)||Us(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${kr}]`).forEach(c=>{c.getAttribute(kr)!==r&&c.remove()});let s=n.querySelector(`[${kr}="${qf(r)}"]`);if(s){Tx(s,e,t);return}let{payload:l}=Gn(e),p=Mx(e,t,l);n.appendChild(p)},go=(e,t)=>{if(!e)return;let n=t?`[${kr}="${qf(t)}"]`:`[${kr}]`;e.querySelectorAll(n).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)})},Yl=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),ho=(e,t)=>{let n=Qo(e),o=yn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,jf(e,n),Gf(e),Kf(e)},Vs=(e,t,n,o)=>{let r=Lr(e),a=Math.max(0,Math.min(r-1,o));wx(e,a),Ql(e,t,n)};var En="suggest_replies";var Zl={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:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},zs={name:En,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. Each suggestion is sent verbatim as the user's next message, so phrase suggestions 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:Zl,origin:"sdk",annotations:{readOnlyHint:!0}},ed=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Pa=e=>e.variant==="tool"&&e.toolCall?.name===En,td=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},$s=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Pa(n))continue;let o=td(n.toolCall?.args);return o.length>0?o:null}return null},Jf=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var nd={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ea,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},od={name:ka,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:nd,origin:"sdk",annotations:{readOnlyHint:!0}},Rr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(od),Jf(e)&&t.push(zs),t};var Kn=po(_s(),1),js=e=>e.replace(/\\n/g,`
|
|
10
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),yo=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)}},
|
|
9
|
+
${e.description}`:"");return window.confirm(n)},ox=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},rx=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},ax=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function jo(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function Ws(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}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var sx="agent_",ix="flow_";function Of(e){return e.startsWith(sx)?{kind:"agentId",agentId:e}:e.startsWith(ix)?{kind:"flowId",flowId:e}:null}function Nf(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let s=n.slice(0,o),l=n.slice(o+1);if(s==="runtype"){let d=Of(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[s];if(!p)throw new Error(`[Persona] No target provider registered for "${s}". Add a \`targetProviders.${s}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=Of(n);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var fo=po(Ds(),1);var x=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Uf=()=>document.createDocumentFragment(),Fe=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let l of Object.keys(s)){let p=s[l];p!=null&&(a[l]=p)}}let r=n.filter(a=>a!=null);return r.length>0&&o.append(...r),o},zn=(...e)=>e.filter(Boolean).join(" ");var wa="ask_user_question",Ca=8,Sr="data-persona-ask-sheet-for",ux="Other",fx="Other\u2026",Vf="Type your own answer here",zf="Send",mx="Next",gx="Back",hx="Submit all",yx="Skip",xx=3,jl="data-ask-current-index",Gl="data-ask-question-count",$f="data-ask-answers",Kl="data-ask-grouped",jf="data-ask-layout",bx=e=>e.layout==="pills"?"pills":"rows",vx=e=>e.getAttribute(jf)==="pills"?"pills":"rows",qf=!1,Gf=e=>e.replace(/["\\]/g,"\\$&"),$n=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===wa,Fs=e=>e?.features?.askUserQuestion??{},jn=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),a=(0,fo.parse)(r,fo.STR|fo.OBJ|fo.ARR);if(a&&typeof a=="object")return{payload:a,complete:n}}catch{}return{payload:null,complete:n}},Aa=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ca&&!qf&&(qf=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ca}.`)),t.slice(0,Ca)},Cx=e=>Aa(e)[0]??null,wx=(e,t)=>Aa(e)[t]??null,Kf=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Xf=(e,t,n)=>{if(e!=="rows")return null;let o=x("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=x("span","persona-ask-row-check");o.appendChild(r)}else{let r=x("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Ax=(e,t,n,o)=>{let a=x("button",n==="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",o?"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),n==="rows"){let s=x("span","persona-ask-row-content"),l=x("span","persona-ask-row-label");if(l.textContent=e.label,s.appendChild(l),e.description){let d=x("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let p=Xf(n,o,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Sx=e=>{let n=x("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 n.setAttribute("aria-hidden","true"),n},Mx=(e,t,n,o)=>{let a=x("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<xx;c++)a.appendChild(Sx(o));return a}if(p.forEach((c,u)=>{a.appendChild(Ax(c,u,o,s))}),e?.allowFreeText!==!1){let c=o==="rows"?ux:fx;if(o==="rows"){let u=x("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let g=x("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??Vf,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),g.appendChild(f),u.appendChild(g);let h=Xf(o,s,p.length);h&&u.appendChild(h),a.appendChild(u)}else{let u=x("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,a.appendChild(u)}}return a},Jf=(e,t)=>{let o=x("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");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Vf,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let a=x("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??zf,a.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(a)}return o},Tx=e=>{let t=x("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=x("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??zf,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Ex=(e,t,n)=>{let o=x("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=x("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??gx,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let a=x("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=x("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=n.skipLabel??yx,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let l=x("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??hx:n.nextLabel??mx,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,a.appendChild(l),o.appendChild(a),o},Go=e=>{let t=e.getAttribute($f);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Qf=(e,t)=>{e.setAttribute($f,JSON.stringify(t))},hn=e=>{let t=Number(e.getAttribute(jl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},kx=(e,t)=>{e.setAttribute(jl,String(Math.max(0,Math.floor(t))))},Mr=e=>{let t=Number(e.getAttribute(Gl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},mo=e=>e.getAttribute(Kl)==="true",Lx=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,a)=>{let s=typeof r?.question=="string"?r.question:"";if(s&&Object.prototype.hasOwnProperty.call(n,s)){let l=n[s];(typeof l=="string"||Array.isArray(l))&&(o[a]=l)}}),o},Px=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Os=(e,t)=>{let{payload:n}=jn(t),o=Aa(n),r=Go(e),a={},s=new Set;return o.forEach((l,p)=>{let d=typeof l?.question=="string"?l.question:"";d&&(s.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),s.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(a[d]=r[p]))}),a},Yf=e=>{let t=Go(e),n=hn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let s=new Set(Array.from(a).map(p=>p.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!s.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},Zf=e=>{if(!mo(e))return;let t=Go(e),n=hn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!r);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=l.length===0}},Xl=(e,t,n)=>{let o=Fs(n),r=vx(e),{payload:a,complete:s}=jn(t),l=mo(e),p=hn(e),d=Mr(e),c=l?wx(a,p):Cx(a),u=!!c?.multiSelect,g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=l?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let M=typeof c?.question=="string"?c.question:"";h.textContent=M,h.classList.toggle("persona-ask-question-skeleton",!M&&!s)}let S=e.querySelector('[data-ask-pill-list="true"]');if(S){let M=Mx(c,o,s,r);S.replaceWith(M)}if(r!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(Jf(o,r))}let L=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!L?e.appendChild(Tx(o)):(!u||l)&&L&&L.remove(),e.setAttribute("data-multi-select",u?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(l){let M=Ex(p,d,o);E?E.replaceWith(M):e.appendChild(M)}else E&&E.remove();Yf(e),Zf(e)},Rx=(e,t,n)=>{let o=Fs(t),r=bx(o),a=e.toolCall.id,s=Aa(n),l=Math.max(1,s.length),p=l>1,d=Lx(e,s),c=p?Px(e,l):0,u=x("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Sr,a),u.setAttribute("data-tool-call-id",a),u.setAttribute("data-message-id",e.id),u.setAttribute(Gl,String(l)),u.setAttribute(jl,String(c)),u.setAttribute(Kl,p?"true":"false"),u.setAttribute(jf,r),Qf(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Kf(u,o);let g=x("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=x("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let h=x("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",g.appendChild(h),u.appendChild(g);let L=x("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 L.setAttribute("data-ask-pill-list","true"),L.setAttribute("role","group"),u.appendChild(L),r!=="rows"&&u.appendChild(Jf(o,r)),Xl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Ix=(e,t,n)=>{let{payload:o}=jn(t),r=Math.max(1,Aa(o).length);r>Mr(e)&&(e.setAttribute(Gl,String(r)),r>1&&!mo(e)&&e.setAttribute(Kl,"true")),Xl(e,t,n)},em=(e,t)=>{let n=x("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=Fs(t);Kf(n,o);let r=x("span","persona-ask-stub-label"),{complete:a}=jn(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Tr=(e,t,n)=>{if(!n||!$n(e)||Fs(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Sr}]`).forEach(d=>{d.getAttribute(Sr)!==r&&d.remove()});let s=n.querySelector(`[${Sr}="${Gf(r)}"]`);if(s){Ix(s,e,t);return}let{payload:l}=jn(e),p=Rx(e,t,l);n.appendChild(p)},go=(e,t)=>{if(!e)return;let n=t?`[${Sr}="${Gf(t)}"]`:`[${Sr}]`;e.querySelectorAll(n).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)})},Jl=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),ho=(e,t)=>{let n=Go(e),o=hn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Qf(e,n),Yf(e),Zf(e)},Ns=(e,t,n,o)=>{let r=Mr(e),a=Math.max(0,Math.min(r-1,o));kx(e,a),Xl(e,t,n)};var Tn="suggest_replies";var Ql={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:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},_s={name:Tn,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. Each suggestion is sent verbatim as the user's next message, so phrase suggestions 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:Ql,origin:"sdk",annotations:{readOnlyHint:!0}},Yl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Sa=e=>e.variant==="tool"&&e.toolCall?.name===Tn,Zl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Us=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Sa(n))continue;let o=Zl(n.toolCall?.args);return o.length>0?o:null}return null},tm=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var ed={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ca,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},td={name:wa,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:ed,origin:"sdk",annotations:{readOnlyHint:!0}},Er=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(td),tm(e)&&t.push(_s),t};var Gn=po(Ds(),1),qs=e=>e.replace(/\\n/g,`
|
|
10
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),yo=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)}},Wx=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},nm=e=>e.status==="complete"?Wx(e):e.status==="pending"?"Waiting":"",Hx=e=>{let n=(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 n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var om=e=>e.status==="complete"?Hx(e):"Using tool...",Vs=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ta=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 Vs(t)},zs=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Vs(t)},nd=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Ta(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},$s=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=r.exec(n))!==null;)s.index>a&&Ma(o,n.slice(a,s.index),[]),s[1]!==void 0?Ma(o,s[1],["bold"]):s[2]!==void 0?Ma(o,s[2],["italic"]):s[3]!==void 0&&Ma(o,s[3],["dim"]),a=s.index+s[0].length;return a<n.length&&Ma(o,n.slice(a),[]),o},Ma=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Bx=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(r);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
11
11
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(s);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
12
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let a=n(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Wa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Js=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Qs=()=>{let e=Lx();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Ys=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Kn.parse)(n,Kn.STR|Kn.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?js(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=js(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Zf=e=>{let t=null,n=0,r=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?js(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?js(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=n)return t!==null?{text:t,raw:a}:null;try{let l=(0,Kn.parse)(a,Kn.STR|Kn.OBJ),p=r(l);p!==null&&(t=p)}catch{}return n=a.length,{text:t||"",raw:a}},close:()=>{}}},Zs=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var em="4.10.1";var Yo=em;var Rx="https://api.runtype.com/v1/dispatch",ei="https://api.runtype.com";function Ix(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;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 ad=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 Wx(e){switch(e){case"json":return Ys;case"regex-json":return Qs;case"xml":return Zs;default:return Js}}var tm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Hx(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=tm(n);if(!tm(o))return e;if(!r||o===n||o.startsWith(n))return t;let s=Wa(e);return Wa(t)!==null&&s===null?t:e}var Zo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=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??Rx,this.headers={"Content-Type":"application/json","X-Persona-Version":Yo,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Wx(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Er(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let a=Hf(o,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)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ei}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yo},body:JSON.stringify(r)});if(!a.ok){let l=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):a.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ei}/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":Yo},body:JSON.stringify(r)});if(!a.ok){let s=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(s.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let c=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:c}),c}let r=await this.buildPayload(t.messages),a=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([c])=>c!=="sessionId"&&c!=="session_id")):void 0,s={sessionId:o.sessionId,messages:t.messages.filter(ad).map(c=>({id:c.id,role:c.role,content:c.contentParts??c.llmContent??c.rawContent??c.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...a&&Object.keys(a).length>0&&{metadata:a},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,c=>{let d={...s,...c};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yo},body:JSON.stringify(d),signal:t.signal})});if(!l.ok){let c=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(c.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let d=new Error(c.error||"Failed to send message");throw n({type:"error",error:d}),d}if(!l.body){let c=new Error("No response body received");throw n({type:"error",error:c}),c}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ei}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(r,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let a=!!(n&&n.length>0),s=a?If(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=a&&l&&this.lastSentClientToolsFingerprint===s,c=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,d=!1,u;for(let g=0;;g++){if(u=await o({...a&&(d||!p)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),u.status===409&&g===0&&a&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:c&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||ei}/resume`,s;r&&(s=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(s&&(p.sessionId=s),r&&s){let c=[...Rr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:d,commit:u}=await this.sendWithClientToolsDiff(s,c,g=>{let f={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(a,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return d.ok&&u(),d}return fetch(a,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};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(n,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(ad).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...Rr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);return s&&(r.context=s),r}async buildPayload(t){let n=t.slice().filter(ad).sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let a=[...Rr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);if(s&&(r.context=s),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,a,s){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let p=d=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...d!==void 0&&{partId:d}};return o.current=u,r(u),u},c=d=>o.current?o.current:p(d);if(l.text!==void 0){l.partId!==void 0&&s.current!==null&&l.partId!==s.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(s.current=l.partId);let d=c(l.partId);l.partId!==void 0&&!d.partId&&(d.partId=l.partId),d.content+=l.text,r(d)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),s.current=null,n({type:"status",status:"idle"})),l.error&&(s.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let a=t.getReader(),s=new TextDecoder,l="",p=Date.now(),c=0,d=()=>p+c++,u=I=>{let q=I.reasoning?{...I.reasoning,chunks:[...I.reasoning.chunks]}:void 0,b=I.toolCall?{...I.toolCall,chunks:I.toolCall.chunks?[...I.toolCall.chunks]:void 0}:void 0,L=I.tools?I.tools.map(W=>({...W,chunks:W.chunks?[...W.chunks]:void 0})):void 0;return{...I,reasoning:q,toolCall:b,tools:L}},g=I=>{if(I.role!=="assistant"||I.variant)return!0;let q=Array.isArray(I.contentParts)&&I.contentParts.length>0,b=typeof I.rawContent=="string"&&I.rawContent.trim()!=="";return typeof I.content=="string"&&I.content.trim()!==""||q||b||!!I.stopReason},f=I=>{g(I)&&n({type:"message",message:u(I)})},h=null,S=null,E={current:null},k={current:null},M=null,A="",w=new Map,T=new Map,R=new Map,v=new Map,B=new Map,F={lastId:null,byStep:new Map},$={lastId:null,byCall:new Map},N=I=>{if(I==null)return null;try{return String(I)}catch{return null}},U=I=>N(I.stepId??I.step_id??I.step??I.parentId??I.flowStepId??I.flow_step_id),fe=I=>N(I.callId??I.call_id??I.requestId??I.request_id??I.toolCallId??I.tool_call_id??I.stepId??I.step_id),ce=o,Le=!1,De=()=>{if(h)return h;let I,q="",b=M;return!Le&&ce?(I=ce,Le=!0,q=r??""):ce&&b?I=`${ce}_${b}`:I=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:I,role:"assistant",content:q,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},f(h),h},ae=(I,q)=>{F.lastId=q,I&&F.byStep.set(I,q)},Ce=(I,q)=>{let b=I.reasoningId??I.id,L=U(I);if(b){let O=String(b);return ae(L,O),O}if(L){let O=F.byStep.get(L);if(O)return F.lastId=O,O}if(F.lastId&&!q)return F.lastId;if(!q)return null;let W=`reason-${d()}`;return ae(L,W),W},ee=I=>{let q=v.get(I);if(q)return q;let b={id:`reason-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:I,status:"streaming",chunks:[]}};return v.set(I,b),f(b),b},le=(I,q)=>{$.lastId=q,I&&$.byCall.set(I,q)},Y=new Set,ve=new Map,Ae=new Set,be=new Map,He=I=>{if(!I)return!1;let q=I.replace(/_+/g,"_").replace(/^_|_$/g,"");return q==="emit_artifact_markdown"||q==="emit_artifact_component"},Ne=(I,q)=>{let b=I.toolId??I.id,L=fe(I);if(b){let O=String(b);return le(L,O),O}if(L){let O=$.byCall.get(L);if(O)return $.lastId=O,O}if($.lastId&&!q)return $.lastId;if(!q)return null;let W=`tool-${d()}`;return le(L,W),W},Xe=I=>{let q=B.get(I);if(q)return q;let b={id:`tool-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:I,status:"pending"}};return B.set(I,b),f(b),b},Oe=I=>{if(typeof I=="number"&&Number.isFinite(I))return I;if(typeof I=="string"){let q=Number(I);if(!Number.isNaN(q)&&Number.isFinite(q))return q;let b=Date.parse(I);if(!Number.isNaN(b))return b}return Date.now()},lt=I=>{if(typeof I=="string")return I;if(I==null)return"";try{return JSON.stringify(I)}catch{return String(I)}},Ye=new Map,Pe=new Map,Se=new Map,Ze=(I,q,b)=>{let L=Se.get(I);L||(L=[],Se.set(I,L));let W=0,O=L.length;for(;W<O;){let _=W+O>>>1;L[_].seq<q?W=_+1:O=_}L[W]?.seq===q?L[W]={seq:q,text:b}:L.splice(W,0,{seq:q,text:b});let G="";for(let _=0;_<L.length;_++)G+=L[_].text;return G},un=(I,q)=>{let b=lt(q),L=Pe.get(I.id),W=Hx(L,b);I.rawContent=W;let O=Ye.get(I.id),G=Me=>{let dt=I.content??"";Me.trim()!==""&&(dt.trim().length===0||Me.startsWith(dt)||Me.trimStart().startsWith(dt.trim()))&&(I.content=Me)},_=()=>{if(O){let Me=O.close?.();Me instanceof Promise&&Me.catch(()=>{})}Ye.delete(I.id),Pe.delete(I.id),I.streaming=!1,f(I)};if(!O){G(b),_();return}let j=Wa(W);if(j!==null&&j.trim()!==""){G(j),_();return}let ne=Me=>{let dt=typeof Me=="string"?Me:Me?.text??null;if(dt!==null&&dt.trim()!=="")return dt;let K=O.getExtractedText();return K!==null&&K.trim()!==""?K:b},Ge;try{Ge=O.processChunk(W)}catch{G(b),_();return}if(Ge instanceof Promise){Ge.then(Me=>{G(ne(Me)),_()}).catch(()=>{G(b),_()});return}G(ne(Ge)),_()},kt=null,xt=(I,q,b,L)=>{I.rawContent=q,Ye.has(I.id)||Ye.set(I.id,this.createStreamParser());let W=Ye.get(I.id),O=q.trim().startsWith("{")||q.trim().startsWith("[");if(O&&Pe.set(I.id,q),W.__isPlainTextParser===!0){I.content=L!==void 0?q:I.content+b,Pe.delete(I.id),Ye.delete(I.id),I.rawContent=void 0,f(I);return}let _=W.processChunk(q);if(_ instanceof Promise)_.then(j=>{let ne=typeof j=="string"?j:j?.text??null;ne!==null&&ne.trim()!==""?(I.content=ne,f(I)):!O&&!q.trim().startsWith("<")&&(I.content=L!==void 0?q:I.content+b,Pe.delete(I.id),Ye.delete(I.id),I.rawContent=void 0,f(I))}).catch(()=>{I.content=L!==void 0?q:I.content+b,Pe.delete(I.id),Ye.delete(I.id),I.rawContent=void 0,f(I)});else{let j=typeof _=="string"?_:_?.text??null;j!==null&&j.trim()!==""?(I.content=j,f(I)):!O&&!q.trim().startsWith("<")&&(I.content=L!==void 0?q:I.content+b,Pe.delete(I.id),Ye.delete(I.id),I.rawContent=void 0,f(I))}},Re=(I,q)=>{let b=q??I.content;if(b==null||b===""){I.streaming=!1,f(I);return}let W=Pe.get(I.id)??lt(b);I.rawContent=W;let O=Ye.get(I.id),G=null,_=!1;if(O&&(G=O.getExtractedText(),G===null&&(G=Wa(W)),G===null)){let j=O.processChunk(W);j instanceof Promise?(_=!0,j.then(ne=>{let Ge=typeof ne=="string"?ne:ne?.text??null;Ge!==null&&(I.content=Ge,I.streaming=!1,Ye.delete(I.id),Pe.delete(I.id),f(I))}).catch(()=>{})):G=typeof j=="string"?j:j?.text??null}if(!_){G!==null&&G.trim()!==""?I.content=G:Pe.has(I.id)||(I.content=lt(b));let j=Ye.get(I.id);if(j){let ne=j.close?.();ne instanceof Promise&&ne.catch(()=>{}),Ye.delete(I.id)}Pe.delete(I.id),I.streaming=!1,f(I)}},me=(I,q,b)=>{let L=T.get(I);if(L)return L;let W={id:`nested-${q}-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...b?{variant:b}:{},...b==="reasoning"?{reasoning:{id:I,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:q}};return T.set(I,W),f(W),W},Je=[],Ee,ue=new Map,se=0,ye="agent",bt=!1,ge=null,pe=null,xn=new Map,Q=this.config.iterationDisplay??"separate";for(Ee=()=>{for(let I=0;I<Je.length;I++){let q=Je[I].payloadType,b=Je[I].payload;if(!bt&&ye!=="flow"&&typeof b.stepType=="string"&&(ye="flow"),q==="reasoning_start"){let L=typeof b.id=="string"?b.id:null,W=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(L&&W){w.set(L,W),me(L,W,"reasoning");continue}let O=Ce(b,!0)??`reason-${d()}`,G=ee(O);G.reasoning=G.reasoning??{id:O,status:"streaming",chunks:[]},G.reasoning.startedAt=G.reasoning.startedAt??Oe(b.startedAt??b.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(b.scope==="loop"||b.scope==="turn")&&(G.reasoning.scope=b.scope),G.streaming=!0,G.reasoning.status="streaming",f(G)}else if(q==="reasoning_delta"){let L=typeof b.id=="string"?b.id:null;if(L&&w.has(L)&&T.has(L)){let _=T.get(L),j=b.reasoningText??b.text??b.delta??"";j&&b.hidden!==!0&&_.reasoning&&(_.reasoning.chunks.push(String(j)),f(_));continue}let W=Ce(b,!1)??Ce(b,!0)??`reason-${d()}`,O=ee(W);O.reasoning=O.reasoning??{id:W,status:"streaming",chunks:[]},O.reasoning.startedAt=O.reasoning.startedAt??Oe(b.startedAt??b.timestamp);let G=b.reasoningText??b.text??b.delta??"";if(G&&b.hidden!==!0){let _=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(_!==void 0){let j=Ze(W,_,String(G));O.reasoning.chunks=[j]}else O.reasoning.chunks.push(String(G))}if(O.reasoning.status=b.done?"complete":"streaming",b.done){O.reasoning.completedAt=Oe(b.completedAt??b.timestamp);let _=O.reasoning.startedAt??Date.now();O.reasoning.durationMs=Math.max(0,(O.reasoning.completedAt??Date.now())-_)}O.streaming=O.reasoning.status!=="complete",f(O)}else if(q==="reasoning_complete"){let L=typeof b.id=="string"?b.id:null;if(L&&w.has(L)&&T.has(L)){let j=T.get(L);if(j.reasoning){let ne=typeof b.text=="string"?b.text:"";ne&&j.reasoning.chunks.length===0&&j.reasoning.chunks.push(ne),j.reasoning.status="complete",j.streaming=!1,f(j)}w.delete(L),T.delete(L);continue}let W=Ce(b,!1)??Ce(b,!0)??`reason-${d()}`,O=typeof b.text=="string"?b.text:"";!v.get(W)&&(O||b.scope==="loop")&&ee(W);let G=v.get(W);if(G?.reasoning){(b.scope==="loop"||b.scope==="turn")&&(G.reasoning.scope=b.scope),O&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(O),G.reasoning.status="complete",G.reasoning.completedAt=Oe(b.completedAt??b.timestamp);let j=G.reasoning.startedAt??Date.now();G.reasoning.durationMs=Math.max(0,(G.reasoning.completedAt??Date.now())-j),G.streaming=!1,f(G)}let _=U(b);_&&F.byStep.delete(_)}else if(q==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof b.iteration=="number"&&(se=b.iteration);let L=(typeof b.toolCallId=="string"?b.toolCallId:void 0)??Ne(b,!0)??`tool-${d()}`,W=b.toolName??b.name;if(He(W)){Y.add(L);continue}le(fe(b),L);let O=Xe(L),G=O.toolCall??{id:L,status:"pending"};G.name=W??G.name,G.status="running",b.parameters!==void 0?G.args=b.parameters:b.args!==void 0&&(G.args=b.args),G.startedAt=G.startedAt??Oe(b.startedAt??b.timestamp),G.completedAt=void 0,G.durationMs=void 0,O.toolCall=G,O.streaming=!0,b.executionId&&(O.agentMetadata={executionId:b.executionId,iteration:b.iteration}),f(O)}else if(q==="tool_output_delta"){let L=Ne(b,!1)??Ne(b,!0)??`tool-${d()}`;if(Y.has(L))continue;let W=Xe(L),O=W.toolCall??{id:L,status:"running"};O.startedAt=O.startedAt??Oe(b.startedAt??b.timestamp);let G=b.text??b.delta??b.message??"";G&&(O.chunks=O.chunks??[],O.chunks.push(String(G))),O.status="running",W.toolCall=O,W.streaming=!0;let _=b.agentContext;(_||b.executionId)&&(W.agentMetadata=W.agentMetadata??{executionId:_?.executionId??b.executionId,iteration:_?.iteration??b.iteration}),f(W)}else if(q==="tool_complete"){let L=Ne(b,!1)??Ne(b,!0)??`tool-${d()}`;if(Y.has(L)){Y.delete(L);continue}let W=Xe(L),O=W.toolCall??{id:L,status:"running"};O.status="complete",b.result!==void 0&&(O.result=b.result),typeof b.duration=="number"&&(O.duration=b.duration),O.completedAt=Oe(b.completedAt??b.timestamp);let G=b.duration??b.executionTime;if(typeof G=="number")O.durationMs=G;else{let ne=O.startedAt??Date.now();O.durationMs=Math.max(0,(O.completedAt??Date.now())-ne)}W.toolCall=O,W.streaming=!1;let _=b.agentContext;(_||b.executionId)&&(W.agentMetadata=W.agentMetadata??{executionId:_?.executionId??b.executionId,iteration:_?.iteration??b.iteration}),f(W);let j=fe(b);j&&$.byCall.delete(j)}else if(q==="await"&&b.toolName){let L=typeof b.toolCallId=="string"&&b.toolCallId.length>0?b.toolCallId:void 0,W=L??b.toolId??`local-${d()}`,O=Xe(W),G=b.toolName,_=b.origin==="webmcp"&&!uo(G)?`webmcp:${G}`:G,j=uo(_),ne=O.toolCall??{id:W,status:"pending"};ne.name=_,ne.args=b.parameters,ne.status=j?"running":"complete",ne.chunks=ne.chunks??[],ne.startedAt=ne.startedAt??Oe(b.startedAt??b.timestamp??b.awaitedAt),j?(ne.completedAt=void 0,ne.duration=void 0,ne.durationMs=void 0):ne.completedAt=ne.completedAt??ne.startedAt,O.toolCall=ne,O.streaming=!1,O.agentMetadata={...O.agentMetadata,executionId:b.executionId??O.agentMetadata?.executionId,awaitingLocalTool:!0,...L?{webMcpToolCallId:L}:{}},f(O)}else if(q==="text_start"){let L=typeof b.id=="string"?b.id:null,W=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(L&&W){w.set(L,W);continue}let O=h;O&&(ye==="flow"?(Re(O),kt=O):(O.streaming=!1,f(O)),h=null),M=typeof b.id=="string"?b.id:M,A=""}else if(q==="text_delta"){let L=typeof b.id=="string"?b.id:null,W=L?w.get(L):void 0;if(L&&W){let G=typeof b.delta=="string"?b.delta:"",_=(R.get(L)??"")+G;if(R.set(L,_),_.trim()==="")continue;let j=me(L,W);j.agentMetadata={...j.agentMetadata,executionId:b.executionId,parentToolId:W},xt(j,_,G,void 0);continue}if(M=typeof b.id=="string"?b.id:M,ye==="flow"){let G=typeof b.delta=="string"?b.delta:"";if(A+=G,A.trim()==="")continue;let _=De();_.agentMetadata={executionId:b.executionId,iteration:b.iteration},xt(_,A,G,void 0),S=_;continue}let O=De();O.content+=b.delta??"",O.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:ge??void 0,agentName:pe?.agentName},S=O,f(O)}else if(q==="text_complete"){let L=typeof b.id=="string"?b.id:null;if(L&&w.has(L)){let O=T.get(L);O&&Re(O),w.delete(L),R.delete(L),T.delete(L);continue}let W=h;W&&(ye==="flow"?(Re(W),kt=W):((W.content??"")===""&&typeof b.text=="string"&&(W.content=b.text),W.streaming=!1,f(W)),h=null),M=null,A=""}else if(q==="step_complete"){let L=b.stepType,W=b.executionType;if(L==="tool"||W==="context")continue;if(b.success===!1){let O=b.error,G=typeof O=="string"&&O!==""?O:O!=null&&typeof O=="object"&&Reflect.has(O,"message")?String(O.message??"Step failed"):"Step failed";n({type:"error",error:new Error(G)});let _=h;_&&_.streaming&&(_.streaming=!1,f(_)),n({type:"status",status:"idle"});continue}{let O=kt;kt=null;let G=b.stopReason,_=b.result?.response;if(O)G&&(O.stopReason=G),_!=null?un(O,_):O.streaming!==!1&&(Ye.delete(O.id),Pe.delete(O.id),O.streaming=!1,f(O));else{let j=_!=null&&_!=="";if(j||G){let ne=De();G&&(ne.stopReason=G),j?Re(ne,_):(ne.streaming=!1,f(ne))}}continue}}else if(q==="execution_start")ye=b.kind==="flow"?"flow":"agent",bt=!0,ye==="agent"&&(pe={executionId:b.executionId,agentId:b.agentId??"virtual",agentName:b.agentName??"",status:"running",currentIteration:0,maxTurns:b.maxTurns??1,startedAt:Oe(b.startedAt)});else if(q==="turn_start"){let L=typeof b.iteration=="number"?b.iteration:se;if(L!==se){if(pe&&(pe.currentIteration=L),Q==="separate"&&L>1){let W=h;W&&(W.streaming=!1,f(W),xn.set(L-1,W),h=null)}se=L}ge=typeof b.id=="string"?b.id:null,S=null}else if(q==="tool_input_delta"){let L=b.toolCallId??$.lastId;if(L){let W=B.get(L);W?.toolCall&&(W.toolCall.chunks=W.toolCall.chunks??[],W.toolCall.chunks.push(b.delta??""),f(W))}}else{if(q==="tool_input_complete")continue;if(q==="turn_complete"){let L=b.stopReason,W=h??S;if(L&&W!==null){let O=b.id;(!O||W.agentMetadata?.turnId===O)&&(W.stopReason=L,f(W))}ge===b.id&&(ge=null)}else if(q==="media_start"){let L=String(b.id);ue.set(L,{mediaType:typeof b.mediaType=="string"?b.mediaType:void 0,role:typeof b.role=="string"?b.role:void 0,toolCallId:b.toolCallId,parts:[]})}else if(q==="media_delta"){let L=ue.get(String(b.id));L&&typeof b.delta=="string"&&L.parts.push(b.delta)}else if(q==="media_complete"){let L=String(b.id),W=ue.get(L);ue.delete(L);let O=(typeof b.mediaType=="string"?b.mediaType:void 0)??W?.mediaType??"application/octet-stream",G=typeof b.data=="string"?b.data:void 0,_=typeof b.url=="string"?b.url:W&&W.parts.length>0?W.parts.join(""):void 0,j=null;if(G)j={type:"media",data:G,mediaType:O};else if(_){let dt=O.toLowerCase();j={type:dt==="image"||dt.startsWith("image/")?"image-url":"file-url",url:_,mediaType:O}}let ne=b.toolCallId??W?.toolCallId,Ge=j?[j]:[],Me=[];for(let dt of Ge){if(!dt||typeof dt!="object")continue;let K=dt,Ue=typeof K.type=="string"?K.type:void 0,Te=typeof K.mediaType=="string"?K.mediaType.toLowerCase():"",Ie=null,ke="";if(Ue==="media"){let et=typeof K.data=="string"?K.data:void 0;if(!et)continue;ke=Te.length>0?Te:"application/octet-stream",Ie=`data:${ke};base64,${et}`}else if(Ue==="image-url"){let et=typeof K.url=="string"?K.url:void 0;if(!et)continue;ke=Te,Ie=et}else if(Ue==="file-url"){let et=typeof K.url=="string"?K.url:void 0;if(!et)continue;ke=Te,Ie=et}else continue;if(Ie)if(Ue==="image-url"||ke.startsWith("image/"))Me.push({type:"image",image:Ie,...ke.includes("/")?{mimeType:ke}:{}});else if(ke.startsWith("audio/"))Me.push({type:"audio",audio:Ie,mimeType:ke});else if(ke.startsWith("video/"))Me.push({type:"video",video:Ie,mimeType:ke});else{let et=ke||"application/octet-stream";Me.push({type:"file",data:Ie,mimeType:et,filename:Ix(et)})}}if(Me.length>0){let dt=d(),K=ne,Te={id:`agent-media-${typeof K=="string"&&K.length>0?`${K}-${dt}`:String(dt)}`,role:"assistant",content:"",contentParts:Me,createdAt:new Date().toISOString(),streaming:!1,sequence:dt,agentMetadata:{executionId:b.executionId,iteration:typeof b.iteration=="number"?b.iteration:se}};f(Te);let Ie=h;Ie&&(Ie.streaming=!1,f(Ie)),h=null,E.current=null}}else if(q==="execution_complete"){let L=b.kind??ye;L==="agent"&&pe&&(pe.status=b.success?"complete":"error",pe.completedAt=Oe(b.completedAt),pe.stopReason=b.stopReason);let W=h;W&&(L==="flow"&&W.streaming!==!1?Re(W):(W.streaming=!1,f(W)),h=null),M=null,A="",kt=null,n({type:"status",status:"idle",terminal:!0})}else if(q==="execution_error"){let L=typeof b.error=="string"?b.error:b.error?.message??"Execution error";n({type:"error",error:new Error(L)})}else if(q!=="ping"){if(q==="approval_start"){let L=b.approvalId??`approval-${d()}`,W={id:`approval-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:L,status:"pending",agentId:pe?.agentId??"virtual",executionId:b.executionId??pe?.executionId??"",toolName:b.toolName??"",toolType:b.toolType,description:b.description??`Execute ${b.toolName??"tool"}`,...typeof b.reason=="string"&&b.reason?{reason:b.reason}:{},parameters:b.parameters}};f(W)}else if(q==="step_await"&&b.awaitReason==="approval_required"){let L=b.approvalId??`approval-${d()}`,W={id:`approval-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:L,status:"pending",agentId:pe?.agentId??"virtual",executionId:b.executionId??pe?.executionId??"",toolName:b.toolName??"",toolType:b.toolType,description:b.description??`Execute ${b.toolName??"tool"}`,...typeof b.reason=="string"&&b.reason?{reason:b.reason}:{},parameters:b.parameters}};f(W)}else if(q==="approval_complete"){let L=b.approvalId;if(L){let O={id:`approval-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:L,status:b.decision??"approved",agentId:pe?.agentId??"virtual",executionId:b.executionId??pe?.executionId??"",toolName:b.toolName??"",description:b.description??"",resolvedAt:Date.now()}};f(O)}}else if(q==="artifact_start"||q==="artifact_delta"||q==="artifact_update"||q==="artifact_complete"){if(q==="artifact_start"){let L=b.artifactType,W=String(b.id),O=typeof b.title=="string"?b.title:void 0,G=b.file,_;G&&typeof G=="object"&&!Array.isArray(G)&&typeof G.path=="string"&&typeof G.mimeType=="string"&&(_={path:G.path,mimeType:G.mimeType,...typeof G.language=="string"?{language:G.language}:{}}),n({type:"artifact_start",id:W,artifactType:L,title:O,component:typeof b.component=="string"?b.component:void 0,..._?{file:_}:{}});let j=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?{...b.props}:void 0;if(be.set(W,{markdown:"",title:O,file:_,...j?{props:j}:{}}),!Ae.has(W)){Ae.add(W);let ne=Jo(this.config.features?.artifacts,L),Ge=typeof b.component=="string"?b.component:void 0,Me={id:`artifact-ref-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:Fs(ne,{artifactId:W,title:O,artifactType:L,status:"streaming",..._?{file:_}:{},...Ge?{component:Ge}:{}})};ve.set(W,Me),f(Me)}}else if(q==="artifact_delta"){let L=String(b.id),W=typeof b.delta=="string"?b.delta:String(b.delta??"");n({type:"artifact_delta",id:L,artDelta:W});let O=be.get(L);O&&(O.markdown+=W)}else if(q==="artifact_update"){let L=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};n({type:"artifact_update",id:String(b.id),props:L,component:typeof b.component=="string"?b.component:void 0});let W=be.get(String(b.id));W&&(W.props={...W.props??{},...L})}else if(q==="artifact_complete"){let L=String(b.id);n({type:"artifact_complete",id:L});let W=ve.get(L);if(W){W.streaming=!1;try{let O=JSON.parse(W.rawContent??"{}");if(O.props){O.props.status="complete";let G=be.get(L);G?.markdown&&(O.props.markdown=G.markdown),G?.file&&(O.props.file=G.file),O.component==="PersonaArtifactInline"&&G?.props&&Object.keys(G.props).length>0&&(O.props.componentProps=G.props)}W.rawContent=JSON.stringify(O)}catch{}be.delete(L),f(W),ve.delete(L)}}}else if(q==="transcript_insert"){let L=b.message;if(!L||typeof L!="object")continue;let W=String(L.id??`msg-${d()}`),O=L.role,_={id:W,role:O==="user"?"user":O==="system"?"system":"assistant",content:typeof L.content=="string"?L.content:"",rawContent:typeof L.rawContent=="string"?L.rawContent:void 0,createdAt:typeof L.createdAt=="string"?L.createdAt:new Date().toISOString(),streaming:L.streaming===!0,...typeof L.variant=="string"?{variant:L.variant}:{},sequence:d()};if(f(_),_.rawContent)try{let ne=JSON.parse(_.rawContent)?.props?.artifactId;typeof ne=="string"&&Ae.add(ne)}catch{}h=null,E.current=null,Ye.delete(W),Pe.delete(W)}else if(q==="error"){if(b.recoverable===!1&&b.error!=null&&b.error!==""){let L=typeof b.error=="string"?b.error:b.error?.message!=null?String(b.error.message):"Execution error";n({type:"error",error:new Error(L)});let W=h;W&&W.streaming&&(W.streaming=!1,f(W)),n({type:"status",status:"idle"})}}else if(q==="step_error"||q==="dispatch_error"||q==="flow_error"){let L=null;if(b.error instanceof Error)L=b.error;else if(q==="dispatch_error"){let W=b.message??b.error;W!=null&&W!==""&&(L=new Error(String(W)))}else{let W=b.error;typeof W=="string"&&W!==""?L=new Error(W):W!=null&&typeof W=="object"&&Reflect.has(W,"message")&&(L=new Error(String(W.message??W)))}if(L){n({type:"error",error:L});let W=h;W&&W.streaming&&(W.streaming=!1,f(W)),n({type:"status",status:"idle"})}}}}}Je.length=0};;){let{done:I,value:q}=await a.read();if(I)break;l+=s.decode(q,{stream:!0});let b=l.split(`
|
|
12
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let a=n(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Ea=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},js=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Gs=()=>{let e=Bx();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Ks=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Gn.parse)(n,Gn.STR|Gn.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?qs(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=qs(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},rm=e=>{let t=null,n=0,r=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?qs(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?qs(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=n)return t!==null?{text:t,raw:a}:null;try{let l=(0,Gn.parse)(a,Gn.STR|Gn.OBJ),p=r(l);p!==null&&(t=p)}catch{}return n=a.length,{text:t||"",raw:a}},close:()=>{}}},Xs=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var am="4.11.0";var Ko=am;var Fx="https://api.runtype.com/v1/dispatch",Js="https://api.runtype.com";function Ox(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;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 od=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 Nx(e){switch(e){case"json":return Ks;case"regex-json":return Gs;case"xml":return Xs;default:return js}}var sm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function _x(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=sm(n);if(!sm(o))return e;if(!r||o===n||o.startsWith(n))return t;let s=Ea(e);return Ea(t)!==null&&s===null?t:e}var Xo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=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??Fx,this.headers={"Content-Type":"application/json","X-Persona-Version":Ko,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Nx(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Ar(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let a=Nf(o,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)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Js}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ko},body:JSON.stringify(r)});if(!a.ok){let l=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):a.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Js}/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":Ko},body:JSON.stringify(r)});if(!a.ok){let s=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(s.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),a=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,s={sessionId:o.sessionId,messages:t.messages.filter(od).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...a&&Object.keys(a).length>0&&{metadata:a},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...s,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ko},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Js}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(r,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let a=!!(n&&n.length>0),s=a?Ff(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=a&&l&&this.lastSentClientToolsFingerprint===s,d=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let g=0;;g++){if(u=await o({...a&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),u.status===409&&g===0&&a&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Js}/resume`,s;r&&(s=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(s&&(p.sessionId=s),r&&s){let d=[...Er(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(s,d,g=>{let f={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(a,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(a,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};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(n,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(od).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...Er(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);return s&&(r.context=s),r}async buildPayload(t){let n=t.slice().filter(od).sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let a=[...Er(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);if(s&&(r.context=s),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,a,s){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);if(l.text!==void 0){l.partId!==void 0&&s.current!==null&&l.partId!==s.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(s.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),s.current=null,n({type:"status",status:"idle"})),l.error&&(s.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let a=t.getReader(),s=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,u=R=>{let z=R.reasoning?{...R.reasoning,chunks:[...R.reasoning.chunks]}:void 0,b=R.toolCall?{...R.toolCall,chunks:R.toolCall.chunks?[...R.toolCall.chunks]:void 0}:void 0,P=R.tools?R.tools.map(I=>({...I,chunks:I.chunks?[...I.chunks]:void 0})):void 0;return{...R,reasoning:z,toolCall:b,tools:P}},g=R=>{if(R.role!=="assistant"||R.variant)return!0;let z=Array.isArray(R.contentParts)&&R.contentParts.length>0,b=typeof R.rawContent=="string"&&R.rawContent.trim()!=="";return typeof R.content=="string"&&R.content.trim()!==""||z||b||!!R.stopReason},f=R=>{g(R)&&n({type:"message",message:u(R)})},h=null,S=null,L={current:null},E={current:null},M=null,A="",w=new Map,T=new Map,H=new Map,C=new Map,B=new Map,F={lastId:null,byStep:new Map},q={lastId:null,byCall:new Map},D=R=>{if(R==null)return null;try{return String(R)}catch{return null}},U=R=>D(R.stepId??R.step_id??R.step??R.parentId??R.flowStepId??R.flow_step_id),se=R=>D(R.callId??R.call_id??R.requestId??R.request_id??R.toolCallId??R.tool_call_id??R.stepId??R.step_id),le=o,Ce=!1,Le=()=>{if(h)return h;let R,z="",b=M;return!Ce&&le?(R=le,Ce=!0,z=r??""):le&&b?R=`${le}_${b}`:R=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:R,role:"assistant",content:z,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(h),h},ae=(R,z)=>{F.lastId=z,R&&F.byStep.set(R,z)},me=(R,z)=>{let b=R.reasoningId??R.id,P=U(R);if(b){let N=String(b);return ae(P,N),N}if(P){let N=F.byStep.get(P);if(N)return F.lastId=N,N}if(F.lastId&&!z)return F.lastId;if(!z)return null;let I=`reason-${c()}`;return ae(P,I),I},Z=R=>{let z=C.get(R);if(z)return z;let b={id:`reason-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:R,status:"streaming",chunks:[]}};return C.set(R,b),f(b),b},de=(R,z)=>{q.lastId=z,R&&q.byCall.set(R,z)},Y=new Set,ve=new Map,Ae=new Set,xe=new Map,Be=R=>{if(!R)return!1;let z=R.replace(/_+/g,"_").replace(/^_|_$/g,"");return z==="emit_artifact_markdown"||z==="emit_artifact_component"},Oe=(R,z)=>{let b=R.toolId??R.id,P=se(R);if(b){let N=String(b);return de(P,N),N}if(P){let N=q.byCall.get(P);if(N)return q.lastId=N,N}if(q.lastId&&!z)return q.lastId;if(!z)return null;let I=`tool-${c()}`;return de(P,I),I},Ve=R=>{let z=B.get(R);if(z)return z;let b={id:`tool-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:R,status:"pending"}};return B.set(R,b),f(b),b},Ne=R=>{if(typeof R=="number"&&Number.isFinite(R))return R;if(typeof R=="string"){let z=Number(R);if(!Number.isNaN(z)&&Number.isFinite(z))return z;let b=Date.parse(R);if(!Number.isNaN(b))return b}return Date.now()},rt=R=>{if(typeof R=="string")return R;if(R==null)return"";try{return JSON.stringify(R)}catch{return String(R)}},Xe=new Map,Pe=new Map,Se=new Map,Je=(R,z,b)=>{let P=Se.get(R);P||(P=[],Se.set(R,P));let I=0,N=P.length;for(;I<N;){let _=I+N>>>1;P[_].seq<z?I=_+1:N=_}P[I]?.seq===z?P[I]={seq:z,text:b}:P.splice(I,0,{seq:z,text:b});let G="";for(let _=0;_<P.length;_++)G+=P[_].text;return G},cn=(R,z)=>{let b=rt(z),P=Pe.get(R.id),I=_x(P,b);R.rawContent=I;let N=Xe.get(R.id),G=Me=>{let at=R.content??"";Me.trim()!==""&&(at.trim().length===0||Me.startsWith(at)||Me.trimStart().startsWith(at.trim()))&&(R.content=Me)},_=()=>{if(N){let Me=N.close?.();Me instanceof Promise&&Me.catch(()=>{})}Xe.delete(R.id),Pe.delete(R.id),R.streaming=!1,f(R)};if(!N){G(b),_();return}let j=Ea(I);if(j!==null&&j.trim()!==""){G(j),_();return}let re=Me=>{let at=typeof Me=="string"?Me:Me?.text??null;if(at!==null&&at.trim()!=="")return at;let K=N.getExtractedText();return K!==null&&K.trim()!==""?K:b},$e;try{$e=N.processChunk(I)}catch{G(b),_();return}if($e instanceof Promise){$e.then(Me=>{G(re(Me)),_()}).catch(()=>{G(b),_()});return}G(re($e)),_()},Et=null,xt=(R,z,b,P)=>{R.rawContent=z,Xe.has(R.id)||Xe.set(R.id,this.createStreamParser());let I=Xe.get(R.id),N=z.trim().startsWith("{")||z.trim().startsWith("[");if(N&&Pe.set(R.id,z),I.__isPlainTextParser===!0){R.content=P!==void 0?z:R.content+b,Pe.delete(R.id),Xe.delete(R.id),R.rawContent=void 0,f(R);return}let _=I.processChunk(z);if(_ instanceof Promise)_.then(j=>{let re=typeof j=="string"?j:j?.text??null;re!==null&&re.trim()!==""?(R.content=re,f(R)):!N&&!z.trim().startsWith("<")&&(R.content=P!==void 0?z:R.content+b,Pe.delete(R.id),Xe.delete(R.id),R.rawContent=void 0,f(R))}).catch(()=>{R.content=P!==void 0?z:R.content+b,Pe.delete(R.id),Xe.delete(R.id),R.rawContent=void 0,f(R)});else{let j=typeof _=="string"?_:_?.text??null;j!==null&&j.trim()!==""?(R.content=j,f(R)):!N&&!z.trim().startsWith("<")&&(R.content=P!==void 0?z:R.content+b,Pe.delete(R.id),Xe.delete(R.id),R.rawContent=void 0,f(R))}},Re=(R,z)=>{let b=z??R.content;if(b==null||b===""){R.streaming=!1,f(R);return}let I=Pe.get(R.id)??rt(b);R.rawContent=I;let N=Xe.get(R.id),G=null,_=!1;if(N&&(G=N.getExtractedText(),G===null&&(G=Ea(I)),G===null)){let j=N.processChunk(I);j instanceof Promise?(_=!0,j.then(re=>{let $e=typeof re=="string"?re:re?.text??null;$e!==null&&(R.content=$e,R.streaming=!1,Xe.delete(R.id),Pe.delete(R.id),f(R))}).catch(()=>{})):G=typeof j=="string"?j:j?.text??null}if(!_){G!==null&&G.trim()!==""?R.content=G:Pe.has(R.id)||(R.content=rt(b));let j=Xe.get(R.id);if(j){let re=j.close?.();re instanceof Promise&&re.catch(()=>{}),Xe.delete(R.id)}Pe.delete(R.id),R.streaming=!1,f(R)}},fe=(R,z,b)=>{let P=T.get(R);if(P)return P;let I={id:`nested-${z}-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...b?{variant:b}:{},...b==="reasoning"?{reasoning:{id:R,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:z}};return T.set(R,I),f(I),I},Ge=[],Te,pe=new Map,ie=0,ge="agent",bt=!1,he=null,ce=null,yn=new Map,Q=this.config.iterationDisplay??"separate";for(Te=()=>{for(let R=0;R<Ge.length;R++){let z=Ge[R].payloadType,b=Ge[R].payload;if(!bt&&ge!=="flow"&&typeof b.stepType=="string"&&(ge="flow"),z==="reasoning_start"){let P=typeof b.id=="string"?b.id:null,I=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(P&&I){w.set(P,I),fe(P,I,"reasoning");continue}let N=me(b,!0)??`reason-${c()}`,G=Z(N);G.reasoning=G.reasoning??{id:N,status:"streaming",chunks:[]},G.reasoning.startedAt=G.reasoning.startedAt??Ne(b.startedAt??b.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(b.scope==="loop"||b.scope==="turn")&&(G.reasoning.scope=b.scope),G.streaming=!0,G.reasoning.status="streaming",f(G)}else if(z==="reasoning_delta"){let P=typeof b.id=="string"?b.id:null;if(P&&w.has(P)&&T.has(P)){let _=T.get(P),j=b.reasoningText??b.text??b.delta??"";j&&b.hidden!==!0&&_.reasoning&&(_.reasoning.chunks.push(String(j)),f(_));continue}let I=me(b,!1)??me(b,!0)??`reason-${c()}`,N=Z(I);N.reasoning=N.reasoning??{id:I,status:"streaming",chunks:[]},N.reasoning.startedAt=N.reasoning.startedAt??Ne(b.startedAt??b.timestamp);let G=b.reasoningText??b.text??b.delta??"";if(G&&b.hidden!==!0){let _=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(_!==void 0){let j=Je(I,_,String(G));N.reasoning.chunks=[j]}else N.reasoning.chunks.push(String(G))}if(N.reasoning.status=b.done?"complete":"streaming",b.done){N.reasoning.completedAt=Ne(b.completedAt??b.timestamp);let _=N.reasoning.startedAt??Date.now();N.reasoning.durationMs=Math.max(0,(N.reasoning.completedAt??Date.now())-_)}N.streaming=N.reasoning.status!=="complete",f(N)}else if(z==="reasoning_complete"){let P=typeof b.id=="string"?b.id:null;if(P&&w.has(P)&&T.has(P)){let j=T.get(P);if(j.reasoning){let re=typeof b.text=="string"?b.text:"";re&&j.reasoning.chunks.length===0&&j.reasoning.chunks.push(re),j.reasoning.status="complete",j.streaming=!1,f(j)}w.delete(P),T.delete(P);continue}let I=me(b,!1)??me(b,!0)??`reason-${c()}`,N=typeof b.text=="string"?b.text:"";!C.get(I)&&(N||b.scope==="loop")&&Z(I);let G=C.get(I);if(G?.reasoning){(b.scope==="loop"||b.scope==="turn")&&(G.reasoning.scope=b.scope),N&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(N),G.reasoning.status="complete",G.reasoning.completedAt=Ne(b.completedAt??b.timestamp);let j=G.reasoning.startedAt??Date.now();G.reasoning.durationMs=Math.max(0,(G.reasoning.completedAt??Date.now())-j),G.streaming=!1,f(G)}let _=U(b);_&&F.byStep.delete(_)}else if(z==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof b.iteration=="number"&&(ie=b.iteration);let P=(typeof b.toolCallId=="string"?b.toolCallId:void 0)??Oe(b,!0)??`tool-${c()}`,I=b.toolName??b.name;if(Be(I)){Y.add(P);continue}de(se(b),P);let N=Ve(P),G=N.toolCall??{id:P,status:"pending"};G.name=I??G.name,G.status="running",b.parameters!==void 0?G.args=b.parameters:b.args!==void 0&&(G.args=b.args),G.startedAt=G.startedAt??Ne(b.startedAt??b.timestamp),G.completedAt=void 0,G.durationMs=void 0,N.toolCall=G,N.streaming=!0,b.executionId&&(N.agentMetadata={executionId:b.executionId,iteration:b.iteration}),f(N)}else if(z==="tool_output_delta"){let P=Oe(b,!1)??Oe(b,!0)??`tool-${c()}`;if(Y.has(P))continue;let I=Ve(P),N=I.toolCall??{id:P,status:"running"};N.startedAt=N.startedAt??Ne(b.startedAt??b.timestamp);let G=b.text??b.delta??b.message??"";G&&(N.chunks=N.chunks??[],N.chunks.push(String(G))),N.status="running",I.toolCall=N,I.streaming=!0;let _=b.agentContext;(_||b.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:_?.executionId??b.executionId,iteration:_?.iteration??b.iteration}),f(I)}else if(z==="tool_complete"){let P=Oe(b,!1)??Oe(b,!0)??`tool-${c()}`;if(Y.has(P)){Y.delete(P);continue}let I=Ve(P),N=I.toolCall??{id:P,status:"running"};N.status="complete",b.result!==void 0&&(N.result=b.result),typeof b.duration=="number"&&(N.duration=b.duration),N.completedAt=Ne(b.completedAt??b.timestamp);let G=b.duration??b.executionTime;if(typeof G=="number")N.durationMs=G;else{let re=N.startedAt??Date.now();N.durationMs=Math.max(0,(N.completedAt??Date.now())-re)}I.toolCall=N,I.streaming=!1;let _=b.agentContext;(_||b.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:_?.executionId??b.executionId,iteration:_?.iteration??b.iteration}),f(I);let j=se(b);j&&q.byCall.delete(j)}else if(z==="await"&&b.toolName){let P=typeof b.toolCallId=="string"&&b.toolCallId.length>0?b.toolCallId:void 0,I=P??b.toolId??`local-${c()}`,N=Ve(I),G=b.toolName,_=b.origin==="webmcp"&&!uo(G)?`webmcp:${G}`:G,j=uo(_),re=N.toolCall??{id:I,status:"pending"};re.name=_,re.args=b.parameters,re.status=j?"running":"complete",re.chunks=re.chunks??[],re.startedAt=re.startedAt??Ne(b.startedAt??b.timestamp??b.awaitedAt),j?(re.completedAt=void 0,re.duration=void 0,re.durationMs=void 0):re.completedAt=re.completedAt??re.startedAt,N.toolCall=re,N.streaming=!1,N.agentMetadata={...N.agentMetadata,executionId:b.executionId??N.agentMetadata?.executionId,awaitingLocalTool:!0,...P?{webMcpToolCallId:P}:{}},f(N)}else if(z==="text_start"){let P=typeof b.id=="string"?b.id:null,I=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(P&&I){w.set(P,I);continue}let N=h;N&&(ge==="flow"?(Re(N),Et=N):(N.streaming=!1,f(N)),h=null),M=typeof b.id=="string"?b.id:M,A=""}else if(z==="text_delta"){let P=typeof b.id=="string"?b.id:null,I=P?w.get(P):void 0;if(P&&I){let G=typeof b.delta=="string"?b.delta:"",_=(H.get(P)??"")+G;if(H.set(P,_),_.trim()==="")continue;let j=fe(P,I);j.agentMetadata={...j.agentMetadata,executionId:b.executionId,parentToolId:I},xt(j,_,G,void 0);continue}if(M=typeof b.id=="string"?b.id:M,ge==="flow"){let G=typeof b.delta=="string"?b.delta:"";if(A+=G,A.trim()==="")continue;let _=Le();_.agentMetadata={executionId:b.executionId,iteration:b.iteration},xt(_,A,G,void 0),S=_;continue}let N=Le();N.content+=b.delta??"",N.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:he??void 0,agentName:ce?.agentName},S=N,f(N)}else if(z==="text_complete"){let P=typeof b.id=="string"?b.id:null;if(P&&w.has(P)){let N=T.get(P);N&&Re(N),w.delete(P),H.delete(P),T.delete(P);continue}let I=h;I&&(ge==="flow"?(Re(I),Et=I):((I.content??"")===""&&typeof b.text=="string"&&(I.content=b.text),I.streaming=!1,f(I)),h=null),M=null,A=""}else if(z==="step_complete"){let P=b.stepType,I=b.executionType;if(P==="tool"||I==="context")continue;if(b.success===!1){let N=b.error,G=typeof N=="string"&&N!==""?N:N!=null&&typeof N=="object"&&Reflect.has(N,"message")?String(N.message??"Step failed"):"Step failed";n({type:"error",error:new Error(G)});let _=h;_&&_.streaming&&(_.streaming=!1,f(_)),n({type:"status",status:"idle"});continue}{let N=Et;Et=null;let G=b.stopReason,_=b.result?.response;if(N)G&&(N.stopReason=G),_!=null?cn(N,_):N.streaming!==!1&&(Xe.delete(N.id),Pe.delete(N.id),N.streaming=!1,f(N));else{let j=_!=null&&_!=="";if(j||G){let re=Le();G&&(re.stopReason=G),j?Re(re,_):(re.streaming=!1,f(re))}}continue}}else if(z==="execution_start")ge=b.kind==="flow"?"flow":"agent",bt=!0,ge==="agent"&&(ce={executionId:b.executionId,agentId:b.agentId??"virtual",agentName:b.agentName??"",status:"running",currentIteration:0,maxTurns:b.maxTurns??1,startedAt:Ne(b.startedAt)});else if(z==="turn_start"){let P=typeof b.iteration=="number"?b.iteration:ie;if(P!==ie){if(ce&&(ce.currentIteration=P),Q==="separate"&&P>1){let I=h;I&&(I.streaming=!1,f(I),yn.set(P-1,I),h=null)}ie=P}he=typeof b.id=="string"?b.id:null,S=null}else if(z==="tool_input_delta"){let P=b.toolCallId??q.lastId;if(P){let I=B.get(P);I?.toolCall&&(I.toolCall.chunks=I.toolCall.chunks??[],I.toolCall.chunks.push(b.delta??""),f(I))}}else{if(z==="tool_input_complete")continue;if(z==="turn_complete"){let P=b.stopReason,I=h??S;if(P&&I!==null){let N=b.id;(!N||I.agentMetadata?.turnId===N)&&(I.stopReason=P,f(I))}he===b.id&&(he=null)}else if(z==="media_start"){let P=String(b.id);pe.set(P,{mediaType:typeof b.mediaType=="string"?b.mediaType:void 0,role:typeof b.role=="string"?b.role:void 0,toolCallId:b.toolCallId,parts:[]})}else if(z==="media_delta"){let P=pe.get(String(b.id));P&&typeof b.delta=="string"&&P.parts.push(b.delta)}else if(z==="media_complete"){let P=String(b.id),I=pe.get(P);pe.delete(P);let N=(typeof b.mediaType=="string"?b.mediaType:void 0)??I?.mediaType??"application/octet-stream",G=typeof b.data=="string"?b.data:void 0,_=typeof b.url=="string"?b.url:I&&I.parts.length>0?I.parts.join(""):void 0,j=null;if(G)j={type:"media",data:G,mediaType:N};else if(_){let at=N.toLowerCase();j={type:at==="image"||at.startsWith("image/")?"image-url":"file-url",url:_,mediaType:N}}let re=b.toolCallId??I?.toolCallId,$e=j?[j]:[],Me=[];for(let at of $e){if(!at||typeof at!="object")continue;let K=at,Ue=typeof K.type=="string"?K.type:void 0,we=typeof K.mediaType=="string"?K.mediaType.toLowerCase():"",ke=null,Ee="";if(Ue==="media"){let Qe=typeof K.data=="string"?K.data:void 0;if(!Qe)continue;Ee=we.length>0?we:"application/octet-stream",ke=`data:${Ee};base64,${Qe}`}else if(Ue==="image-url"){let Qe=typeof K.url=="string"?K.url:void 0;if(!Qe)continue;Ee=we,ke=Qe}else if(Ue==="file-url"){let Qe=typeof K.url=="string"?K.url:void 0;if(!Qe)continue;Ee=we,ke=Qe}else continue;if(ke)if(Ue==="image-url"||Ee.startsWith("image/"))Me.push({type:"image",image:ke,...Ee.includes("/")?{mimeType:Ee}:{}});else if(Ee.startsWith("audio/"))Me.push({type:"audio",audio:ke,mimeType:Ee});else if(Ee.startsWith("video/"))Me.push({type:"video",video:ke,mimeType:Ee});else{let Qe=Ee||"application/octet-stream";Me.push({type:"file",data:ke,mimeType:Qe,filename:Ox(Qe)})}}if(Me.length>0){let at=c(),K=re,we={id:`agent-media-${typeof K=="string"&&K.length>0?`${K}-${at}`:String(at)}`,role:"assistant",content:"",contentParts:Me,createdAt:new Date().toISOString(),streaming:!1,sequence:at,agentMetadata:{executionId:b.executionId,iteration:typeof b.iteration=="number"?b.iteration:ie}};f(we);let ke=h;ke&&(ke.streaming=!1,f(ke)),h=null,L.current=null}}else if(z==="execution_complete"){let P=b.kind??ge;P==="agent"&&ce&&(ce.status=b.success?"complete":"error",ce.completedAt=Ne(b.completedAt),ce.stopReason=b.stopReason);let I=h;I&&(P==="flow"&&I.streaming!==!1?Re(I):(I.streaming=!1,f(I)),h=null),M=null,A="",Et=null,n({type:"status",status:"idle",terminal:!0})}else if(z==="execution_error"){let P=typeof b.error=="string"?b.error:b.error?.message??"Execution error";n({type:"error",error:new Error(P)})}else if(z!=="ping"){if(z==="approval_start"){let P=b.approvalId??`approval-${c()}`,I={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:ce?.agentId??"virtual",executionId:b.executionId??ce?.executionId??"",toolName:b.toolName??"",toolType:b.toolType,description:b.description??`Execute ${b.toolName??"tool"}`,...typeof b.reason=="string"&&b.reason?{reason:b.reason}:{},parameters:b.parameters}};f(I)}else if(z==="step_await"&&b.awaitReason==="approval_required"){let P=b.approvalId??`approval-${c()}`,I={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:ce?.agentId??"virtual",executionId:b.executionId??ce?.executionId??"",toolName:b.toolName??"",toolType:b.toolType,description:b.description??`Execute ${b.toolName??"tool"}`,...typeof b.reason=="string"&&b.reason?{reason:b.reason}:{},parameters:b.parameters}};f(I)}else if(z==="approval_complete"){let P=b.approvalId;if(P){let N={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:b.decision??"approved",agentId:ce?.agentId??"virtual",executionId:b.executionId??ce?.executionId??"",toolName:b.toolName??"",description:b.description??"",resolvedAt:Date.now()}};f(N)}}else if(z==="artifact_start"||z==="artifact_delta"||z==="artifact_update"||z==="artifact_complete"){if(z==="artifact_start"){let P=b.artifactType,I=String(b.id),N=typeof b.title=="string"?b.title:void 0,G=b.file,_;G&&typeof G=="object"&&!Array.isArray(G)&&typeof G.path=="string"&&typeof G.mimeType=="string"&&(_={path:G.path,mimeType:G.mimeType,...typeof G.language=="string"?{language:G.language}:{}}),n({type:"artifact_start",id:I,artifactType:P,title:N,component:typeof b.component=="string"?b.component:void 0,..._?{file:_}:{}});let j=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?{...b.props}:void 0;if(xe.set(I,{markdown:"",title:N,file:_,...j?{props:j}:{}}),!Ae.has(I)){Ae.add(I);let re=jo(this.config.features?.artifacts,P),$e=typeof b.component=="string"?b.component:void 0,Me={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Ws(re,{artifactId:I,title:N,artifactType:P,status:"streaming",..._?{file:_}:{},...$e?{component:$e}:{}})};ve.set(I,Me),f(Me)}}else if(z==="artifact_delta"){let P=String(b.id),I=typeof b.delta=="string"?b.delta:String(b.delta??"");n({type:"artifact_delta",id:P,artDelta:I});let N=xe.get(P);N&&(N.markdown+=I)}else if(z==="artifact_update"){let P=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};n({type:"artifact_update",id:String(b.id),props:P,component:typeof b.component=="string"?b.component:void 0});let I=xe.get(String(b.id));I&&(I.props={...I.props??{},...P})}else if(z==="artifact_complete"){let P=String(b.id);n({type:"artifact_complete",id:P});let I=ve.get(P);if(I){I.streaming=!1;try{let N=JSON.parse(I.rawContent??"{}");if(N.props){N.props.status="complete";let G=xe.get(P);G?.markdown&&(N.props.markdown=G.markdown),G?.file&&(N.props.file=G.file),N.component==="PersonaArtifactInline"&&G?.props&&Object.keys(G.props).length>0&&(N.props.componentProps=G.props)}I.rawContent=JSON.stringify(N)}catch{}xe.delete(P),f(I),ve.delete(P)}}}else if(z==="transcript_insert"){let P=b.message;if(!P||typeof P!="object")continue;let I=String(P.id??`msg-${c()}`),N=P.role,_={id:I,role:N==="user"?"user":N==="system"?"system":"assistant",content:typeof P.content=="string"?P.content:"",rawContent:typeof P.rawContent=="string"?P.rawContent:void 0,createdAt:typeof P.createdAt=="string"?P.createdAt:new Date().toISOString(),streaming:P.streaming===!0,...typeof P.variant=="string"?{variant:P.variant}:{},sequence:c()};if(f(_),_.rawContent)try{let re=JSON.parse(_.rawContent)?.props?.artifactId;typeof re=="string"&&Ae.add(re)}catch{}h=null,L.current=null,Xe.delete(I),Pe.delete(I)}else if(z==="error"){if(b.recoverable===!1&&b.error!=null&&b.error!==""){let P=typeof b.error=="string"?b.error:b.error?.message!=null?String(b.error.message):"Execution error";n({type:"error",error:new Error(P)});let I=h;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}else if(z==="step_error"||z==="dispatch_error"||z==="flow_error"){let P=null;if(b.error instanceof Error)P=b.error;else if(z==="dispatch_error"){let I=b.message??b.error;I!=null&&I!==""&&(P=new Error(String(I)))}else{let I=b.error;typeof I=="string"&&I!==""?P=new Error(I):I!=null&&typeof I=="object"&&Reflect.has(I,"message")&&(P=new Error(String(I.message??I)))}if(P){n({type:"error",error:P});let I=h;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}}}}Ge.length=0};;){let{done:R,value:z}=await a.read();if(R)break;l+=s.decode(z,{stream:!0});let b=l.split(`
|
|
13
13
|
|
|
14
|
-
`);l=b.pop()??"";for(let
|
|
15
|
-
`),O="message",G="",_=null;for(let Me of W)Me.startsWith("event:")?O=Me.replace("event:","").trim():Me.startsWith("data:")?G+=Me.replace("data:","").trim():Me.startsWith("id:")&&(_=Me.slice(3).trim());let j=()=>{_!==null&&_!==""&&n({type:"cursor",id:_})};if(!G){j();continue}let ne;try{ne=JSON.parse(G)}catch(Me){n({type:"error",error:Me instanceof Error?Me:new Error("Failed to parse chat stream payload")});continue}let Ge=O!=="message"?O:ne.type??"message";if(this.onSSEEvent?.(Ge,ne),this.parseSSEEvent){E.current=h;let Me=await this.handleCustomSSEEvent(ne,n,E,f,d,k);if(E.current&&E.current!==h&&(h=E.current),Me){j();continue}}Je.push({payloadType:Ge,payload:ne}),Ee(),j()}}Ee()}};function nm(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ir(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function xo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ti="[Image]";function om(e){return typeof e=="string"?[{type:"text",text:e}]:e}function rm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function ni(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function am(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function bo(e){return{type:"text",text:e}}function sm(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function im(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function lm(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var dm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Bx=["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"],Xn=[...dm,...Bx];function Dx(e){return dm.includes(e)||e.startsWith("image/")}function oi(e){return Dx(e.type)}async function cm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;oi(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function pm(e,t=Xn,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Fx(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function um(e,t){let n=Fx(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]||n||"FILE"}var ri=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let a=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of s)l()}r.onended=()=>{let s=this.activeSources.indexOf(r);s!==-1&&this.activeSources.splice(s,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<n;a++){let s=r.getInt16(a*2,!0);o[a]=s/32768}return o}};var fm=16e3,Nx=24e3,Ox=4096,_x=1380533830;function Ux(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===_x?new Uint8Array(e,44):new Uint8Array(e)}function qx(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Ha=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:fm,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){a.getTracks().forEach(u=>u.stop());return}this.mediaStream=a;let s=window.AudioContext||window.webkitAudioContext,l=new s({sampleRate:fm});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ri(Nx);if(r!==this.callGeneration){p.destroy(),a.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let c=`${qx(o)}/ws/agents/${encodeURIComponent(t)}/voice`,d=new WebSocket(c,["runtype.bearer",n]);d.binaryType="arraybuffer",this.ws=d,d.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,a,d,r))},d.onmessage=u=>this.handleMessage(u,r),d.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},d.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let g=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${g}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(a){throw this.cleanup(),this.emitError(a),this.emitStatus("error"),a}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let a=t.createMediaStreamSource(n);this.sourceNode=a;let s=t.createScriptProcessor(Ox,1,1);this.processor=s,s.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),c=new Int16Array(p.length);for(let d=0;d<p.length;d++){let u=Math.max(-1,Math.min(1,p[d]));c[d]=u<0?u*32768:u*32767}o.send(c.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=Ux(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var er=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(a=>a[0]).map(a=>a.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(a=>a({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Co(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ha(e.runtype);case"browser":if(!er.isSupported())throw new Error("Browser speech recognition not supported");return new er(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ai(e){if(e?.type==="custom"&&e.custom)return Co({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Co({type:"runtype",runtype:e.runtype});if(er.isSupported())return Co({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ba(e){try{return ai(e),!0}catch{return!1}}function Wr(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 n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var vo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let s=a.find(l=>l.name===t.voice);s&&(r.voice=s)}else a.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(a):Wr(a));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=s=>{let l=s.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var tr=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,n){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,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function sd(e){if(!e)return"";let t=Vx(e);return mm(t!==null?t:e)}function Vx(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function mm(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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
14
|
+
`);l=b.pop()??"";for(let P of b){let I=P.split(`
|
|
15
|
+
`),N="message",G="",_=null;for(let Me of I)Me.startsWith("event:")?N=Me.replace("event:","").trim():Me.startsWith("data:")?G+=Me.replace("data:","").trim():Me.startsWith("id:")&&(_=Me.slice(3).trim());let j=()=>{_!==null&&_!==""&&n({type:"cursor",id:_})};if(!G){j();continue}let re;try{re=JSON.parse(G)}catch(Me){n({type:"error",error:Me instanceof Error?Me:new Error("Failed to parse chat stream payload")});continue}let $e=N!=="message"?N:re.type??"message";if(this.onSSEEvent?.($e,re),this.parseSSEEvent){L.current=h;let Me=await this.handleCustomSSEEvent(re,n,L,f,c,E);if(L.current&&L.current!==h&&(h=L.current),Me){j();continue}}Ge.push({payloadType:$e,payload:re}),Te(),j()}}Te()}};function im(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function kr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function xo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Qs="[Image]";function lm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function dm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ys(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function cm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function bo(e){return{type:"text",text:e}}function pm(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function um(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function fm(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var mm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ux=["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"],Kn=[...mm,...Ux];function qx(e){return mm.includes(e)||e.startsWith("image/")}function Zs(e){return qx(e.type)}async function gm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Zs(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function hm(e,t=Kn,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Vx(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function ym(e,t){let n=Vx(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]||n||"FILE"}var ei=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let a=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of s)l()}r.onended=()=>{let s=this.activeSources.indexOf(r);s!==-1&&this.activeSources.splice(s,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<n;a++){let s=r.getInt16(a*2,!0);o[a]=s/32768}return o}};var xm=16e3,zx=24e3,$x=4096,jx=1380533830;function Gx(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===jx?new Uint8Array(e,44):new Uint8Array(e)}function Kx(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var ka=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:xm,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){a.getTracks().forEach(u=>u.stop());return}this.mediaStream=a;let s=window.AudioContext||window.webkitAudioContext,l=new s({sampleRate:xm});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ei(zx);if(r!==this.callGeneration){p.destroy(),a.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${Kx(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,a,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let g=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${g}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(a){throw this.cleanup(),this.emitError(a),this.emitStatus("error"),a}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let a=t.createMediaStreamSource(n);this.sourceNode=a;let s=t.createScriptProcessor($x,1,1);this.processor=s,s.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=Gx(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Jo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(a=>a[0]).map(a=>a.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(a=>a({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function vo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ka(e.runtype);case"browser":if(!Jo.isSupported())throw new Error("Browser speech recognition not supported");return new Jo(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ti(e){if(e?.type==="custom"&&e.custom)return vo({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return vo({type:"runtype",runtype:e.runtype});if(Jo.isSupported())return vo({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function La(e){try{return ti(e),!0}catch{return!1}}function Lr(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 n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Co=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let s=a.find(l=>l.name===t.voice);s&&(r.voice=s)}else a.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(a):Lr(a));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=s=>{let l=s.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Qo=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,n){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,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function rd(e){if(!e)return"";let t=Xx(e);return bm(t!==null?t:e)}function Xx(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function bm(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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /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
|
|
17
|
+
`),t.trim()}var ad=null,vm=e=>{ad=e},sd=()=>ad?ad():import("./runtype-tts-entry");var Yx=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Zx(e,t){return Yx.some(n=>e[n]!==t[n])}function id(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
18
18
|
|
|
19
|
-
_Details: ${n.message}_`:o}var Da=e=>({isError:!0,content:[{type:"text",text:e}]}),xm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,bm=e=>uo(e)||e===En,Hr=class{constructor(t={},n){this.config=t;this.callbacks=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.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new tr(()=>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 n=t.message.toolCall,o=!!n?.name&&(uo(n.name)||n.name===En&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(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.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Zo(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,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()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||ld().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 Ba(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}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 n=vo.isSupported()?new vo({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,a=this.config.clientToken,s=t.browserFallback!==!1;if(o&&r&&a)return ld().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let c=new l({host:o,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return s&&n?new p(c,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):c});if(s&&n)return a&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Co(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,s,l)=>{if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:s,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:s,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{console.error("Voice error:",a),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(a=>{this.voiceStatus=a,this.voiceActive=a==="listening",this.callbacks.onVoiceStatusChanged?.(a)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!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.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;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){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}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,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!Gx(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new Zo(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:a,id:s,createdAt:l,sequence:p,streaming:c=!1,voiceProcessing:d,rawContent:u}=t,f={id:s??(n==="user"?Ir():n==="assistant"?xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:c,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...d!==void 0&&{voiceProcessing:d},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}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 n=[];for(let o of t){let{role:r,content:a,llmContent:s,contentParts:l,id:p,createdAt:c,sequence:d,streaming:u=!1,voiceProcessing:g,rawContent:f}=o,S={id:p??(r==="user"?Ir():r==="assistant"?xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:c??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...l!==void 0&&{contentParts:l},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(S)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:a,id:s,createdAt:l,sequence:p}=t,c={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(c),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let a=r.blocks.join(`
|
|
19
|
+
_Details: ${n.message}_`:o}var Pa=e=>({isError:!0,content:[{type:"text",text:e}]}),Am=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Sm=e=>uo(e)||e===Tn,Pr=class{constructor(t={},n){this.config=t;this.callbacks=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.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Qo(()=>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 n=t.message.toolCall,o=!!n?.name&&(uo(n.name)||n.name===Tn&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(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.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Xo(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,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()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||sd().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 La(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}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 n=Co.isSupported()?new Co({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,a=this.config.clientToken,s=t.browserFallback!==!1;if(o&&r&&a)return sd().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:o,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return s&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(s&&n)return a&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=vo(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,s,l)=>{if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:s,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:s,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{console.error("Voice error:",a),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(a=>{this.voiceStatus=a,this.voiceActive=a==="listening",this.callbacks.onVoiceStatusChanged?.(a)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!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.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;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){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}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,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!Zx(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new Xo(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:a,id:s,createdAt:l,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,f={id:s??(n==="user"?kr():n==="assistant"?xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}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 n=[];for(let o of t){let{role:r,content:a,llmContent:s,contentParts:l,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:g,rawContent:f}=o,S={id:p??(r==="user"?kr():r==="assistant"?xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...l!==void 0&&{contentParts:l},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(S)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:a,id:s,createdAt:l,sequence:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let a=r.blocks.join(`
|
|
20
20
|
|
|
21
21
|
`),s=[a,n].filter(Boolean).join(`
|
|
22
22
|
|
|
23
|
-
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(l){let c=[];a&&c.push(bo(a)),c.push(...r.contentParts),c.push(...t.contentParts),t.contentParts=c}else if(p){let c=[];s&&c.push(bo(s)),c.push(...r.contentParts),t.contentParts=c}else a&&(t.llmContent=s);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=Ir(),a=xo();this.activeAssistantMessageId=null;let s=n?.contentParts&&ni(n.contentParts)?ti:"",l={id:r,role:"user",content:o||s,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let d=this.messages.find(u=>u.id===r)??l;if(await this.applyMentionBundle(d,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:p.signal,assistantMessageId:a},this.handleEvent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!u){let g=dd(d,this.config.errorMessage);if(g){let f={id:a,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(d instanceof Error?this.callbacks.onError?.(d):this.callbacks.onError?.(new Error(String(d))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=xo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId: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 s=dd(r,this.config.errorMessage);if(s){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:s,sequence:this.nextSequence()};this.appendMessage(l)}}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,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let a of this.messages)a.streaming&&a.id!==o&&(a.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.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(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={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},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(a=>a.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,a={...t,status:n,resolvedAt:Date.now()},s=this.messages.find(d=>d.id===r),l={id:r,role:"assistant",content:"",createdAt:s?.createdAt??new Date().toISOString(),...s?.sequence!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,c=p&&typeof p=="object"?p.onDecision:void 0;try{let d;if(c?d=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):d=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),d){let u=null;if(d instanceof Response){if(!d.ok){let g=await d.json().catch(()=>null);throw new Error(g?.error??`Approval request failed: ${d.status}`)}u=d.body}else d instanceof ReadableStream&&(u=d);u?await this.connectStream(u,{allowReentry:!0}):(n==="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(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(d=>d.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 s=typeof n=="string"?void 0:n;if(s===void 0&&typeof n=="string"){let d=t.toolCall?.args,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===1){let g=typeof u[0]?.question=="string"?u[0].question:"";g&&(s={[g]:n})}}this.markAskUserQuestionResolved(t,s),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,p=t.toolCall?.args,c=Array.isArray(p?.questions)?p.questions:[];if(c.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([u,g])=>`${u}: ${Array.isArray(g)?g.join(", "):g}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let d=s??{};c.forEach((u,g)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let h=d[f],S=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";this.appendMessage({id:`ask-user-q-${l}-${g}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${g}`,role:"user",content:S||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let d=await this.client.resumeFlow(r,{[a]:n});if(!d.ok){let u=await d.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${d.status}`)}d.body?await this.connectStream(d.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let a=this.webMcpEpoch;queueMicrotask(()=>{a===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==En?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(n.map(async p=>{let c=p.toolCall?.name,d=p.toolCall?.id;if(!c||!d)return null;let u=`${t}:${d}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let g=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??c;if(c===En)return{dedupeKey:u,resumeKey:f,output:ed(),toolMessage:p,startedAt:g,completedAt:Date.now()};let h=new AbortController;this.webMcpResolveControllers.add(h),r.push(h);let S=this.client.executeWebMcpToolCall(c,p.toolCall?.args,h.signal),E;if(!S)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await S}catch(k){let M=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));return M||this.callbacks.onError?.(k instanceof Error?k:new Error(String(k))),this.markWebMcpToolComplete(p,Da(M?"Aborted by cancel()":xm(k)),g),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,Da("Aborted by cancel()"),g),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:E,toolMessage:p,startedAt:g,completedAt:Date.now()}})),l=[];try{if(l=s.filter(d=>d!==null),l.length===0)return;let p={};for(let d of l)p[d.resumeKey]=d.output;let c=await this.client.resumeFlow(t,p,{signal:a.signal});if(!c.ok){let d=await c.json().catch(()=>null);throw new Error(d?.error??`Resume failed: ${c.status}`)}for(let d of l)this.webMcpResolvedKeys.add(d.dedupeKey),this.markWebMcpToolComplete(d.toolMessage,d.output,d.startedAt,d.completedAt,d.toolMessage.toolCall?.name===En?{suggestRepliesResolved:!0}:void 0);c.body&&await this.connectStream(c.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let d of l)this.markWebMcpToolComplete(d.toolMessage,Da("Aborted by cancel()"),d.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let h=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h))return;this.webMcpInflightKeys.add(h);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(h)}catch(S){this.callbacks.onError?.(S instanceof Error?S:new Error(String(S)))}finally{this.webMcpInflightKeys.delete(h)}return}let a=`${n}:${r}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let c=o===En,d=t.toolCall?.args,u=c?null:this.client.executeWebMcpToolCall(o,d,p),g="execute",f=s;try{let h;if(c?h=ed():u?h=await u:h={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,Da("Aborted by cancel()"),s);return}let S=t.agentMetadata?.webMcpToolCallId??o;g="resume",await this.resumeWithToolOutput(n,S,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,h,s,f,c?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(h){let S=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));(g==="execute"||S||p.aborted)&&this.markWebMcpToolComplete(t,Da(S||p.aborted?"Aborted by cancel()":xm(h)),s),S||this.callbacks.onError?.(h instanceof Error?h:new Error(String(h)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let a=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!a.ok){let s=await a.json().catch(()=>null);throw new Error(s?.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 n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=Jo(this.config.features?.artifacts,t.artifactType),r=Fs(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),a=this.messages.find(s=>s.id===n);if(a){a.rawContent=r,a.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}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 n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.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(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(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=Promise.resolve().then(()=>(ym(),hm)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>dd(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=xo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=sd(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Wr(t)}toggleReadAloud(t){let n=this.messages.find(a=>a.id===t);if(!n||n.role!=="assistant")return;let o=sd(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,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 n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,a)=>{if(a!==o)return r;let s={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(s.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(s.agentMetadata={...s.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let d=r.approval,u=n.approval;s.approval={...d,...u,executionId:u.executionId||d.executionId,toolName:u.toolName||d.toolName,description:u.description||d.description,toolType:u.toolType??d.toolType,reason:u.reason??d.reason,parameters:u.parameters??d.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,c=n.toolCall?.id;if(l&&bm(l)&&p&&c&&n.agentMetadata?.awaitingLocalTool===!0){let d=`${p}:${c}`,u=this.webMcpInflightKeys.has(d),g=this.webMcpResolvedKeys.has(d),f=r.toolCall?.name,h=r.agentMetadata?.executionId===p&&r.toolCall?.id===c&&f!==void 0&&bm(f)&&r.toolCall?.status==="complete";(u||g||h)&&(s.agentMetadata={...s.agentMetadata??{},awaitingLocalTool:!1},s.toolCall=r.toolCall,s.streaming=r.streaming)}return s}),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((n,o)=>{let r=new Date(n.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(a)&&r!==a)return r-a;let s=n.sequence??0,l=o.sequence??0;return s!==l?s-l:n.id.localeCompare(o.id)})}};var cd=[["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 pd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var ud=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var fd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var md=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var gd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var hd=[["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 yd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var xd=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var bd=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var Cd=[["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 vd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var wd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var Ad=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Sd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var Md=[["path",{d:"M20 6 9 17l-5-5"}]];var Td=[["path",{d:"m6 9 6 6 6-6"}]];var Ed=[["path",{d:"m15 18-6-6 6-6"}]];var kd=[["path",{d:"m9 18 6-6-6-6"}]];var Ld=[["path",{d:"m18 15-6-6-6 6"}]];var si=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var ii=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var Pd=[["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 Rd=[["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 Id=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var li=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Wd=[["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 Hd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Bd=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var Dd=[["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 di=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var ci=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Fd=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var Nd=[["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 Od=[["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 _d=[["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 Ud=[["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 qd=[["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 Vd=[["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 zd=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var $d=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var jd=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var Gd=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var Kd=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var pi=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var Xd=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var Jd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var Qd=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Yd=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Zd=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var ec=[["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 ui=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var tc=[["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 nc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var oc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var rc=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var ac=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var fi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var sc=[["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 ic=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var lc=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var dc=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var cc=[["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 pc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var uc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var fc=[["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 mc=[["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 gc=[["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 hc=[["path",{d:"M5 12h14"}]];var yc=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var xc=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var bc=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var Cc=[["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 vc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var wc=[["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 Ac=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var Sc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var Mc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var Tc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Ec=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var kc=[["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 Lc=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var Pc=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var Rc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Ic=[["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 Wc=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Hc=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var Bc=[["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 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:"m9 12 2 2 4-4"}]];var mi=[["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 Fc=[["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"}]];var Nc=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var Oc=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var _c=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var gi=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var Uc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var qc=[["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 Vc=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var zc=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var $c=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var jc=[["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 Gc=[["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 Kc=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var Xc=[["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 Jc=[["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 hi=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var Qc=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Yc=[["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 Zc=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var ep=[["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 tp=[["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"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var np=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var op=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var rp=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var Kx={activity:cd,"arrow-down":pd,"arrow-up":gd,"arrow-up-right":md,bot:Cd,"chevron-down":Td,"chevron-up":Ld,"chevron-right":kd,"chevron-left":Ed,check:Md,clipboard:Rd,"clipboard-copy":Pd,"code-xml":li,copy:Wd,file:Vd,"file-code":_d,"file-spreadsheet":Ud,"file-text":qd,"image-plus":tc,loader:sc,"loader-circle":fi,mic:mc,paperclip:Cc,"refresh-cw":kc,search:Rc,send:Ic,"shield-alert":Bc,"shield-check":Dc,"shield-x":mi,square:Uc,"thumbs-down":jc,"thumbs-up":Gc,upload:Yc,"volume-2":ep,x:op,user:Zc,mail:lc,phone:Sc,calendar:Ad,clock:Id,building:vd,"map-pin":dc,lock:ic,key:rc,"credit-card":Hd,"at-sign":hd,hash:Qd,globe:Jd,link:ac,"circle-check":si,"circle-x":ii,"triangle-alert":hi,info:oc,ban:yd,shield:Fc,"arrow-left":ud,"arrow-right":fd,"external-link":Nd,ellipsis:ci,"ellipsis-vertical":di,menu:pc,house:ui,plus:Tc,minus:hc,pencil:wc,trash:Jc,"trash-2":Xc,save:Pc,download:Dd,share:Hc,funnel:pi,settings:Wc,"rotate-cw":Lc,maximize:cc,minimize:gc,"shopping-cart":Oc,"shopping-bag":Nc,package:bc,truck:Qc,tag:$c,gift:Xd,receipt:Ec,wallet:np,store:Vc,"dollar-sign":Bd,percent:Ac,play:Mc,pause:vc,"volume-x":tp,camera:Sd,image:nc,film:$d,headphones:Yd,"message-circle":uc,"message-square":fc,bell:xd,heart:Zd,star:qc,eye:Od,"eye-off":Fd,bookmark:bd,"calendar-days":wd,history:ec,timer:Kc,folder:Kd,"folder-open":Gd,files:zd,sparkles:gi,zap:rp,sun:zc,moon:xc,flag:jd,monitor:yc,smartphone:_c},te=(e,t=24,n="currentColor",o=2)=>{let r=Kx[e];return r?Xx(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Xx(e,t,n,o){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",n),r.setAttribute("stroke-width",String(o)),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 s=a[0],l=a[1];if(!l)return;let p=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(l).forEach(([c,d])=>{c!=="stroke"&&p.setAttribute(c,String(d))}),r.appendChild(p)}),r}var yi={allowedTypes:Xn,maxFileSize:10*1024*1024,maxFiles:4};function Jx(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Qx(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var nr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??yi.allowedTypes,maxFileSize:t.maxFileSize??yi.maxFileSize,maxFiles:t.maxFiles??yi.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:yi.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)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}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){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=pm(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await cm(n),a=oi(n)?URL.createObjectURL(n):null,s={id:Jx(),file:n,previewUrl:a,contentPart:r};this.attachments.push(s),this.renderPreview(s)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(a=>a.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=oi(t.file),o=y("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let s=y("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=y("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let l=Qx(t.file.type),p=te(l,20,"var(--persona-muted, #6b7280)",1.5);p&&s.appendChild(p);let c=y("span");c.textContent=um(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",s.appendChild(c),o.appendChild(s)}let r=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let a=te("x",10,"var(--persona-text-inverse, #ffffff)",2);a?r.appendChild(a):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var Cm=/\s/;function Yx(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
|
|
24
|
-
`:o===""||
|
|
25
|
-
`||s==="\uFFFC"||!r&&
|
|
26
|
-
`).some(
|
|
27
|
-
`)[0]).startsWith(w.trigger):!1),a=(A,w)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:w}))}catch{}},s=Be("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,c=e.textarea,d=null,u=null,g=null,f=null,h=()=>{if(l)return Promise.resolve(l);if(p)return p;let A=ap().then(w=>(l=w.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:d??void 0,anchor:e.anchor,contextRow:s,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:M,emit:a}),l)).catch(w=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",w),p===A&&(p=null),null));return p=A,A},S=()=>{Em().then(A=>{let w=A.mountInlineComposer({textarea:e.textarea,renderToken:R=>Fa(R,{render:t.renderMentionToken}),onMentionRemoved:R=>l?.untrackMention(R)});d=w.input,u=w.destroy;let T=c;T.replaceWith(w.element),c=w.element,f={next:w.element,prev:T},g?.(w.element,T),l?l.rebindComposer(w.input):p&&p.then(R=>R?.rebindComposer(w.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};t.display==="inline"&&S();let E=[],k=new Map;for(let A of n){if(!A.showButton)continue;let w=Sm({config:{...t,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{h().then(T=>T?.openMenu(A.trigger))}});E.push(w),k.set(A.trigger,w.button)}let M=(A,w,T)=>{let R=k.get(w);R&&(R.setAttribute("aria-expanded",A?"true":"false"),A?R.setAttribute("aria-controls",T):R.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(A=>A.wrapper),contextRow:s,handleInput:A=>{if(l){l.handleInput();return}if(!wm(A))return;let w=c,T=w.selectionStart??0;vm(w.value,T,n)&&h().then(R=>R?.handleInput())},handleKeydown:A=>{if(l?.isMenuOpen())return l.handleKeydown(A);if(A.key==="Backspace"&&l?.hasMentions()&&!f){let w=c,T=w.selectionStart===0&&w.selectionEnd===0;if((w.value.length===0||T)&&l.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(l??await h())?.dispatchInlineCommand(A)??null:null,clear:()=>l?.clear(),prefetch:()=>{ap().catch(()=>{})},onComposerSwap:A=>{g=A,f&&A(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let A of E)A.wrapper.remove();s.remove()}}}var Lm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Na(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];Lm(a)&&Lm(r)?n[o]=Na(a,r):n[o]=r}return n}var cn="min(440px, calc(100vw - 24px))",xi="440px",rb={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:cn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",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",size:"32px",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)"},ct={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",launcher:rb,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",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",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",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"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],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 Pm(e,t){if(!(!e&&!t))return e?t?Na(e,t):e:t}function Br(e){return e?{...ct,...e,theme:Pm(ct.theme,e.theme),darkTheme:Pm(ct.darkTheme,e.darkTheme),launcher:{...ct.launcher,...e.launcher,dock:{...ct.launcher?.dock,...e.launcher?.dock},clearChat:{...ct.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...ct.copy,...e.copy},sendButton:{...ct.sendButton,...e.sendButton},statusIndicator:{...ct.statusIndicator,...e.statusIndicator},voiceRecognition:{...ct.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=ct.features?.artifacts,n=e.features?.artifacts,o=ct.features?.scrollToBottom,r=e.features?.scrollToBottom,a=ct.features?.scrollBehavior,s=e.features?.scrollBehavior,l=ct.features?.streamAnimation,p=e.features?.streamAnimation,c=ct.features?.askUserQuestion,d=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},g=o===void 0&&r===void 0?void 0:{...o,...r},f=a===void 0&&s===void 0?void 0:{...a,...s},h=l===void 0&&p===void 0?void 0:{...l,...p},S=c===void 0&&d===void 0?void 0:{...c,...d,styles:{...c?.styles,...d?.styles}};return{...ct.features,...e.features,...g!==void 0?{scrollToBottom:g}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...h!==void 0?{streamAnimation:h}:{},...S!==void 0?{askUserQuestion:S}:{}}})(),suggestionChips:e.suggestionChips??ct.suggestionChips,suggestionChipsConfig:{...ct.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...ct.layout,...e.layout,header:{...ct.layout?.header,...e.layout?.header},messages:{...ct.layout?.messages,...e.layout?.messages,avatar:{...ct.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...ct.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...ct.layout?.slots,...e.layout?.slots}},markdown:{...ct.markdown,...e.markdown,options:{...ct.markdown?.options,...e.markdown?.options}},messageActions:{...ct.messageActions,...e.messageActions}}:ct}var bi="16px",Ci="transparent",sp={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:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},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"}},ip={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"}},lp={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:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:cn,maxWidth:xi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:bi,canvasBackground:Ci},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},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"},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 Xt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Xt(e,o):o}function vi(e){let t={};function n(o,r){for(let[a,s]of Object.entries(o)){let l=`${r}.${a}`;if(typeof s=="string"){let p=Xt(e,s);p!==void 0&&(t[l]={path:l,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&n(s,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function dp(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Rm(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];a&&typeof a=="object"&&!Array.isArray(a)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Rm(a,r):n[o]=r}return n}function ab(e,t){return t?Rm(e,t):e}function Oa(e,t={}){let n={palette:sp,semantic:ip,components:lp},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:ab(n.components,e?.components)};if(t.validate!==!1){let r=dp(o);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)o=r.transform(o);return o}function wi(e){let t=vi(e),n={};for(let[v,B]of Object.entries(t)){let F=v.replace(/\./g,"-");n[`--persona-${F}`]=B.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??bi,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ci,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let s=n["--persona-components-markdown-heading-h2-fontSize"];s&&(n["--persona-md-h2-size"]=s);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let c=e.components,d=c?.iconButton;d&&(d.background&&(n["--persona-icon-btn-bg"]=d.background),d.border&&(n["--persona-icon-btn-border"]=d.border),d.color&&(n["--persona-icon-btn-color"]=d.color),d.padding&&(n["--persona-icon-btn-padding"]=d.padding),d.borderRadius&&(n["--persona-icon-btn-radius"]=d.borderRadius),d.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=d.hoverBackground),d.hoverColor&&(n["--persona-icon-btn-hover-color"]=d.hoverColor),d.activeBackground&&(n["--persona-icon-btn-active-bg"]=d.activeBackground),d.activeBorder&&(n["--persona-icon-btn-active-border"]=d.activeBorder));let u=c?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let g=c?.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let f=c?.artifact;if(f?.toolbar){let v=f.toolbar;v.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=v.iconHoverColor),v.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=v.iconHoverBackground),v.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=v.iconPadding),v.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=v.iconBorderRadius),v.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=v.iconBorder),v.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=v.toggleGroupGap),v.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=v.toggleBorderRadius),v.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=v.toggleGroupPadding),v.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=v.toggleGroupBorder),v.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=v.toggleGroupBorderRadius),v.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Xt(e,v.toggleGroupBackground)??v.toggleGroupBackground),v.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=v.copyBackground),v.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=v.copyBorder),v.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=v.copyColor),v.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=v.copyBorderRadius),v.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=v.copyPadding),v.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=v.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??v.copyMenuBackground),v.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=v.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??v.copyMenuBorder),v.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=v.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??v.copyMenuShadow),v.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=v.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??v.copyMenuBorderRadius),v.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=v.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??v.copyMenuItemHoverBackground),v.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=v.iconBackground),v.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=v.toolbarBorder)}if(f?.tab){let v=f.tab;v.background&&(n["--persona-artifact-tab-bg"]=v.background),v.activeBackground&&(n["--persona-artifact-tab-active-bg"]=v.activeBackground),v.activeBorder&&(n["--persona-artifact-tab-active-border"]=v.activeBorder),v.borderRadius&&(n["--persona-artifact-tab-radius"]=v.borderRadius),v.textColor&&(n["--persona-artifact-tab-color"]=v.textColor),v.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=v.hoverBackground),v.listBackground&&(n["--persona-artifact-tab-list-bg"]=v.listBackground),v.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=v.listBorderColor),v.listPadding&&(n["--persona-artifact-tab-list-padding"]=v.listPadding)}if(f?.pane){let v=f.pane;if(v.toolbarBackground){let B=Xt(e,v.toolbarBackground)??v.toolbarBackground;n["--persona-artifact-toolbar-bg"]=B}}if(f?.card){let v=f.card;v.background&&(n["--persona-artifact-card-bg"]=v.background),v.border&&(n["--persona-artifact-card-border"]=v.border),v.borderRadius&&(n["--persona-artifact-card-radius"]=v.borderRadius),v.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=v.hoverBackground),v.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=v.hoverBorderColor)}if(f?.inline){let v=f.inline;v.background&&(n["--persona-artifact-inline-bg"]=Xt(e,v.background)??v.background),v.border&&(n["--persona-artifact-inline-border"]=v.border),v.borderRadius&&(n["--persona-artifact-inline-radius"]=v.borderRadius),v.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Xt(e,v.chromeBackground)??v.chromeBackground),v.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Xt(e,v.chromeBorder)??v.chromeBorder),v.titleColor&&(n["--persona-artifact-inline-title-color"]=Xt(e,v.titleColor)??v.titleColor),v.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Xt(e,v.mutedColor)??v.mutedColor),v.frameHeight&&(n["--persona-artifact-inline-frame-height"]=v.frameHeight)}let h=c?.code;h&&(h.keywordColor&&(n["--persona-code-keyword-color"]=h.keywordColor),h.stringColor&&(n["--persona-code-string-color"]=h.stringColor),h.commentColor&&(n["--persona-code-comment-color"]=h.commentColor),h.numberColor&&(n["--persona-code-number-color"]=h.numberColor),h.tagColor&&(n["--persona-code-tag-color"]=h.tagColor),h.attrColor&&(n["--persona-code-attr-color"]=h.attrColor),h.propertyColor&&(n["--persona-code-property-color"]=h.propertyColor),h.lineNumberColor&&(n["--persona-code-line-number-color"]=h.lineNumberColor),h.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=h.gutterBorderColor),h.background&&(n["--persona-code-bg"]=Xt(e,h.background)??h.background));let S=n["--persona-surface"],E=n["--persona-container"],k=n["--persona-palette-colors-gray-100"]??"#f3f4f6",M=n["--persona-palette-colors-gray-200"]??"#e5e7eb",A=n["--persona-palette-colors-gray-300"]??"#d1d5db",w=!E||E===S,T=w?k:E,R=w?M:E;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??T,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??R,w&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??A),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??T,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??T,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??T,n}var Im={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 sb={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"}}},Wm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},_a=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",ib=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":_a()},Ai=e=>ib(e),lb=e=>Oa(e),db=e=>Oa({...e,palette:{...e?.palette,colors:{...sb.colors,...e?.palette?.colors}}},{validate:!1}),wo=e=>{let t=Ai(e),n=Wm(e?.theme),o=Wm(e?.darkTheme);return t==="dark"?db(Na(n??{},o??{})):lb(n)},cb=e=>wi(e),or=(e,t)=>{let n=wo(t),o=cb(n);for(let[r,a]of Object.entries(o))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",Ai(t))},Dr=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(_a())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(_a());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Bn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Hm(e){let t=Bn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Si(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
23
|
+
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(l){let d=[];a&&d.push(bo(a)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];s&&d.push(bo(s)),d.push(...r.contentParts),t.contentParts=d}else a&&(t.llmContent=s);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=kr(),a=xo();this.activeAssistantMessageId=null;let s=n?.contentParts&&Ys(n.contentParts)?Qs:"",l={id:r,role:"user",content:o||s,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(u=>u.id===r)??l;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:a},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let g=id(c,this.config.errorMessage);if(g){let f={id:a,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=xo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId: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 s=id(r,this.config.errorMessage);if(s){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:s,sequence:this.nextSequence()};this.appendMessage(l)}}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,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let a of this.messages)a.streaming&&a.id!==o&&(a.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.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(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={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},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(a=>a.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,a={...t,status:n,resolvedAt:Date.now()},s=this.messages.find(c=>c.id===r),l={id:r,role:"assistant",content:"",createdAt:s?.createdAt??new Date().toISOString(),...s?.sequence!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let g=await c.json().catch(()=>null);throw new Error(g?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="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(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.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 s=typeof n=="string"?void 0:n;if(s===void 0&&typeof n=="string"){let c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let g=typeof u[0]?.question=="string"?u[0].question:"";g&&(s={[g]:n})}}this.markAskUserQuestionResolved(t,s),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,g])=>`${u}: ${Array.isArray(g)?g.join(", "):g}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=s??{};d.forEach((u,g)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let h=c[f],S=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";this.appendMessage({id:`ask-user-q-${l}-${g}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${g}`,role:"user",content:S||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[a]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let a=this.webMcpEpoch;queueMicrotask(()=>{a===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Tn?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${t}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let g=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===Tn)return{dedupeKey:u,resumeKey:f,output:Yl(),toolMessage:p,startedAt:g,completedAt:Date.now()};let h=new AbortController;this.webMcpResolveControllers.add(h),r.push(h);let S=this.client.executeWebMcpToolCall(d,p.toolCall?.args,h.signal),L;if(!S)L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{L=await S}catch(E){let M=E instanceof Error&&(E.name==="AbortError"||E.message.includes("aborted")||E.message.includes("abort"));return M||this.callbacks.onError?.(E instanceof Error?E:new Error(String(E))),this.markWebMcpToolComplete(p,Pa(M?"Aborted by cancel()":Am(E)),g),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,Pa("Aborted by cancel()"),g),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:L,toolMessage:p,startedAt:g,completedAt:Date.now()}})),l=[];try{if(l=s.filter(c=>c!==null),l.length===0)return;let p={};for(let c of l)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:a.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of l)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Tn?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of l)this.markWebMcpToolComplete(c.toolMessage,Pa("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let h=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h))return;this.webMcpInflightKeys.add(h);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(h)}catch(S){this.callbacks.onError?.(S instanceof Error?S:new Error(String(S)))}finally{this.webMcpInflightKeys.delete(h)}return}let a=`${n}:${r}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let d=o===Tn,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),g="execute",f=s;try{let h;if(d?h=Yl():u?h=await u:h={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,Pa("Aborted by cancel()"),s);return}let S=t.agentMetadata?.webMcpToolCallId??o;g="resume",await this.resumeWithToolOutput(n,S,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,h,s,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(h){let S=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));(g==="execute"||S||p.aborted)&&this.markWebMcpToolComplete(t,Pa(S||p.aborted?"Aborted by cancel()":Am(h)),s),S||this.callbacks.onError?.(h instanceof Error?h:new Error(String(h)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let a=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!a.ok){let s=await a.json().catch(()=>null);throw new Error(s?.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 n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=jo(this.config.features?.artifacts,t.artifactType),r=Ws(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),a=this.messages.find(s=>s.id===n);if(a){a.rawContent=r,a.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}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 n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.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(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(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=Promise.resolve().then(()=>(wm(),Cm)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>id(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=xo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=rd(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Lr(t)}toggleReadAloud(t){let n=this.messages.find(a=>a.id===t);if(!n||n.role!=="assistant")return;let o=rd(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,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 n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,a)=>{if(a!==o)return r;let s={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(s.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(s.agentMetadata={...s.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,u=n.approval;s.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&Sm(l)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),g=this.webMcpResolvedKeys.has(c),f=r.toolCall?.name,h=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&f!==void 0&&Sm(f)&&r.toolCall?.status==="complete";(u||g||h)&&(s.agentMetadata={...s.agentMetadata??{},awaitingLocalTool:!1},s.toolCall=r.toolCall,s.streaming=r.streaming)}return s}),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((n,o)=>{let r=new Date(n.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(a)&&r!==a)return r-a;let s=n.sequence??0,l=o.sequence??0;return s!==l?s-l:n.id.localeCompare(o.id)})}};var ld=[["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 dd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var cd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var pd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var ud=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var fd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var md=[["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 gd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var hd=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var yd=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var xd=[["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 bd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var vd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var Cd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var wd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var Ad=[["path",{d:"M20 6 9 17l-5-5"}]];var Sd=[["path",{d:"m6 9 6 6 6-6"}]];var Md=[["path",{d:"m15 18-6-6 6-6"}]];var Td=[["path",{d:"m9 18 6-6-6-6"}]];var Ed=[["path",{d:"m18 15-6-6-6 6"}]];var ni=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var oi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var kd=[["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 Ld=[["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 Pd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var ri=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Rd=[["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 Id=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Wd=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var Hd=[["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 ai=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var si=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Bd=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var Dd=[["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 Fd=[["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 Od=[["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 Nd=[["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 _d=[["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 Ud=[["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 qd=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var Vd=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var zd=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var $d=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var jd=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var ii=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var Gd=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var Kd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var Xd=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Jd=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Qd=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Yd=[["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 li=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var Zd=[["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 ec=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var tc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var nc=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var oc=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var di=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var rc=[["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 ac=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var sc=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var ic=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var lc=[["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 dc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var cc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var pc=[["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 uc=[["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 fc=[["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 mc=[["path",{d:"M5 12h14"}]];var gc=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var hc=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var yc=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var xc=[["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 bc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var vc=[["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 Cc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var wc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var Ac=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var Sc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Mc=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var Tc=[["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 Ec=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var kc=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var Lc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Pc=[["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 Rc=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Ic=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var Wc=[["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 Hc=[["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 ci=[["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 Bc=[["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"}]];var Dc=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var Fc=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var Oc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var pi=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var Nc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var _c=[["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 Uc=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var qc=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var Vc=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var zc=[["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 $c=[["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 jc=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var Gc=[["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 Kc=[["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 ui=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var Xc=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Jc=[["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 Qc=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Yc=[["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 Zc=[["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"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var ep=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var tp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var np=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var eb={activity:ld,"arrow-down":dd,"arrow-up":fd,"arrow-up-right":ud,bot:xd,"chevron-down":Sd,"chevron-up":Ed,"chevron-right":Td,"chevron-left":Md,check:Ad,clipboard:Ld,"clipboard-copy":kd,"code-xml":ri,copy:Rd,file:Ud,"file-code":Od,"file-spreadsheet":Nd,"file-text":_d,"image-plus":Zd,loader:rc,"loader-circle":di,mic:uc,paperclip:xc,"refresh-cw":Tc,search:Lc,send:Pc,"shield-alert":Wc,"shield-check":Hc,"shield-x":ci,square:Nc,"thumbs-down":zc,"thumbs-up":$c,upload:Jc,"volume-2":Yc,x:tp,user:Qc,mail:sc,phone:wc,calendar:Cd,clock:Pd,building:bd,"map-pin":ic,lock:ac,key:nc,"credit-card":Id,"at-sign":md,hash:Xd,globe:Kd,link:oc,"circle-check":ni,"circle-x":oi,"triangle-alert":ui,info:tc,ban:gd,shield:Bc,"arrow-left":cd,"arrow-right":pd,"external-link":Dd,ellipsis:si,"ellipsis-vertical":ai,menu:dc,house:li,plus:Sc,minus:mc,pencil:vc,trash:Kc,"trash-2":Gc,save:kc,download:Hd,share:Ic,funnel:ii,settings:Rc,"rotate-cw":Ec,maximize:lc,minimize:fc,"shopping-cart":Fc,"shopping-bag":Dc,package:yc,truck:Xc,tag:Vc,gift:Gd,receipt:Mc,wallet:ep,store:Uc,"dollar-sign":Wd,percent:Cc,play:Ac,pause:bc,"volume-x":Zc,camera:wd,image:ec,film:Vd,headphones:Jd,"message-circle":cc,"message-square":pc,bell:hd,heart:Qd,star:_c,eye:Fd,"eye-off":Bd,bookmark:yd,"calendar-days":vd,history:Yd,timer:jc,folder:jd,"folder-open":$d,files:qd,sparkles:pi,zap:np,sun:qc,moon:hc,flag:zd,monitor:gc,smartphone:Oc},te=(e,t=24,n="currentColor",o=2)=>{let r=eb[e];return r?tb(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function tb(e,t,n,o){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",n),r.setAttribute("stroke-width",String(o)),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 s=a[0],l=a[1];if(!l)return;let p=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(l).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),r.appendChild(p)}),r}var fi={allowedTypes:Kn,maxFileSize:10*1024*1024,maxFiles:4};function nb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ob(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Yo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??fi.allowedTypes,maxFileSize:t.maxFileSize??fi.maxFileSize,maxFiles:t.maxFiles??fi.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:fi.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)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}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){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=hm(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await gm(n),a=Zs(n)?URL.createObjectURL(n):null,s={id:nb(),file:n,previewUrl:a,contentPart:r};this.attachments.push(s),this.renderPreview(s)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(a=>a.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Zs(t.file),o=x("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let s=x("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=x("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let l=ob(t.file.type),p=te(l,20,"var(--persona-muted, #6b7280)",1.5);p&&s.appendChild(p);let d=x("span");d.textContent=ym(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",s.appendChild(d),o.appendChild(s)}let r=x("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let a=te("x",10,"var(--persona-text-inverse, #ffffff)",2);a?r.appendChild(a):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var Mm=/\s/;function rb(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
|
|
24
|
+
`:o===""||Mm.test(o)}function ab(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let s=e[a];if(s===n)return rb(e,a,o)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(s===`
|
|
25
|
+
`||s==="\uFFFC"||!r&&Mm.test(s))return null;a--}return null}function Tm(e,t,n){for(let o of n){let r=ab(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Em(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function km(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},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}var Ht={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Vt=1e5,mi=Vt+1;var sb=8,ib=8,op=10,rp=new WeakMap,Lm=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,lb=e=>{let t=e.getRootNode?.();return Lm(t)?t:e.ownerDocument.body},ap=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Nt(e){rp.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:a=sb,viewportPadding:s=ib}=e,l=()=>t.ownerDocument,p=()=>l().defaultView??window,d=null,c=null,u=null,g=!1,f=!1,h=!1,S=()=>(typeof o=="function"?o():o).trim(),L=()=>{u?.(),u=null,d?.remove(),d=null,c=null},E=()=>{if(!d)return;let q=l(),D=p(),U=t.getBoundingClientRect(),se=d.getBoundingClientRect(),le=q.documentElement.clientWidth||D.innerWidth,Ce=q.documentElement.clientHeight||D.innerHeight,Le=le-s-se.width,ae=U.left+U.width/2-se.width/2,me=ap(ae,s,Le),Z=U.top-s,de=Ce-s-U.bottom,Y=se.height+a,ve=Z>=Y||Z>=de?"top":"bottom",Ae=ve==="top"?U.top-a-se.height:U.bottom+a,xe=Ce-s-se.height,Be=ap(Ae,s,xe),Oe=U.left+U.width/2,Ve=Math.max(op,se.width-op),Ne=ap(Oe-me,op,Ve);d.dataset.placement=ve,d.style.left=`${me}px`,d.style.top=`${Be}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${Ne}px`)},M=()=>{if(h||!r||d||!t.isConnected)return;let q=S(),D=lb(t);if(!q||!D)return;let U=l(),se=p();d=U.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(mi),c=U.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=q,d.appendChild(c);let le=U.createElement("span");le.className="persona-control-tooltip__arrow",d.appendChild(le),D.appendChild(d),E(),d.dataset.state="open";let Ce=()=>{if(!t.isConnected){L();return}c&&(c.textContent=S()),E()};se.addEventListener("scroll",Ce,!0),se.addEventListener("resize",Ce);let Le=t.getRootNode(),ae=Lm(Le)?Le:U.documentElement,me=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||L()});me?.observe(ae,{childList:!0,subtree:!0}),u=()=>{se.removeEventListener("scroll",Ce,!0),se.removeEventListener("resize",Ce),me?.disconnect()}},A=()=>{g||f?M():L()},w=()=>{let q=p();(!q.matchMedia||!q.matchMedia("(hover: none)").matches)&&(g=!0,A())},T=()=>{g=!1,A()},H=()=>{f=!0,A()},C=()=>{f=!1,A()},B=q=>{q.key==="Escape"&&(g=!1,f=!1,L())};n.addEventListener("mouseenter",w),n.addEventListener("mouseleave",T),t.addEventListener("focus",H),t.addEventListener("blur",C),t.addEventListener("keydown",B);let F={get isOpen(){return d!==null},show:M,hide:L,reposition:E,destroy:()=>{h||(h=!0,L(),n.removeEventListener("mouseenter",w),n.removeEventListener("mouseleave",T),t.removeEventListener("focus",H),t.removeEventListener("blur",C),t.removeEventListener("keydown",B),rp.delete(t))}};return rp.set(t,F),F}function Pm(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,a=Math.round(r*.6),s=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",p=x("div","persona-send-button-wrapper"),d=Fe("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=te(s,a,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(d),Nt({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??l}),{button:d,wrapper:p}}var{setLoader:db,load:cb}=vr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),Rm=db,sp=cb;var{setLoader:pb,load:ub}=vr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),Im=pb,Wm=ub;function Ra(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Fe("span",{className:zn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=te(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=x("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Fe("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Hm(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=km(t).filter(A=>A.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(A=>A.sources.some(w=>typeof w.matchCommand=="function")),r=A=>o.some(w=>w.trigger?w.position==="line-start"?A.split(`
|
|
26
|
+
`).some(H=>H.startsWith(w.trigger)):(w.position==="anywhere"?A:A.split(`
|
|
27
|
+
`)[0]).startsWith(w.trigger):!1),a=(A,w)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:w}))}catch{}},s=Fe("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,d=e.textarea,c=null,u=null,g=null,f=null,h=()=>{if(l)return Promise.resolve(l);if(p)return p;let A=sp().then(w=>(l=w.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:s,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:M,emit:a}),l)).catch(w=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",w),p===A&&(p=null),null));return p=A,A},S=()=>{Wm().then(A=>{let w=A.mountInlineComposer({textarea:e.textarea,renderToken:H=>Ra(H,{render:t.renderMentionToken}),onMentionRemoved:H=>l?.untrackMention(H)});c=w.input,u=w.destroy;let T=d;T.replaceWith(w.element),d=w.element,f={next:w.element,prev:T},g?.(w.element,T),l?l.rebindComposer(w.input):p&&p.then(H=>H?.rebindComposer(w.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};t.display==="inline"&&S();let L=[],E=new Map;for(let A of n){if(!A.showButton)continue;let w=Pm({config:{...t,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{h().then(T=>T?.openMenu(A.trigger))}});L.push(w),E.set(A.trigger,w.button)}let M=(A,w,T)=>{let H=E.get(w);H&&(H.setAttribute("aria-expanded",A?"true":"false"),A?H.setAttribute("aria-controls",T):H.removeAttribute("aria-controls"))};return{affordanceButtons:L.map(A=>A.wrapper),contextRow:s,handleInput:A=>{if(l){l.handleInput();return}if(!Em(A))return;let w=d,T=w.selectionStart??0;Tm(w.value,T,n)&&h().then(H=>H?.handleInput())},handleKeydown:A=>{if(l?.isMenuOpen())return l.handleKeydown(A);if(A.key==="Backspace"&&l?.hasMentions()&&!f){let w=d,T=w.selectionStart===0&&w.selectionEnd===0;if((w.value.length===0||T)&&l.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(l??await h())?.dispatchInlineCommand(A)??null:null,clear:()=>l?.clear(),prefetch:()=>{sp().catch(()=>{})},onComposerSwap:A=>{g=A,f&&A(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let A of L)A.wrapper.remove();s.remove()}}}var Bm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ia(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];Bm(a)&&Bm(r)?n[o]=Ia(a,r):n[o]=r}return n}var ln="min(440px, calc(100vw - 24px))",gi="440px",fb={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:ln,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",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",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},lt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:fb,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",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",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",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"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],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 Dm(e,t){if(!(!e&&!t))return e?t?Ia(e,t):e:t}function Rr(e){return e?{...lt,...e,theme:Dm(lt.theme,e.theme),darkTheme:Dm(lt.darkTheme,e.darkTheme),launcher:{...lt.launcher,...e.launcher,dock:{...lt.launcher?.dock,...e.launcher?.dock},clearChat:{...lt.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...lt.copy,...e.copy},sendButton:{...lt.sendButton,...e.sendButton},statusIndicator:{...lt.statusIndicator,...e.statusIndicator},voiceRecognition:{...lt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=lt.features?.artifacts,n=e.features?.artifacts,o=lt.features?.scrollToBottom,r=e.features?.scrollToBottom,a=lt.features?.scrollBehavior,s=e.features?.scrollBehavior,l=lt.features?.streamAnimation,p=e.features?.streamAnimation,d=lt.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},g=o===void 0&&r===void 0?void 0:{...o,...r},f=a===void 0&&s===void 0?void 0:{...a,...s},h=l===void 0&&p===void 0?void 0:{...l,...p},S=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...lt.features,...e.features,...g!==void 0?{scrollToBottom:g}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...h!==void 0?{streamAnimation:h}:{},...S!==void 0?{askUserQuestion:S}:{}}})(),suggestionChips:e.suggestionChips??lt.suggestionChips,suggestionChipsConfig:{...lt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...lt.layout,...e.layout,header:{...lt.layout?.header,...e.layout?.header},messages:{...lt.layout?.messages,...e.layout?.messages,avatar:{...lt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...lt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...lt.layout?.slots,...e.layout?.slots}},markdown:{...lt.markdown,...e.markdown,options:{...lt.markdown?.options,...e.markdown?.options}},messageActions:{...lt.messageActions,...e.messageActions}}:lt}var hi="16px",yi="transparent",ip={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:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},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"}},lp={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"}},dp={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:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:ln,maxWidth:gi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:hi,canvasBackground:yi},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},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"},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 Kt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Kt(e,o):o}function xi(e){let t={};function n(o,r){for(let[a,s]of Object.entries(o)){let l=`${r}.${a}`;if(typeof s=="string"){let p=Kt(e,s);p!==void 0&&(t[l]={path:l,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&n(s,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function cp(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Fm(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];a&&typeof a=="object"&&!Array.isArray(a)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Fm(a,r):n[o]=r}return n}function mb(e,t){return t?Fm(e,t):e}function Wa(e,t={}){let n={palette:ip,semantic:lp,components:dp},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:mb(n.components,e?.components)};if(t.validate!==!1){let r=cp(o);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)o=r.transform(o);return o}function bi(e){let t=xi(e),n={};for(let[C,B]of Object.entries(t)){let F=C.replace(/\./g,"-");n[`--persona-${F}`]=B.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??hi,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??yi,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let s=n["--persona-components-markdown-heading-h2-fontSize"];s&&(n["--persona-md-h2-size"]=s);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let d=e.components,c=d?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=d?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let g=d?.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let f=d?.artifact;if(f?.toolbar){let C=f.toolbar;C.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=C.iconHoverColor),C.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=C.iconHoverBackground),C.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=C.iconPadding),C.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=C.iconBorderRadius),C.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=C.iconBorder),C.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=C.toggleGroupGap),C.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=C.toggleBorderRadius),C.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=C.toggleGroupPadding),C.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=C.toggleGroupBorder),C.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=C.toggleGroupBorderRadius),C.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Kt(e,C.toggleGroupBackground)??C.toggleGroupBackground),C.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=C.copyBackground),C.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=C.copyBorder),C.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=C.copyColor),C.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=C.copyBorderRadius),C.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=C.copyPadding),C.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=C.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??C.copyMenuBackground),C.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=C.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??C.copyMenuBorder),C.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=C.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??C.copyMenuShadow),C.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=C.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??C.copyMenuBorderRadius),C.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=C.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??C.copyMenuItemHoverBackground),C.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=C.iconBackground),C.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=C.toolbarBorder)}if(f?.tab){let C=f.tab;C.background&&(n["--persona-artifact-tab-bg"]=C.background),C.activeBackground&&(n["--persona-artifact-tab-active-bg"]=C.activeBackground),C.activeBorder&&(n["--persona-artifact-tab-active-border"]=C.activeBorder),C.borderRadius&&(n["--persona-artifact-tab-radius"]=C.borderRadius),C.textColor&&(n["--persona-artifact-tab-color"]=C.textColor),C.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=C.hoverBackground),C.listBackground&&(n["--persona-artifact-tab-list-bg"]=C.listBackground),C.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=C.listBorderColor),C.listPadding&&(n["--persona-artifact-tab-list-padding"]=C.listPadding)}if(f?.pane){let C=f.pane;if(C.toolbarBackground){let B=Kt(e,C.toolbarBackground)??C.toolbarBackground;n["--persona-artifact-toolbar-bg"]=B}}if(f?.card){let C=f.card;C.background&&(n["--persona-artifact-card-bg"]=C.background),C.border&&(n["--persona-artifact-card-border"]=C.border),C.borderRadius&&(n["--persona-artifact-card-radius"]=C.borderRadius),C.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=C.hoverBackground),C.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=C.hoverBorderColor)}if(f?.inline){let C=f.inline;C.background&&(n["--persona-artifact-inline-bg"]=Kt(e,C.background)??C.background),C.border&&(n["--persona-artifact-inline-border"]=C.border),C.borderRadius&&(n["--persona-artifact-inline-radius"]=C.borderRadius),C.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Kt(e,C.chromeBackground)??C.chromeBackground),C.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Kt(e,C.chromeBorder)??C.chromeBorder),C.titleColor&&(n["--persona-artifact-inline-title-color"]=Kt(e,C.titleColor)??C.titleColor),C.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Kt(e,C.mutedColor)??C.mutedColor),C.frameHeight&&(n["--persona-artifact-inline-frame-height"]=C.frameHeight)}let h=d?.code;h&&(h.keywordColor&&(n["--persona-code-keyword-color"]=h.keywordColor),h.stringColor&&(n["--persona-code-string-color"]=h.stringColor),h.commentColor&&(n["--persona-code-comment-color"]=h.commentColor),h.numberColor&&(n["--persona-code-number-color"]=h.numberColor),h.tagColor&&(n["--persona-code-tag-color"]=h.tagColor),h.attrColor&&(n["--persona-code-attr-color"]=h.attrColor),h.propertyColor&&(n["--persona-code-property-color"]=h.propertyColor),h.lineNumberColor&&(n["--persona-code-line-number-color"]=h.lineNumberColor),h.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=h.gutterBorderColor),h.background&&(n["--persona-code-bg"]=Kt(e,h.background)??h.background));let S=n["--persona-surface"],L=n["--persona-container"],E=n["--persona-palette-colors-gray-100"]??"#f3f4f6",M=n["--persona-palette-colors-gray-200"]??"#e5e7eb",A=n["--persona-palette-colors-gray-300"]??"#d1d5db",w=!L||L===S,T=w?E:L,H=w?M:L;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??T,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??H,w&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??A),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??T,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??T,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??T,n}var Om={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 gb={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"}}},Nm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ha=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",hb=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ha()},vi=e=>hb(e),yb=e=>Wa(e),xb=e=>Wa({...e,palette:{...e?.palette,colors:{...gb.colors,...e?.palette?.colors}}},{validate:!1}),wo=e=>{let t=vi(e),n=Nm(e?.theme),o=Nm(e?.darkTheme);return t==="dark"?xb(Ia(n??{},o??{})):yb(n)},bb=e=>bi(e),Zo=(e,t)=>{let n=wo(t),o=bb(n);for(let[r,a]of Object.entries(o))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",vi(t))},Ir=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ha())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ha());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Wn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function _m(e){let t=Wn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Ci(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
28
28
|
`);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
|
|
29
|
-
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function
|
|
30
|
-
`).length,f=e.artifactType==="markdown"?e.file:void 0,h={artifactId:s,artifactType:e.artifactType,title:e.title,typeLabel:o,file:f,chars:u,lines:g,elapsedMs:p,content:()=>
|
|
29
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Ba(e){let t=_m(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Ao(e){switch(Ba(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=_m(e.path);return t?t.toUpperCase():"File"}}}function Um(e){let t=e.markdown??"";return e.file?{filename:Wn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Ci(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var pp="http://www.w3.org/2000/svg";function qm(e){let t=document.createElementNS(pp,"svg");t.setAttribute("class",zn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(pp,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(pp,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var So=(e,t,n)=>{let o=n;for(let r of t){let a=x("span","persona-tool-char");a.style.setProperty("--char-index",String(o)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),o++}return o};function Vm(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),So(e,t,0)}var up="persona-artifact-status-label",zm="persona-artifact-status-detail",$m="data-artifact-status-label",fp=new Map,jm=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Wr(e){e&&fp.delete(e)}function vb(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Ao(t):e.artifactType==="component"?"Component":"Document"}function Hr(e,t,n){let o=vb(e),r=`Generating ${o.toLowerCase()}...`,a=t?.statusLabel;if(typeof a=="string")return{label:a};if(typeof a!="function")return{label:r};let s=e.id,l=fp.get(s);e.status!=="complete"&&l===void 0&&(l=jm(),fp.set(s,l));let p=l===void 0?0:Math.max(0,jm()-l),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",u=d?0:c.length,g=d||c===""?0:c.split(`
|
|
30
|
+
`).length,f=e.artifactType==="markdown"?e.file:void 0,h={artifactId:s,artifactType:e.artifactType,title:e.title,typeLabel:o,file:f,chars:u,lines:g,elapsedMs:p,content:()=>d?"":c,surface:n};try{let S=a(h);return typeof S=="string"?{label:S}:S&&typeof S=="object"&&typeof S.label=="string"?{label:S.label,detail:typeof S.detail=="string"?S.detail:void 0}:{label:r}}catch{return{label:r}}}function Cb(e){e.className=up,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function er(e,t,n){let o=e.querySelector(`:scope > .${up}`);o||(o=x("span",up),e.appendChild(o)),o.getAttribute($m)!==t.label&&(Cb(o),Vm(o,t.label,n),o.setAttribute($m,t.label));let r=e.querySelector(`:scope > .${zm}`),a=t.detail;a?(r||(r=x("span",zm),e.appendChild(r)),r.textContent!==a&&(r.textContent=a)):r&&r.remove()}var wb={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},Ab=15e4,wi={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function Sb(e,t){let n=(e||"").trim().toLowerCase();if(n&&wi[n])return wi[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(wi[r])return wi[r]}}return null}function Ai(e,t){let n=[],o=0,r=0,a=s=>{s>r&&n.push({type:"plain",value:e.slice(r,s)})};for(;o<e.length;){let s=!1;for(let l of t){l.re.lastIndex=o;let p=l.re.exec(e);if(p&&p.index===o&&p[0].length>0){a(o);let d=l.map?l.map(p[0]):l.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,s=!0;break}}s||(o+=1)}return a(e.length),n}var Mb=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),Tb=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:e=>Mb.has(e)?"keyword":"plain"}];function Gm(e){return Ai(e,Tb)}var Eb=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];function kb(e){let t=Ai(e,Eb);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var Lb=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function Km(e){let t=Ai(e,Lb),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let s=o+1;for(;s<t.length&&t[s].value.trim()==="";)s+=1;let l=t[s];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let a=r.value.replace(/\s+$/,"");a&&(n=a[a.length-1])}return t}var Pb=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function Rb(e){let t=[],n=(a,s)=>{s&&t.push({type:a,value:s})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let s=e.indexOf("-->",r+4),l=s===-1?o:s+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let s=e.indexOf(">",r),l=s===-1?o:s+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let s=e.indexOf(">",r),l=s===-1?o:s+1,p=e.slice(r,l);for(let c of Ai(p,Pb))t.push(c);r=l;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),g=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),f=g?r+g.index:o,h=e.slice(r,f),S=c==="script"?Gm(h):Km(h);for(let L of S)t.push(L);r=f}continue}let a=e.indexOf("<",r);if(a===r)n("plain",e[r]),r+=1;else{let s=a===-1?o:a;n("plain",e.slice(r,s)),r=s}}return t}function Ib(e,t){switch(t){case"html":return Rb(e);case"css":return Km(e);case"js":return Gm(e);case"json":return kb(e)}}function Wb(e){let t=Uf(),n=x("span","persona-code-line"),o=(r,a)=>{if(!a)return;let s=wb[r];if(s){let l=x("span",s);l.textContent=a,n.appendChild(l)}else n.appendChild(document.createTextNode(a))};for(let r of e){let a=r.value.split(`
|
|
31
31
|
`);for(let s=0;s<a.length;s+=1)s>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
|
|
32
|
-
`)),n=y("span","persona-code-line")),o(r.type,a[s])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Vm(e,t,n){let o=e.length<=mb?gb(t,n):null,r=o?Ab(e,o):[{type:"plain",value:e}];return Sb(r)}var Ht={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},zt=1e5,Mo=zt+1;function To(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:a}=e,s=y("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(Mo)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",r==="bottom-right"?s.style.right="0":s.style.left="0");for(let f of t){if(f.dividerBefore){let E=document.createElement("hr");s.appendChild(E)}let h=document.createElement("button");if(h.type="button",h.setAttribute("role","menuitem"),h.setAttribute("data-dropdown-item-id",f.id),f.destructive&&h.setAttribute("data-destructive",""),f.icon){let E=te(f.icon,16,"currentColor",1.5);E&&h.appendChild(E)}let S=document.createElement("span");S.textContent=f.label,h.appendChild(S),h.addEventListener("click",E=>{E.stopPropagation(),d(),n(f.id)}),s.appendChild(h)}let l=null;function p(){if(!a)return;let f=o.getBoundingClientRect();s.style.top=`${f.bottom+4}px`,r==="bottom-right"?(s.style.right=`${window.innerWidth-f.right}px`,s.style.left="auto"):(s.style.left=`${f.left}px`,s.style.right="auto")}function c(){p(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=h=>{!s.contains(h.target)&&!o.contains(h.target)&&d()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function d(){s.classList.add("persona-hidden"),l?.(),l=null}function u(){s.classList.contains("persona-hidden")?c():d()}function g(){d(),s.remove()}return a&&a.appendChild(s),{element:s,show:c,hide:d,toggle:u,destroy:g}}function Et(e){let{icon:t,label:n,size:o,strokeWidth:r,className:a,onClick:s,aria:l}=e,p=y("button","persona-icon-btn"+(a?" "+a:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let c=te(t,o??16,"currentColor",r??2);if(c&&p.appendChild(c),s&&p.addEventListener("click",s),l)for(let[d,u]of Object.entries(l))p.setAttribute(d,u);return p}function Jn(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:a,className:s,onClick:l,aria:p}=e,c="persona-label-btn";o!=="default"&&(c+=" persona-label-btn--"+o),c+=" persona-label-btn--"+r,s&&(c+=" "+s);let d=y("button",c);if(d.type="button",d.setAttribute("aria-label",n),t){let g=te(t,a??14,"currentColor",2);g&&d.appendChild(g)}let u=y("span");if(u.textContent=n,d.appendChild(u),l&&d.addEventListener("click",l),p)for(let[g,f]of Object.entries(p))d.setAttribute(g,f);return d}function Or(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,a=y("div","persona-toggle-group"+(r?" "+r:""));a.setAttribute("role","group");let s=n,l=[];function p(){for(let d of l)d.btn.setAttribute("aria-pressed",d.id===s?"true":"false")}for(let d of t){let u;d.icon?u=Et({icon:d.icon,label:d.label,className:d.className,onClick:()=>{s=d.id,p(),o(d.id)}}):(u=y("button","persona-icon-btn"+(d.className?" "+d.className:"")),u.type="button",u.setAttribute("aria-label",d.label),u.title=d.label,u.textContent=d.label,u.addEventListener("click",()=>{s=d.id,p(),o(d.id)})),u.setAttribute("aria-pressed",d.id===s?"true":"false"),l.push({id:d.id,btn:u}),a.appendChild(u)}function c(d){s=d,p()}return{element:a,setSelected:c}}function Ei(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:a="bottom-left",portal:s,className:l,hover:p}=e,c=y("div","persona-combo-btn"+(l?" "+l:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let d=y("span","persona-combo-btn-label");d.textContent=t,c.appendChild(d);let u=te(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),p&&(c.style.borderRadius=p.borderRadius??"10px",c.style.padding=p.padding??"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{c.style.backgroundColor=p.background??"",c.style.borderColor=p.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=To({items:o,onSelect:f=>{c.setAttribute("aria-expanded","false"),r(f)},anchor:c,position:a,portal:s});return s||c.appendChild(g.element),c.addEventListener("click",f=>{f.stopPropagation();let h=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",h?"false":"true"),g.toggle()}),c.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),c.click())}),{element:c,setLabel:f=>{d.textContent=f,c.setAttribute("aria-label",f)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let f=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",f?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var ki="persona-artifact-custom-action-btn";function _r(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+ki+(n?" persona-artifact-doc-copy-btn":"");o=y("button",r)}else{let r="persona-icon-btn "+ki+(n?" persona-artifact-doc-icon-btn":"");o=y("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=y("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Jn({icon:e.icon,label:e.label,className:ki+(n?" persona-artifact-doc-copy-btn":"")}):o=Et({icon:e.icon,label:e.label,className:ki+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function qa(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function zm(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Bn(n.path):o,a=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n?Ao(n):l==="component"?"Component":"Document",c=document.createElement("div");c.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),a&&c.setAttribute("data-open-artifact",a);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let h=t?.config?.features?.artifacts,S={id:a,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{}},E=Nr(S,h,"card");rr(f,E,h)}else a&&Fr(a),f.textContent=p;if(u.append(g,f),c.append(d,u),s==="complete"){let h=t?.config?.features?.artifacts?.cardActions;if(h&&h.length>0){let E={artifactId:a||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let k of h)try{if(k.visible===void 0||k.visible(E)){let M=_r(k);M.setAttribute("data-artifact-custom-action",k.id),M.className=`${M.className} persona-flex-shrink-0`,c.append(M)}}catch{}}let S=Jn({label:"Download",className:"persona-flex-shrink-0"});S.title=`Download ${r}`,S.setAttribute("data-download-artifact",a),c.append(S)}return c}var Li=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",s=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:s,status:a},config:t.config,defaultRenderer:()=>zm(e,t)});if(l)return l}return zm(e,t)};var Eo=new WeakMap;function fp(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let a=Eo.get(r);if(!a)return;let s=o.get(r.getAttribute("data-artifact-inline")??"");s&&a(s,n)})}function Xm(e){return Eo.has(e)}function Mb(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete";if(e.artifactType==="component"){let a=e.componentProps,s=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:s}}let r=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...r?{file:r}:{}}}function $m(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Bn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Ao(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Tb(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var jm=180,Eb=240,kb=.8,Lb=300,Pb=500,Rb="cubic-bezier(0.2, 0, 0, 1)",Gm=240,Ib=.35;function Wb(e,t,n){let{swap:o,onSettled:r}=n,a=!1;try{a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{a=!1}if(!t||!e.isConnected||a||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let s=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&s.push(l.animate([{opacity:1},{opacity:0}],{duration:jm,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let k of s)k.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){l(),r();return}let c=Math.abs(t-p),d=Math.round(Math.min(Pb,Math.max(Lb,Eb+c*kb))),u=Math.round(d*Ib),g=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=g?g.animate([{opacity:0},{opacity:1}],{duration:Gm,delay:u,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:d,easing:Rb});e.style.height=`${p}px`;let S=!1,E=()=>{S||(S=!0,l(),r())};Promise.allSettled([h.finished,f?.finished].filter(Boolean)).then(E),window.setTimeout(E,Math.max(d,u+Gm)+120)},jm)}function Hb(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Va="--persona-artifact-inline-body-height";function Bb(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,a=320,s=t?.height;typeof s=="number"||s==="auto"?(r=s,a=s):s&&typeof s=="object"&&(r=s.streaming??320,a=s.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:t?.followOutput!==!1,c,d,u=t?.fadeMask;u===!0?(c=!0,d=!0):u===!1?(c=!1,d=!1):u&&typeof u=="object"?(c=u.top===!0,d=u.bottom===!0):l==="clip"?(c=!1,d=!0):(c=!0,d=!0);let g=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:a,followOutput:p,overflow:l,fadeTop:c,fadeBottom:d,transition:g,completeDisplay:f}}function Km(e,t){let n=Mb(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:a,showExpand:s,showViewToggle:l}=Hb(o),p=o?.inlineActions??[],c=Bb(o),d=c.completeDisplay==="card",u=null,g=n,f=y("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let h=ee=>Li(Tb(ee),t),S=ee=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Va),f.replaceChildren(h(ee)),Eo.set(f,le=>{f.replaceChildren(h(le))})};if(d&&n.status==="complete")return S(n),f;let E=Pi(n,{config:t.config,bodyLayout:c,resolveViewMode:()=>u??c.viewMode}),k=y("div","persona-artifact-inline-body");k.appendChild(E.el);let M=ee=>{let le=ee.status!=="complete",Y=le?c.streamingHeight:c.completeHeight,ve=typeof Y=="number";ve?f.style.setProperty(Va,`${Y}px`):f.style.removeProperty(Va);let Ae=!!E.el.querySelector(".persona-code-pre"),be=!!E.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");k.classList.toggle("persona-artifact-content-flush",Ae),k.classList.toggle("persona-artifact-inline-body--sized",ve&&be),k.classList.toggle("persona-artifact-inline-body--cap",!le&&!be&&typeof c.completeHeight=="number")},A=n.status,w=(ee,le)=>{A!=="complete"&&ee.status==="complete"?(typeof c.completeHeight=="number"?f.style.setProperty(Va,`${c.completeHeight}px`):f.style.removeProperty(Va),Qm(k,le?.suppressTransition?"none":c.transition,ee.id,()=>{E.update(ee),M(ee)})):E.update(ee),M(ee),A=ee.status};M(n);let T=c.overflow==="clip"&&s&&!!n.id;if(T&&(k.setAttribute("data-expand-artifact-inline",n.id),k.setAttribute("role","button"),k.setAttribute("tabindex","0"),k.classList.add("persona-cursor-pointer"),k.setAttribute("aria-label",`Open ${$m(n).title} in panel`)),!r)return f.appendChild(k),Eo.set(f,w),f;let R=y("div","persona-artifact-inline-chrome");R.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let v=y("div","persona-artifact-inline-chrome-lead"),B=y("span","persona-flex persona-items-center persona-flex-shrink-0"),F=te("file-text",16,"currentColor",2);F&&B.appendChild(F);let $=y("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),N=y("span","persona-artifact-inline-type");v.append(B,$,N);let U=y("div","persona-artifact-inline-chrome-actions"),fe=y("span","persona-flex persona-items-center persona-gap-1"),ce=()=>u??c.viewMode,Le=l?Or({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:ce(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ee=>{let le=ee==="source"?"source":"rendered";le!==ce()&&(u=le,E.update(g),M(g))}}):null,De=a?Et({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;De&&n.id&&De.setAttribute("data-copy-artifact",n.id);let ae=s?Et({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ae&&n.id&&ae.setAttribute("data-expand-artifact-inline",n.id),U.appendChild(fe),Le&&U.appendChild(Le.element),De&&U.appendChild(De),ae&&U.appendChild(ae),R.append(v,U),f.append(R,k);let Ce=ee=>{let{title:le,typeLabel:Y}=$m(ee);$.textContent=le,$.title=le,T&&k.setAttribute("aria-label",`Open ${le} in panel`);let ve=ee.status!=="complete";if(ve){N.classList.contains("persona-artifact-inline-status")||(N.className="persona-artifact-inline-status",N.removeAttribute("data-preserve-animation"),N.replaceChildren());let Ae=Nr(ee,o,"inline-chrome");rr(N,Ae,o)}else Fr(ee.id),N.className="persona-artifact-inline-type",N.removeAttribute("data-preserve-animation"),N.replaceChildren(),N.textContent=Y;if(De&&De.classList.toggle("persona-hidden",ve),Le){let Ae=ee.artifactType==="markdown"?ee.file:void 0,be=!1;if(!ve&&Ae&&c.viewMode!=="source"){let He=Ua(Ae);He==="markdown"?be=!0:(He==="html"||He==="svg")&&(be=o?.filePreview?.enabled!==!1)}Le.element.classList.toggle("persona-hidden",!be),Le.setSelected(ce())}if(fe.replaceChildren(),!ve&&p.length>0){let Ae=qa(ee);if(Ae)for(let be of p)try{if(be.visible===void 0||be.visible(Ae)){let He=_r(be,{documentChrome:!0});He.setAttribute("data-artifact-custom-action",be.id),He.classList.add("persona-flex-shrink-0"),fe.appendChild(He)}}catch{}}};return Ce(n),Eo.set(f,(ee,le)=>{if(d&&A!=="complete"&&ee.status==="complete"){let Y=f.isConnected?f.getBoundingClientRect().height:0;A="complete";let ve=ee,Ae=!1,be=He=>{ve=He,Ae=!0};Eo.set(f,be),Wb(f,Y,{swap:()=>{S(ve),Ae=!1,Eo.set(f,be)},onSettled:()=>{Ae?S(ve):Eo.set(f,He=>{f.replaceChildren(h(He))})}});return}(ee.status!=="complete"||ee.id!==g.id)&&(u=null),g=ee,w(ee,le),Ce(ee)}),f}var Jm=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",s=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:s,status:a},config:t.config,defaultRenderer:()=>Km(e,t)});if(l)return l}return Km(e,t)};var mp=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):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(([n,o])=>{this.register(n,o)})}},kn=new mp;kn.register("PersonaArtifactCard",Li,{bubbleChrome:!1});kn.register("PersonaArtifactInline",Jm,{bubbleChrome:!1});function za(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Si(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var gp=!1;function Db(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Qm(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,a=!1;try{a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{a=!1}if(t!=="auto"||!e||typeof r!="function"||gp||a){o();return}gp=!0;let s=Db(n);e.style.setProperty("view-transition-name",s);let l=()=>{gp=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Fb="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Nb="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Ob(e){let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function _b(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var Ub=220;function qb(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Vb(e){return`
|
|
33
|
-
<script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function zb(e,t,n){let o=y("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let s=n.renderIndicator({artifactId:e,config:t});if(s)return o.appendChild(s),{el:o,revealLabel:()=>{}}}catch{}let r=y("div","persona-artifact-frame-loading-indicator");r.appendChild(Dm());let a=null;return n.label!==!1&&(a=y("div","persona-artifact-frame-loading-text"),a.textContent=n.label,r.appendChild(a)),o.appendChild(r),{el:o,revealLabel:()=>{a&&a.classList.add("persona-artifact-frame-loading-text--visible")}}}function $b(e,t,n,o,r,a){let s=null,l=0,p=!1,c=new Set,d=()=>{c.forEach(A=>clearTimeout(A)),c.clear()},u=(A,w)=>{let T=setTimeout(()=>{c.delete(T),A()},w);c.add(T)},g=()=>{s&&s.parentElement&&s.remove(),s=null},f=()=>{if(s||p)return;let A=zb(r,a,o);s=A.el,e.appendChild(s),l=Date.now(),o.label!==!1&&u(A.revealLabel,o.labelDelayMs)},h=()=>{s&&(s.classList.add("persona-artifact-frame-loading--out"),u(g,Ub))},S=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",k):t.removeEventListener("load",M)},E=()=>{if(p||(p=!0,S(),d(),!s))return;let A=Math.max(0,o.minVisibleMs-(Date.now()-l));A>0?u(h,A):h()};function k(A){if(n===null)return;let w=A.data;!w||w.persona!=="artifact-preview-ready"||w.token!==n||A.source===t.contentWindow&&E()}function M(){let A=w=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>w()):setTimeout(w,0)};A(()=>A(()=>E()))}return u(f,o.delayMs),u(E,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",k):t.addEventListener("load",M),()=>{p=!0,d(),S(),g()}}function Pi(e,t){let{config:n}=t,o=t.registry??kn,r=t.bodyLayout,a=n.markdown?Xo(n.markdown):null,s=Tr(n.sanitize),l=e,p=!1,c=ae=>{let Ce=zn()!==null;a&&!Ce&&!p&&(p=!0,Mr(()=>De(l)));let ee=a?a(ae):Wn(ae);return a&&Ce&&s?s(ee):ee},d=y("div","persona-artifact-preview-body"),u=null,g=null,f=null,h=()=>{f&&(f(),f=null),u=null,g=null},S=null,E=null,k=null,M=!1,A=()=>{S=null,E=null,k=null,M=!1},w=null,T=null,R=()=>{w=null,T=null},v=40,B=0,F=ae=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ae()):setTimeout(ae,0),$=ae=>ae.scrollHeight-ae.clientHeight-ae.scrollTop<=v,N=ae=>{if(!r)return;let Ce=ae.scrollHeight-ae.clientHeight>1,ee=ae.scrollHeight-ae.clientHeight-ae.scrollTop;ae.classList.toggle("persona-artifact-fade-top",r.fadeTop&&Ce&&ae.scrollTop>1),ae.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&Ce&&ee>1)},U=ae=>{B||(B=F(()=>{B=0,ae.scrollTop=ae.scrollHeight,N(ae)}))},fe=(ae,Ce,ee,le)=>{let Y=!!r,ve=ee.id+"|"+(Y?"w":"p");if(!S||k!==ve||S.parentElement!==d){h(),R(),d.replaceChildren();let He=y("pre",Fb+" persona-code-pre"),Ne=y("code","persona-code");if(He.appendChild(Ne),Y){let Xe=y("div","persona-artifact-source-window");if(Xe.appendChild(He),d.appendChild(Xe),!(r?.overflow==="clip")&&typeof Xe.addEventListener=="function"){let lt=()=>Xe.scrollHeight-Xe.clientHeight>1;Xe.addEventListener("scroll",()=>{$(Xe)&&(M=!1),N(Xe)},{passive:!0}),Xe.addEventListener("wheel",Ye=>{lt()&&Ye.deltaY<0&&(M=!0)},{passive:!0}),Xe.addEventListener("touchmove",()=>{lt()&&(M=!0)},{passive:!0})}S=Xe}else d.appendChild(He),S=He;E=Ne,k=ve}let Ae=Y?S:null;Ae&&(Ae.classList.toggle("persona-artifact-source-window--fixed",le),Ae.classList.toggle("persona-artifact-source-window--clip",le&&r?.overflow==="clip"));let be=Ae?$(Ae):!0;if(E.replaceChildren(Vm(ae,Ce?.language,Ce?.path)),Ae){let He=ee.status!=="complete";le&&He&&r?.followOutput&&!M&&be?U(Ae):He||(M=!1),N(Ae)}},ce=ae=>{h(),A(),R(),d.replaceChildren();let Ce=y("div",Nb);Ce.innerHTML=c(ae),d.appendChild(Ce)},Le=ae=>{let Ce=ae.id,ee=n.features?.artifacts,le=Nr(ae,ee,"status-body");if(w&&T===Ce&&w.parentElement===d){let Ae=w.querySelector(".persona-artifact-status-view-text");Ae&&rr(Ae,le,ee);return}h(),A(),d.replaceChildren();let Y=y("div","persona-artifact-status-view"),ve=y("div","persona-artifact-status-view-text");rr(ve,le,ee),Y.appendChild(ve),d.appendChild(Y),w=Y,T=Ce},De=ae=>{l=ae;let Ce=t.resolveViewMode?.(ae)??r?.viewMode??"rendered",ee=ae.artifactType==="markdown"?ae.file:void 0,le=ae.status!=="complete";le||Fr(ae.id);let Y=le?r?.streamingHeight:r?.completeHeight,ve=!!r&&typeof Y=="number";if(r?.streamingView==="status"&&le){Le(ae);return}if(ee){let be=Si(ae.markdown??""),He=Ua(ee),Ne=n.features?.artifacts?.filePreview?.enabled!==!1;if(!le&&Ce==="rendered"&&Ne&&(He==="html"||He==="svg")){let Oe=ae.id+"\0"+be;if(u&&g===Oe&&u.parentElement===d)return;A(),R(),h(),d.replaceChildren();let lt=n.features?.artifacts?.filePreview,Ye=lt?.iframeSandbox??"allow-scripts";!lt?.dangerouslyAllowSameOrigin&&Ye.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Ye=Ye.split(/\s+/).filter(kt=>kt&&kt!=="allow-same-origin").join(" "));let Pe=_b(lt?.loading),Se=y("div","persona-artifact-frame"),Ze=y("iframe","persona-artifact-iframe");Ze.setAttribute("sandbox",Ye),Ze.setAttribute("data-artifact-id",ae.id);let un=null;Pe.enabled&&Pe.injectReadySignal?(un=qb(),Ze.srcdoc=be+Vb(un)):Ze.srcdoc=be,Se.appendChild(Ze),d.appendChild(Se),Pe.enabled&&(f=$b(Se,Ze,un,Pe,ae.id,n)),u=Se,g=Oe;return}if(h(),!le&&He==="markdown"&&Ce==="rendered"){ce(be);return}fe(be,{language:ee.language,path:ee.path},ae,ve);return}if(ae.artifactType==="markdown"){if(Ce==="source"){h(),fe(ae.markdown??"",void 0,ae,ve);return}ce(ae.markdown??"");return}h(),A(),R(),d.replaceChildren();let Ae=ae.component?o.get(ae.component):void 0;if(Ae){let He={message:{id:ae.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ne=Ae(ae.props??{},He);if(Ne){d.appendChild(Ne);return}}catch{}}d.appendChild(Ob(ae))};return De(e),{el:d,update(ae){De(ae)}}}var Ym=(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:g=>g.getAttribute("im-preserve")==="true",shouldReAppend:g=>g.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function n(g,f,h={}){g=d(g);let S=u(f),E=c(g,S,h),k=r(E,()=>l(E,g,S,M=>M.morphStyle==="innerHTML"?(a(M,g,S),Array.from(g.childNodes)):o(M,g,S)));return E.pantry.remove(),k}function o(g,f,h){let S=u(f);return a(g,S,h,f,f.nextSibling),Array.from(S.childNodes)}function r(g,f){if(!g.config.restoreFocus)return f();let h=document.activeElement;if(!(h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement))return f();let{id:S,selectionStart:E,selectionEnd:k}=h,M=f();return S&&S!==document.activeElement?.getAttribute("id")&&(h=g.target.querySelector(`[id="${S}"]`),h?.focus()),h&&!h.selectionEnd&&k&&h.setSelectionRange(E,k),M}let a=(function(){function g(w,T,R,v=null,B=null){T instanceof HTMLTemplateElement&&R instanceof HTMLTemplateElement&&(T=T.content,R=R.content),v||(v=T.firstChild);for(let F of R.childNodes){if(v&&v!=B){let N=h(w,F,v,B);if(N){N!==v&&E(w,v,N),s(N,F,w),v=N.nextSibling;continue}}if(F instanceof Element){let N=F.getAttribute("id");if(w.persistentIds.has(N)){let U=k(T,N,v,w);s(U,F,w),v=U.nextSibling;continue}}let $=f(T,F,v,w);$&&(v=$.nextSibling)}for(;v&&v!=B;){let F=v;v=v.nextSibling,S(w,F)}}function f(w,T,R,v){if(v.callbacks.beforeNodeAdded(T)===!1)return null;if(v.idMap.has(T)){let B=document.createElement(T.tagName);return w.insertBefore(B,R),s(B,T,v),v.callbacks.afterNodeAdded(B),B}else{let B=document.importNode(T,!0);return w.insertBefore(B,R),v.callbacks.afterNodeAdded(B),B}}let h=(function(){function w(v,B,F,$){let N=null,U=B.nextSibling,fe=0,ce=F;for(;ce&&ce!=$;){if(R(ce,B)){if(T(v,ce,B))return ce;N===null&&(v.idMap.has(ce)||(N=ce))}if(N===null&&U&&R(ce,U)&&(fe++,U=U.nextSibling,fe>=2&&(N=void 0)),v.activeElementAndParents.includes(ce))break;ce=ce.nextSibling}return N||null}function T(v,B,F){let $=v.idMap.get(B),N=v.idMap.get(F);if(!N||!$)return!1;for(let U of $)if(N.has(U))return!0;return!1}function R(v,B){let F=v,$=B;return F.nodeType===$.nodeType&&F.tagName===$.tagName&&(!F.getAttribute?.("id")||F.getAttribute?.("id")===$.getAttribute?.("id"))}return w})();function S(w,T){if(w.idMap.has(T))A(w.pantry,T,null);else{if(w.callbacks.beforeNodeRemoved(T)===!1)return;T.parentNode?.removeChild(T),w.callbacks.afterNodeRemoved(T)}}function E(w,T,R){let v=T;for(;v&&v!==R;){let B=v;v=v.nextSibling,S(w,B)}return v}function k(w,T,R,v){let B=v.target.getAttribute?.("id")===T&&v.target||v.target.querySelector(`[id="${T}"]`)||v.pantry.querySelector(`[id="${T}"]`);return M(B,v),A(w,B,R),B}function M(w,T){let R=w.getAttribute("id");for(;w=w.parentNode;){let v=T.idMap.get(w);v&&(v.delete(R),v.size||T.idMap.delete(w))}}function A(w,T,R){if(w.moveBefore)try{w.moveBefore(T,R)}catch{w.insertBefore(T,R)}else w.insertBefore(T,R)}return g})(),s=(function(){function g(M,A,w){return w.ignoreActive&&M===document.activeElement?null:(w.callbacks.beforeNodeMorphed(M,A)===!1||(M instanceof HTMLHeadElement&&w.head.ignore||(M instanceof HTMLHeadElement&&w.head.style!=="morph"?p(M,A,w):(f(M,A,w),k(M,w)||a(w,M,A))),w.callbacks.afterNodeMorphed(M,A)),M)}function f(M,A,w){let T=A.nodeType;if(T===1){let R=M,v=A,B=R.attributes,F=v.attributes;for(let $ of F)E($.name,R,"update",w)||R.getAttribute($.name)!==$.value&&R.setAttribute($.name,$.value);for(let $=B.length-1;0<=$;$--){let N=B[$];if(N&&!v.hasAttribute(N.name)){if(E(N.name,R,"remove",w))continue;R.removeAttribute(N.name)}}k(R,w)||h(R,v,w)}(T===8||T===3)&&M.nodeValue!==A.nodeValue&&(M.nodeValue=A.nodeValue)}function h(M,A,w){if(M instanceof HTMLInputElement&&A instanceof HTMLInputElement&&A.type!=="file"){let T=A.value,R=M.value;S(M,A,"checked",w),S(M,A,"disabled",w),A.hasAttribute("value")?R!==T&&(E("value",M,"update",w)||(M.setAttribute("value",T),M.value=T)):E("value",M,"remove",w)||(M.value="",M.removeAttribute("value"))}else if(M instanceof HTMLOptionElement&&A instanceof HTMLOptionElement)S(M,A,"selected",w);else if(M instanceof HTMLTextAreaElement&&A instanceof HTMLTextAreaElement){let T=A.value,R=M.value;if(E("value",M,"update",w))return;T!==R&&(M.value=T),M.firstChild&&M.firstChild.nodeValue!==T&&(M.firstChild.nodeValue=T)}}function S(M,A,w,T){let R=A[w],v=M[w];if(R!==v){let B=E(w,M,"update",T);B||(M[w]=A[w]),R?B||M.setAttribute(w,""):E(w,M,"remove",T)||M.removeAttribute(w)}}function E(M,A,w,T){return M==="value"&&T.ignoreActiveValue&&A===document.activeElement?!0:T.callbacks.beforeAttributeUpdated(M,A,w)===!1}function k(M,A){return!!A.ignoreActiveValue&&M===document.activeElement&&M!==document.body}return g})();function l(g,f,h,S){if(g.head.block){let E=f.querySelector("head"),k=h.querySelector("head");if(E&&k){let M=p(E,k,g);return Promise.all(M).then(()=>{let A=Object.assign(g,{head:{block:!1,ignore:!0}});return S(A)})}}return S(g)}function p(g,f,h){let S=[],E=[],k=[],M=[],A=new Map;for(let T of f.children)A.set(T.outerHTML,T);for(let T of g.children){let R=A.has(T.outerHTML),v=h.head.shouldReAppend(T),B=h.head.shouldPreserve(T);R||B?v?E.push(T):(A.delete(T.outerHTML),k.push(T)):h.head.style==="append"?v&&(E.push(T),M.push(T)):h.head.shouldRemove(T)!==!1&&E.push(T)}M.push(...A.values());let w=[];for(let T of M){let R=document.createRange().createContextualFragment(T.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(R)!==!1){if("href"in R&&R.href||"src"in R&&R.src){let v,B=new Promise(function(F){v=F});R.addEventListener("load",function(){v()}),w.push(B)}g.appendChild(R),h.callbacks.afterNodeAdded(R),S.push(R)}}for(let T of E)h.callbacks.beforeNodeRemoved(T)!==!1&&(g.removeChild(T),h.callbacks.afterNodeRemoved(T));return h.head.afterHeadMorphed(g,{added:S,kept:k,removed:E}),w}let c=(function(){function g(w,T,R){let{persistentIds:v,idMap:B}=M(w,T),F=f(R),$=F.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes($))throw`Do not understand how to morph style ${$}`;return{target:w,newContent:T,config:F,morphStyle:$,ignoreActive:F.ignoreActive,ignoreActiveValue:F.ignoreActiveValue,restoreFocus:F.restoreFocus,idMap:B,persistentIds:v,pantry:h(),activeElementAndParents:S(w),callbacks:F.callbacks,head:F.head}}function f(w){let T=Object.assign({},t);return Object.assign(T,w),T.callbacks=Object.assign({},t.callbacks,w.callbacks),T.head=Object.assign({},t.head,w.head),T}function h(){let w=document.createElement("div");return w.hidden=!0,document.body.insertAdjacentElement("afterend",w),w}function S(w){let T=[],R=document.activeElement;if(R?.tagName!=="BODY"&&w.contains(R))for(;R&&(T.push(R),R!==w);)R=R.parentElement;return T}function E(w){let T=Array.from(w.querySelectorAll("[id]"));return w.getAttribute?.("id")&&T.push(w),T}function k(w,T,R,v){for(let B of v){let F=B.getAttribute("id");if(T.has(F)){let $=B;for(;$;){let N=w.get($);if(N==null&&(N=new Set,w.set($,N)),N.add(F),$===R)break;$=$.parentElement}}}}function M(w,T){let R=E(w),v=E(T),B=A(R,v),F=new Map;k(F,B,w,R);let $=T.__idiomorphRoot||T;return k(F,B,$,v),{persistentIds:B,idMap:F}}function A(w,T){let R=new Set,v=new Map;for(let{id:F,tagName:$}of w)v.has(F)?R.add(F):v.set(F,$);let B=new Set;for(let{id:F,tagName:$}of T)B.has(F)?R.add(F):v.get(F)===$&&B.add(F);for(let F of R)B.delete(F);return B}return g})(),{normalizeElement:d,normalizeParent:u}=(function(){let g=new WeakSet;function f(k){return k instanceof Document?k.documentElement:k}function h(k){if(k==null)return document.createElement("div");if(typeof k=="string")return h(E(k));if(g.has(k))return k;if(k instanceof Node){if(k.parentNode)return new S(k);{let M=document.createElement("div");return M.append(k),M}}else{let M=document.createElement("div");for(let A of[...k])M.append(A);return M}}class S{constructor(M){this.originalNode=M,this.realParentNode=M.parentNode,this.previousSibling=M.previousSibling,this.nextSibling=M.nextSibling}get childNodes(){let M=[],A=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;A&&A!=this.nextSibling;)M.push(A),A=A.nextSibling;return M}querySelectorAll(M){return this.childNodes.reduce((A,w)=>{if(w instanceof Element){w.matches(M)&&A.push(w);let T=w.querySelectorAll(M);for(let R=0;R<T.length;R++)A.push(T[R])}return A},[])}insertBefore(M,A){return this.realParentNode.insertBefore(M,A)}moveBefore(M,A){return this.realParentNode.moveBefore(M,A)}get __idiomorphRoot(){return this.originalNode}}function E(k){let M=new DOMParser,A=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(A.match(/<\/html>/)||A.match(/<\/head>/)||A.match(/<\/body>/)){let w=M.parseFromString(k,"text/html");if(A.match(/<\/html>/))return g.add(w),w;{let T=w.firstChild;return T&&g.add(T),T}}else{let T=M.parseFromString("<body><template>"+k+"</template></body>","text/html").body.querySelector("template").content;return g.add(T),T}}return{normalizeElement:f,normalizeParent:h}})();return{morph:n,defaults:t}})();var Ri=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Ym.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,a){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return 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 s=r.textContent??"",l=a.textContent??"";if(s!==l)return}return!1}}}}})};var Zm=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var hp={index:-1,draft:""};function eg(e){let{direction:t,history:n,currentValue:o,atStart:r,state:a}=e,s=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!r)return{handled:!1,state:a};if(!s){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(a.index>0){let l=a.index-1;return{handled:!0,value:n[l],state:{index:l,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<n.length-1){let l=a.index+1;return{handled:!0,value:n[l],state:{index:l,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function tg(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 ng(){return new Map}function og(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function rg(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function ag(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ii(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Dn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ko(e,t){return Dn(e)-e.scrollTop<=t}function Wi(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:c=!1}=e,d=n-o;return s||Math.abs(d)<a?{action:"none",delta:d,nextLastScrollTop:n}:!t&&r&&(!c||d>0)?{action:"resume",delta:d,nextLastScrollTop:n}:t&&l&&d<0?{action:"pause",delta:d,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:d,nextLastScrollTop:n}:{action:"none",delta:d,nextLastScrollTop:n}}function Hi(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function sg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function ig(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function lg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var $a={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},jb=["pre","code","a","script","style"],Bi=e=>({type:e?.type??$a.type,placeholder:e?.placeholder??$a.placeholder,speed:e?.speed??$a.speed,duration:e?.duration??$a.duration,buffer:e?.buffer??$a.buffer}),cg=[{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"}],ja=new Map;for(let e of cg)ja.set(e.name,e);var ar=e=>{ja.set(e.name,e)},bp=e=>{cg.some(t=>t.name===e)||ja.delete(e)},Cp=()=>Array.from(ja.keys()),Ur=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:ja.get(e)??null,Di=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);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(`
|
|
34
|
-
`);return a<0?"":e.slice(0,a)}return e},Gb=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},Kb=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},yp=/\s/,Xb=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Jb=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),l=0;for(;l<a.length;)if(yp.test(a[l])){let p=l;for(;p<a.length&&yp.test(a[p]);)p+=1;s.appendChild(o.createTextNode(a.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let c=l;for(;c<a.length&&!yp.test(a[c]);)p.appendChild(Gb(o,a[c],t,n.value)),n.value+=1,c+=1;s.appendChild(p),l=c}r.replaceChild(s,e)},Qb=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),l=a.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?s.appendChild(o.createTextNode(p)):(s.appendChild(Kb(o,p,t,n.value)),n.value+=1));r.replaceChild(s,e)},Ga=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let a=new Set((o?.skipTags??jb).map(u=>u.toLowerCase())),s=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=s.nextNode();for(;p;)Xb(p,a)||l.push(p),p=s.nextNode();let c={value:o?.startIndex??0},d=t==="char"?Jb:Qb;for(let u of l)d(u,n,c);return r.innerHTML},Fi=(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},Ka=(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 n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},dg=new WeakMap,Yb=(e,t)=>{if(!e.styles)return;let n=dg.get(t);if(n||(n=new Set,dg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.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)},xp=new WeakMap,Zb=(e,t)=>{if(!e.onAttach)return;let n=xp.get(t);if(n||(n=new Map,xp.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},pg=e=>{let t=xp.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ni=(e,t)=>{Yb(e,t),Zb(e,t)};function vp(e,t=zt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Xa=0,Lo=null;function wp(e=document){if(Xa++,Xa===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Lo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Xa=Math.max(0,Xa-1),Xa===0&&Lo)){let n=e.body,o=e.defaultView??window;n.style.overflow=Lo.originalOverflow,n.style.position=Lo.originalPosition,n.style.top=Lo.originalTop,n.style.width=Lo.originalWidth,o.scrollTo(0,Lo.scrollY),Lo=null}}}var Ja={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Rt=e=>(e?.launcher?.mountMode??"floating")==="docked",Po=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",nn=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ja.side,width:t?.width??Ja.width,animate:t?.animate??Ja.animate,reveal:t?.reveal??Ja.reveal,maxHeight:t?.maxHeight??Ja.maxHeight}};var Ln={"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 eC="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Oi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=eC,buttonSize:r,iconSize:a="28px"}=t,s=e?.launcher??{},l=r??s.closeButtonSize??"32px",p=y("div",o),c=s.closeButtonTooltipText??"Close chat",d=s.closeButtonShowTooltip??!0,u=s.closeButtonIconName??"x",g=s.closeButtonIconText??"\xD7",f=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),h=Be("button",{className:$n("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:l,width:l,display:n?void 0:"none",color:s.closeButtonColor||Jt.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:f?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),S=te(u,a,"currentColor",1);if(S?(S.style.display="block",h.appendChild(S)):h.textContent=g,p.appendChild(h),d&&c){let E=null,k=()=>{if(E)return;let A=h.ownerDocument,w=A.body;if(!w)return;E=Hn(A,"div","persona-clear-chat-tooltip"),E.textContent=c;let T=Hn(A,"div");T.className="persona-clear-chat-tooltip-arrow",E.appendChild(T);let R=h.getBoundingClientRect();E.style.position="fixed",E.style.zIndex=String(Mo),E.style.left=`${R.left+R.width/2}px`,E.style.top=`${R.top-8}px`,E.style.transform="translate(-50%, -100%)",w.appendChild(E)},M=()=>{E&&E.parentNode&&(E.parentNode.removeChild(E),E=null)};p.addEventListener("mouseenter",k),p.addEventListener("mouseleave",M),h.addEventListener("focus",k),h.addEventListener("blur",M),p._cleanupTooltip=()=>{M(),p.removeEventListener("mouseenter",k),p.removeEventListener("mouseleave",M),h.removeEventListener("focus",k),h.removeEventListener("blur",M)}}return{button:h,wrapper:p}},tC="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",_i=(e,t={})=>{let{wrapperClassName:n=tC,buttonSize:o,iconSize:r="20px"}=t,s=(e?.launcher??{}).clearChat??{},l=o??s.size??"32px",p=s.iconName??"refresh-cw",c=s.iconColor??"",d=s.backgroundColor??"",u=s.borderWidth??"",g=s.borderColor??"",f=s.borderRadius??"",h=s.paddingX??"",S=s.paddingY??"",E=s.tooltipText??"Clear chat",k=s.showTooltip??!0,M=y("div",n),A=!!(u||g),w=Be("button",{className:$n("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"hover:persona-bg-gray-100",!A&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:l,width:l,color:c||Jt.actionIconColor,backgroundColor:d||void 0,border:A?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:S||void 0,paddingBottom:S||void 0}}),T=te(p,r,"currentColor",1);if(T&&(T.style.display="block",w.appendChild(T)),M.appendChild(w),k&&E){let R=null,v=()=>{if(R)return;let F=w.ownerDocument,$=F.body;if(!$)return;R=Hn(F,"div","persona-clear-chat-tooltip"),R.textContent=E;let N=Hn(F,"div");N.className="persona-clear-chat-tooltip-arrow",R.appendChild(N);let U=w.getBoundingClientRect();R.style.position="fixed",R.style.zIndex=String(Mo),R.style.left=`${U.left+U.width/2}px`,R.style.top=`${U.top-8}px`,R.style.transform="translate(-50%, -100%)",$.appendChild(R)},B=()=>{R&&R.parentNode&&(R.parentNode.removeChild(R),R=null)};M.addEventListener("mouseenter",v),M.addEventListener("mouseleave",B),w.addEventListener("focus",v),w.addEventListener("blur",B),M._cleanupTooltip=()=>{B(),M.removeEventListener("mouseenter",v),M.removeEventListener("mouseleave",B),w.removeEventListener("focus",v),w.removeEventListener("blur",B)}}return{button:w,wrapper:M}};var Jt={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))"},Qn=e=>{let{config:t,showClose:n=!0}=e,o=Be("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:{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",s=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,c=Be("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(!l)if(p){let T=parseFloat(a)||24,R=te(p,T*.6,"currentColor",1);R?c.replaceChildren(R):c.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let T=y("img");T.src=t.launcher.iconUrl,T.alt="",T.className="persona-rounded-xl persona-object-cover",T.style.height=a,T.style.width=a,c.replaceChildren(T)}else c.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let d=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Be("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Jt.titleColor}}),g=Be("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Jt.subtitleColor}});d.append(u,g),l?o.append(d):o.append(c,d);let f=r.clearChat??{},h=f.enabled??!0,S=f.placement??"inline",E=null,k=null;if(h){let R=_i(t,{wrapperClassName:S==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=R.button,k=R.wrapper,S==="top-right"&&(k.style.right="48px"),S==="inline"&&o.appendChild(k)}let M=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&S==="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:A,wrapper:w}=Oi(t,{showClose:n,wrapperClassName:M});return s!=="top-right"&&o.appendChild(w),{header:o,iconHolder:c,headerTitle:u,headerSubtitle:g,closeButton:A,closeButtonWrapper:w,clearChatButton:E,clearChatButtonWrapper:k}},sr=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",a=o.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))};var Ap=e=>{let t=Qn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function nC(e,t,n){if(t?.length)for(let o of t){let r=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let a=te(o.icon,14,"currentColor",2);a&&r.appendChild(a)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let a=y("div","persona-relative");a.appendChild(r);let s=To({items:o.menuItems,onSelect:l=>n?.(l),anchor:a,position:"bottom-left"});a.appendChild(s.element),r.addEventListener("click",l=>{l.stopPropagation(),s.toggle()}),e.appendChild(a)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Sp=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:a}=e,s=t?.launcher??{},l=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,c,d;if(p)c=Ei({label:s.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=Jt.titleColor,d=c.querySelector(".persona-combo-btn-label")??c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=y("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Jt.titleColor,d.textContent=s.title??"Chat Assistant",c.appendChild(d),nC(c,r?.trailingActions,r?.onAction??a),r?.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let A=r.onTitleClick;c.addEventListener("click",w=>{w.target.closest("button")||A()}),c.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),A())})}let M=r?.titleRowHover;M&&(c.style.borderRadius=M.borderRadius??"10px",c.style.padding=M.padding??"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{c.style.backgroundColor=M.background??"",c.style.borderColor=M.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}l.appendChild(c);let u=s.closeButtonSize??"32px",g=y("div",""),f=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=s.closeButtonColor||Jt.actionIconColor;let h=s.closeButtonIconName??"x",S=te(h,"28px","currentColor",1);S?f.appendChild(S):f.textContent="\xD7",o&&f.addEventListener("click",o),g.appendChild(f),l.appendChild(g);let E=y("div");E.style.display="none";let k=y("span");return k.style.display="none",{header:l,iconHolder:E,headerTitle:d,headerSubtitle:k,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Ui={default:Ap,minimal:Sp},Mp=e=>Ui[e]??Ui.default,qr=(e,t,n)=>{if(t?.render){let s=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=y("div");l.style.display="none";let p=y("span"),c=y("span"),d=y("button");d.style.display="none";let u=y("div");return u.style.display="none",{header:s,iconHolder:l,headerTitle:p,headerSubtitle:c,closeButton:d,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",a=Mp(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.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 qi=e=>{let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let s=parseFloat(t.style.maxHeight);return Number.isFinite(s)&&s>0?s:n*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let s=Math.min(t.scrollHeight,r());t.style.height=`${s}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:a}},Vi=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,a=t.stopIconName??"square",s=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",c=e?.copy?.stopButtonLabel??"Stop",d=t.showTooltip??!1,u=t.size??"40px",g=t.backgroundColor,f=t.textColor,h=y("div","persona-send-button-wrapper"),S=Be("button",{className:$n("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||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}}),E=null,k=null;if(n){let T=parseFloat(u)||24,R=f?.trim()||"currentColor";r?(E=te(r,T,R,2),E?S.appendChild(E):S.textContent=o):S.textContent=o,k=te(a,T,R,2)}else S.textContent=p;let M=null;d&&s&&(M=y("div","persona-send-button-tooltip"),M.textContent=s,h.appendChild(M)),S.setAttribute("aria-label",s),h.appendChild(S);let A="send";return{button:S,wrapper:h,setMode:T=>{if(T===A)return;A=T;let R=T==="stop"?l:s;if(S.setAttribute("aria-label",R),M&&(M.textContent=R),n){if(E&&k){let v=T==="stop"?k:E;S.replaceChildren(v)}}else S.textContent=T==="stop"?c:p}}},zi=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let s=e?.sendButton?.size??"40px",l=t.iconName??"mic",p=t.iconSize??s,c=parseFloat(p)||24,d=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,g=y("div","persona-send-button-wrapper"),f=Be("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:d||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}}),S=te(l,c,u||"currentColor",1.5);S?f.appendChild(S):f.textContent="\u{1F3A4}",g.appendChild(f);let E=t.tooltipText??"Start voice recognition";if((t.showTooltip??!1)&&E){let M=y("div","persona-send-button-tooltip");M.textContent=E,g.appendChild(M)}return{button:f,wrapper:g}},$i=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=y("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 r=y("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Xn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let a=t.buttonIconName??"paperclip",s=n,l=parseFloat(s)||40,p=Math.round(l*.6),c=y("div","persona-send-button-wrapper"),d=Be("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1"}}),u=te(a,p,"currentColor",1.5);u?d.appendChild(u):d.textContent="\u{1F4CE}",d.addEventListener("click",h=>{h.preventDefault(),r.click()}),c.appendChild(d);let g=t.buttonTooltipText??"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,c.appendChild(f),{button:d,wrapper:c,input:r,previewsContainer:o}},ji=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let a=t.idleText??"Online";if(t.idleLink){let s=y("a");s.href=t.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=a,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=a;return o},Gi=()=>Be("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Vr=e=>{let{config:t}=e,n=Be("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Gi(),r=Be("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=qi(t);s();let l=Vi(t),p=zi(t),c=$i(t),d=ji(t);c&&(c.previewsContainer.style.gap="8px",r.append(c.previewsContainer,c.input)),r.append(a);let u=Be("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(g,f),r.append(u),r.addEventListener("click",h=>{h.target!==l.button&&h.target!==l.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==c?.button&&h.target!==c?.wrapper&&a.focus()}),n.append(o,r,d),{footer:n,suggestions:o,composerForm:r,textarea:a,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:d,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:l.setMode}};var ug=()=>{let e=Be("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=te("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=y("span","persona-pill-peek__text"),r=y("span","persona-pill-peek__caret"),a=te("chevron-up",16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,o,r),{root:e,textNode:o}},fg=e=>{let{config:t}=e,n=Be("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Gi(),r=ji(t);r.style.display="none";let{textarea:a,attachAutoResize:s}=qi(t);a.style.maxHeight="100px",s();let l=Vi(t),p=zi(t),c=$i(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let d=Be("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&g.append(p.wrapper),g.append(l.wrapper),d.addEventListener("click",h=>{h.target!==l.button&&h.target!==l.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==c?.button&&h.target!==c?.wrapper&&a.focus()}),c&&d.append(c.input),d.append(u,a,g),c&&n.append(c.previewsContainer),n.append(o,d,r);let f=d;return{footer:n,suggestions:o,composerForm:d,textarea:a,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:l.setMode}};var mg=e=>{let t=e?.launcher?.enabled??!0,n=Rt(e);if(Po(e)){let d=e?.launcher?.composerBar??{},u=y("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=d.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??zt);let g=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");g.style.width="100%",u.appendChild(g);let f=y("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=d.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??zt),{wrapper:u,panel:g,pillRoot:f}}if(n){let d=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return d.appendChild(u),{wrapper:d,panel:u}}if(!t){let d=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),g=e?.launcher?.width??"100%";return d.style.width=g,u.style.width="100%",d.appendChild(u),{wrapper:d,panel:u}}let r=e?.launcher??{},a=r.position&&Ln[r.position]?Ln[r.position]:Ln["bottom-right"],s=y("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String(e?.launcher?.zIndex??zt);let l=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=e?.launcher?.width??e?.launcherWidth??cn;return l.style.width=c,l.style.maxWidth=c,s.appendChild(l),{wrapper:s,panel:l}},oC=(e,t)=>{let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Oi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let a=e?.launcher?.clearChat?.enabled??!0,s=null,l=null;if(a){let w=_i(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=w.button,l=w.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=Be("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Be("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let d=Be("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Be("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),g=Be("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},d,u),f=y("div","persona-flex persona-flex-col persona-gap-3"),h=e?.layout?.contentMaxWidth;h&&(f.style.maxWidth=h,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,f);let E=Be("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),k=fg({config:e}),{root:M,textNode:A}=ug();return n.append(p,r,c,E),l&&n.appendChild(l),{container:n,body:c,messagesWrapper:f,composerOverlay:E,suggestions:k.suggestions,textarea:k.textarea,sendButton:k.sendButton,sendButtonWrapper:k.sendButtonWrapper,micButton:k.micButton,micButtonWrapper:k.micButtonWrapper,composerForm:k.composerForm,statusText:k.statusText,introTitle:d,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:s,clearChatButtonWrapper:l,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:p,footer:k.footer,attachmentButton:k.attachmentButton,attachmentButtonWrapper:k.attachmentButtonWrapper,attachmentInput:k.attachmentInput,attachmentPreviewsContainer:k.attachmentPreviewsContainer,actionsRow:k.actionsRow,leftActions:k.leftActions,rightActions:k.rightActions,setSendButtonMode:k.setSendButtonMode,peekBanner:M,peekTextNode:A}},gg=(e,t=!0)=>{if(Po(e))return oC(e,t);let n=Be("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,a=o?qr(e,o,{showClose:t}):Qn({config:e,showClose:t}),s=Be("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"}});s.style.setProperty("scrollbar-gutter","stable");let l=Be("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Be("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),c=Be("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Rt(e)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),d=y("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(d.style.maxWidth=u,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(c.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(c,d);let f=Vr({config:e}),h=e?.layout?.showFooter!==!1;r?sr(n,a,e):(a.header.style.display="none",sr(n,a,e)),n.append(s);let S=Be("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return h||(f.footer.style.display="none"),n.append(f.footer),n.append(S),{container:n,body:s,messagesWrapper:d,composerOverlay:S,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:l,introSubtitle:p,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:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var Tp=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
|
|
32
|
+
`)),n=x("span","persona-code-line")),o(r.type,a[s])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Xm(e,t,n){let o=e.length<=Ab?Sb(t,n):null,r=o?Ib(e,o):[{type:"plain",value:e}];return Wb(r)}function Mo(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:a}=e,s=x("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(mi)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",r==="bottom-right"?s.style.right="0":s.style.left="0");for(let f of t){if(f.dividerBefore){let L=document.createElement("hr");s.appendChild(L)}let h=document.createElement("button");if(h.type="button",h.setAttribute("role","menuitem"),h.setAttribute("data-dropdown-item-id",f.id),f.destructive&&h.setAttribute("data-destructive",""),f.icon){let L=te(f.icon,16,"currentColor",1.5);L&&h.appendChild(L)}let S=document.createElement("span");S.textContent=f.label,h.appendChild(S),h.addEventListener("click",L=>{L.stopPropagation(),c(),n(f.id)}),s.appendChild(h)}let l=null;function p(){if(!a)return;let f=o.getBoundingClientRect();s.style.top=`${f.bottom+4}px`,r==="bottom-right"?(s.style.right=`${window.innerWidth-f.right}px`,s.style.left="auto"):(s.style.left=`${f.left}px`,s.style.right="auto")}function d(){p(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=h=>{!s.contains(h.target)&&!o.contains(h.target)&&c()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function c(){s.classList.add("persona-hidden"),l?.(),l=null}function u(){s.classList.contains("persona-hidden")?d():c()}function g(){c(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:c,toggle:u,destroy:g}}function Tt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:a,onClick:s,aria:l}=e,p=x("button","persona-icon-btn"+(a?" "+a:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=te(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),s&&p.addEventListener("click",s),l)for(let[c,u]of Object.entries(l))p.setAttribute(c,u);return p}function Xn(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:a,className:s,onClick:l,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,s&&(d+=" "+s);let c=x("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let g=te(t,a??14,"currentColor",2);g&&c.appendChild(g)}let u=x("span");if(u.textContent=n,c.appendChild(u),l&&c.addEventListener("click",l),p)for(let[g,f]of Object.entries(p))c.setAttribute(g,f);return c}function Br(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,a=x("div","persona-toggle-group"+(r?" "+r:""));a.setAttribute("role","group");let s=n,l=[];function p(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===s?"true":"false")}for(let c of t){let u;c.icon?u=Tt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{s=c.id,p(),o(c.id)}}):(u=x("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{s=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===s?"true":"false"),l.push({id:c.id,btn:u}),a.appendChild(u)}function d(c){s=c,p()}return{element:a,setSelected:d}}function Si(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:a="bottom-left",portal:s,className:l,hover:p}=e,d=x("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=x("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=te(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let g=Mo({items:o,onSelect:f=>{d.setAttribute("aria-expanded","false"),r(f)},anchor:d,position:a,portal:s});return s||d.appendChild(g.element),d.addEventListener("click",f=>{f.stopPropagation();let h=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",h?"false":"true"),g.toggle()}),d.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d.click())}),{element:d,setLabel:f=>{c.textContent=f,d.setAttribute("aria-label",f)},open:()=>{d.setAttribute("aria-expanded","true"),g.show()},close:()=>{d.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let f=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),d.remove()}}}var Mi="persona-artifact-custom-action-btn";function Dr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Mi+(n?" persona-artifact-doc-copy-btn":"");o=x("button",r)}else{let r="persona-icon-btn "+Mi+(n?" persona-artifact-doc-icon-btn":"");o=x("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=x("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Xn({icon:e.icon,label:e.label,className:Mi+(n?" persona-artifact-doc-copy-btn":"")}):o=Tt({icon:e.icon,label:e.label,className:Mi+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Da(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function Jm(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Wn(n.path):o,a=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n?Ao(n):l==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),a&&d.setAttribute("data-open-artifact",a);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let h=t?.config?.features?.artifacts,S={id:a,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{}},L=Hr(S,h,"card");er(f,L,h)}else a&&Wr(a),f.textContent=p;if(u.append(g,f),d.append(c,u),s==="complete"){let h=t?.config?.features?.artifacts?.cardActions;if(h&&h.length>0){let L={artifactId:a||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let E of h)try{if(E.visible===void 0||E.visible(L)){let M=Dr(E);M.setAttribute("data-artifact-custom-action",E.id),M.className=`${M.className} persona-flex-shrink-0`,d.append(M)}}catch{}}let S=Xn({label:"Download",className:"persona-flex-shrink-0"});S.title=`Download ${r}`,S.setAttribute("data-download-artifact",a),d.append(S)}return d}var Ti=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",s=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:s,status:a},config:t.config,defaultRenderer:()=>Jm(e,t)});if(l)return l}return Jm(e,t)};var To=new WeakMap;function mp(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let a=To.get(r);if(!a)return;let s=o.get(r.getAttribute("data-artifact-inline")??"");s&&a(s,n)})}function tg(e){return To.has(e)}function Hb(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete";if(e.artifactType==="component"){let a=e.componentProps,s=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:s}}let r=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...r?{file:r}:{}}}function Qm(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Wn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Ao(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Bb(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var Ym=180,Db=240,Fb=.8,Ob=300,Nb=500,_b="cubic-bezier(0.2, 0, 0, 1)",Zm=240,Ub=.35;function qb(e,t,n){let{swap:o,onSettled:r}=n,a=!1;try{a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{a=!1}if(!t||!e.isConnected||a||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let s=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&s.push(l.animate([{opacity:1},{opacity:0}],{duration:Ym,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let E of s)E.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){l(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(Nb,Math.max(Ob,Db+d*Fb))),u=Math.round(c*Ub),g=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=g?g.animate([{opacity:0},{opacity:1}],{duration:Zm,delay:u,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:_b});e.style.height=`${p}px`;let S=!1,L=()=>{S||(S=!0,l(),r())};Promise.allSettled([h.finished,f?.finished].filter(Boolean)).then(L),window.setTimeout(L,Math.max(c,u+Zm)+120)},Ym)}function Vb(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Fa="--persona-artifact-inline-body-height";function zb(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,a=320,s=t?.height;typeof s=="number"||s==="auto"?(r=s,a=s):s&&typeof s=="object"&&(r=s.streaming??320,a=s.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let g=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:a,followOutput:p,overflow:l,fadeTop:d,fadeBottom:c,transition:g,completeDisplay:f}}function eg(e,t){let n=Hb(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:a,showExpand:s,showViewToggle:l}=Vb(o),p=o?.inlineActions??[],d=zb(o),c=d.completeDisplay==="card",u=null,g=n,f=x("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let h=Z=>Ti(Bb(Z),t),S=Z=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Fa),f.replaceChildren(h(Z)),To.set(f,de=>{f.replaceChildren(h(de))})};if(c&&n.status==="complete")return S(n),f;let L=Ei(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),E=x("div","persona-artifact-inline-body");E.appendChild(L.el);let M=Z=>{let de=Z.status!=="complete",Y=de?d.streamingHeight:d.completeHeight,ve=typeof Y=="number";ve?f.style.setProperty(Fa,`${Y}px`):f.style.removeProperty(Fa);let Ae=!!L.el.querySelector(".persona-code-pre"),xe=!!L.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");E.classList.toggle("persona-artifact-content-flush",Ae),E.classList.toggle("persona-artifact-inline-body--sized",ve&&xe),E.classList.toggle("persona-artifact-inline-body--cap",!de&&!xe&&typeof d.completeHeight=="number")},A=n.status,w=(Z,de)=>{A!=="complete"&&Z.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(Fa,`${d.completeHeight}px`):f.style.removeProperty(Fa),og(E,de?.suppressTransition?"none":d.transition,Z.id,()=>{L.update(Z),M(Z)})):L.update(Z),M(Z),A=Z.status};M(n);let T=d.overflow==="clip"&&s&&!!n.id;if(T&&(E.setAttribute("data-expand-artifact-inline",n.id),E.setAttribute("role","button"),E.setAttribute("tabindex","0"),E.classList.add("persona-cursor-pointer"),E.setAttribute("aria-label",`Open ${Qm(n).title} in panel`)),!r)return f.appendChild(E),To.set(f,w),f;let H=x("div","persona-artifact-inline-chrome");H.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let C=x("div","persona-artifact-inline-chrome-lead"),B=x("span","persona-flex persona-items-center persona-flex-shrink-0"),F=te("file-text",16,"currentColor",2);F&&B.appendChild(F);let q=x("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),D=x("span","persona-artifact-inline-type");C.append(B,q,D);let U=x("div","persona-artifact-inline-chrome-actions"),se=x("span","persona-flex persona-items-center persona-gap-1"),le=()=>u??d.viewMode,Ce=l?Br({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:le(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Z=>{let de=Z==="source"?"source":"rendered";de!==le()&&(u=de,L.update(g),M(g))}}):null,Le=a?Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Le&&n.id&&Le.setAttribute("data-copy-artifact",n.id);let ae=s?Tt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ae&&n.id&&ae.setAttribute("data-expand-artifact-inline",n.id),U.appendChild(se),Ce&&U.appendChild(Ce.element),Le&&U.appendChild(Le),ae&&U.appendChild(ae),H.append(C,U),f.append(H,E);let me=Z=>{let{title:de,typeLabel:Y}=Qm(Z);q.textContent=de,q.title=de,T&&E.setAttribute("aria-label",`Open ${de} in panel`);let ve=Z.status!=="complete";if(ve){D.classList.contains("persona-artifact-inline-status")||(D.className="persona-artifact-inline-status",D.removeAttribute("data-preserve-animation"),D.replaceChildren());let Ae=Hr(Z,o,"inline-chrome");er(D,Ae,o)}else Wr(Z.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=Y;if(Le&&Le.classList.toggle("persona-hidden",ve),Ce){let Ae=Z.artifactType==="markdown"?Z.file:void 0,xe=!1;if(!ve&&Ae&&d.viewMode!=="source"){let Be=Ba(Ae);Be==="markdown"?xe=!0:(Be==="html"||Be==="svg")&&(xe=o?.filePreview?.enabled!==!1)}Ce.element.classList.toggle("persona-hidden",!xe),Ce.setSelected(le())}if(se.replaceChildren(),!ve&&p.length>0){let Ae=Da(Z);if(Ae)for(let xe of p)try{if(xe.visible===void 0||xe.visible(Ae)){let Be=Dr(xe,{documentChrome:!0});Be.setAttribute("data-artifact-custom-action",xe.id),Be.classList.add("persona-flex-shrink-0"),se.appendChild(Be)}}catch{}}};return me(n),To.set(f,(Z,de)=>{if(c&&A!=="complete"&&Z.status==="complete"){let Y=f.isConnected?f.getBoundingClientRect().height:0;A="complete";let ve=Z,Ae=!1,xe=Be=>{ve=Be,Ae=!0};To.set(f,xe),qb(f,Y,{swap:()=>{S(ve),Ae=!1,To.set(f,xe)},onSettled:()=>{Ae?S(ve):To.set(f,Be=>{f.replaceChildren(h(Be))})}});return}(Z.status!=="complete"||Z.id!==g.id)&&(u=null),g=Z,w(Z,de),me(Z)}),f}var ng=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",s=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:s,status:a},config:t.config,defaultRenderer:()=>eg(e,t)});if(l)return l}return eg(e,t)};var gp=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):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(([n,o])=>{this.register(n,o)})}},En=new gp;En.register("PersonaArtifactCard",Ti,{bubbleChrome:!1});En.register("PersonaArtifactInline",ng,{bubbleChrome:!1});function Oa(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Ci(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var hp=!1;function $b(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function og(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,a=!1;try{a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{a=!1}if(t!=="auto"||!e||typeof r!="function"||hp||a){o();return}hp=!0;let s=$b(n);e.style.setProperty("view-transition-name",s);let l=()=>{hp=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var jb="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Gb="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Kb(e){let t=x("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=x("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=x("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function Xb(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var Jb=220;function Qb(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Yb(e){return`
|
|
33
|
+
<script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function Zb(e,t,n){let o=x("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let s=n.renderIndicator({artifactId:e,config:t});if(s)return o.appendChild(s),{el:o,revealLabel:()=>{}}}catch{}let r=x("div","persona-artifact-frame-loading-indicator");r.appendChild(qm());let a=null;return n.label!==!1&&(a=x("div","persona-artifact-frame-loading-text"),a.textContent=n.label,r.appendChild(a)),o.appendChild(r),{el:o,revealLabel:()=>{a&&a.classList.add("persona-artifact-frame-loading-text--visible")}}}function ev(e,t,n,o,r,a){let s=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(A=>clearTimeout(A)),d.clear()},u=(A,w)=>{let T=setTimeout(()=>{d.delete(T),A()},w);d.add(T)},g=()=>{s&&s.parentElement&&s.remove(),s=null},f=()=>{if(s||p)return;let A=Zb(r,a,o);s=A.el,e.appendChild(s),l=Date.now(),o.label!==!1&&u(A.revealLabel,o.labelDelayMs)},h=()=>{s&&(s.classList.add("persona-artifact-frame-loading--out"),u(g,Jb))},S=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",E):t.removeEventListener("load",M)},L=()=>{if(p||(p=!0,S(),c(),!s))return;let A=Math.max(0,o.minVisibleMs-(Date.now()-l));A>0?u(h,A):h()};function E(A){if(n===null)return;let w=A.data;!w||w.persona!=="artifact-preview-ready"||w.token!==n||A.source===t.contentWindow&&L()}function M(){let A=w=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>w()):setTimeout(w,0)};A(()=>A(()=>L()))}return u(f,o.delayMs),u(L,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",E):t.addEventListener("load",M),()=>{p=!0,c(),S(),g()}}function Ei(e,t){let{config:n}=t,o=t.registry??En,r=t.bodyLayout,a=n.markdown?$o(n.markdown):null,s=wr(n.sanitize),l=e,p=!1,d=ae=>{let me=Vn()!==null;a&&!me&&!p&&(p=!0,Cr(()=>Le(l)));let Z=a?a(ae):In(ae);return a&&me&&s?s(Z):Z},c=x("div","persona-artifact-preview-body"),u=null,g=null,f=null,h=()=>{f&&(f(),f=null),u=null,g=null},S=null,L=null,E=null,M=!1,A=()=>{S=null,L=null,E=null,M=!1},w=null,T=null,H=()=>{w=null,T=null},C=40,B=0,F=ae=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ae()):setTimeout(ae,0),q=ae=>ae.scrollHeight-ae.clientHeight-ae.scrollTop<=C,D=ae=>{if(!r)return;let me=ae.scrollHeight-ae.clientHeight>1,Z=ae.scrollHeight-ae.clientHeight-ae.scrollTop;ae.classList.toggle("persona-artifact-fade-top",r.fadeTop&&me&&ae.scrollTop>1),ae.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&me&&Z>1)},U=ae=>{B||(B=F(()=>{B=0,ae.scrollTop=ae.scrollHeight,D(ae)}))},se=(ae,me,Z,de)=>{let Y=!!r,ve=Z.id+"|"+(Y?"w":"p");if(!S||E!==ve||S.parentElement!==c){h(),H(),c.replaceChildren();let Be=x("pre",jb+" persona-code-pre"),Oe=x("code","persona-code");if(Be.appendChild(Oe),Y){let Ve=x("div","persona-artifact-source-window");if(Ve.appendChild(Be),c.appendChild(Ve),!(r?.overflow==="clip")&&typeof Ve.addEventListener=="function"){let rt=()=>Ve.scrollHeight-Ve.clientHeight>1;Ve.addEventListener("scroll",()=>{q(Ve)&&(M=!1),D(Ve)},{passive:!0}),Ve.addEventListener("wheel",Xe=>{rt()&&Xe.deltaY<0&&(M=!0)},{passive:!0}),Ve.addEventListener("touchmove",()=>{rt()&&(M=!0)},{passive:!0})}S=Ve}else c.appendChild(Be),S=Be;L=Oe,E=ve}let Ae=Y?S:null;Ae&&(Ae.classList.toggle("persona-artifact-source-window--fixed",de),Ae.classList.toggle("persona-artifact-source-window--clip",de&&r?.overflow==="clip"));let xe=Ae?q(Ae):!0;if(L.replaceChildren(Xm(ae,me?.language,me?.path)),Ae){let Be=Z.status!=="complete";de&&Be&&r?.followOutput&&!M&&xe?U(Ae):Be||(M=!1),D(Ae)}},le=ae=>{h(),A(),H(),c.replaceChildren();let me=x("div",Gb);me.innerHTML=d(ae),c.appendChild(me)},Ce=ae=>{let me=ae.id,Z=n.features?.artifacts,de=Hr(ae,Z,"status-body");if(w&&T===me&&w.parentElement===c){let Ae=w.querySelector(".persona-artifact-status-view-text");Ae&&er(Ae,de,Z);return}h(),A(),c.replaceChildren();let Y=x("div","persona-artifact-status-view"),ve=x("div","persona-artifact-status-view-text");er(ve,de,Z),Y.appendChild(ve),c.appendChild(Y),w=Y,T=me},Le=ae=>{l=ae;let me=t.resolveViewMode?.(ae)??r?.viewMode??"rendered",Z=ae.artifactType==="markdown"?ae.file:void 0,de=ae.status!=="complete";de||Wr(ae.id);let Y=de?r?.streamingHeight:r?.completeHeight,ve=!!r&&typeof Y=="number";if(r?.streamingView==="status"&&de){Ce(ae);return}if(Z){let xe=Ci(ae.markdown??""),Be=Ba(Z),Oe=n.features?.artifacts?.filePreview?.enabled!==!1;if(!de&&me==="rendered"&&Oe&&(Be==="html"||Be==="svg")){let Ne=ae.id+"\0"+xe;if(u&&g===Ne&&u.parentElement===c)return;A(),H(),h(),c.replaceChildren();let rt=n.features?.artifacts?.filePreview,Xe=rt?.iframeSandbox??"allow-scripts";!rt?.dangerouslyAllowSameOrigin&&Xe.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Xe=Xe.split(/\s+/).filter(Et=>Et&&Et!=="allow-same-origin").join(" "));let Pe=Xb(rt?.loading),Se=x("div","persona-artifact-frame"),Je=x("iframe","persona-artifact-iframe");Je.setAttribute("sandbox",Xe),Je.setAttribute("data-artifact-id",ae.id);let cn=null;Pe.enabled&&Pe.injectReadySignal?(cn=Qb(),Je.srcdoc=xe+Yb(cn)):Je.srcdoc=xe,Se.appendChild(Je),c.appendChild(Se),Pe.enabled&&(f=ev(Se,Je,cn,Pe,ae.id,n)),u=Se,g=Ne;return}if(h(),!de&&Be==="markdown"&&me==="rendered"){le(xe);return}se(xe,{language:Z.language,path:Z.path},ae,ve);return}if(ae.artifactType==="markdown"){if(me==="source"){h(),se(ae.markdown??"",void 0,ae,ve);return}le(ae.markdown??"");return}h(),A(),H(),c.replaceChildren();let Ae=ae.component?o.get(ae.component):void 0;if(Ae){let Be={message:{id:ae.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Oe=Ae(ae.props??{},Be);if(Oe){c.appendChild(Oe);return}}catch{}}c.appendChild(Kb(ae))};return Le(e),{el:c,update(ae){Le(ae)}}}var rg=(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:g=>g.getAttribute("im-preserve")==="true",shouldReAppend:g=>g.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function n(g,f,h={}){g=c(g);let S=u(f),L=d(g,S,h),E=r(L,()=>l(L,g,S,M=>M.morphStyle==="innerHTML"?(a(M,g,S),Array.from(g.childNodes)):o(M,g,S)));return L.pantry.remove(),E}function o(g,f,h){let S=u(f);return a(g,S,h,f,f.nextSibling),Array.from(S.childNodes)}function r(g,f){if(!g.config.restoreFocus)return f();let h=document.activeElement;if(!(h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement))return f();let{id:S,selectionStart:L,selectionEnd:E}=h,M=f();return S&&S!==document.activeElement?.getAttribute("id")&&(h=g.target.querySelector(`[id="${S}"]`),h?.focus()),h&&!h.selectionEnd&&E&&h.setSelectionRange(L,E),M}let a=(function(){function g(w,T,H,C=null,B=null){T instanceof HTMLTemplateElement&&H instanceof HTMLTemplateElement&&(T=T.content,H=H.content),C||(C=T.firstChild);for(let F of H.childNodes){if(C&&C!=B){let D=h(w,F,C,B);if(D){D!==C&&L(w,C,D),s(D,F,w),C=D.nextSibling;continue}}if(F instanceof Element){let D=F.getAttribute("id");if(w.persistentIds.has(D)){let U=E(T,D,C,w);s(U,F,w),C=U.nextSibling;continue}}let q=f(T,F,C,w);q&&(C=q.nextSibling)}for(;C&&C!=B;){let F=C;C=C.nextSibling,S(w,F)}}function f(w,T,H,C){if(C.callbacks.beforeNodeAdded(T)===!1)return null;if(C.idMap.has(T)){let B=document.createElement(T.tagName);return w.insertBefore(B,H),s(B,T,C),C.callbacks.afterNodeAdded(B),B}else{let B=document.importNode(T,!0);return w.insertBefore(B,H),C.callbacks.afterNodeAdded(B),B}}let h=(function(){function w(C,B,F,q){let D=null,U=B.nextSibling,se=0,le=F;for(;le&&le!=q;){if(H(le,B)){if(T(C,le,B))return le;D===null&&(C.idMap.has(le)||(D=le))}if(D===null&&U&&H(le,U)&&(se++,U=U.nextSibling,se>=2&&(D=void 0)),C.activeElementAndParents.includes(le))break;le=le.nextSibling}return D||null}function T(C,B,F){let q=C.idMap.get(B),D=C.idMap.get(F);if(!D||!q)return!1;for(let U of q)if(D.has(U))return!0;return!1}function H(C,B){let F=C,q=B;return F.nodeType===q.nodeType&&F.tagName===q.tagName&&(!F.getAttribute?.("id")||F.getAttribute?.("id")===q.getAttribute?.("id"))}return w})();function S(w,T){if(w.idMap.has(T))A(w.pantry,T,null);else{if(w.callbacks.beforeNodeRemoved(T)===!1)return;T.parentNode?.removeChild(T),w.callbacks.afterNodeRemoved(T)}}function L(w,T,H){let C=T;for(;C&&C!==H;){let B=C;C=C.nextSibling,S(w,B)}return C}function E(w,T,H,C){let B=C.target.getAttribute?.("id")===T&&C.target||C.target.querySelector(`[id="${T}"]`)||C.pantry.querySelector(`[id="${T}"]`);return M(B,C),A(w,B,H),B}function M(w,T){let H=w.getAttribute("id");for(;w=w.parentNode;){let C=T.idMap.get(w);C&&(C.delete(H),C.size||T.idMap.delete(w))}}function A(w,T,H){if(w.moveBefore)try{w.moveBefore(T,H)}catch{w.insertBefore(T,H)}else w.insertBefore(T,H)}return g})(),s=(function(){function g(M,A,w){return w.ignoreActive&&M===document.activeElement?null:(w.callbacks.beforeNodeMorphed(M,A)===!1||(M instanceof HTMLHeadElement&&w.head.ignore||(M instanceof HTMLHeadElement&&w.head.style!=="morph"?p(M,A,w):(f(M,A,w),E(M,w)||a(w,M,A))),w.callbacks.afterNodeMorphed(M,A)),M)}function f(M,A,w){let T=A.nodeType;if(T===1){let H=M,C=A,B=H.attributes,F=C.attributes;for(let q of F)L(q.name,H,"update",w)||H.getAttribute(q.name)!==q.value&&H.setAttribute(q.name,q.value);for(let q=B.length-1;0<=q;q--){let D=B[q];if(D&&!C.hasAttribute(D.name)){if(L(D.name,H,"remove",w))continue;H.removeAttribute(D.name)}}E(H,w)||h(H,C,w)}(T===8||T===3)&&M.nodeValue!==A.nodeValue&&(M.nodeValue=A.nodeValue)}function h(M,A,w){if(M instanceof HTMLInputElement&&A instanceof HTMLInputElement&&A.type!=="file"){let T=A.value,H=M.value;S(M,A,"checked",w),S(M,A,"disabled",w),A.hasAttribute("value")?H!==T&&(L("value",M,"update",w)||(M.setAttribute("value",T),M.value=T)):L("value",M,"remove",w)||(M.value="",M.removeAttribute("value"))}else if(M instanceof HTMLOptionElement&&A instanceof HTMLOptionElement)S(M,A,"selected",w);else if(M instanceof HTMLTextAreaElement&&A instanceof HTMLTextAreaElement){let T=A.value,H=M.value;if(L("value",M,"update",w))return;T!==H&&(M.value=T),M.firstChild&&M.firstChild.nodeValue!==T&&(M.firstChild.nodeValue=T)}}function S(M,A,w,T){let H=A[w],C=M[w];if(H!==C){let B=L(w,M,"update",T);B||(M[w]=A[w]),H?B||M.setAttribute(w,""):L(w,M,"remove",T)||M.removeAttribute(w)}}function L(M,A,w,T){return M==="value"&&T.ignoreActiveValue&&A===document.activeElement?!0:T.callbacks.beforeAttributeUpdated(M,A,w)===!1}function E(M,A){return!!A.ignoreActiveValue&&M===document.activeElement&&M!==document.body}return g})();function l(g,f,h,S){if(g.head.block){let L=f.querySelector("head"),E=h.querySelector("head");if(L&&E){let M=p(L,E,g);return Promise.all(M).then(()=>{let A=Object.assign(g,{head:{block:!1,ignore:!0}});return S(A)})}}return S(g)}function p(g,f,h){let S=[],L=[],E=[],M=[],A=new Map;for(let T of f.children)A.set(T.outerHTML,T);for(let T of g.children){let H=A.has(T.outerHTML),C=h.head.shouldReAppend(T),B=h.head.shouldPreserve(T);H||B?C?L.push(T):(A.delete(T.outerHTML),E.push(T)):h.head.style==="append"?C&&(L.push(T),M.push(T)):h.head.shouldRemove(T)!==!1&&L.push(T)}M.push(...A.values());let w=[];for(let T of M){let H=document.createRange().createContextualFragment(T.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(H)!==!1){if("href"in H&&H.href||"src"in H&&H.src){let C,B=new Promise(function(F){C=F});H.addEventListener("load",function(){C()}),w.push(B)}g.appendChild(H),h.callbacks.afterNodeAdded(H),S.push(H)}}for(let T of L)h.callbacks.beforeNodeRemoved(T)!==!1&&(g.removeChild(T),h.callbacks.afterNodeRemoved(T));return h.head.afterHeadMorphed(g,{added:S,kept:E,removed:L}),w}let d=(function(){function g(w,T,H){let{persistentIds:C,idMap:B}=M(w,T),F=f(H),q=F.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(q))throw`Do not understand how to morph style ${q}`;return{target:w,newContent:T,config:F,morphStyle:q,ignoreActive:F.ignoreActive,ignoreActiveValue:F.ignoreActiveValue,restoreFocus:F.restoreFocus,idMap:B,persistentIds:C,pantry:h(),activeElementAndParents:S(w),callbacks:F.callbacks,head:F.head}}function f(w){let T=Object.assign({},t);return Object.assign(T,w),T.callbacks=Object.assign({},t.callbacks,w.callbacks),T.head=Object.assign({},t.head,w.head),T}function h(){let w=document.createElement("div");return w.hidden=!0,document.body.insertAdjacentElement("afterend",w),w}function S(w){let T=[],H=document.activeElement;if(H?.tagName!=="BODY"&&w.contains(H))for(;H&&(T.push(H),H!==w);)H=H.parentElement;return T}function L(w){let T=Array.from(w.querySelectorAll("[id]"));return w.getAttribute?.("id")&&T.push(w),T}function E(w,T,H,C){for(let B of C){let F=B.getAttribute("id");if(T.has(F)){let q=B;for(;q;){let D=w.get(q);if(D==null&&(D=new Set,w.set(q,D)),D.add(F),q===H)break;q=q.parentElement}}}}function M(w,T){let H=L(w),C=L(T),B=A(H,C),F=new Map;E(F,B,w,H);let q=T.__idiomorphRoot||T;return E(F,B,q,C),{persistentIds:B,idMap:F}}function A(w,T){let H=new Set,C=new Map;for(let{id:F,tagName:q}of w)C.has(F)?H.add(F):C.set(F,q);let B=new Set;for(let{id:F,tagName:q}of T)B.has(F)?H.add(F):C.get(F)===q&&B.add(F);for(let F of H)B.delete(F);return B}return g})(),{normalizeElement:c,normalizeParent:u}=(function(){let g=new WeakSet;function f(E){return E instanceof Document?E.documentElement:E}function h(E){if(E==null)return document.createElement("div");if(typeof E=="string")return h(L(E));if(g.has(E))return E;if(E instanceof Node){if(E.parentNode)return new S(E);{let M=document.createElement("div");return M.append(E),M}}else{let M=document.createElement("div");for(let A of[...E])M.append(A);return M}}class S{constructor(M){this.originalNode=M,this.realParentNode=M.parentNode,this.previousSibling=M.previousSibling,this.nextSibling=M.nextSibling}get childNodes(){let M=[],A=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;A&&A!=this.nextSibling;)M.push(A),A=A.nextSibling;return M}querySelectorAll(M){return this.childNodes.reduce((A,w)=>{if(w instanceof Element){w.matches(M)&&A.push(w);let T=w.querySelectorAll(M);for(let H=0;H<T.length;H++)A.push(T[H])}return A},[])}insertBefore(M,A){return this.realParentNode.insertBefore(M,A)}moveBefore(M,A){return this.realParentNode.moveBefore(M,A)}get __idiomorphRoot(){return this.originalNode}}function L(E){let M=new DOMParser,A=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(A.match(/<\/html>/)||A.match(/<\/head>/)||A.match(/<\/body>/)){let w=M.parseFromString(E,"text/html");if(A.match(/<\/html>/))return g.add(w),w;{let T=w.firstChild;return T&&g.add(T),T}}else{let T=M.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return g.add(T),T}}return{normalizeElement:f,normalizeParent:h}})();return{morph:n,defaults:t}})();var ki=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;rg.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,a){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return 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 s=r.textContent??"",l=a.textContent??"";if(s!==l)return}return!1}}}}})};var ag=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var yp={index:-1,draft:""};function sg(e){let{direction:t,history:n,currentValue:o,atStart:r,state:a}=e,s=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!r)return{handled:!1,state:a};if(!s){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(a.index>0){let l=a.index-1;return{handled:!0,value:n[l],state:{index:l,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<n.length-1){let l=a.index+1;return{handled:!0,value:n[l],state:{index:l,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function ig(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 lg(){return new Map}function dg(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function cg(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function pg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Li(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Hn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Eo(e,t){return Hn(e)-e.scrollTop<=t}function Pi(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function Ri(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function ug(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function fg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function mg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Na={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},tv=["pre","code","a","script","style"],Ii=e=>({type:e?.type??Na.type,placeholder:e?.placeholder??Na.placeholder,speed:e?.speed??Na.speed,duration:e?.duration??Na.duration,buffer:e?.buffer??Na.buffer}),hg=[{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"}],_a=new Map;for(let e of hg)_a.set(e.name,e);var tr=e=>{_a.set(e.name,e)},vp=e=>{hg.some(t=>t.name===e)||_a.delete(e)},Cp=()=>Array.from(_a.keys()),Fr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:_a.get(e)??null,Wi=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);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(`
|
|
34
|
+
`);return a<0?"":e.slice(0,a)}return e},nv=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},ov=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},xp=/\s/,rv=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},av=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),l=0;for(;l<a.length;)if(xp.test(a[l])){let p=l;for(;p<a.length&&xp.test(a[p]);)p+=1;s.appendChild(o.createTextNode(a.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=l;for(;d<a.length&&!xp.test(a[d]);)p.appendChild(nv(o,a[d],t,n.value)),n.value+=1,d+=1;s.appendChild(p),l=d}r.replaceChild(s,e)},sv=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),l=a.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?s.appendChild(o.createTextNode(p)):(s.appendChild(ov(o,p,t,n.value)),n.value+=1));r.replaceChild(s,e)},Ua=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let a=new Set((o?.skipTags??tv).map(u=>u.toLowerCase())),s=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=s.nextNode();for(;p;)rv(p,a)||l.push(p),p=s.nextNode();let d={value:o?.startIndex??0},c=t==="char"?av:sv;for(let u of l)c(u,n,d);return r.innerHTML},Hi=(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},qa=(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 n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},gg=new WeakMap,iv=(e,t)=>{if(!e.styles)return;let n=gg.get(t);if(n||(n=new Set,gg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.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)},bp=new WeakMap,lv=(e,t)=>{if(!e.onAttach)return;let n=bp.get(t);if(n||(n=new Map,bp.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},yg=e=>{let t=bp.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Bi=(e,t)=>{iv(e,t),lv(e,t)};function wp(e,t=Vt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Va=0,ko=null;function Ap(e=document){if(Va++,Va===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;ko={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Va=Math.max(0,Va-1),Va===0&&ko)){let n=e.body,o=e.defaultView??window;n.style.overflow=ko.originalOverflow,n.style.position=ko.originalPosition,n.style.top=ko.originalTop,n.style.width=ko.originalWidth,o.scrollTo(0,ko.scrollY),ko=null}}}var za={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Lt=e=>(e?.launcher?.mountMode??"floating")==="docked",Lo=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",tn=e=>{let t=e?.launcher?.dock;return{side:t?.side??za.side,width:t?.width??za.width,animate:t?.animate??za.animate,reveal:t?.reveal??za.reveal,maxHeight:t?.maxHeight??za.maxHeight}};var kn={"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 dv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Di=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=dv,buttonSize:r,iconSize:a="28px"}=t,s=e?.launcher??{},l=r??s.closeButtonSize??"32px",p=x("div",o),d=s.closeButtonTooltipText??"Close chat",c=s.closeButtonShowTooltip??!0,u=s.closeButtonIconName??"x",g=s.closeButtonIconText??"\xD7",f=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),h=Fe("button",{className:zn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:s.closeButtonColor||Xt.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:f?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),S=te(u,a,"currentColor",1);return S?(S.style.display="block",h.appendChild(S)):h.textContent=g,p.appendChild(h),Nt({anchor:h,trigger:p,text:()=>h.getAttribute("aria-label")??d,enabled:c}),{button:h,wrapper:p}},cv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Fi=(e,t={})=>{let{wrapperClassName:n=cv,buttonSize:o,iconSize:r="20px"}=t,s=(e?.launcher??{}).clearChat??{},l=o??s.size??"32px",p=s.iconName??"refresh-cw",d=s.iconColor??"",c=s.backgroundColor??"",u=s.borderWidth??"",g=s.borderColor??"",f=s.borderRadius??"",h=s.paddingX??"",S=s.paddingY??"",L=s.tooltipText??"Clear chat",E=s.showTooltip??!0,M=x("div",n),A=!!(u||g),w=Fe("button",{className:zn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!A&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":L},style:{height:l,width:l,color:d||Xt.actionIconColor,backgroundColor:c||void 0,border:A?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:S||void 0,paddingBottom:S||void 0}}),T=te(p,r,"currentColor",1);return T&&(T.style.display="block",w.appendChild(T)),M.appendChild(w),Nt({anchor:w,trigger:M,text:()=>w.getAttribute("aria-label")??L,enabled:E}),{button:w,wrapper:M}};var Xt={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))"},Jn=e=>{let{config:t,showClose:n=!0}=e,o=Fe("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:{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",s=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,d=Fe("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(!l)if(p){let T=parseFloat(a)||24,H=te(p,T*.6,"currentColor",1);H?d.replaceChildren(H):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let T=x("img");T.src=t.launcher.iconUrl,T.alt="",T.className="persona-rounded-xl persona-object-cover",T.style.height=a,T.style.width=a,d.replaceChildren(T)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=x("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Fe("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Xt.titleColor}}),g=Fe("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Xt.subtitleColor}});c.append(u,g),l?o.append(c):o.append(d,c);let f=r.clearChat??{},h=f.enabled??!0,S=f.placement??"inline",L=null,E=null;if(h){let H=Fi(t,{wrapperClassName:S==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});L=H.button,E=H.wrapper,S==="top-right"&&(E.style.right="48px"),S==="inline"&&o.appendChild(E)}let M=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&S==="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:A,wrapper:w}=Di(t,{showClose:n,wrapperClassName:M});return s!=="top-right"&&o.appendChild(w),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:g,closeButton:A,closeButtonWrapper:w,clearChatButton:L,clearChatButtonWrapper:E}},nr=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",a=o.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))};var Sp=e=>{let t=Jn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function pv(e,t,n){if(t?.length)for(let o of t){let r=x("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let a=te(o.icon,14,"currentColor",2);a&&r.appendChild(a)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let a=x("div","persona-relative");a.appendChild(r);let s=Mo({items:o.menuItems,onSelect:l=>n?.(l),anchor:a,position:"bottom-left"});a.appendChild(s.element),r.addEventListener("click",l=>{l.stopPropagation(),s.toggle()}),e.appendChild(a)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Mp=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:a}=e,s=t?.launcher??{},l=x("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=Si({label:s.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Xt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=x("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=x("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Xt.titleColor,c.textContent=s.title??"Chat Assistant",d.appendChild(c),pv(d,r?.trailingActions,r?.onAction??a),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let A=r.onTitleClick;d.addEventListener("click",w=>{w.target.closest("button")||A()}),d.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),A())})}let M=r?.titleRowHover;M&&(d.style.borderRadius=M.borderRadius??"10px",d.style.padding=M.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=M.background??"",d.style.borderColor=M.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let u=s.closeButtonSize??"32px",g=x("div",""),f=x("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=s.closeButtonColor||Xt.actionIconColor;let h=s.closeButtonIconName??"x",S=te(h,"28px","currentColor",1);S?f.appendChild(S):f.textContent="\xD7",o&&f.addEventListener("click",o),g.appendChild(f),l.appendChild(g);let L=x("div");L.style.display="none";let E=x("span");return E.style.display="none",{header:l,iconHolder:L,headerTitle:c,headerSubtitle:E,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Oi={default:Sp,minimal:Mp},Tp=e=>Oi[e]??Oi.default,Or=(e,t,n)=>{if(t?.render){let s=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=x("div");l.style.display="none";let p=x("span"),d=x("span"),c=x("button");c.style.display="none";let u=x("div");return u.style.display="none",{header:s,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",a=Tp(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.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 Ni=e=>{let t=x("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let s=parseFloat(t.style.maxHeight);return Number.isFinite(s)&&s>0?s:n*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let s=Math.min(t.scrollHeight,r());t.style.height=`${s}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:a}},_i=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,a=t.stopIconName??"square",s=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",g=t.backgroundColor,f=t.textColor,h=x("div","persona-send-button-wrapper"),S=Fe("button",{className:zn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||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}}),L=null,E=null;if(n){let w=parseFloat(u)||24,T=f?.trim()||"currentColor";r?(L=te(r,w,T,2),L?S.appendChild(L):S.textContent=o):S.textContent=o,E=te(a,w,T,2)}else S.textContent=p;S.setAttribute("aria-label",s),h.appendChild(S),Nt({anchor:S,trigger:h,text:()=>S.getAttribute("aria-label")??"",enabled:c});let M="send";return{button:S,wrapper:h,setMode:w=>{if(w===M)return;M=w;let T=w==="stop"?l:s;if(S.setAttribute("aria-label",T),n){if(L&&E){let H=w==="stop"?E:L;S.replaceChildren(H)}}else S.textContent=w==="stop"?d:p}}},Ui=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let s=e?.sendButton?.size??"40px",l=t.iconName??"mic",p=t.iconSize??s,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,g=x("div","persona-send-button-wrapper"),f=Fe("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":t.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||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}}),S=te(l,d,u||"currentColor",1.5);S?f.appendChild(S):f.textContent="\u{1F3A4}",g.appendChild(f);let L=t.tooltipText??"Start voice recognition",E=t.showTooltip??!1;return Nt({anchor:f,trigger:g,text:()=>f.getAttribute("aria-label")??L,enabled:E}),{button:f,wrapper:g}},qi=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=x("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 r=x("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Kn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let a=t.buttonIconName??"paperclip",s=n,l=parseFloat(s)||40,p=Math.round(l*.6),d=x("div","persona-send-button-wrapper"),c=Fe("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1"}}),u=te(a,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",f=>{f.preventDefault(),r.click()}),d.appendChild(c);let g=t.buttonTooltipText??"Attach file";return Nt({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??g}),{button:c,wrapper:d,input:r,previewsContainer:o}},Vi=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=x("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let a=t.idleText??"Online";if(t.idleLink){let s=x("a");s.href=t.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=a,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=a;return o},zi=()=>Fe("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Nr=e=>{let{config:t}=e,n=Fe("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=zi(),r=Fe("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=Ni(t);s();let l=_i(t),p=Ui(t),d=qi(t),c=Vi(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(a);let u=Fe("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=x("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=x("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&g.append(d.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(g,f),r.append(u),r.addEventListener("click",h=>{h.target!==l.button&&h.target!==l.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==d?.button&&h.target!==d?.wrapper&&a.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:a,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:l.setMode}};var xg=()=>{let e=Fe("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=x("span","persona-pill-peek__icon"),n=te("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=x("span","persona-pill-peek__text"),r=x("span","persona-pill-peek__caret"),a=te("chevron-up",16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,o,r),{root:e,textNode:o}},bg=e=>{let{config:t}=e,n=Fe("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=zi(),r=Vi(t);r.style.display="none";let{textarea:a,attachAutoResize:s}=Ni(t);a.style.maxHeight="100px",s();let l=_i(t),p=Ui(t),d=qi(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Fe("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=x("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let g=x("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&g.append(p.wrapper),g.append(l.wrapper),c.addEventListener("click",h=>{h.target!==l.button&&h.target!==l.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==d?.button&&h.target!==d?.wrapper&&a.focus()}),d&&c.append(d.input),c.append(u,a,g),d&&n.append(d.previewsContainer),n.append(o,c,r);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:a,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:l.setMode}};var vg=e=>{let t=e?.launcher?.enabled??!0,n=Lt(e);if(Lo(e)){let c=e?.launcher?.composerBar??{},u=x("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Vt);let g=x("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");g.style.width="100%",u.appendChild(g);let f=x("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Vt),{wrapper:u,panel:g,pillRoot:f}}if(n){let c=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=x("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=x("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),g=e?.launcher?.width??"100%";return c.style.width=g,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=e?.launcher??{},a=r.position&&kn[r.position]?kn[r.position]:kn["bottom-right"],s=x("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String(e?.launcher?.zIndex??Vt);let l=x("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??ln;return l.style.width=d,l.style.maxWidth=d,s.appendChild(l),{wrapper:s,panel:l}},uv=(e,t)=>{let n=x("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Di(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let a=e?.launcher?.clearChat?.enabled??!0,s=null,l=null;if(a){let w=Fi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=w.button,l=w.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=Fe("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Fe("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"}});d.style.setProperty("scrollbar-gutter","stable");let c=Fe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Fe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),g=Fe("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},c,u),f=x("div","persona-flex persona-flex-col persona-gap-3"),h=e?.layout?.contentMaxWidth;h&&(f.style.maxWidth=h,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(g.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(g,f);let L=Fe("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),E=bg({config:e}),{root:M,textNode:A}=xg();return n.append(p,r,d,L),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:f,composerOverlay:L,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:s,clearChatButtonWrapper:l,iconHolder:x("span"),headerTitle:x("span"),headerSubtitle:x("span"),header:p,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:M,peekTextNode:A}},Cg=(e,t=!0)=>{if(Lo(e))return uv(e,t);let n=Fe("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,a=o?Or(e,o,{showClose:t}):Jn({config:e,showClose:t}),s=Fe("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"}});s.style.setProperty("scrollbar-gutter","stable");let l=Fe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Fe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=Fe("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Lt(e)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),c=x("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(d.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(d,c);let f=Nr({config:e}),h=e?.layout?.showFooter!==!1;r?nr(n,a,e):(a.header.style.display="none",nr(n,a,e)),n.append(s);let S=Fe("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return h||(f.footer.style.display="none"),n.append(f.footer),n.append(S),{container:n,body:s,messagesWrapper:c,composerOverlay:S,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:l,introSubtitle:p,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:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var Ep=(e,t)=>{let n=x("button");n.type="button",n.innerHTML=`
|
|
35
35
|
<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>
|
|
36
36
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
37
37
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -39,14 +39,14 @@ _Details: ${n.message}_`:o}var Da=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
39
39
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
40
40
|
</span>
|
|
41
41
|
<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>
|
|
42
|
-
`,n.addEventListener("click",t);let o=a=>{let s=a.launcher??{},l=Rt(a),p=n.querySelector("[data-role='launcher-title']");if(p){let A=s.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let A=s.subtitle??"Here to help you get answers fast";c.textContent=A,c.setAttribute("title",A)}let d=n.querySelector(".persona-flex-col");d&&(s.textHidden||l?d.style.display="none":d.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(s.agentIconHidden)u.style.display="none";else{let A=s.agentIconSize??"40px";if(u.style.height=A,u.style.width=A,s.agentIconBackgroundColor?(u.style.backgroundColor=s.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",s.agentIconName){let w=parseFloat(A)||24,T=te(s.agentIconName,w*.6,"var(--persona-text-inverse, #ffffff)",2);T?(u.appendChild(T),u.style.display=""):(u.textContent=s.agentIconText??"\u{1F4AC}",u.style.display="")}else s.iconUrl?u.style.display="none":(u.textContent=s.agentIconText??"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let A=s.agentIconSize??"40px";g.style.height=A,g.style.width=A,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(g.src=s.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let A=s.callToActionIconSize??"32px";f.style.height=A,f.style.width=A,s.callToActionIconBackgroundColor?(f.style.backgroundColor=s.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(f.style.color=s.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let w=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,w=(parseFloat(s.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),s.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",s.callToActionIconName){let T=parseFloat(A)||24,R=Math.max(T-w,8),v=te(s.callToActionIconName,R,"currentColor",2);v?f.appendChild(v):f.textContent=s.callToActionIconText??"\u2197"}else f.textContent=s.callToActionIconText??"\u2197"}let h=s.position&&Ln[s.position]?Ln[s.position]:Ln["bottom-right"],S="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?E:`${S} ${h}`,l||(n.style.zIndex=String(s.zIndex??zt));let k="1px solid var(--persona-border, #e5e7eb)",M="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=s.border??k,n.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:M,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=s.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var hg=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=mg(e),a=gg(e,t),s={wrapper:n,panel:o,pillRoot:r},l={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},p={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},c={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:l,header:p,composer:c,replaceHeader:g=>(p.element.replaceWith(g.header),p.element=g.header,p.iconHolder=g.iconHolder,p.headerTitle=g.headerTitle,p.headerSubtitle=g.headerSubtitle,p.closeButton=g.closeButton,p.closeButtonWrapper=g.closeButtonWrapper,p.clearChatButton=g.clearChatButton,p.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},Ep=({config:e,plugins:t,onToggle:n})=>{let o=t.find(a=>a.renderLauncher);if(o?.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>Tp(e,n).element,onToggle:n});if(a)return{instance:null,element:a}}let r=Tp(e,n);return{instance:r,element:r.element}};var rC=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}},aC=(e,t)=>{if(!e)return null;let n=rC(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},sC=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},iC=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},kp=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(":"))},Lp=320,Cg=320,lC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),dC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),cC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),pC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),uC=e=>{if(!e||e.length===0)return null;let t=Be("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Be("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=y("span","persona-mention-chip-icon"),a=te(n.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),o.appendChild(r),o.appendChild(Be("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},fC=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Fa(o.ref,{readonly:!0,render:t}))}return n},yg="\uE000",xg="\uE001",mC=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),a=g=>`${yg}${r}:${g}${xg}`,s=t.map((g,f)=>g.kind==="text"?g.text:a(f)).join(""),l=n(s);if(!t.every((g,f)=>g.kind==="text"||l.includes(a(f)))){e.replaceChildren(fC(t,o));return}e.innerHTML=l;let c=new RegExp(`${yg}${r}:(\\d+)${xg}`),d=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let g=d.nextNode();g;g=d.nextNode())u.push(g);for(let g of u){let f=g;for(let h=c.exec(f.data);h;h=c.exec(f.data)){let S=t[Number(h[1])],E=f.splitText(h.index);E.data=E.data.slice(h[0].length),S?.kind==="mention"&&E.parentNode?.insertBefore(Fa(S.ref,{readonly:!0,render:o}),E),f=E}}},gC=(e,t,n)=>{if(e.length===0)return null;try{let o=y("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,a=!1,s=()=>{a||(a=!0,o.remove(),n?.())};return e.forEach((l,p)=>{let c=y("img");c.alt=l.alt?.trim()||`Attached image ${p+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Lp}px`,c.style.maxHeight=`${Cg}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let d=!1;r+=1,c.addEventListener("error",()=>{d||(d=!0,r=Math.max(0,r-1),c.remove(),r===0&&s())}),c.addEventListener("load",()=>{d=!0}),iC(l.image)?(c.src=l.image,o.appendChild(c)):(d=!0,r=Math.max(0,r-1),c.remove())}),r===0?(s(),null):o}catch{return n?.(),null}},hC=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!kp(o.audio))return;let r=y("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Lp}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},yC=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!kp(o.video))return;let r=y("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Lp}px`,r.style.maxHeight=`${Cg}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},xC=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!kp(o.data))return;let r=y("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ir=()=>{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 n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Pp=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:ir};if(t){let r=t(o);if(r!==null)return r}return ir()},bC=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=y("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},bg=(e,t,n="div")=>{let o=y(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},CC=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Rp=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,a=t.showDownvote??!0,s=t.showReadAloud??!1;if(!o&&!r&&!a&&!s){let h=y("div");return h.style.display="none",h.id=`actions-${e.id}`,h.setAttribute("data-actions-for",e.id),h}let l=t.visibility??"hover",p=t.align??"right",c=t.layout??"pill-inside",d={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${d} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(h,S,E)=>{let k=Et({icon:h,label:S,size:14,className:"persona-message-action-btn"});return k.setAttribute("data-action",E),k};return o&&g.appendChild(f("copy","Copy message","copy")),s&&g.appendChild(f("volume-2","Read aloud","read-aloud")),r&&g.appendChild(f("thumbs-up","Upvote","upvote")),a&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},zr=(e,t,n,o,r,a)=>{let s=n??{},l=s.layout??"bubble",p=s.avatar,c=s.timestamp,d=p?.show??!1,u=c?.show??!1,g=p?.position??"left",f=c?.position??"below",h=CC(e.role,l),S=y("div",h.join(" "));S.id=`bubble-${e.id}`,S.setAttribute("data-message-id",e.id),S.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(S.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",S.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(S.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",S.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=lC(e),k=e.content?.trim()??"",A=E.length>0&&k===ti,w=Bi(a?.widgetConfig?.features?.streamAnimation),T=a?.widgetConfig?.features?.streamAnimation?.plugins,R=e.role==="assistant"&&w.type!=="none"?Ur(w.type,T):null,v=e.role==="assistant"&&R?.isAnimating?.(e)===!0,B=e.role==="assistant"&&R!==null&&(!!e.streaming||v);B&&R?.bubbleClass&&S.classList.add(R.bubbleClass);let F=document.createElement("div");F.classList.add("persona-message-content"),e.streaming&&F.classList.add("persona-content-streaming"),B&&R&&(R.containerClass&&F.classList.add(R.containerClass),F.style.setProperty("--persona-stream-step",`${w.speed}ms`),F.style.setProperty("--persona-stream-duration",`${w.duration}ms`));let $=B?Di(e.content??"",w.buffer,R,e,!!e.streaming):e.content??"",N=()=>{let Y=t({text:$,message:e,streaming:!!e.streaming,raw:e.rawContent});return B&&R?.wrap==="char"?Ga(Y,"char",e.id,{skipTags:R.skipTags}):B&&R?.wrap==="word"?Ga(Y,"word",e.id,{skipTags:R.skipTags}):Y},U=null;if(A?(U=document.createElement("div"),U.innerHTML=N(),U.style.display="none",F.appendChild(U)):e.contentSegments?.length?mC(F,e.contentSegments,Y=>t({text:Y,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):F.innerHTML=N(),B&&R?.useCaret&&!A&&k){let Y=Fi(),ve=F.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ae=ve[ve.length-1];if(Ae?.parentNode)Ae.parentNode.insertBefore(Y,Ae.nextSibling);else{let be=F.lastElementChild;be?be.appendChild(Y):F.appendChild(Y)}}if(u&&f==="inline"&&e.createdAt){let Y=bg(e,c,"span");Y.classList.add("persona-timestamp-inline");let ve=F.lastElementChild;ve?ve.appendChild(Y):F.appendChild(Y)}if(E.length>0){let Y=gC(E,!A&&!!k,()=>{A&&U&&(U.style.display="")});Y?S.appendChild(Y):A&&U&&(U.style.display="")}let fe=dC(e);if(fe.length>0){let Y=hC(fe);Y&&S.appendChild(Y)}let ce=cC(e);if(ce.length>0){let Y=yC(ce);Y&&S.appendChild(Y)}let Le=pC(e);if(Le.length>0){let Y=xC(Le);Y&&S.appendChild(Y)}let De=e.contentSegments?.length?null:uC(e.contextMentions);if(De&&S.appendChild(De),S.appendChild(F),u&&f==="below"&&e.createdAt){let Y=bg(e,c);Y.classList.add("persona-mt-1"),S.appendChild(Y)}let ae=e.role==="assistant"?aC(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!($&&$.trim()),ve=w.placeholder==="skeleton",Ae=ve&&w.buffer==="line"&&Y;if(Y)Ae&&S.appendChild(Ka());else if(ve)S.appendChild(Ka());else{let be=Pp("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);be&&S.appendChild(be)}}if(ae&&e.stopReason&&!e.streaming&&(k||(F.style.display="none"),S.appendChild(sC(e.stopReason,ae))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Y=Rp(e,o,r);S.appendChild(Y)}if(!d||e.role==="system")return S;let ee=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),le=bC(p,e.role);return g==="right"||g==="left"&&e.role==="user"?ee.append(S,le):ee.append(le,S),S.classList.remove("persona-max-w-[85%]"),S.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ee},vg=(e,t,n,o,r,a)=>{let s=n??{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):zr(e,t,n,o,r,a)};var $r=new Set,vC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),wC=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
43
|
-
`):""},
|
|
42
|
+
`,n.addEventListener("click",t);let o=a=>{let s=a.launcher??{},l=Lt(a),p=n.querySelector("[data-role='launcher-title']");if(p){let A=s.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let A=s.subtitle??"Here to help you get answers fast";d.textContent=A,d.setAttribute("title",A)}let c=n.querySelector(".persona-flex-col");c&&(s.textHidden||l?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(s.agentIconHidden)u.style.display="none";else{let A=s.agentIconSize??"40px";if(u.style.height=A,u.style.width=A,s.agentIconBackgroundColor?(u.style.backgroundColor=s.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",s.agentIconName){let w=parseFloat(A)||24,T=te(s.agentIconName,w*.6,"var(--persona-text-inverse, #ffffff)",2);T?(u.appendChild(T),u.style.display=""):(u.textContent=s.agentIconText??"\u{1F4AC}",u.style.display="")}else s.iconUrl?u.style.display="none":(u.textContent=s.agentIconText??"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let A=s.agentIconSize??"40px";g.style.height=A,g.style.width=A,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(g.src=s.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let A=s.callToActionIconSize??"32px";f.style.height=A,f.style.width=A,s.callToActionIconBackgroundColor?(f.style.backgroundColor=s.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(f.style.color=s.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let w=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,w=(parseFloat(s.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),s.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",s.callToActionIconName){let T=parseFloat(A)||24,H=Math.max(T-w,8),C=te(s.callToActionIconName,H,"currentColor",2);C?f.appendChild(C):f.textContent=s.callToActionIconText??"\u2197"}else f.textContent=s.callToActionIconText??"\u2197"}let h=s.position&&kn[s.position]?kn[s.position]:kn["bottom-right"],S="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",L="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-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?L:`${S} ${h}`,l||(n.style.zIndex=String(s.zIndex??Vt));let E="1px solid var(--persona-border, #e5e7eb)",M="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=s.border??E,n.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:M,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=s.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var wg=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=vg(e),a=Cg(e,t),s={wrapper:n,panel:o,pillRoot:r},l={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},p={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={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:s,panelElements:a,transcript:l,header:p,composer:d,replaceHeader:g=>(p.element.replaceWith(g.header),p.element=g.header,p.iconHolder=g.iconHolder,p.headerTitle=g.headerTitle,p.headerSubtitle=g.headerSubtitle,p.closeButton=g.closeButton,p.closeButtonWrapper=g.closeButtonWrapper,p.clearChatButton=g.clearChatButton,p.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{d.footer.replaceWith(g),d.footer=g}}},kp=({config:e,plugins:t,onToggle:n})=>{let o=t.find(a=>a.renderLauncher);if(o?.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>Ep(e,n).element,onToggle:n});if(a)return{instance:null,element:a}}let r=Ep(e,n);return{instance:r,element:r.element}};var fv=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}},mv=(e,t)=>{if(!e)return null;let n=fv(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},gv=(e,t)=>{let n=x("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},hv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Lp=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(":"))},Pp=320,Tg=320,yv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),xv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),bv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),vv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Cv=e=>{if(!e||e.length===0)return null;let t=Fe("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Fe("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=x("span","persona-mention-chip-icon"),a=te(n.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),o.appendChild(r),o.appendChild(Fe("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},wv=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Ra(o.ref,{readonly:!0,render:t}))}return n},Ag="\uE000",Sg="\uE001",Av=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),a=g=>`${Ag}${r}:${g}${Sg}`,s=t.map((g,f)=>g.kind==="text"?g.text:a(f)).join(""),l=n(s);if(!t.every((g,f)=>g.kind==="text"||l.includes(a(f)))){e.replaceChildren(wv(t,o));return}e.innerHTML=l;let d=new RegExp(`${Ag}${r}:(\\d+)${Sg}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let g=c.nextNode();g;g=c.nextNode())u.push(g);for(let g of u){let f=g;for(let h=d.exec(f.data);h;h=d.exec(f.data)){let S=t[Number(h[1])],L=f.splitText(h.index);L.data=L.data.slice(h[0].length),S?.kind==="mention"&&L.parentNode?.insertBefore(Ra(S.ref,{readonly:!0,render:o}),L),f=L}}},Sv=(e,t,n)=>{if(e.length===0)return null;try{let o=x("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,a=!1,s=()=>{a||(a=!0,o.remove(),n?.())};return e.forEach((l,p)=>{let d=x("img");d.alt=l.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Pp}px`,d.style.maxHeight=`${Tg}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&s())}),d.addEventListener("load",()=>{c=!0}),hv(l.image)?(d.src=l.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(s(),null):o}catch{return n?.(),null}},Mv=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Lp(o.audio))return;let r=x("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Pp}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Tv=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Lp(o.video))return;let r=x("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Pp}px`,r.style.maxHeight=`${Tg}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ev=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Lp(o.data))return;let r=x("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},or=()=>{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 n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Rp=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:or};if(t){let r=t(o);if(r!==null)return r}return or()},kv=(e,t)=>{let n=x("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=x("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Mg=(e,t,n="div")=>{let o=x(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Lv=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Ip=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,a=t.showDownvote??!0,s=t.showReadAloud??!1;if(!o&&!r&&!a&&!s){let h=x("div");return h.style.display="none",h.id=`actions-${e.id}`,h.setAttribute("data-actions-for",e.id),h}let l=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],g=x("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(h,S,L)=>{let E=Tt({icon:h,label:S,size:14,className:"persona-message-action-btn"});return E.setAttribute("data-action",L),E};return o&&g.appendChild(f("copy","Copy message","copy")),s&&g.appendChild(f("volume-2","Read aloud","read-aloud")),r&&g.appendChild(f("thumbs-up","Upvote","upvote")),a&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},_r=(e,t,n,o,r,a)=>{let s=n??{},l=s.layout??"bubble",p=s.avatar,d=s.timestamp,c=p?.show??!1,u=d?.show??!1,g=p?.position??"left",f=d?.position??"below",h=Lv(e.role,l),S=x("div",h.join(" "));S.id=`bubble-${e.id}`,S.setAttribute("data-message-id",e.id),S.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(S.style.backgroundColor="transparent",S.style.color="var(--persona-primary, var(--persona-text))"):e.role==="user"?(S.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",S.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(S.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",S.style.color="var(--persona-message-assistant-text, var(--persona-text))");let L=yv(e),E=e.content?.trim()??"",A=L.length>0&&E===Qs,w=Ii(a?.widgetConfig?.features?.streamAnimation),T=a?.widgetConfig?.features?.streamAnimation?.plugins,H=e.role==="assistant"&&w.type!=="none"?Fr(w.type,T):null,C=e.role==="assistant"&&H?.isAnimating?.(e)===!0,B=e.role==="assistant"&&H!==null&&(!!e.streaming||C);B&&H?.bubbleClass&&S.classList.add(H.bubbleClass);let F=document.createElement("div");F.classList.add("persona-message-content"),e.streaming&&F.classList.add("persona-content-streaming"),B&&H&&(H.containerClass&&F.classList.add(H.containerClass),F.style.setProperty("--persona-stream-step",`${w.speed}ms`),F.style.setProperty("--persona-stream-duration",`${w.duration}ms`));let q=B?Wi(e.content??"",w.buffer,H,e,!!e.streaming):e.content??"",D=()=>{let Y=t({text:q,message:e,streaming:!!e.streaming,raw:e.rawContent});return B&&H?.wrap==="char"?Ua(Y,"char",e.id,{skipTags:H.skipTags}):B&&H?.wrap==="word"?Ua(Y,"word",e.id,{skipTags:H.skipTags}):Y},U=null;if(A?(U=document.createElement("div"),U.innerHTML=D(),U.style.display="none",F.appendChild(U)):e.contentSegments?.length?Av(F,e.contentSegments,Y=>t({text:Y,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):F.innerHTML=D(),B&&H?.useCaret&&!A&&E){let Y=Hi(),ve=F.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ae=ve[ve.length-1];if(Ae?.parentNode)Ae.parentNode.insertBefore(Y,Ae.nextSibling);else{let xe=F.lastElementChild;xe?xe.appendChild(Y):F.appendChild(Y)}}if(u&&f==="inline"&&e.createdAt){let Y=Mg(e,d,"span");Y.classList.add("persona-timestamp-inline");let ve=F.lastElementChild;ve?ve.appendChild(Y):F.appendChild(Y)}if(L.length>0){let Y=Sv(L,!A&&!!E,()=>{A&&U&&(U.style.display="")});Y?S.appendChild(Y):A&&U&&(U.style.display="")}let se=xv(e);if(se.length>0){let Y=Mv(se);Y&&S.appendChild(Y)}let le=bv(e);if(le.length>0){let Y=Tv(le);Y&&S.appendChild(Y)}let Ce=vv(e);if(Ce.length>0){let Y=Ev(Ce);Y&&S.appendChild(Y)}let Le=e.contentSegments?.length?null:Cv(e.contextMentions);if(Le&&S.appendChild(Le),S.appendChild(F),u&&f==="below"&&e.createdAt){let Y=Mg(e,d);Y.classList.add("persona-mt-1"),S.appendChild(Y)}let ae=e.role==="assistant"?mv(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(q&&q.trim()),ve=w.placeholder==="skeleton",Ae=ve&&w.buffer==="line"&&Y;if(Y)Ae&&S.appendChild(qa());else if(ve)S.appendChild(qa());else{let xe=Rp("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);xe&&S.appendChild(xe)}}if(ae&&e.stopReason&&!e.streaming&&(E||(F.style.display="none"),S.appendChild(gv(e.stopReason,ae))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Y=Ip(e,o,r);S.appendChild(Y)}if(!c||e.role==="system")return S;let Z=x("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),de=kv(p,e.role);return g==="right"||g==="left"&&e.role==="user"?Z.append(S,de):Z.append(de,S),Z},Eg=(e,t,n,o,r,a)=>{let s=n??{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):_r(e,t,n,o,r,a)};var Ur=new Set,Pv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Rv=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
43
|
+
`):""},kg=(e,t)=>{let n=Ur.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),a=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let d=te(n?"chevron-up":"chevron-down",16,"currentColor",2);d?l.appendChild(d):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",a&&(a.style.display=n?"none":a.textContent||a.childNodes.length?"":"none")},Wp=(e,t)=>{let n=e.reasoning,o=x("div",["persona-message-bubble","persona-reasoning-bubble","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"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},a=r.expandable!==!1,s=a&&Ur.has(e.id),l=n.status!=="complete",p=Rv(e,r.previewMaxLines??3),d=x("button",a?"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":"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");d.type="button",a&&(d.setAttribute("aria-expanded",s?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=x("div","persona-flex persona-flex-col persona-text-left"),u=x("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=t?.reasoning??{},h=String(n.startedAt??Date.now()),S=()=>{let le=x("span","");return le.setAttribute("data-tool-elapsed",h),le.textContent=zs(n),le},L=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:g,previewText:p,isActive:l,config:t??{},elapsed:zs(n),createElapsedElement:S});typeof L=="string"&&L.trim()?(u.textContent=L,c.appendChild(u)):L instanceof HTMLElement?c.appendChild(L):(u.textContent=g,c.appendChild(u));let E=x("span","persona-text-xs persona-text-persona-primary");E.textContent=nm(n),c.appendChild(E);let M=r.loadingAnimation??"none",A=f.activeTextTemplate,w=f.completeTextTemplate,T=l?A:w,H=L instanceof HTMLElement,C=(le,Ce)=>{u.textContent="";let Le=$s(le,""),ae=0;for(let me of Le){let Z=me.styles.length>0?(()=>{let de=x("span",me.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return u.appendChild(de),de})():u;if(me.isDuration&&l)Z.appendChild(S());else{let de=me.isDuration?zs(n):me.text;Ce?ae=So(Z,de,ae):Z.appendChild(document.createTextNode(de))}}};if(!H&&T)if(E.style.display="none",u.style.display="",l&&M!=="none"){let le=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),M==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${le}ms`),C(T,!1)):(u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${le}ms`),M==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),C(T,!0))}else C(T,!1);else if(!H&&l&&M!=="none"){u.style.display="";let le=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),M==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${le}ms`);else{u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${le}ms`),M==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Ce=u.textContent||g;u.textContent="",So(u,Ce,0)}n.status==="complete"&&(u.style.display="none")}else H||(n.status==="complete"?u.style.display="none":u.style.display="");let B=null;if(a){B=x("div","persona-flex persona-items-center");let Ce=te(s?"chevron-up":"chevron-down",16,"currentColor",2);Ce?B.appendChild(Ce):B.textContent=s?"Hide":"Show";let Le=x("div","persona-flex persona-items-center persona-ml-auto");Le.append(B),d.append(c,Le)}else d.append(c);let F=x("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(F.setAttribute("data-persona-collapsed-preview","reasoning"),F.style.display="none",F.style.whiteSpace="pre-wrap",!s&&l&&r.activePreview&&p){let le=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:l,config:t??{}});Pv(F,le)||(F.textContent=p),F.style.display=""}if(!s&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!a)return o.append(d,F),o;let q=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");q.style.display=s?"":"none";let D=n.chunks.join(""),U=x("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return U.textContent=D||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),q.appendChild(U),(()=>{if(d.setAttribute("aria-expanded",s?"true":"false"),B){B.innerHTML="";let Ce=te(s?"chevron-up":"chevron-down",16,"currentColor",2);Ce?B.appendChild(Ce):B.textContent=s?"Hide":"Show"}q.style.display=s?"":"none",F.style.display=s?"none":F.textContent||F.childNodes.length?"":"none"})(),o.append(d,F,q),o};var qr=new Set,Iv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Wv=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(-t).join(`
|
|
44
44
|
`);let r=yo(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
45
|
-
`):""},Wp=(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)"},MC=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",a=SC(e,o?.previewMaxLines??3),s=n?Yf(n):"";if(!n)return{summary:s,previewText:a,isActive:!1};let l=n.status!=="complete",p=t?.toolCall??{},c=s;return r==="tool-name"?c=n.name?.trim()||s:r==="tool-preview"&&a&&(c=a),l&&p.activeTextTemplate?c=rd(n,p.activeTextTemplate,c):!l&&p.completeTextTemplate&&(c=rd(n,p.completeTextTemplate,c)),{summary:c,previewText:a,isActive:l}},Ag=(e,t,n)=>{let o=jr.has(e),r=n?.toolCall??{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let c=a.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=te(o?"chevron-up":"chevron-down",16,d,2);u?c.appendChild(u):c.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Hp=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","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"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let a=t?.features?.toolCallDisplay??{},s=a.expandable!==!1,l=s&&jr.has(e.id),{summary:p,previewText:c,isActive:d}=MC(e,t),u=y("button",s?"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":"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");u.type="button",s&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let h=String(n.startedAt??Date.now()),S=()=>{let N=y("span","");return N.setAttribute("data-tool-elapsed",h),N.textContent=Ia(n),N},E=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:c,collapsedMode:a.collapsedMode??"tool-call",isActive:d,config:t??{},elapsed:Ia(n),createElapsedElement:S});typeof E=="string"&&E.trim()?(f.textContent=E,g.appendChild(f)):E instanceof HTMLElement?g.appendChild(E):(f.textContent=p,g.appendChild(f));let k=a.loadingAnimation??"none",M=o.activeTextTemplate,A=o.completeTextTemplate,w=d?M:A,T=E instanceof HTMLElement,R=(N,U)=>{f.textContent="";let fe=n.name?.trim()||"tool",ce=Xs(N,fe),Le=0;for(let De of ce){let ae=De.styles.length>0?(()=>{let Ce=y("span",De.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return f.appendChild(Ce),Ce})():f;if(De.isDuration&&d)ae.appendChild(S());else{let Ce=De.isDuration?Ia(n):De.text;U?Le=So(ae,Ce,Le):ae.appendChild(document.createTextNode(Ce))}}};if(!T)if(d&&k!=="none"){let N=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),k==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${N}ms`),w&&R(w,!1);else if(f.classList.add(`persona-tool-loading-${k}`),f.style.setProperty("--persona-tool-anim-duration",`${N}ms`),k==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),w)R(w,!0);else{let U=f.textContent||p;f.textContent="",So(f,U,0)}}else w&&R(w,!1);let v=null;if(s){v=y("div","persona-flex persona-items-center");let N=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=te(l?"chevron-up":"chevron-down",16,N,2);U?v.appendChild(U):v.textContent=l?"Hide":"Show";let fe=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");fe.append(v),u.append(g,fe)}else u.append(g);let B=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(B.setAttribute("data-persona-collapsed-preview","tool"),B.style.display="none",B.style.whiteSpace="pre-wrap",!l&&d&&a.activePreview&&c){let N=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:c,isActive:d,config:t??{}});AC(B,N)||(B.textContent=c),B.style.display=""}if(!l&&d&&a.activeMinHeight&&(r.style.minHeight=a.activeMinHeight),!s)return r.append(u,B),r;let F=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(F.style.display=l?"":"none",o.contentBackgroundColor&&(F.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(F.style.color=o.contentTextColor),o.contentPaddingX&&(F.style.paddingLeft=o.contentPaddingX,F.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(F.style.paddingTop=o.contentPaddingY,F.style.paddingBottom=o.contentPaddingY),n.name){let N=y("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?N.style.color=o.contentTextColor:o.headerTextColor&&(N.style.color=o.headerTextColor),N.textContent=n.name,F.appendChild(N)}if(n.args!==void 0){let N=y("div","persona-space-y-1"),U=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Arguments";let fe=y("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");fe.style.fontSize="0.75rem",fe.style.lineHeight="1rem",Wp(fe,o),fe.textContent=yo(n.args),N.append(U,fe),F.appendChild(N)}if(n.chunks&&n.chunks.length){let N=y("div","persona-space-y-1"),U=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Activity";let fe=y("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");fe.style.fontSize="0.75rem",fe.style.lineHeight="1rem",Wp(fe,o),fe.textContent=n.chunks.join(""),N.append(U,fe),F.appendChild(N)}if(n.status==="complete"&&n.result!==void 0){let N=y("div","persona-space-y-1"),U=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Result";let fe=y("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");fe.style.fontSize="0.75rem",fe.style.lineHeight="1rem",Wp(fe,o),fe.textContent=yo(n.result),N.append(U,fe),F.appendChild(N)}if(n.status==="complete"&&typeof n.duration=="number"){let N=y("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(N.style.color=o.contentTextColor),N.textContent=`Duration: ${n.duration}ms`,F.appendChild(N)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),v){v.innerHTML="";let N=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=te(l?"chevron-up":"chevron-down",16,N,2);U?v.appendChild(U):v.textContent=l?"Hide":"Show"}F.style.display=l?"":"none",B.style.display=l?"none":B.textContent||B.childNodes.length?"":"none"})(),r.append(u,B,F),r};var lr=new Map,Ki=e=>{let n=(e.startsWith(Tn)?e.slice(Tn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Sg=e=>e?.approval!==!1?e?.approval:void 0,Mg=(e,t)=>{let n=Sg(t)?.detailsDisplay??"collapsed";return lr.get(e)??n==="expanded"},Tg=(e,t,n)=>{let o=Sg(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let s=te(t?"chevron-up":"chevron-down",14,"currentColor",2);s&&a.appendChild(s)}},Eg=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let a=Mg(e,n);Tg(o,a,n),r.style.display=a?"":"none"};var Xi=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",a=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",a.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",a.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return a;let s=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=y("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",d=te(p,20,c,2);d&&l.appendChild(d);let u=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",g.appendChild(f),!r){let v=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");v.setAttribute("data-approval-status",n.status),n.status==="approved"?(v.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",v.style.color="var(--persona-palette-colors-success-700, #15803d)",v.textContent="Approved"):n.status==="denied"?(v.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",v.style.color="var(--persona-palette-colors-error-700, #b91c1c)",v.textContent="Denied"):n.status==="timeout"&&(v.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",v.style.color="var(--persona-palette-colors-warning-700, #b45309)",v.textContent="Timeout"),g.appendChild(v)}u.appendChild(g);let S=n.toolType==="webmcp"||n.toolName.startsWith(Tn)?Ta(n.toolName):void 0,E=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...S?{displayTitle:S}:{},...n.reason?{reason:n.reason}:{}}),k=!n.toolName,M=E||(k?n.description:`The assistant wants to use \u201C${S??Ki(n.toolName)}\u201D.`),A=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(A.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(A.style.color=o.descriptionColor),A.textContent=M,u.appendChild(A),n.reason){let v=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");v.setAttribute("data-approval-reason","true"),o?.reasonColor?v.style.color=o.reasonColor:o?.descriptionColor&&(v.style.color=o.descriptionColor);let B=y("span","persona-font-medium");B.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,v.appendChild(B),v.appendChild(document.createTextNode(n.reason)),u.appendChild(v)}let w=o?.detailsDisplay??"collapsed",T=!!n.description&&!k,R=T||!!n.parameters;if(w!=="hidden"&&R){let v=Mg(e.id,t),B=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");B.type="button",B.setAttribute("data-expand-header","true"),B.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(B.style.color=o.descriptionColor);let F=y("span");F.setAttribute("data-approval-details-label","true");let $=y("span","persona-inline-flex persona-items-center");$.setAttribute("data-approval-details-chevron","true"),B.append(F,$),Tg(B,v,t),u.appendChild(B);let N=y("div");if(N.setAttribute("data-approval-details","true"),N.style.display=v?"":"none",T){let U=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(U.style.color=o.descriptionColor),U.textContent=n.description,N.appendChild(U)}if(n.parameters){let U=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(U.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(U.style.color=o.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=yo(n.parameters),N.appendChild(U)}u.appendChild(N)}if(r){let v=y("div","persona-flex persona-gap-2 persona-mt-2");v.setAttribute("data-approval-buttons","true");let B=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");B.type="button",B.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",B.style.color=o?.approveButtonTextColor??"#ffffff",B.setAttribute("data-approval-action","approve");let F=te("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);F&&(F.style.marginRight="4px",B.appendChild(F));let $=document.createTextNode(o?.approveLabel??"Approve");B.appendChild($);let N=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");N.type="button",N.style.backgroundColor=o?.denyButtonColor??"transparent",N.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",N.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,N.setAttribute("data-approval-action","deny");let U=te("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);U&&(U.style.marginRight="4px",N.appendChild(U));let fe=document.createTextNode(o?.denyLabel??"Deny");N.appendChild(fe),v.append(B,N),u.appendChild(v)}return s.append(l,u),a.appendChild(s),a};function TC(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function kg(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:a=!1,horizontalOffset:s,verticalOffset:l,zIndex:p=2147483e3,onOpen:c,onDismiss:d}=e,u=e.container??TC(t),g=!1,f=null,h=()=>{if(!g)return;let k=t.getBoundingClientRect();n.style.position="fixed",a&&(n.style.minWidth=`${k.width}px`),s&&(n.style.maxWidth=`${k.width}px`);let M=n.getBoundingClientRect(),A=l?.()??null,w=A!=null?k.top+A:k.top,T=o==="top-start"||o==="top-end"?w-r-M.height:k.bottom+r,v=o==="bottom-end"||o==="top-end"?k.right-M.width:k.left,B=s?.()??null;if(B!=null){let F=Math.max(k.left,k.right-M.width);v=Math.min(Math.max(k.left+B,k.left),F)}n.style.top=`${T}px`,n.style.left=`${v}px`},S=()=>{g&&(g=!1,f&&(f(),f=null),n.remove())},E=()=>{if(g)return;g=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),h();let k=(t.ownerDocument??document).defaultView??window,M=t.ownerDocument??document,A=()=>{if(!t.isConnected){S(),d?.("anchor-removed");return}h()},w=R=>{let v=typeof R.composedPath=="function"?R.composedPath():[];v.includes(n)||v.includes(t)||(S(),d?.("outside"))},T=k.setTimeout(()=>{M.addEventListener("pointerdown",w,!0)},0);k.addEventListener("scroll",A,!0),k.addEventListener("resize",A),f=()=>{k.clearTimeout(T),M.removeEventListener("pointerdown",w,!0),k.removeEventListener("scroll",A,!0),k.removeEventListener("resize",A)},c?.()};return{get isOpen(){return g},open:E,close:S,toggle:()=>g?S():E(),reposition:h,destroy:S}}function Lg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var EC=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Pg=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},dr=(e,t)=>{Pg(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},kC=e=>e?.approval!==!1?e?.approval:void 0,LC=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return lr.get(e)??n==="expanded"},Bp=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},PC=(e,t)=>{let n=y("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Tn)?Ta(e.toolName):void 0,a=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(a)return n.textContent=a,n;let s=r??Ki(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=s,n.appendChild(p),l){n.append(" from ");let c=document.createElement("strong");c.textContent=l,n.appendChild(c)}return n},RC=e=>{let t=y("div","persona-approval-resolved"),n=te("ban",15,"currentColor",2);n&&t.appendChild(n);let o=y("span","persona-approval-resolved-name");return o.textContent=e.toolName?Ki(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},IC=(e,t,n,o,r,a,s)=>{let l=y("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",c=!!n.description&&p!=="hidden",d=n.parameters!=null&&p!=="hidden",u=c||d,g=u&&LC(t.id,o),f=o?.showDetailsLabel??"Show details",h=o?.hideDetailsLabel??"Hide details",S=y("button","persona-approval-head");S.type="button",u?(S.setAttribute("data-action","toggle-params"),S.setAttribute("aria-expanded",g?"true":"false"),S.setAttribute("aria-label",g?h:f)):S.setAttribute("data-static","true");let E=y("span","persona-approval-logo"),k=te("shield-check",16,"currentColor",2);k&&E.appendChild(k),S.appendChild(E);let M=PC(n,o);if(u){let B=y("span","persona-approval-toggle");B.setAttribute("aria-hidden","true");let F=te("chevron-down",14,"currentColor",2);F&&B.appendChild(F),M.append(" "),M.appendChild(B)}S.appendChild(M),l.appendChild(S);let A=y("div","persona-approval-body");if(u){let B=y("div","persona-approval-details");if(B.setAttribute("data-role","params"),B.hidden=!g,c){let F=y("p","persona-approval-desc");o?.descriptionColor&&(F.style.color=o.descriptionColor),F.textContent=n.description,B.appendChild(F)}if(d){let F=y("pre","persona-approval-params");o?.parameterBackgroundColor&&(F.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(F.style.color=o.parameterTextColor),F.textContent=yo(n.parameters),B.appendChild(F)}A.appendChild(B)}if(n.reason){let B=y("p","persona-approval-reason");o?.reasonColor?B.style.color=o.reasonColor:o?.descriptionColor&&(B.style.color=o.descriptionColor);let F=y("span","persona-approval-reason-label");F.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,B.append(F,document.createTextNode(n.reason)),A.appendChild(B)}let w=y("div","persona-approval-actions"),T=null,R=B=>{o?.approveButtonColor&&(B.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(B.style.color=o.approveButtonTextColor)},v=y("button","persona-approval-deny");if(v.type="button",v.setAttribute("data-action","deny"),o?.denyButtonColor&&(v.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(v.style.color=o.denyButtonTextColor),v.append(o?.denyLabel??"Deny"),s){let B=y("div","persona-approval-split"),F=y("button","persona-approval-primary");F.type="button",F.setAttribute("data-action","always"),R(F),F.append(o?.approveLabel??"Always allow",Bp("\u23CE"));let $=y("button","persona-approval-caret");$.type="button",$.setAttribute("data-action","toggle-menu"),$.setAttribute("aria-label","More options"),R($);let N=te("chevron-down",15,"currentColor",2);N&&$.appendChild(N),B.append(F,$),w.append(B,v),v.append(Bp("Esc"));let U=y("div","persona-approval-menu"),fe=y("button","persona-approval-menu-item");fe.type="button",fe.append("Allow once",Bp("\u2318\u23CE")),U.appendChild(fe),T=kg({anchor:B,content:U,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,T),fe.addEventListener("click",()=>{dr(e,t.id),r()})}else{let B=y("button","persona-approval-primary persona-approval-primary--solo");B.type="button",B.setAttribute("data-action","allow"),R(B),B.append(o?.approveLabel??"Allow"),w.append(B,v)}return A.appendChild(w),l.appendChild(A),l.addEventListener("click",B=>{let F=B.target instanceof Element?B.target.closest("[data-action]"):null;if(!F)return;let $=F.getAttribute("data-action");if($==="toggle-params"){let N=l.querySelector('[data-role="params"]');if(N){let U=N.hidden;N.hidden=!U,S.setAttribute("aria-expanded",U?"true":"false"),S.setAttribute("aria-label",U?h:f),lr.set(t.id,U)}return}if($==="toggle-menu"){T?.toggle();return}if($==="always"){dr(e,t.id),r({remember:!0});return}if($==="allow"){dr(e,t.id),r();return}if($==="deny"){dr(e,t.id),a();return}}),l},Rg=()=>{let e=EC();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:a,config:s})=>{let l=o?.approval;if(!l)return null;let p=kC(s);if(l.status!=="pending"){if(dr(e,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return RC(l)}Pg(e,o.id);let c=p?.enableAlwaysAllow===!0,d=IC(e,o,l,p,r,a,c);if(c){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=g=>{Lg(g)||o.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),dr(e,o.id),g.key==="Escape"?a():g.metaKey||g.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return d}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])dr(e,o);e.latestPendingApprovalId=null}}};var Ig=e=>{let t=[],n=null;return{buttons:t,render:(r,a,s,l,p,c)=>{e.innerHTML="",t.length=0;let d=c?.agentPushed===!0;if(d||(n=null),!r||!r.length||!d&&(l??(a?a.getMessages():[])).some(E=>E.role==="user"))return;let u=document.createDocumentFragment(),g=a?a.isStreaming():!1,f=h=>{switch(h){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'}};if(r.forEach(h=>{let S=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");S.type="button",S.textContent=h,S.disabled=g,p?.fontFamily&&(S.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(S.style.fontWeight=p.fontWeight),p?.paddingX&&(S.style.paddingLeft=p.paddingX,S.style.paddingRight=p.paddingX),p?.paddingY&&(S.style.paddingTop=p.paddingY,S.style.paddingBottom=p.paddingY),S.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",d&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:h},bubbles:!0,composed:!0})),a.sendMessage(h))}),u.appendChild(S),t.push(S)}),e.appendChild(u),d){let h=JSON.stringify(r);h!==n&&(n=h,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var Qa=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ya=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var WC=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),HC=new Set(["step_start","execution_start"]),BC=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),DC=new Set(["step_complete","agent_turn_complete"]),FC=new Set(["flow_complete","agent_complete"]),Wg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Bg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,cr=(e,t)=>{let n=e[t];return Bg(n)?n:void 0};function Dp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ji(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function NC(e,t){return typeof t.type=="string"?t.type:e}function OC(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function _C(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Hg(e){let t=cr(e,"result"),n=[cr(e,"tokens"),cr(e,"totalTokens"),t?cr(t,"tokens"):void 0,cr(e,"usage"),t?cr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=pn(o.output)??pn(o.outputTokens)??pn(o.completionTokens);if(r!==void 0)return r}return pn(e.outputTokens)??pn(e.completionTokens)??(t?pn(t.outputTokens)??pn(t.completionTokens):void 0)}function UC(e){let t=cr(e,"result");return pn(e.executionTime)??pn(e.executionTimeMs)??pn(e.execution_time)??pn(e.duration)??(t?pn(t.executionTime)??pn(t.executionTimeMs):void 0)}function qC(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Za=class{constructor(t=qC){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Ji(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!Bg(n)){Wg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=NC(t,n),r=this.now();if(WC.has(o)){this.startRun(r);return}if(HC.has(o)){this.run||this.startRun(r);return}if(BC.has(o)){if(!_C(o,n))return;let a=OC(n);if(!a)return;this.run||this.startRun(r);let s=this.run;s.firstDeltaAt??(s.firstDeltaAt=r),s.visibleCharCount+=a.length;let l=s.exactOutputTokens+Dp(s.visibleCharCount),p=r-s.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ji(l,p),outputTokens:l,durationMs:p,source:s.exactOutputTokens>0?"usage":"estimate"};return}if(DC.has(o)){if(!this.run)return;let a=this.run,s=Hg(n);s!==void 0&&(a.exactOutputTokens+=s,a.visibleCharCount=0);let l=a.exactOutputTokens>0,p=a.exactOutputTokens+Dp(a.visibleCharCount),c=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Ji(p,c),outputTokens:p,durationMs:c,source:l?"usage":"estimate"};return}if(FC.has(o)){if(!this.run)return;let a=this.run,s=Hg(n),l=s??a.exactOutputTokens+Dp(a.visibleCharCount),p=s!==void 0||a.exactOutputTokens>0?"usage":"estimate",c=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Ji(l,c),outputTokens:l,durationMs:c,source:p},this.run=null;return}if(Wg.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:UC(n)??o-t.startedAt}};function Gr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var VC={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},zC={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},$C=["flowName","stepName","reasoningText","text","name","tool","toolName"],jC=100;function GC(e,t){let n={...VC,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return zC}function KC(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function XC(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),a=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${a}`}function JC(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),a=n;for(let s of r)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function QC(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function YC(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function ZC(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function ev(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function tv(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let a=t.find(l=>l.renderEventStreamPayload);if(a?.renderEventStreamPayload&&n){let l=a.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>s(),parsedPayload:r});if(l)return l}return s();function s(){let l=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function Fp(e,t,n,o,r,a,s,l){let p=r.has(e.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Gr(c,o.classNames?.eventRow);let d=s.find(g=>g.renderEventStreamRow);if(d?.renderEventStreamRow&&l){let g=d.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>a(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(u()),c;function u(){let g=y("div",""),f=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",e.id);let h=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=te(p?"chevron-down":"chevron-right","14px","currentColor",2);S&&h.appendChild(S);let E=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=o.timestampFormat??"relative";E.textContent=k==="relative"?KC(e.timestamp,n):XC(e.timestamp);let M=null;o.showSequenceNumbers!==!1&&(M=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(t+1));let A=GC(e.type,o.badgeColors),w=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");w.style.backgroundColor=A.bg,w.style.color=A.text,w.style.borderColor=A.text+"50",w.textContent=e.type;let T=o.descriptionFields??$C,R=JC(e.payload,T),v=null;R&&(v=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),v.textContent=R);let B=y("div","persona-flex-1 persona-min-w-0"),F=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),$=te("clipboard","12px","currentColor",1.5);return $&&F.appendChild($),F.addEventListener("click",async N=>{N.stopPropagation(),await QC(YC(e)),F.innerHTML="";let U=te("check","12px","currentColor",1.5);U&&F.appendChild(U),setTimeout(()=>{F.innerHTML="";let fe=te("clipboard","12px","currentColor",1.5);fe&&F.appendChild(fe)},1500)}),f.appendChild(h),f.appendChild(E),M&&f.appendChild(M),f.appendChild(w),v&&f.appendChild(v),f.appendChild(B),f.appendChild(F),g.appendChild(f),p&&g.appendChild(tv(e,s,l)),g}}function Dg(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:a=[],getThroughput:s}=e,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,c=l?.iconName??"arrow-down",d=l?.label??"",u=r?.features?.eventStream??{},g=a.find(h=>h.renderEventStreamView);if(g?.renderEventStreamView&&r){let h=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(h)return{element:h,update:()=>{},destroy:()=>{}}}return f();function f(){let h=u.classNames,S=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Gr(S,h?.panel);let E=[],k="",M="",A=null,w=[],T={},R=0,v=Ii(),B=0,F=0,$=!1,N=null,U=!1,fe=0,ce=new Set,Le=new Map,De="",ae="",Ce=null,ee,le,Y,ve,Ae=null,be=null,He=null;function Ne(){let _=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),j=y("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Gr(j,h?.headerBar),s){be=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),be.style.cursor="help",Ae=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Ae.textContent="-- tok/s",He=y("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),He.style.display="none",He.style.pointerEvents="none";let et=be,Ro=He,Io=()=>{if(!Ro.textContent)return;let ls=et.getBoundingClientRect(),Zt=_.getBoundingClientRect();Ro.style.left=`${ls.left-Zt.left}px`,Ro.style.top=`${ls.bottom-Zt.top+4}px`,Ro.style.display="block"},dl=()=>{Ro.style.display="none"};be.addEventListener("mouseenter",Io),be.addEventListener("mouseleave",dl),be.appendChild(Ae)}let ne=y("div","persona-flex-1");ee=y("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ge=y("option","");Ge.value="",Ge.textContent="All events (0)",ee.appendChild(Ge),le=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),le.type="button",le.title="Copy All";let dt=te("clipboard-copy","12px","currentColor",1.5);dt&&le.appendChild(dt);let K=y("span","persona-event-copy-all persona-text-xs");K.textContent="Copy All",le.appendChild(K),be&&j.appendChild(be),j.appendChild(ne),j.appendChild(ee),j.appendChild(le);let Ue=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Gr(Ue,h?.searchBar);let Te=te("search","14px","var(--persona-muted, #9ca3af)",1.5),Ie=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Te&&Ie.appendChild(Te),Y=y("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Gr(Y,h?.searchInput),Y.type="text",Y.placeholder="Search event payloads...",ve=y("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ve.type="button",ve.style.display="none";let ke=te("x","12px","currentColor",2);return ke&&ve.appendChild(ke),Ue.appendChild(Ie),Ue.appendChild(Y),Ue.appendChild(ve),_.appendChild(j),_.appendChild(Ue),He&&_.appendChild(He),_}let Xe,Oe=a.find(_=>_.renderEventStreamToolbar);Oe?.renderEventStreamToolbar&&r?Xe=Oe.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ne(),eventCount:t.getSize(),filteredCount:0,onFilterChange:j=>{k=j,Ee(),ye()},onSearchChange:j=>{M=j,Ee(),ye()}})??Ne():Xe=Ne();let lt=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");lt.style.display="none";function Ye(){if(!s||!Ae||!be)return;let _=s(),j=ZC(_);Ae.textContent=j;let ne=ev(_);He&&(He.textContent=ne,ne||(He.style.display="none")),be.setAttribute("aria-label",ne?`Throughput: ${j}, ${ne}`:`Throughput: ${j}`)}let Pe=y("div","persona-flex-1 persona-min-h-0 persona-relative"),Se=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Se.style.height="100%";let Ze=y("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Gr(Ze,h?.scrollIndicator),Ze.style.display="none",Ze.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false");let un=te(c,"14px","currentColor",2);un&&Ze.appendChild(un);let kt=y("span","");kt.textContent=d,Ze.appendChild(kt);let xt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");xt.style.display="none",Pe.appendChild(Se),Pe.appendChild(xt),Pe.appendChild(Ze),S.setAttribute("tabindex","0"),S.appendChild(Xe),S.appendChild(lt),S.appendChild(Pe);function Re(){let _=t.getAll(),j={};for(let Ue of _)j[Ue.type]=(j[Ue.type]||0)+1;let ne=Object.keys(j).sort(),Ge=ne.length!==w.length||!ne.every((Ue,Te)=>Ue===w[Te]),Me=!Ge&&ne.some(Ue=>j[Ue]!==T[Ue]),dt=_.length!==Object.values(T).reduce((Ue,Te)=>Ue+Te,0);if(!Ge&&!Me&&!dt||(w=ne,T=j,!ee))return;let K=ee.value;if(ee.options[0].textContent=`All events (${_.length})`,Ge){for(;ee.options.length>1;)ee.remove(1);for(let Ue of ne){let Te=y("option","");Te.value=Ue,Te.textContent=`${Ue} (${j[Ue]||0})`,ee.appendChild(Te)}K&&ne.includes(K)?ee.value=K:K&&(ee.value="",k="")}else for(let Ue=1;Ue<ee.options.length;Ue++){let Te=ee.options[Ue];Te.textContent=`${Te.value} (${j[Te.value]||0})`}}function me(){let _=t.getAll();if(k&&(_=_.filter(j=>j.type===k)),M){let j=M.toLowerCase();_=_.filter(ne=>ne.type.toLowerCase().includes(j)||ne.payload.toLowerCase().includes(j))}return _}function Je(){return k!==""||M!==""}function Ee(){R=0,B=0,v.resume(),Ze.style.display="none"}function ue(_){ce.has(_)?ce.delete(_):ce.add(_),Ce=_;let j=Se.scrollTop,ne=v.isFollowing();U=!0,v.pause(),ye(),Se.scrollTop=j,ne&&v.resume(),U=!1}function se(){return ko(Se,50)}function ye(){F=Date.now(),$=!1,Ye(),Re();let _=t.getEvictedCount();_>0?(lt.textContent=`${_.toLocaleString()} older events truncated`,lt.style.display=""):lt.style.display="none",E=me();let j=E.length,ne=t.getSize()>0;j===0&&ne&&Je()?(xt.textContent=M?`No events matching '${M}'`:"No events matching filter",xt.style.display="",Se.style.display="none"):(xt.style.display="none",Se.style.display=""),le&&(le.title=Je()?`Copy Filtered (${j})`:"Copy All"),p&&!v.isFollowing()&&j>R&&(B+=j-R,kt.textContent=d?`${d}${B>0?` (${B})`:""}`:"",Ze.style.display=""),R=j;let Ge=t.getAll(),Me=Ge.length>0?Ge[0].timestamp:0,dt=new Set(E.map(Te=>Te.id));for(let Te of ce)dt.has(Te)||ce.delete(Te);let K=k!==De||M!==ae,Ue=Le.size===0&&E.length>0;if(K||Ue||E.length===0){Se.innerHTML="",Le.clear();let Te=document.createDocumentFragment();for(let Ie=0;Ie<E.length;Ie++){let ke=Fp(E[Ie],Ie,Me,u,ce,ue,a,r);Le.set(E[Ie].id,ke),Te.appendChild(ke)}Se.appendChild(Te),De=k,ae=M,Ce=null}else{if(Ce!==null){let Ie=Le.get(Ce);if(Ie&&Ie.parentNode===Se){let ke=E.findIndex(et=>et.id===Ce);if(ke>=0){let et=Fp(E[ke],ke,Me,u,ce,ue,a,r);Se.insertBefore(et,Ie),Ie.remove(),Le.set(Ce,et)}}Ce=null}let Te=new Set(E.map(Ie=>Ie.id));for(let[Ie,ke]of Le)Te.has(Ie)||(ke.remove(),Le.delete(Ie));for(let Ie=0;Ie<E.length;Ie++){let ke=E[Ie];if(!Le.has(ke.id)){let et=Fp(ke,Ie,Me,u,ce,ue,a,r);Le.set(ke.id,et),Se.appendChild(et)}}}v.isFollowing()&&(Se.scrollTop=Se.scrollHeight)}function bt(){if(Date.now()-F>=jC){N!==null&&(cancelAnimationFrame(N),N=null),ye();return}$||($=!0,N=requestAnimationFrame(()=>{N=null,ye()}))}let ge=(_,j)=>{if(!le)return;le.innerHTML="";let ne=te(_,"12px","currentColor",1.5);ne&&le.appendChild(ne);let Ge=y("span","persona-text-xs");Ge.textContent="Copy All",le.appendChild(Ge),setTimeout(()=>{le.innerHTML="";let Me=te("clipboard-copy","12px","currentColor",1.5);Me&&le.appendChild(Me);let dt=y("span","persona-text-xs");dt.textContent="Copy All",le.appendChild(dt),le.disabled=!1},j)},pe=async()=>{if(le){le.disabled=!0;try{let _;Je()?_=E:n?(_=await n(),_.length===0&&(_=t.getAll())):_=t.getAll();let j=_.map(ne=>{try{return JSON.parse(ne.payload)}catch{return ne.payload}});await navigator.clipboard.writeText(JSON.stringify(j,null,2)),ge("check",1500)}catch{ge("x",1500)}}},xn=()=>{ee&&(k=ee.value,Ee(),ye())},Q=()=>{!Y||!ve||(ve.style.display=Y.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{M=Y.value,Ee(),ye()},150))},I=()=>{!Y||!ve||(Y.value="",M="",ve.style.display="none",A&&clearTimeout(A),Ee(),ye())},q=()=>{if(U)return;let _=Se.scrollTop,{action:j,nextLastScrollTop:ne}=Wi({following:v.isFollowing(),currentScrollTop:_,lastScrollTop:fe,nearBottom:se(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});fe=ne,j==="resume"?(v.resume(),B=0,Ze.style.display="none"):j==="pause"&&(v.pause(),p&&(kt.textContent=d,Ze.style.display=""))},b=_=>{let j=Hi({following:v.isFollowing(),deltaY:_.deltaY,nearBottom:se(),resumeWhenNearBottom:!0});j==="pause"?(v.pause(),p&&(kt.textContent=d,Ze.style.display="")):j==="resume"&&(v.resume(),B=0,Ze.style.display="none")},L=()=>{p&&(Se.scrollTop=Se.scrollHeight,v.resume(),B=0,Ze.style.display="none")},W=_=>{let j=_.target;if(!j||j.closest("button"))return;let ne=j.closest("[data-event-id]");if(!ne)return;let Ge=ne.getAttribute("data-event-id");Ge&&ue(Ge)},O=_=>{if((_.metaKey||_.ctrlKey)&&_.key==="f"){_.preventDefault(),Y?.focus(),Y?.select();return}_.key==="Escape"&&(Y&&document.activeElement===Y?(I(),Y.blur(),S.focus()):o&&o())};le&&le.addEventListener("click",pe),ee&&ee.addEventListener("change",xn),Y&&Y.addEventListener("input",Q),ve&&ve.addEventListener("click",I),Se.addEventListener("scroll",q),Se.addEventListener("wheel",b,{passive:!0}),Se.addEventListener("click",W),Ze.addEventListener("click",L),S.addEventListener("keydown",O);function G(){A&&clearTimeout(A),N!==null&&(cancelAnimationFrame(N),N=null),$=!1,Le.clear(),le&&le.removeEventListener("click",pe),ee&&ee.removeEventListener("change",xn),Y&&Y.removeEventListener("input",Q),ve&&ve.removeEventListener("click",I),Se.removeEventListener("scroll",q),Se.removeEventListener("wheel",b),Se.removeEventListener("click",W),Ze.removeEventListener("click",L),S.removeEventListener("keydown",O)}return{element:S,update:bt,destroy:G}}}function Fg(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let a=[],s=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let g=u;return a.findIndex(f=>f===g||f.contains(g))},c=u=>{let g=p(u.target);if(g<0)return;let f=g;if(u.key===r)f=Math.min(g+1,a.length-1);else if(u.key===o)f=Math.max(g-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=a.length-1;else return;u.preventDefault(),f!==g&&t.onSelect(f)},d=u=>{let g=p(u.target);g>=0&&l(a[g])};return e.addEventListener("keydown",c),e.addEventListener("focusin",d),{beforeRender(){s=typeof document<"u"&&e.contains(document.activeElement)},render(u,g){if(a=u,u.forEach((f,h)=>{f.setAttribute("role","tab");let S=h===g;f.setAttribute("aria-selected",S?"true":"false"),f.tabIndex=S||g<0&&h===0?0:-1}),s){let f=(g>=0?u[g]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){e.removeEventListener("keydown",c),e.removeEventListener("focusin",d)}}}function Ng(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",a=n?.toolbarTitle??"Artifacts",s=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),c=Q=>({start:Q===!1?!1:typeof Q=="object"&&Q?Q.start!==!1:!0,end:Q===!1?!1:typeof Q=="object"&&Q?Q.end!==!1:!0}),{start:d,end:u}=c(n?.tabFade),g=typeof document<"u"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{g?.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"),U?.hide()};g&&g.addEventListener("click",()=>{f(),t.onDismiss?.()});let h=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");h.setAttribute("data-persona-theme-zone","artifact-pane"),r&&h.classList.add("persona-artifact-pane-document");let S=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");S.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&S.classList.add("persona-artifact-toolbar-document");let E=y("span","persona-text-xs persona-font-medium persona-truncate");E.textContent=a;let k=Et({icon:"x",label:s});k.addEventListener("click",()=>{f(),t.onDismiss?.()});let M="rendered",A=Or({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:Q=>{M=Q==="source"?"source":"rendered",ge()}}),w=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),T=n?.documentToolbarShowCopyLabel===!0,R=n?.documentToolbarShowCopyChevron===!0,v=n?.documentToolbarCopyMenuItems,B=!!(R&&v&&v.length>0),F=null,$,N=null,U=null;if(r&&(T||R)&&!B){if($=T?Jn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Et({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let Q=te("chevron-down",14,"currentColor",2);Q&&$.appendChild(Q)}}else r&&B?(F=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=T?Jn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Et({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),N=Et({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),F.append($,N)):r?$=Et({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):($=Et({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&$.classList.add("persona-hidden"));let fe=r?Et({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Et({icon:"refresh-cw",label:"Refresh"}),ce=r?Et({icon:"x",label:s,className:"persona-artifact-doc-icon-btn"}):Et({icon:"x",label:s}),Le=Et({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Le.classList.add("persona-hidden");let De=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ae=e.features?.artifacts?.toolbarActions??[],Ce=()=>{let Q=Pe.find(L=>L.id===Se)??Pe[Pe.length-1],I=Q?.id??null,q=Q?.artifactType==="markdown"?Q.markdown??"":"",b=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:q,jsonPayload:b,id:I}},ee=async()=>{let Q=Pe.find(I=>I.id===Se)??Pe[Pe.length-1];try{await navigator.clipboard.writeText(za(Q))}catch{}};if($.addEventListener("click",async()=>{let Q=n?.onDocumentToolbarCopyMenuSelect;if(Q&&B){let{markdown:I,jsonPayload:q,id:b}=Ce();try{await Q({actionId:"primary",artifactId:b,markdown:I,jsonPayload:q})}catch{}return}await ee()}),N&&v?.length){let Q=()=>h.closest("[data-persona-root]")??document.body,I=()=>{U=To({items:v.map(q=>({id:q.id,label:q.label})),onSelect:async q=>{let{markdown:b,jsonPayload:L,id:W}=Ce(),O=n?.onDocumentToolbarCopyMenuSelect;try{O?await O({actionId:q,artifactId:W,markdown:b,jsonPayload:L}):q==="markdown"||q==="md"?await navigator.clipboard.writeText(b):q==="json"||q==="source"?await navigator.clipboard.writeText(L):await navigator.clipboard.writeText(b||L)}catch{}},anchor:F??N,position:"bottom-right",portal:Q()})};h.isConnected?I():requestAnimationFrame(I),N.addEventListener("click",q=>{q.stopPropagation(),U?.toggle()})}fe.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}ge()}),ce.addEventListener("click",()=>{f(),t.onDismiss?.()});let le=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)S.replaceChildren(),F?w.append(F,fe,ce):w.append($,fe,ce),w.insertBefore(De,ce),w.insertBefore(Le,ce),S.append(A.element,le,w);else{let Q=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");Q.append($,De,Le,k),S.appendChild(E),S.appendChild(Q)}l&&(S.style.paddingLeft=l,S.style.paddingRight=l);let Y=y("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&Y.style.setProperty("--persona-artifact-tab-fade-size",p);let ve=e.features?.artifacts?.renderTabBar,Ae=y("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),be=Fg(Y,{onSelect:Q=>t.onSelect(Pe[Q].id)}),He=Q=>{let I=Q.scrollWidth-Q.clientWidth,q=I>1,b=Math.abs(Q.scrollLeft);Q.classList.toggle("persona-artifact-tab-fade-start",d&&q&&b>1),Q.classList.toggle("persona-artifact-tab-fade-end",u&&q&&b<I-1)},Ne=0,Xe=()=>{if(Ne)return;let Q=()=>{Ne=0,He(Y)};Ne=typeof requestAnimationFrame=="function"?requestAnimationFrame(Q):setTimeout(Q,0)};Y.addEventListener("scroll",()=>Xe(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>He(Y)).observe(Y);let Oe=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),lt=()=>{Oe.scrollLeft=0},Ye=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(lt):setTimeout(lt,0)};if(l){for(let Q of[Y,Ae])Q.style.paddingLeft=l,Q.style.paddingRight=l;Oe.style.padding=l}h.appendChild(S),h.appendChild(Y),h.appendChild(Ae),h.appendChild(Oe);let Pe=[],Se=null,Ze=!1,un=!1,kt=!0,xt=!1,Re=null,me="",Je=null,Ee=!1,ue=Q=>Q.artifactType==="markdown"&&!!Q.file||r?M:"rendered",se=Q=>{r||(Q&&!Ee?(S.insertBefore(A.element,E),Ee=!0):!Q&&Ee&&(A.element.remove(),Ee=!1))},ye=()=>Se&&Pe.find(Q=>Q.id===Se)||Pe[Pe.length-1],bt=()=>{let Q=qa(ye());if(!Q){De.replaceChildren();return}let I=ae.filter(q=>q.visible===void 0||q.visible(Q)).map(q=>_r(q,{documentChrome:r,onClick:()=>{let b=qa(ye());if(b)try{Promise.resolve(q.onClick(b)).catch(()=>{})}catch{}}}));De.replaceChildren(...I)},ge=()=>{bt();let Q=r&&Pe.length<=1,I=!!ve;if(Y.classList.toggle("persona-hidden",Q||I),Ae.classList.toggle("persona-hidden",Q||!I),I&&ve){let L=Pe.map(W=>W.id).join("|")+" "+(Se??"");if(L!==me){me=L;let W=ve({records:Pe,selectedId:Se,onSelect:t.onSelect});Ae.firstElementChild!==W&&Ae.replaceChildren(W)}}else{be.beforeRender(),Y.replaceChildren();let L=[],W=-1;for(let[O,G]of Pe.entries()){let _=y("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");_.type="button";let j=G.artifactType==="markdown"?G.file:void 0,ne=j?Bn(j.path):G.title||G.id.slice(0,8),Ge=j?.path||G.title||ne;_.textContent=ne,_.title=Ge,_.setAttribute("aria-label",Ge),G.id===Se&&(_.classList.add("persona-bg-persona-container","persona-border-persona-border"),W=O),_.addEventListener("click",()=>t.onSelect(G.id)),Y.appendChild(_),L.push(_)}if(be.render(L,W),W>=0&&Se!==Re){Re=Se;let O=L[W];typeof O.scrollIntoView=="function"&&O.scrollIntoView({block:"nearest",inline:"nearest"})}He(Y)}let q=Se&&Pe.find(L=>L.id===Se)||Pe[Pe.length-1];if(!q){Oe.replaceChildren(),Je=null,se(!1);return}let b=q.artifactType==="markdown"?q.file:void 0;if(se(!!b),r){let L=b?Ao(b):q.artifactType==="markdown"?"MD":q.component??"Component",W=(q.title||"Document").trim(),O=b?Bn(b.path):W.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${O} \xB7 ${L}`}else E.textContent=b?Bn(b.path):a;Je?(Je.el.parentElement!==Oe&&Oe.replaceChildren(Je.el),Je.update(q)):(Je=Pi(q,{config:e,resolveViewMode:ue}),Oe.replaceChildren(Je.el)),Oe.classList.toggle("persona-artifact-content-flush",!!Oe.querySelector(".persona-code-pre"))},pe=()=>{let Q=Pe.length>0;if(h.classList.toggle("persona-hidden",!Q),g){let b=((typeof h.closest=="function"?h.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;Q&&b&&Ze?(g.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},xn=()=>{xt=!1,ge(),pe()};return{element:h,backdrop:g,update(Q){let I=Q.selectedId??Q.artifacts[Q.artifacts.length-1]?.id??null,q=I!==Se;Pe=Q.artifacts,Se=I,Pe.length>0&&(Ze=!0),xt=!0,kt&&xn(),q&<()},setMobileOpen(Q){Ze=Q,!Q&&g?(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):pe()},setExpanded(Q){Q!==un&&(un=Q,Ye());let I=te(Q?"minimize":"maximize",16,"currentColor",2);I&&Le.replaceChildren(I);let q=Q?"Collapse artifacts panel":"Expand artifacts panel";Le.setAttribute("aria-label",q),Le.title=q},setExpandToggleVisible(Q){Le.classList.toggle("persona-hidden",!Q)},setCopyButtonVisible(Q){r||$.classList.toggle("persona-hidden",!Q)},setCustomActions(Q){ae=Q,bt()},setTabFade(Q){let I=c(Q);I.start===d&&I.end===u||(d=I.start,u=I.end,He(Y))},setRenderTabBar(Q){Q!==ve&&(ve=Q,me="",ge())},setVisible(Q){Q!==kt&&(kt=Q,Q&&xt&&xn())}}}function Qt(e){return e?.features?.artifacts?.enabled===!0}function Og(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"),!Qt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function nv(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 _g=["panel","seamless","detached"];function Np(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&_g.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Op(e){return!e||!Qt(e)?!1:Np(e)==="detached"}function es(e,t){if(!Qt(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-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),nv(e),Og(e,t);return}let n=t.features?.artifacts?.layout,o=Np(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let a=n?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=n?.documentToolbarIconColor?.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Og(e,t)}function ts(e,t){for(let l of _g)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Qt(t))return;let n=t.features?.artifacts?.layout,o=Np(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let a=n?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=n?.chatShadow?.trim();s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}function Ug(e,t){return!t||!Qt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function ov(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function rv(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 av(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function sv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function _p(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function qg(e,t,n,o,r,a){let s=ov(r,200),l=sv(t,n,o,200);l=Math.max(s,l);let p=rv(a);return p!==null&&(l=Math.min(l,p)),av(e,s,l)}var Vg={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Up=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(a=>{if(a.dataset.enhanced==="true")return;let s=a.dataset.tvForm??"init";a.dataset.enhanced="true";let l=Vg[s]??Vg.init;a.classList.add("persona-form-card","persona-space-y-4");let p=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=l.title,p.appendChild(c),l.description){let h=y("p","persona-text-sm persona-text-persona-muted");h.textContent=l.description,p.appendChild(h)}let d=document.createElement("form");d.className="persona-form-grid persona-space-y-3",l.fields.forEach(h=>{let S=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${t.id}-${s}-${h.name}`;let E=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=h.label,S.appendChild(E);let k=h.type??"text",M;k==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=k),M.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",M.id=`${t.id}-${s}-${h.name}`,M.name=h.name,M.placeholder=h.placeholder??"",h.required&&(M.required=!0),S.appendChild(M),d.appendChild(S)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=l.submitLabel??"Submit",u.appendChild(g),u.appendChild(f),d.appendChild(u),a.replaceChildren(p,d),d.addEventListener("submit",async h=>{h.preventDefault();let S=n.formEndpoint??"/form",E=new FormData(d),k={};E.forEach((M,A)=>{k[A]=M}),k.type=s,f.disabled=!0,g.textContent="Submitting\u2026";try{let M=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let A=await M.json();g.textContent=A.message??"Thanks! We'll be in touch soon.",A.success&&A.nextPrompt&&await o.sendMessage(String(A.nextPrompt))}catch(M){g.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var qp=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 n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(a=>a.id));return[...n.filter(a=>!o.has(a.id)),...t].sort((a,s)=>(s.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},ns=new qp;var zg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iv=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),$g=(e,t,n)=>{if(!zg(e)||!zg(t)||iv.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let a=n?`${n}.${r}`:r;o[r]=$g(e[r],t[r],a)}return o};function Qi(e,t){let n=$g(e,t,"");return Br(n)}var jg=()=>{let e=new Map,t=(r,a)=>(e.has(r)||e.set(r,new Set),e.get(r).add(a),()=>n(r,a)),n=(r,a)=>{e.get(r)?.delete(a)};return{on:t,off:n,emit:(r,a)=>{e.get(r)?.forEach(s=>{try{s(a)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var lv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},dv=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let a=t[r];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},os=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=lv(e),n=dv(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...a}=o;return{type:String(r),payload:a,raw:o}}catch{return null}},Vp=e=>typeof e=="string"?e:e==null?"":String(e),pr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Vp(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Vp(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Vp(n.text)}}},Gg=e=>Array.isArray(e)?e.map(t=>String(t)):[],rs=e=>{let t=new Set(Gg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Gg(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&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 l=s?e.parsers.reduce((c,d)=>c||d?.({text:s,message:a.message})||null,null):null;if(!l)return null;t.add(a.message.id),o();let p={action:l,message:a.message};e.emit("action:detected",p);for(let c of e.handlers)if(c)try{let d=()=>{e.emit("action:resubmit",p)},u=c(l,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:d});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var cv=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}},pv=e=>e.map(t=>({...t,streaming:!1})),uv=e=>e.map(t=>({...t,status:"complete"})),Yi=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?cv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?pv(n.messages):void 0,artifacts:n.artifacts?uv(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Kr=po(_s(),1);function fv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function mv(e,t){if(!fv(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Zi(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=(0,Kr.parse)(n,Kr.STR|Kr.OBJ),a=mv(r,n);a&&(e=a)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Kg(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function el(e,t){let{config:n,message:o,onPropsUpdate:r}=t,a=kn.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return a(e.props,s)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function Xg(){let e=Zi();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Jg(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 as(e){let t=Jg(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function tl(e){let t=Jg(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var gv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function nl(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:c=gv}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,f.appendChild(h);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,f.appendChild(S),g.appendChild(f);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let R=1;R<=5;R++){let v=document.createElement("button");v.type="button",v.className="persona-feedback-rating-btn persona-feedback-star-btn",v.setAttribute("role","radio"),v.setAttribute("aria-checked","false"),v.setAttribute("aria-label",`${R} star${R>1?"s":""}: ${c[R-1]}`),v.title=c[R-1],v.dataset.rating=String(R),v.innerHTML=`
|
|
45
|
+
`):""},Hp=(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)"},Hv=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",a=Wv(e,o?.previewMaxLines??3),s=n?om(n):"";if(!n)return{summary:s,previewText:a,isActive:!1};let l=n.status!=="complete",p=t?.toolCall??{},d=s;return r==="tool-name"?d=n.name?.trim()||s:r==="tool-preview"&&a&&(d=a),l&&p.activeTextTemplate?d=nd(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=nd(n,p.completeTextTemplate,d)),{summary:d,previewText:a,isActive:l}},Lg=(e,t,n)=>{let o=qr.has(e),r=n?.toolCall??{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let d=a.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=te(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Bp=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=x("div",["persona-message-bubble","persona-tool-bubble","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"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let a=t?.features?.toolCallDisplay??{},s=a.expandable!==!1,l=s&&qr.has(e.id),{summary:p,previewText:d,isActive:c}=Hv(e,t),u=x("button",s?"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":"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");u.type="button",s&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let g=x("div","persona-flex persona-flex-col persona-text-left"),f=x("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let h=String(n.startedAt??Date.now()),S=()=>{let D=x("span","");return D.setAttribute("data-tool-elapsed",h),D.textContent=Ta(n),D},L=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:a.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:Ta(n),createElapsedElement:S});typeof L=="string"&&L.trim()?(f.textContent=L,g.appendChild(f)):L instanceof HTMLElement?g.appendChild(L):(f.textContent=p,g.appendChild(f));let E=a.loadingAnimation??"none",M=o.activeTextTemplate,A=o.completeTextTemplate,w=c?M:A,T=L instanceof HTMLElement,H=(D,U)=>{f.textContent="";let se=n.name?.trim()||"tool",le=$s(D,se),Ce=0;for(let Le of le){let ae=Le.styles.length>0?(()=>{let me=x("span",Le.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return f.appendChild(me),me})():f;if(Le.isDuration&&c)ae.appendChild(S());else{let me=Le.isDuration?Ta(n):Le.text;U?Ce=So(ae,me,Ce):ae.appendChild(document.createTextNode(me))}}};if(!T)if(c&&E!=="none"){let D=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),E==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),w&&H(w,!1);else if(f.classList.add(`persona-tool-loading-${E}`),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),E==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),w)H(w,!0);else{let U=f.textContent||p;f.textContent="",So(f,U,0)}}else w&&H(w,!1);let C=null;if(s){C=x("div","persona-flex persona-items-center");let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=te(l?"chevron-up":"chevron-down",16,D,2);U?C.appendChild(U):C.textContent=l?"Hide":"Show";let se=x("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");se.append(C),u.append(g,se)}else u.append(g);let B=x("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(B.setAttribute("data-persona-collapsed-preview","tool"),B.style.display="none",B.style.whiteSpace="pre-wrap",!l&&c&&a.activePreview&&d){let D=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});Iv(B,D)||(B.textContent=d),B.style.display=""}if(!l&&c&&a.activeMinHeight&&(r.style.minHeight=a.activeMinHeight),!s)return r.append(u,B),r;let F=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(F.style.display=l?"":"none",o.contentBackgroundColor&&(F.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(F.style.color=o.contentTextColor),o.contentPaddingX&&(F.style.paddingLeft=o.contentPaddingX,F.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(F.style.paddingTop=o.contentPaddingY,F.style.paddingBottom=o.contentPaddingY),n.name){let D=x("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?D.style.color=o.contentTextColor:o.headerTextColor&&(D.style.color=o.headerTextColor),D.textContent=n.name,F.appendChild(D)}if(n.args!==void 0){let D=x("div","persona-space-y-1"),U=x("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Arguments";let se=x("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");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",Hp(se,o),se.textContent=yo(n.args),D.append(U,se),F.appendChild(D)}if(n.chunks&&n.chunks.length){let D=x("div","persona-space-y-1"),U=x("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Activity";let se=x("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");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",Hp(se,o),se.textContent=n.chunks.join(""),D.append(U,se),F.appendChild(D)}if(n.status==="complete"&&n.result!==void 0){let D=x("div","persona-space-y-1"),U=x("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Result";let se=x("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");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",Hp(se,o),se.textContent=yo(n.result),D.append(U,se),F.appendChild(D)}if(n.status==="complete"&&typeof n.duration=="number"){let D=x("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(D.style.color=o.contentTextColor),D.textContent=`Duration: ${n.duration}ms`,F.appendChild(D)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),C){C.innerHTML="";let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=te(l?"chevron-up":"chevron-down",16,D,2);U?C.appendChild(U):C.textContent=l?"Hide":"Show"}F.style.display=l?"":"none",B.style.display=l?"none":B.textContent||B.childNodes.length?"":"none"})(),r.append(u,B,F),r};var rr=new Map,$i=e=>{let n=(e.startsWith(Mn)?e.slice(Mn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Pg=e=>e?.approval!==!1?e?.approval:void 0,Rg=(e,t)=>{let n=Pg(t)?.detailsDisplay??"collapsed";return rr.get(e)??n==="expanded"},Ig=(e,t,n)=>{let o=Pg(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let s=te(t?"chevron-up":"chevron-down",14,"currentColor",2);s&&a.appendChild(s)}},Wg=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let a=Rg(e,n);Ig(o,a,n),r.style.display=a?"":"none"};var ji=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",a=x("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",a.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",a.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return a;let s=x("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=x("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=te(p,20,d,2);c&&l.appendChild(c);let u=x("div","persona-flex-1 persona-min-w-0"),g=x("div","persona-flex persona-items-center persona-gap-2"),f=x("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",g.appendChild(f),!r){let C=x("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");C.setAttribute("data-approval-status",n.status),n.status==="approved"?(C.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",C.style.color="var(--persona-palette-colors-success-700, #15803d)",C.textContent="Approved"):n.status==="denied"?(C.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",C.style.color="var(--persona-palette-colors-error-700, #b91c1c)",C.textContent="Denied"):n.status==="timeout"&&(C.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",C.style.color="var(--persona-palette-colors-warning-700, #b45309)",C.textContent="Timeout"),g.appendChild(C)}u.appendChild(g);let S=n.toolType==="webmcp"||n.toolName.startsWith(Mn)?va(n.toolName):void 0,L=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...S?{displayTitle:S}:{},...n.reason?{reason:n.reason}:{}}),E=!n.toolName,M=L||(E?n.description:`The assistant wants to use \u201C${S??$i(n.toolName)}\u201D.`),A=x("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(A.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(A.style.color=o.descriptionColor),A.textContent=M,u.appendChild(A),n.reason){let C=x("p","persona-text-sm persona-mt-1 persona-text-persona-muted");C.setAttribute("data-approval-reason","true"),o?.reasonColor?C.style.color=o.reasonColor:o?.descriptionColor&&(C.style.color=o.descriptionColor);let B=x("span","persona-font-medium");B.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,C.appendChild(B),C.appendChild(document.createTextNode(n.reason)),u.appendChild(C)}let w=o?.detailsDisplay??"collapsed",T=!!n.description&&!E,H=T||!!n.parameters;if(w!=="hidden"&&H){let C=Rg(e.id,t),B=x("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");B.type="button",B.setAttribute("data-expand-header","true"),B.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(B.style.color=o.descriptionColor);let F=x("span");F.setAttribute("data-approval-details-label","true");let q=x("span","persona-inline-flex persona-items-center");q.setAttribute("data-approval-details-chevron","true"),B.append(F,q),Ig(B,C,t),u.appendChild(B);let D=x("div");if(D.setAttribute("data-approval-details","true"),D.style.display=C?"":"none",T){let U=x("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(U.style.color=o.descriptionColor),U.textContent=n.description,D.appendChild(U)}if(n.parameters){let U=x("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(U.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(U.style.color=o.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=yo(n.parameters),D.appendChild(U)}u.appendChild(D)}if(r){let C=x("div","persona-flex persona-gap-2 persona-mt-2");C.setAttribute("data-approval-buttons","true");let B=x("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");B.type="button",B.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",B.style.color=o?.approveButtonTextColor??"#ffffff",B.setAttribute("data-approval-action","approve");let F=te("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);F&&(F.style.marginRight="4px",B.appendChild(F));let q=document.createTextNode(o?.approveLabel??"Approve");B.appendChild(q);let D=x("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");D.type="button",D.style.backgroundColor=o?.denyButtonColor??"transparent",D.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",D.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,D.setAttribute("data-approval-action","deny");let U=te("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);U&&(U.style.marginRight="4px",D.appendChild(U));let se=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(se),C.append(B,D),u.appendChild(C)}return s.append(l,u),a.appendChild(s),a};function Bv(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Hg(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:a=!1,horizontalOffset:s,verticalOffset:l,zIndex:p=2147483e3,onOpen:d,onDismiss:c}=e,u=e.container??Bv(t),g=!1,f=null,h=()=>{if(!g)return;let E=t.getBoundingClientRect();n.style.position="fixed",a&&(n.style.minWidth=`${E.width}px`),s&&(n.style.maxWidth=`${E.width}px`);let M=n.getBoundingClientRect(),A=l?.()??null,w=A!=null?E.top+A:E.top,T=o==="top-start"||o==="top-end"?w-r-M.height:E.bottom+r,C=o==="bottom-end"||o==="top-end"?E.right-M.width:E.left,B=s?.()??null;if(B!=null){let F=Math.max(E.left,E.right-M.width);C=Math.min(Math.max(E.left+B,E.left),F)}n.style.top=`${T}px`,n.style.left=`${C}px`},S=()=>{g&&(g=!1,f&&(f(),f=null),n.remove())},L=()=>{if(g)return;g=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),h();let E=(t.ownerDocument??document).defaultView??window,M=t.ownerDocument??document,A=()=>{if(!t.isConnected){S(),c?.("anchor-removed");return}h()},w=H=>{let C=typeof H.composedPath=="function"?H.composedPath():[];C.includes(n)||C.includes(t)||(S(),c?.("outside"))},T=E.setTimeout(()=>{M.addEventListener("pointerdown",w,!0)},0);E.addEventListener("scroll",A,!0),E.addEventListener("resize",A),f=()=>{E.clearTimeout(T),M.removeEventListener("pointerdown",w,!0),E.removeEventListener("scroll",A,!0),E.removeEventListener("resize",A)},d?.()};return{get isOpen(){return g},open:L,close:S,toggle:()=>g?S():L(),reposition:h,destroy:S}}function Bg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Dv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Dg=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},ar=(e,t)=>{Dg(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Fv=e=>e?.approval!==!1?e?.approval:void 0,Ov=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return rr.get(e)??n==="expanded"},Dp=e=>{let t=x("span","persona-approval-kbd");return t.textContent=e,t},Nv=(e,t)=>{let n=x("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Mn)?va(e.toolName):void 0,a=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(a)return n.textContent=a,n;let s=r??$i(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=s,n.appendChild(p),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},_v=e=>{let t=x("div","persona-approval-resolved"),n=te("ban",15,"currentColor",2);n&&t.appendChild(n);let o=x("span","persona-approval-resolved-name");return o.textContent=e.toolName?$i(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Uv=(e,t,n,o,r,a,s)=>{let l=x("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,g=u&&Ov(t.id,o),f=o?.showDetailsLabel??"Show details",h=o?.hideDetailsLabel??"Hide details",S=x("button","persona-approval-head");S.type="button",u?(S.setAttribute("data-action","toggle-params"),S.setAttribute("aria-expanded",g?"true":"false"),S.setAttribute("aria-label",g?h:f)):S.setAttribute("data-static","true");let L=x("span","persona-approval-logo"),E=te("shield-check",16,"currentColor",2);E&&L.appendChild(E),S.appendChild(L);let M=Nv(n,o);if(u){let B=x("span","persona-approval-toggle");B.setAttribute("aria-hidden","true");let F=te("chevron-down",14,"currentColor",2);F&&B.appendChild(F),M.append(" "),M.appendChild(B)}S.appendChild(M),l.appendChild(S);let A=x("div","persona-approval-body");if(u){let B=x("div","persona-approval-details");if(B.setAttribute("data-role","params"),B.hidden=!g,d){let F=x("p","persona-approval-desc");o?.descriptionColor&&(F.style.color=o.descriptionColor),F.textContent=n.description,B.appendChild(F)}if(c){let F=x("pre","persona-approval-params");o?.parameterBackgroundColor&&(F.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(F.style.color=o.parameterTextColor),F.textContent=yo(n.parameters),B.appendChild(F)}A.appendChild(B)}if(n.reason){let B=x("p","persona-approval-reason");o?.reasonColor?B.style.color=o.reasonColor:o?.descriptionColor&&(B.style.color=o.descriptionColor);let F=x("span","persona-approval-reason-label");F.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,B.append(F,document.createTextNode(n.reason)),A.appendChild(B)}let w=x("div","persona-approval-actions"),T=null,H=B=>{o?.approveButtonColor&&(B.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(B.style.color=o.approveButtonTextColor)},C=x("button","persona-approval-deny");if(C.type="button",C.setAttribute("data-action","deny"),o?.denyButtonColor&&(C.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(C.style.color=o.denyButtonTextColor),C.append(o?.denyLabel??"Deny"),s){let B=x("div","persona-approval-split"),F=x("button","persona-approval-primary");F.type="button",F.setAttribute("data-action","always"),H(F),F.append(o?.approveLabel??"Always allow",Dp("\u23CE"));let q=x("button","persona-approval-caret");q.type="button",q.setAttribute("data-action","toggle-menu"),q.setAttribute("aria-label","More options"),H(q);let D=te("chevron-down",15,"currentColor",2);D&&q.appendChild(D),B.append(F,q),w.append(B,C),C.append(Dp("Esc"));let U=x("div","persona-approval-menu"),se=x("button","persona-approval-menu-item");se.type="button",se.append("Allow once",Dp("\u2318\u23CE")),U.appendChild(se),T=Hg({anchor:B,content:U,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,T),se.addEventListener("click",()=>{ar(e,t.id),r()})}else{let B=x("button","persona-approval-primary persona-approval-primary--solo");B.type="button",B.setAttribute("data-action","allow"),H(B),B.append(o?.approveLabel??"Allow"),w.append(B,C)}return A.appendChild(w),l.appendChild(A),l.addEventListener("click",B=>{let F=B.target instanceof Element?B.target.closest("[data-action]"):null;if(!F)return;let q=F.getAttribute("data-action");if(q==="toggle-params"){let D=l.querySelector('[data-role="params"]');if(D){let U=D.hidden;D.hidden=!U,S.setAttribute("aria-expanded",U?"true":"false"),S.setAttribute("aria-label",U?h:f),rr.set(t.id,U)}return}if(q==="toggle-menu"){T?.toggle();return}if(q==="always"){ar(e,t.id),r({remember:!0});return}if(q==="allow"){ar(e,t.id),r();return}if(q==="deny"){ar(e,t.id),a();return}}),l},Fg=()=>{let e=Dv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:a,config:s})=>{let l=o?.approval;if(!l)return null;let p=Fv(s);if(l.status!=="pending"){if(ar(e,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return _v(l)}Dg(e,o.id);let d=p?.enableAlwaysAllow===!0,c=Uv(e,o,l,p,r,a,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=g=>{Bg(g)||o.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),ar(e,o.id),g.key==="Escape"?a():g.metaKey||g.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])ar(e,o);e.latestPendingApprovalId=null}}};var Og=e=>{let t=[],n=null;return{buttons:t,render:(r,a,s,l,p,d)=>{e.innerHTML="",t.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(l??(a?a.getMessages():[])).some(L=>L.role==="user"))return;let u=document.createDocumentFragment(),g=a?a.isStreaming():!1,f=h=>{switch(h){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'}};if(r.forEach(h=>{let S=x("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");S.type="button",S.textContent=h,S.disabled=g,p?.fontFamily&&(S.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(S.style.fontWeight=p.fontWeight),p?.paddingX&&(S.style.paddingLeft=p.paddingX,S.style.paddingRight=p.paddingX),p?.paddingY&&(S.style.paddingTop=p.paddingY,S.style.paddingBottom=p.paddingY),S.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",c&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:h},bubbles:!0,composed:!0})),a.sendMessage(h))}),u.appendChild(S),t.push(S)}),e.appendChild(u),c){let h=JSON.stringify(r);h!==n&&(n=h,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var $a=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ja=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var qv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Vv=new Set(["step_start","execution_start"]),zv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),$v=new Set(["step_complete","agent_turn_complete"]),jv=new Set(["flow_complete","agent_complete"]),Ng=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Ug=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),dn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,sr=(e,t)=>{let n=e[t];return Ug(n)?n:void 0};function Fp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Gi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Gv(e,t){return typeof t.type=="string"?t.type:e}function Kv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Xv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function _g(e){let t=sr(e,"result"),n=[sr(e,"tokens"),sr(e,"totalTokens"),t?sr(t,"tokens"):void 0,sr(e,"usage"),t?sr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=dn(o.output)??dn(o.outputTokens)??dn(o.completionTokens);if(r!==void 0)return r}return dn(e.outputTokens)??dn(e.completionTokens)??(t?dn(t.outputTokens)??dn(t.completionTokens):void 0)}function Jv(e){let t=sr(e,"result");return dn(e.executionTime)??dn(e.executionTimeMs)??dn(e.execution_time)??dn(e.duration)??(t?dn(t.executionTime)??dn(t.executionTimeMs):void 0)}function Qv(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ga=class{constructor(t=Qv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Gi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!Ug(n)){Ng.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Gv(t,n),r=this.now();if(qv.has(o)){this.startRun(r);return}if(Vv.has(o)){this.run||this.startRun(r);return}if(zv.has(o)){if(!Xv(o,n))return;let a=Kv(n);if(!a)return;this.run||this.startRun(r);let s=this.run;s.firstDeltaAt??(s.firstDeltaAt=r),s.visibleCharCount+=a.length;let l=s.exactOutputTokens+Fp(s.visibleCharCount),p=r-s.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Gi(l,p),outputTokens:l,durationMs:p,source:s.exactOutputTokens>0?"usage":"estimate"};return}if($v.has(o)){if(!this.run)return;let a=this.run,s=_g(n);s!==void 0&&(a.exactOutputTokens+=s,a.visibleCharCount=0);let l=a.exactOutputTokens>0,p=a.exactOutputTokens+Fp(a.visibleCharCount),d=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Gi(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(jv.has(o)){if(!this.run)return;let a=this.run,s=_g(n),l=s??a.exactOutputTokens+Fp(a.visibleCharCount),p=s!==void 0||a.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Gi(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(Ng.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:Jv(n)??o-t.startedAt}};function Vr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Yv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Zv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},eC=["flowName","stepName","reasoningText","text","name","tool","toolName"],tC=100;function nC(e,t){let n={...Yv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Zv}function oC(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function rC(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),a=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${a}`}function aC(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),a=n;for(let s of r)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function sC(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function iC(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function lC(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function dC(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function cC(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let a=t.find(l=>l.renderEventStreamPayload);if(a?.renderEventStreamPayload&&n){let l=a.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>s(),parsedPayload:r});if(l)return l}return s();function s(){let l=x("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=x("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function Op(e,t,n,o,r,a,s,l){let p=r.has(e.id),d=x("div","persona-border-b persona-border-persona-divider persona-text-xs");Vr(d,o.classNames?.eventRow);let c=s.find(g=>g.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let g=c.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>a(e.id)});if(g)return d.appendChild(g),d}return d.appendChild(u()),d;function u(){let g=x("div",""),f=x("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",e.id);let h=x("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=te(p?"chevron-down":"chevron-right","14px","currentColor",2);S&&h.appendChild(S);let L=x("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),E=o.timestampFormat??"relative";L.textContent=E==="relative"?oC(e.timestamp,n):rC(e.timestamp);let M=null;o.showSequenceNumbers!==!1&&(M=x("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(t+1));let A=nC(e.type,o.badgeColors),w=x("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");w.style.backgroundColor=A.bg,w.style.color=A.text,w.style.borderColor=A.text+"50",w.textContent=e.type;let T=o.descriptionFields??eC,H=aC(e.payload,T),C=null;H&&(C=x("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),C.textContent=H);let B=x("div","persona-flex-1 persona-min-w-0"),F=x("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),q=te("clipboard","12px","currentColor",1.5);return q&&F.appendChild(q),F.addEventListener("click",async D=>{D.stopPropagation(),await sC(iC(e)),F.innerHTML="";let U=te("check","12px","currentColor",1.5);U&&F.appendChild(U),setTimeout(()=>{F.innerHTML="";let se=te("clipboard","12px","currentColor",1.5);se&&F.appendChild(se)},1500)}),f.appendChild(h),f.appendChild(L),M&&f.appendChild(M),f.appendChild(w),C&&f.appendChild(C),f.appendChild(B),f.appendChild(F),g.appendChild(f),p&&g.appendChild(cC(e,s,l)),g}}function qg(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:a=[],getThroughput:s}=e,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",u=r?.features?.eventStream??{},g=a.find(h=>h.renderEventStreamView);if(g?.renderEventStreamView&&r){let h=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(h)return{element:h,update:()=>{},destroy:()=>{}}}return f();function f(){let h=u.classNames,S=x("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Vr(S,h?.panel);let L=[],E="",M="",A=null,w=[],T={},H=0,C=Li(),B=0,F=0,q=!1,D=null,U=!1,se=0,le=new Set,Ce=new Map,Le="",ae="",me=null,Z,de,Y,ve,Ae=null,xe=null,Be=null;function Oe(){let _=x("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),j=x("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Vr(j,h?.headerBar),s){xe=x("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),xe.style.cursor="help",Ae=x("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Ae.textContent="-- tok/s",Be=x("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Be.style.display="none",Be.style.pointerEvents="none";let Qe=xe,Po=Be,Ro=()=>{if(!Po.textContent)return;let ns=Qe.getBoundingClientRect(),Yt=_.getBoundingClientRect();Po.style.left=`${ns.left-Yt.left}px`,Po.style.top=`${ns.bottom-Yt.top+4}px`,Po.style.display="block"},sl=()=>{Po.style.display="none"};xe.addEventListener("mouseenter",Ro),xe.addEventListener("mouseleave",sl),xe.appendChild(Ae)}let re=x("div","persona-flex-1");Z=x("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let $e=x("option","");$e.value="",$e.textContent="All events (0)",Z.appendChild($e),de=x("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),de.type="button",de.title="Copy All";let at=te("clipboard-copy","12px","currentColor",1.5);at&&de.appendChild(at);let K=x("span","persona-event-copy-all persona-text-xs");K.textContent="Copy All",de.appendChild(K),xe&&j.appendChild(xe),j.appendChild(re),j.appendChild(Z),j.appendChild(de);let Ue=x("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Vr(Ue,h?.searchBar);let we=te("search","14px","var(--persona-muted, #9ca3af)",1.5),ke=x("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");we&&ke.appendChild(we),Y=x("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Vr(Y,h?.searchInput),Y.type="text",Y.placeholder="Search event payloads...",ve=x("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ve.type="button",ve.style.display="none";let Ee=te("x","12px","currentColor",2);return Ee&&ve.appendChild(Ee),Ue.appendChild(ke),Ue.appendChild(Y),Ue.appendChild(ve),_.appendChild(j),_.appendChild(Ue),Be&&_.appendChild(Be),_}let Ve,Ne=a.find(_=>_.renderEventStreamToolbar);Ne?.renderEventStreamToolbar&&r?Ve=Ne.renderEventStreamToolbar({config:r,defaultRenderer:()=>Oe(),eventCount:t.getSize(),filteredCount:0,onFilterChange:j=>{E=j,Te(),ge()},onSearchChange:j=>{M=j,Te(),ge()}})??Oe():Ve=Oe();let rt=x("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");rt.style.display="none";function Xe(){if(!s||!Ae||!xe)return;let _=s(),j=lC(_);Ae.textContent=j;let re=dC(_);Be&&(Be.textContent=re,re||(Be.style.display="none")),xe.setAttribute("aria-label",re?`Throughput: ${j}, ${re}`:`Throughput: ${j}`)}let Pe=x("div","persona-flex-1 persona-min-h-0 persona-relative"),Se=x("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Se.style.height="100%";let Je=x("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Vr(Je,h?.scrollIndicator),Je.style.display="none",Je.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let cn=te(d,"14px","currentColor",2);cn&&Je.appendChild(cn);let Et=x("span","");Et.textContent=c,Je.appendChild(Et);let xt=x("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");xt.style.display="none",Pe.appendChild(Se),Pe.appendChild(xt),Pe.appendChild(Je),S.setAttribute("tabindex","0"),S.appendChild(Ve),S.appendChild(rt),S.appendChild(Pe);function Re(){let _=t.getAll(),j={};for(let Ue of _)j[Ue.type]=(j[Ue.type]||0)+1;let re=Object.keys(j).sort(),$e=re.length!==w.length||!re.every((Ue,we)=>Ue===w[we]),Me=!$e&&re.some(Ue=>j[Ue]!==T[Ue]),at=_.length!==Object.values(T).reduce((Ue,we)=>Ue+we,0);if(!$e&&!Me&&!at||(w=re,T=j,!Z))return;let K=Z.value;if(Z.options[0].textContent=`All events (${_.length})`,$e){for(;Z.options.length>1;)Z.remove(1);for(let Ue of re){let we=x("option","");we.value=Ue,we.textContent=`${Ue} (${j[Ue]||0})`,Z.appendChild(we)}K&&re.includes(K)?Z.value=K:K&&(Z.value="",E="")}else for(let Ue=1;Ue<Z.options.length;Ue++){let we=Z.options[Ue];we.textContent=`${we.value} (${j[we.value]||0})`}}function fe(){let _=t.getAll();if(E&&(_=_.filter(j=>j.type===E)),M){let j=M.toLowerCase();_=_.filter(re=>re.type.toLowerCase().includes(j)||re.payload.toLowerCase().includes(j))}return _}function Ge(){return E!==""||M!==""}function Te(){H=0,B=0,C.resume(),Je.style.display="none"}function pe(_){le.has(_)?le.delete(_):le.add(_),me=_;let j=Se.scrollTop,re=C.isFollowing();U=!0,C.pause(),ge(),Se.scrollTop=j,re&&C.resume(),U=!1}function ie(){return Eo(Se,50)}function ge(){F=Date.now(),q=!1,Xe(),Re();let _=t.getEvictedCount();_>0?(rt.textContent=`${_.toLocaleString()} older events truncated`,rt.style.display=""):rt.style.display="none",L=fe();let j=L.length,re=t.getSize()>0;j===0&&re&&Ge()?(xt.textContent=M?`No events matching '${M}'`:"No events matching filter",xt.style.display="",Se.style.display="none"):(xt.style.display="none",Se.style.display=""),de&&(de.title=Ge()?`Copy Filtered (${j})`:"Copy All"),p&&!C.isFollowing()&&j>H&&(B+=j-H,Et.textContent=c?`${c}${B>0?` (${B})`:""}`:"",Je.style.display=""),H=j;let $e=t.getAll(),Me=$e.length>0?$e[0].timestamp:0,at=new Set(L.map(we=>we.id));for(let we of le)at.has(we)||le.delete(we);let K=E!==Le||M!==ae,Ue=Ce.size===0&&L.length>0;if(K||Ue||L.length===0){Se.innerHTML="",Ce.clear();let we=document.createDocumentFragment();for(let ke=0;ke<L.length;ke++){let Ee=Op(L[ke],ke,Me,u,le,pe,a,r);Ce.set(L[ke].id,Ee),we.appendChild(Ee)}Se.appendChild(we),Le=E,ae=M,me=null}else{if(me!==null){let ke=Ce.get(me);if(ke&&ke.parentNode===Se){let Ee=L.findIndex(Qe=>Qe.id===me);if(Ee>=0){let Qe=Op(L[Ee],Ee,Me,u,le,pe,a,r);Se.insertBefore(Qe,ke),ke.remove(),Ce.set(me,Qe)}}me=null}let we=new Set(L.map(ke=>ke.id));for(let[ke,Ee]of Ce)we.has(ke)||(Ee.remove(),Ce.delete(ke));for(let ke=0;ke<L.length;ke++){let Ee=L[ke];if(!Ce.has(Ee.id)){let Qe=Op(Ee,ke,Me,u,le,pe,a,r);Ce.set(Ee.id,Qe),Se.appendChild(Qe)}}}C.isFollowing()&&(Se.scrollTop=Se.scrollHeight)}function bt(){if(Date.now()-F>=tC){D!==null&&(cancelAnimationFrame(D),D=null),ge();return}q||(q=!0,D=requestAnimationFrame(()=>{D=null,ge()}))}let he=(_,j)=>{if(!de)return;de.innerHTML="";let re=te(_,"12px","currentColor",1.5);re&&de.appendChild(re);let $e=x("span","persona-text-xs");$e.textContent="Copy All",de.appendChild($e),setTimeout(()=>{de.innerHTML="";let Me=te("clipboard-copy","12px","currentColor",1.5);Me&&de.appendChild(Me);let at=x("span","persona-text-xs");at.textContent="Copy All",de.appendChild(at),de.disabled=!1},j)},ce=async()=>{if(de){de.disabled=!0;try{let _;Ge()?_=L:n?(_=await n(),_.length===0&&(_=t.getAll())):_=t.getAll();let j=_.map(re=>{try{return JSON.parse(re.payload)}catch{return re.payload}});await navigator.clipboard.writeText(JSON.stringify(j,null,2)),he("check",1500)}catch{he("x",1500)}}},yn=()=>{Z&&(E=Z.value,Te(),ge())},Q=()=>{!Y||!ve||(ve.style.display=Y.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{M=Y.value,Te(),ge()},150))},R=()=>{!Y||!ve||(Y.value="",M="",ve.style.display="none",A&&clearTimeout(A),Te(),ge())},z=()=>{if(U)return;let _=Se.scrollTop,{action:j,nextLastScrollTop:re}=Pi({following:C.isFollowing(),currentScrollTop:_,lastScrollTop:se,nearBottom:ie(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});se=re,j==="resume"?(C.resume(),B=0,Je.style.display="none"):j==="pause"&&(C.pause(),p&&(Et.textContent=c,Je.style.display=""))},b=_=>{let j=Ri({following:C.isFollowing(),deltaY:_.deltaY,nearBottom:ie(),resumeWhenNearBottom:!0});j==="pause"?(C.pause(),p&&(Et.textContent=c,Je.style.display="")):j==="resume"&&(C.resume(),B=0,Je.style.display="none")},P=()=>{p&&(Se.scrollTop=Se.scrollHeight,C.resume(),B=0,Je.style.display="none")},I=_=>{let j=_.target;if(!j||j.closest("button"))return;let re=j.closest("[data-event-id]");if(!re)return;let $e=re.getAttribute("data-event-id");$e&&pe($e)},N=_=>{if((_.metaKey||_.ctrlKey)&&_.key==="f"){_.preventDefault(),Y?.focus(),Y?.select();return}_.key==="Escape"&&(Y&&document.activeElement===Y?(R(),Y.blur(),S.focus()):o&&o())};de&&de.addEventListener("click",ce),Z&&Z.addEventListener("change",yn),Y&&Y.addEventListener("input",Q),ve&&ve.addEventListener("click",R),Se.addEventListener("scroll",z),Se.addEventListener("wheel",b,{passive:!0}),Se.addEventListener("click",I),Je.addEventListener("click",P),S.addEventListener("keydown",N);function G(){A&&clearTimeout(A),D!==null&&(cancelAnimationFrame(D),D=null),q=!1,Ce.clear(),de&&de.removeEventListener("click",ce),Z&&Z.removeEventListener("change",yn),Y&&Y.removeEventListener("input",Q),ve&&ve.removeEventListener("click",R),Se.removeEventListener("scroll",z),Se.removeEventListener("wheel",b),Se.removeEventListener("click",I),Je.removeEventListener("click",P),S.removeEventListener("keydown",N)}return{element:S,update:bt,destroy:G}}}function Vg(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let a=[],s=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let g=u;return a.findIndex(f=>f===g||f.contains(g))},d=u=>{let g=p(u.target);if(g<0)return;let f=g;if(u.key===r)f=Math.min(g+1,a.length-1);else if(u.key===o)f=Math.max(g-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=a.length-1;else return;u.preventDefault(),f!==g&&t.onSelect(f)},c=u=>{let g=p(u.target);g>=0&&l(a[g])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){s=typeof document<"u"&&e.contains(document.activeElement)},render(u,g){if(a=u,u.forEach((f,h)=>{f.setAttribute("role","tab");let S=h===g;f.setAttribute("aria-selected",S?"true":"false"),f.tabIndex=S||g<0&&h===0?0:-1}),s){let f=(g>=0?u[g]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function zg(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",a=n?.toolbarTitle??"Artifacts",s=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=Q=>({start:Q===!1?!1:typeof Q=="object"&&Q?Q.start!==!1:!0,end:Q===!1?!1:typeof Q=="object"&&Q?Q.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),g=typeof document<"u"?x("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{g?.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"),U?.hide()};g&&g.addEventListener("click",()=>{f(),t.onDismiss?.()});let h=x("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");h.setAttribute("data-persona-theme-zone","artifact-pane"),r&&h.classList.add("persona-artifact-pane-document");let S=x("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");S.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&S.classList.add("persona-artifact-toolbar-document");let L=x("span","persona-text-xs persona-font-medium persona-truncate");L.textContent=a;let E=Tt({icon:"x",label:s});E.addEventListener("click",()=>{f(),t.onDismiss?.()});let M="rendered",A=Br({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:Q=>{M=Q==="source"?"source":"rendered",he()}}),w=x("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),T=n?.documentToolbarShowCopyLabel===!0,H=n?.documentToolbarShowCopyChevron===!0,C=n?.documentToolbarCopyMenuItems,B=!!(H&&C&&C.length>0),F=null,q,D=null,U=null;if(r&&(T||H)&&!B){if(q=T?Xn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H){let Q=te("chevron-down",14,"currentColor",2);Q&&q.appendChild(Q)}}else r&&B?(F=x("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),q=T?Xn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=Tt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),F.append(q,D)):r?q=Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(q=Tt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&q.classList.add("persona-hidden"));let se=r?Tt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Tt({icon:"refresh-cw",label:"Refresh"}),le=r?Tt({icon:"x",label:s,className:"persona-artifact-doc-icon-btn"}):Tt({icon:"x",label:s}),Ce=Tt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Ce.classList.add("persona-hidden");let Le=x("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ae=e.features?.artifacts?.toolbarActions??[],me=()=>{let Q=Pe.find(P=>P.id===Se)??Pe[Pe.length-1],R=Q?.id??null,z=Q?.artifactType==="markdown"?Q.markdown??"":"",b=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:z,jsonPayload:b,id:R}},Z=async()=>{let Q=Pe.find(R=>R.id===Se)??Pe[Pe.length-1];try{await navigator.clipboard.writeText(Oa(Q))}catch{}};if(q.addEventListener("click",async()=>{let Q=n?.onDocumentToolbarCopyMenuSelect;if(Q&&B){let{markdown:R,jsonPayload:z,id:b}=me();try{await Q({actionId:"primary",artifactId:b,markdown:R,jsonPayload:z})}catch{}return}await Z()}),D&&C?.length){let Q=()=>h.closest("[data-persona-root]")??document.body,R=()=>{U=Mo({items:C.map(z=>({id:z.id,label:z.label})),onSelect:async z=>{let{markdown:b,jsonPayload:P,id:I}=me(),N=n?.onDocumentToolbarCopyMenuSelect;try{N?await N({actionId:z,artifactId:I,markdown:b,jsonPayload:P}):z==="markdown"||z==="md"?await navigator.clipboard.writeText(b):z==="json"||z==="source"?await navigator.clipboard.writeText(P):await navigator.clipboard.writeText(b||P)}catch{}},anchor:F??D,position:"bottom-right",portal:Q()})};h.isConnected?R():requestAnimationFrame(R),D.addEventListener("click",z=>{z.stopPropagation(),U?.toggle()})}se.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}he()}),le.addEventListener("click",()=>{f(),t.onDismiss?.()});let de=x("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)S.replaceChildren(),F?w.append(F,se,le):w.append(q,se,le),w.insertBefore(Le,le),w.insertBefore(Ce,le),S.append(A.element,de,w);else{let Q=x("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");Q.append(q,Le,Ce,E),S.appendChild(L),S.appendChild(Q)}l&&(S.style.paddingLeft=l,S.style.paddingRight=l);let Y=x("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&Y.style.setProperty("--persona-artifact-tab-fade-size",p);let ve=e.features?.artifacts?.renderTabBar,Ae=x("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),xe=Vg(Y,{onSelect:Q=>t.onSelect(Pe[Q].id)}),Be=Q=>{let R=Q.scrollWidth-Q.clientWidth,z=R>1,b=Math.abs(Q.scrollLeft);Q.classList.toggle("persona-artifact-tab-fade-start",c&&z&&b>1),Q.classList.toggle("persona-artifact-tab-fade-end",u&&z&&b<R-1)},Oe=0,Ve=()=>{if(Oe)return;let Q=()=>{Oe=0,Be(Y)};Oe=typeof requestAnimationFrame=="function"?requestAnimationFrame(Q):setTimeout(Q,0)};Y.addEventListener("scroll",()=>Ve(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Be(Y)).observe(Y);let Ne=x("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),rt=()=>{Ne.scrollLeft=0},Xe=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(rt):setTimeout(rt,0)};if(l){for(let Q of[Y,Ae])Q.style.paddingLeft=l,Q.style.paddingRight=l;Ne.style.padding=l}h.appendChild(S),h.appendChild(Y),h.appendChild(Ae),h.appendChild(Ne);let Pe=[],Se=null,Je=!1,cn=!1,Et=!0,xt=!1,Re=null,fe="",Ge=null,Te=!1,pe=Q=>Q.artifactType==="markdown"&&!!Q.file||r?M:"rendered",ie=Q=>{r||(Q&&!Te?(S.insertBefore(A.element,L),Te=!0):!Q&&Te&&(A.element.remove(),Te=!1))},ge=()=>Se&&Pe.find(Q=>Q.id===Se)||Pe[Pe.length-1],bt=()=>{let Q=Da(ge());if(!Q){Le.replaceChildren();return}let R=ae.filter(z=>z.visible===void 0||z.visible(Q)).map(z=>Dr(z,{documentChrome:r,onClick:()=>{let b=Da(ge());if(b)try{Promise.resolve(z.onClick(b)).catch(()=>{})}catch{}}}));Le.replaceChildren(...R)},he=()=>{bt();let Q=r&&Pe.length<=1,R=!!ve;if(Y.classList.toggle("persona-hidden",Q||R),Ae.classList.toggle("persona-hidden",Q||!R),R&&ve){let P=Pe.map(I=>I.id).join("|")+" "+(Se??"");if(P!==fe){fe=P;let I=ve({records:Pe,selectedId:Se,onSelect:t.onSelect});Ae.firstElementChild!==I&&Ae.replaceChildren(I)}}else{xe.beforeRender(),Y.replaceChildren();let P=[],I=-1;for(let[N,G]of Pe.entries()){let _=x("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");_.type="button";let j=G.artifactType==="markdown"?G.file:void 0,re=j?Wn(j.path):G.title||G.id.slice(0,8),$e=j?.path||G.title||re;_.textContent=re,_.title=$e,_.setAttribute("aria-label",$e),G.id===Se&&(_.classList.add("persona-bg-persona-container","persona-border-persona-border"),I=N),_.addEventListener("click",()=>t.onSelect(G.id)),Y.appendChild(_),P.push(_)}if(xe.render(P,I),I>=0&&Se!==Re){Re=Se;let N=P[I];typeof N.scrollIntoView=="function"&&N.scrollIntoView({block:"nearest",inline:"nearest"})}Be(Y)}let z=Se&&Pe.find(P=>P.id===Se)||Pe[Pe.length-1];if(!z){Ne.replaceChildren(),Ge=null,ie(!1);return}let b=z.artifactType==="markdown"?z.file:void 0;if(ie(!!b),r){let P=b?Ao(b):z.artifactType==="markdown"?"MD":z.component??"Component",I=(z.title||"Document").trim(),N=b?Wn(b.path):I.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";de.textContent=`${N} \xB7 ${P}`}else L.textContent=b?Wn(b.path):a;Ge?(Ge.el.parentElement!==Ne&&Ne.replaceChildren(Ge.el),Ge.update(z)):(Ge=Ei(z,{config:e,resolveViewMode:pe}),Ne.replaceChildren(Ge.el)),Ne.classList.toggle("persona-artifact-content-flush",!!Ne.querySelector(".persona-code-pre"))},ce=()=>{let Q=Pe.length>0;if(h.classList.toggle("persona-hidden",!Q),g){let b=((typeof h.closest=="function"?h.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;Q&&b&&Je?(g.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},yn=()=>{xt=!1,he(),ce()};return{element:h,backdrop:g,update(Q){let R=Q.selectedId??Q.artifacts[Q.artifacts.length-1]?.id??null,z=R!==Se;Pe=Q.artifacts,Se=R,Pe.length>0&&(Je=!0),xt=!0,Et&&yn(),z&&rt()},setMobileOpen(Q){Je=Q,!Q&&g?(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):ce()},setExpanded(Q){Q!==cn&&(cn=Q,Xe());let R=te(Q?"minimize":"maximize",16,"currentColor",2);R&&Ce.replaceChildren(R);let z=Q?"Collapse artifacts panel":"Expand artifacts panel";Ce.setAttribute("aria-label",z),Ce.title=z},setExpandToggleVisible(Q){Ce.classList.toggle("persona-hidden",!Q)},setCopyButtonVisible(Q){r||q.classList.toggle("persona-hidden",!Q)},setCustomActions(Q){ae=Q,bt()},setTabFade(Q){let R=d(Q);R.start===c&&R.end===u||(c=R.start,u=R.end,Be(Y))},setRenderTabBar(Q){Q!==ve&&(ve=Q,fe="",he())},setVisible(Q){Q!==Et&&(Et=Q,Q&&xt&&yn())}}}function Jt(e){return e?.features?.artifacts?.enabled===!0}function $g(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"),!Jt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function pC(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 jg=["panel","seamless","detached"];function Np(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&jg.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function _p(e){return!e||!Jt(e)?!1:Np(e)==="detached"}function Ka(e,t){if(!Jt(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-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),pC(e),$g(e,t);return}let n=t.features?.artifacts?.layout,o=Np(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let a=n?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=n?.documentToolbarIconColor?.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),$g(e,t)}function Xa(e,t){for(let l of jg)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Jt(t))return;let n=t.features?.artifacts?.layout,o=Np(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let a=n?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=n?.chatShadow?.trim();s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}function Gg(e,t){return!t||!Jt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function uC(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function fC(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 mC(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function gC(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Up(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function Kg(e,t,n,o,r,a){let s=uC(r,200),l=gC(t,n,o,200);l=Math.max(s,l);let p=fC(a);return p!==null&&(l=Math.min(l,p)),mC(e,s,l)}var Xg={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},qp=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(a=>{if(a.dataset.enhanced==="true")return;let s=a.dataset.tvForm??"init";a.dataset.enhanced="true";let l=Xg[s]??Xg.init;a.classList.add("persona-form-card","persona-space-y-4");let p=x("div","persona-space-y-1"),d=x("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let h=x("p","persona-text-sm persona-text-persona-muted");h.textContent=l.description,p.appendChild(h)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(h=>{let S=x("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${t.id}-${s}-${h.name}`;let L=x("span","persona-text-xs persona-font-medium persona-text-persona-muted");L.textContent=h.label,S.appendChild(L);let E=h.type??"text",M;E==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=E),M.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",M.id=`${t.id}-${s}-${h.name}`,M.name=h.name,M.placeholder=h.placeholder??"",h.required&&(M.required=!0),S.appendChild(M),c.appendChild(S)});let u=x("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=x("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=x("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=l.submitLabel??"Submit",u.appendChild(g),u.appendChild(f),c.appendChild(u),a.replaceChildren(p,c),c.addEventListener("submit",async h=>{h.preventDefault();let S=n.formEndpoint??"/form",L=new FormData(c),E={};L.forEach((M,A)=>{E[A]=M}),E.type=s,f.disabled=!0,g.textContent="Submitting\u2026";try{let M=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let A=await M.json();g.textContent=A.message??"Thanks! We'll be in touch soon.",A.success&&A.nextPrompt&&await o.sendMessage(String(A.nextPrompt))}catch(M){g.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Vp=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 n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(a=>a.id));return[...n.filter(a=>!o.has(a.id)),...t].sort((a,s)=>(s.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Ja=new Vp;var Jg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hC=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),Qg=(e,t,n)=>{if(!Jg(e)||!Jg(t)||hC.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let a=n?`${n}.${r}`:r;o[r]=Qg(e[r],t[r],a)}return o};function Ki(e,t){let n=Qg(e,t,"");return Rr(n)}var Yg=()=>{let e=new Map,t=(r,a)=>(e.has(r)||e.set(r,new Set),e.get(r).add(a),()=>n(r,a)),n=(r,a)=>{e.get(r)?.delete(a)};return{on:t,off:n,emit:(r,a)=>{e.get(r)?.forEach(s=>{try{s(a)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var yC=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},xC=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let a=t[r];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Qa=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=yC(e),n=xC(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...a}=o;return{type:String(r),payload:a,raw:o}}catch{return null}},zp=e=>typeof e=="string"?e:e==null?"":String(e),ir={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:zp(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=zp(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:zp(n.text)}}},Zg=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ya=e=>{let t=new Set(Zg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Zg(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&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 l=s?e.parsers.reduce((d,c)=>d||c?.({text:s,message:a.message})||null,null):null;if(!l)return null;t.add(a.message.id),o();let p={action:l,message:a.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(l,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var bC=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}},vC=e=>e.map(t=>({...t,streaming:!1})),CC=e=>e.map(t=>({...t,status:"complete"})),Xi=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?bC(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?vC(n.messages):void 0,artifacts:n.artifacts?CC(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var zr=po(Ds(),1);function wC(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function AC(e,t){if(!wC(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Ji(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=(0,zr.parse)(n,zr.STR|zr.OBJ),a=AC(r,n);a&&(e=a)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function eh(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Qi(e,t){let{config:n,message:o,onPropsUpdate:r}=t,a=En.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return a(e.props,s)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function th(){let e=Ji();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function nh(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 Za(e){let t=nh(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Yi(e){let t=nh(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var SC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Zi(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:d=SC}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,f.appendChild(h);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,f.appendChild(S),g.appendChild(f);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-csat",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let H=1;H<=5;H++){let C=document.createElement("button");C.type="button",C.className="persona-feedback-rating-btn persona-feedback-star-btn",C.setAttribute("role","radio"),C.setAttribute("aria-checked","false"),C.setAttribute("aria-label",`${H} star${H>1?"s":""}: ${d[H-1]}`),C.title=d[H-1],C.dataset.rating=String(H),C.innerHTML=`
|
|
46
46
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
47
47
|
<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>
|
|
48
48
|
</svg>
|
|
49
|
-
`,v.addEventListener("click",()=>{u=R,k.forEach((B,F)=>{let $=F<R;B.classList.toggle("selected",$),B.setAttribute("aria-checked",F===R-1?"true":"false")})}),k.push(v),E.appendChild(v)}g.appendChild(E);let M=null;if(p){let R=document.createElement("div");R.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=a,M.rows=3,M.setAttribute("aria-label","Additional comments"),R.appendChild(M),g.appendChild(R)}let A=document.createElement("div");A.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=l,w.addEventListener("click",()=>{n?.(),d.remove()});let T=document.createElement("button");return T.type="button",T.className="persona-feedback-btn persona-feedback-btn-submit",T.textContent=s,T.addEventListener("click",async()=>{if(u===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let R=M?.value.trim()||void 0;await t(u,R),d.remove()}catch(R){T.disabled=!1,T.textContent=s,console.error("[CSAT Feedback] Failed to submit:",R)}}),A.appendChild(w),A.appendChild(T),g.appendChild(A),d.appendChild(g),d}function ol(e){let{onSubmit:t,onDismiss:n,title:o="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:s="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:c="Not likely",highLabel:d="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let S=document.createElement("h3");S.className="persona-feedback-title",S.textContent=o,h.appendChild(S);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=r,h.appendChild(E),f.appendChild(h);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 M=document.createElement("div");M.className="persona-feedback-labels";let A=document.createElement("span");A.className="persona-feedback-label-low",A.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=d,M.appendChild(A),M.appendChild(w);let T=document.createElement("div");T.className="persona-feedback-numbers";let R=[];for(let N=0;N<=10;N++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${N} out of 10`),U.textContent=String(N),U.dataset.rating=String(N),N<=6?U.classList.add("persona-feedback-detractor"):N<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{g=N,R.forEach((fe,ce)=>{fe.classList.toggle("selected",ce===N),fe.setAttribute("aria-checked",ce===N?"true":"false")})}),R.push(U),T.appendChild(U)}k.appendChild(M),k.appendChild(T),f.appendChild(k);let v=null;if(p){let N=document.createElement("div");N.className="persona-feedback-comment-container",v=document.createElement("textarea"),v.className="persona-feedback-comment",v.placeholder=a,v.rows=3,v.setAttribute("aria-label","Additional comments"),N.appendChild(v),f.appendChild(N)}let B=document.createElement("div");B.className="persona-feedback-actions";let F=document.createElement("button");F.type="button",F.className="persona-feedback-btn persona-feedback-btn-skip",F.textContent=l,F.addEventListener("click",()=>{n?.(),u.remove()});let $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=s,$.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let N=v?.value.trim()||void 0;await t(g,N),u.remove()}catch(N){$.disabled=!1,$.textContent=s,console.error("[NPS Feedback] Failed to submit:",N)}}),B.appendChild(F),B.appendChild($),f.appendChild(B),u.appendChild(f),u}var Xr="persona-chat-history",hv=30*1e3,yv=641,xv={"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 bv(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let a=xv[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 o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function rl(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 Cv(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 vv(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var zp=e=>!e||typeof e!="object"?{}:{...e},Qg=e=>e.map(t=>({...t,streaming:!1})),Yg=(e,t,n)=>{let o=e?.markdown?Xo(e.markdown):null,r=Tr(e?.sanitize);return 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."),a=>{let s=a.text??"",l=a.message.rawContent??null;if(t){let d=t.process({text:s,raw:l??s,message:a.message,streaming:a.streaming});d!==null&&(s=d.text,d.persist||(a.message.__skipPersist=!0),d.resubmit&&!a.streaming&&n&&n())}let p=zn()!==null,c;if(e?.postprocessMessage){let d=e.postprocessMessage({...a,text:s,raw:l??a.text??""});c=r?r(d):d}else if(o){let d=a.streaming?kf(s):s,u=o(d);c=r&&p?r(u):u}else c=Wn(s);return c}};function Zg(e){let t=y("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 n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",a=e?.iconStrokeWidth??.5,s=te(n,o,r,a);if(s&&t.appendChild(s),e?.label){let l=y("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var wv=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];n[o]=a?{...a,...r}:r}return n},Av=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:wv(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),al=(e,t,n)=>{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 o=Br(t),r=ns.getForInstance(o.plugins),{plugin:a,teardown:s}=Rg();o.components&&kn.registerAll(o.components);let l=jg(),c=o.persistState===!1?null:o.storageAdapter??Yi(),d={},u=null,g=!1,f=i=>{if(o.onStateLoaded)try{let m=o.onStateLoaded(i);if(m&&typeof m=="object"&&"state"in m){let{state:x,open:C}=m;return C&&(g=!0),x}return m}catch(m){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return i};if(c?.load)try{let i=c.load();if(i&&typeof i.then=="function")u=i.then(m=>f(m??{messages:[],metadata:{}}));else{let x=f(i??{messages:[],metadata:{}});x.metadata&&(d=zp(x.metadata)),x.messages?.length&&(o={...o,initialMessages:x.messages}),x.artifacts?.length&&(o={...o,initialArtifacts:x.artifacts,initialSelectedArtifactId:x.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=f({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let h=()=>d,S=i=>{d=i({...d})??{},Ml()},E=o.actionParsers&&o.actionParsers.length?o.actionParsers:[os],k=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[pr.message,pr.messageAndClick],M=rs({parsers:E,handlers:k,getSessionMetadata:h,updateSessionMetadata:S,emit:l.emit,documentRef:typeof document<"u"?document:null});M.syncFromMetadata();let A=o.launcher?.enabled??!0,w=o.launcher?.autoExpand??!1,T=o.autoFocusInput??!1,R=w,v=A,B=o.layout?.header?.layout,F=!1,$=()=>Po(o),N=()=>A||$(),U=$()?!1:A?w:!0,fe=!1,ce=null,Le=()=>{fe=!0,ce&&clearTimeout(ce),ce=setTimeout(()=>{fe&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),fe=!1)},1e4)},De=Yg(o,M,Le),ae=o.features?.showReasoning??!0,Ce=o.features?.showToolCalls??!0,ee=o.features?.showEventStreamToggle??!1,le=o.features?.scrollToBottom??{},Y=o.features?.scrollBehavior??{},Ae=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,be=ee?new Ya(Ae):null,He=o.features?.eventStream?.maxEvents??2e3,Ne=ee?new Qa(He,be):null,Xe=ee?new Za:null,Oe=null,lt=!1,Ye=null,Pe=0;be?.open().then(()=>Ne?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Se={onCopy:i=>{l.emit("message:copy",i),z?.isClientTokenMode()&&z.submitMessageFeedback(i.id,"copy").catch(m=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",m)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{l.emit("message:feedback",i),z?.isClientTokenMode()&&z.submitMessageFeedback(i.messageId,i.type).catch(m=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",m)}),o.messageActions?.onFeedback?.(i)}},Ze=o.statusIndicator??{},un=i=>i==="idle"?Ze.idleText??Ht.idle:i==="connecting"?Ze.connectingText??Ht.connecting:i==="connected"?Ze.connectedText??Ht.connected:i==="error"?Ze.errorText??Ht.error:i==="paused"?Ze.pausedText??Ht.paused:i==="resuming"?Ze.resumingText??Ht.resuming:Ht[i];function kt(i,m,x,C){if(C==="idle"&&x.idleLink){i.textContent="";let P=document.createElement("a");P.href=x.idleLink,P.target="_blank",P.rel="noopener noreferrer",P.textContent=m,P.style.color="inherit",P.style.textDecoration="none",i.appendChild(P)}else i.textContent=m}let xt=hg({config:o,showClose:N()}),{wrapper:Re,panel:me,pillRoot:Je}=xt.shell,Ee=xt.panelElements,{container:ue,body:se,messagesWrapper:ye,suggestions:bt,textarea:ge,sendButton:pe,sendButtonWrapper:xn,composerForm:Q,statusText:I,introTitle:q,introSubtitle:b,closeButton:L,iconHolder:W,headerTitle:O,headerSubtitle:G,header:_,footer:j,actionsRow:ne,rightActions:Ge}=Ee,Me=Ee.leftActions,dt=Ee.setSendButtonMode,K=Ee.micButton,Ue=Ee.micButtonWrapper,Te=Ee.attachmentButton,Ie=Ee.attachmentButtonWrapper,ke=Ee.attachmentInput,et=Ee.attachmentPreviewsContainer;ue.classList.add("persona-relative"),se.classList.add("persona-relative");let Ro=12,Io=()=>le.label??"",dl=()=>le.iconName??"arrow-down",ls=()=>le.enabled!==!1,Zt=()=>Y.mode??"anchor-top",Yn=()=>Zt()==="follow"||Zt()==="anchor-top"&&aa,su=()=>Y.anchorTopOffset??16,Nh=()=>Y.restorePosition??"bottom",iu=()=>Y.pauseOnInteraction===!0,lu=()=>Y.showActivityWhilePinned!==!1,du=()=>Y.announce===!0,It=y("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");It.type="button",It.style.display="none",It.setAttribute("data-persona-scroll-to-bottom","true");let Qr=y("span","persona-flex persona-items-center"),cl=y("span",""),Wo=y("span","");Wo.setAttribute("data-persona-scroll-to-bottom-count",""),Wo.style.display="none",It.append(Qr,cl,Wo),ue.appendChild(It);let Zn=y("div","persona-stream-anchor-spacer");Zn.setAttribute("aria-hidden","true"),Zn.setAttribute("data-persona-anchor-spacer",""),Zn.style.flexShrink="0",Zn.style.pointerEvents="none",Zn.style.height="0px",se.appendChild(Zn);let Ho=y("div","persona-sr-only");Ho.setAttribute("aria-live","polite"),Ho.setAttribute("aria-atomic","true"),Ho.setAttribute("role","status"),Ho.setAttribute("data-persona-live-region",""),Object.assign(Ho.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(Ho);let Yr=null,ds=null,cu=i=>{!du()||!i||(ds=i,Yr===null&&(Yr=setTimeout(()=>{Yr=null,ds&&du()&&(Ho.textContent=ds),ds=null},400)))},ur=()=>{let m=j.style.display==="none"?0:j.offsetHeight;It.style.bottom=`${m+Ro}px`};ur();let pu=()=>{let i=!!Io();It.setAttribute("aria-label",Io()||"Jump to latest"),It.title=Io(),It.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Qr.innerHTML="";let m=te(dl(),"14px","currentColor",2);m?(Qr.appendChild(m),Qr.style.display=""):Qr.style.display="none",cl.textContent=Io(),cl.style.display=i?"":"none"};pu();let Mt=null,on=null,uu=null,fu=r.find(i=>i.renderHeader);if(fu?.renderHeader){let i=fu.renderHeader({config:o,defaultRenderer:()=>{let m=Qn({config:o,showClose:N()});return sr(ue,m,o),m.header},onClose:()=>mt(!1,"user")});if(i){let m=ue.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(i),_=i,xt.header.element=i)}}let pl=()=>{if(!Ne)return;if(lt=!0,!Oe&&Ne&&(Oe=Dg({buffer:Ne,getFullHistory:()=>Ne.getAllFromStore(),onClose:()=>Zr(),config:o,plugins:r,getThroughput:()=>Xe?.getMetric()??{status:"idle"}})),Oe&&(se.style.display="none",j.parentNode?.insertBefore(Oe.element,j),Oe.update()),st){st.style.boxShadow=`inset 0 0 0 1.5px ${Jt.actionIconColor}`;let m=o.features?.eventStream?.classNames?.toggleButtonActive;m&&m.split(/\s+/).forEach(x=>x&&st.classList.add(x))}let i=()=>{if(!lt)return;let m=Date.now();m-Pe>=200&&(Oe?.update(),Pe=m),Ye=requestAnimationFrame(i)};Pe=0,Ye=requestAnimationFrame(i),an(),l.emit("eventStream:opened",{timestamp:Date.now()})},Zr=()=>{if(lt){if(lt=!1,Oe&&Oe.element.remove(),se.style.display="",st){st.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(m=>m&&st.classList.remove(m))}Ye!==null&&(cancelAnimationFrame(Ye),Ye=null),an(),l.emit("eventStream:closed",{timestamp:Date.now()})}},st=null;if(ee){let i=o.features?.eventStream?.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");st=y("button",m),st.style.width="28px",st.style.height="28px",st.style.color=Jt.actionIconColor,st.type="button",st.setAttribute("aria-label","Event Stream"),st.title="Event Stream";let x=te("activity","18px","currentColor",1.5);x&&st.appendChild(x);let C=Ee.clearChatButtonWrapper,P=Ee.closeButtonWrapper,H=C||P;H&&H.parentNode===_?_.insertBefore(st,H):_.appendChild(st),st.addEventListener("click",()=>{lt?Zr():pl()})}let Oh=i=>{let m=o.attachments;if(!m?.enabled)return;let x=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!x){x=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),x.setAttribute("data-persona-composer-attachment-previews",""),x.style.display="none";let P=i.querySelector("[data-persona-composer-form]");P?.parentNode?P.parentNode.insertBefore(x,P):i.insertBefore(x,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let P=y("input");P.type="file",P.setAttribute("data-persona-composer-attachment-input",""),P.accept=(m.allowedTypes??Xn).join(","),P.multiple=(m.maxFiles??4)>1,P.style.display="none",P.setAttribute("aria-label",m.buttonTooltipText??"Attach files"),i.appendChild(P)}},mu=r.find(i=>i.renderComposer);if(mu?.renderComposer){let i=o.composer,m=mu.renderComposer({config:o,defaultRenderer:()=>Vr({config:o}).footer,onSubmit:x=>{if(!z||z.isStreaming())return;let C=x.trim(),P=Mt?.hasAttachments()??!1;if(!C&&!P)return;Vu();let H;P&&(H=[],H.push(...Mt.getContentParts()),C&&H.push(bo(C))),z.sendMessage(C,{contentParts:H}),P&&Mt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ke?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:x=>{o.composer={...o.composer,selectedModelId:x},o.agent&&(o.agent={...o.agent,model:x})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{uu?.()}:void 0});m&&(xt.replaceComposer(m),j=xt.composer.footer)}let _h=i=>{let m=(...ie)=>{for(let re of ie){let xe=i.querySelector(re);if(xe)return xe}return null},x=i.querySelector("[data-persona-composer-form]"),C=i.querySelector("[data-persona-composer-input]"),P=i.querySelector("[data-persona-composer-submit]"),H=i.querySelector("[data-persona-composer-mic]"),J=i.querySelector("[data-persona-composer-status]");x&&(Q=x),C&&(ge=C),P&&(pe=P),H&&(K=H,Ue=H.parentElement),J&&(I=J);let V=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(bt=V);let X=m("[data-persona-composer-attachment-button]",".persona-attachment-button");X&&(Te=X,Ie=X.parentElement),ke=m("[data-persona-composer-attachment-input]",'input[type="file"]'),et=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let oe=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");oe&&(ne=oe),Me=m(".persona-widget-composer__left-actions")};Oh(j),_h(j);let eo=o.layout?.contentMaxWidth??($()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(eo&&(ye.style.maxWidth=eo,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%"),eo&&Q&&!$()&&(Q.style.maxWidth=eo,Q.style.marginLeft="auto",Q.style.marginRight="auto"),eo&&bt&&!$()&&(bt.style.maxWidth=eo,bt.style.marginLeft="auto",bt.style.marginRight="auto"),eo&&et&&!$()&&(et.style.maxWidth=eo,et.style.marginLeft="auto",et.style.marginRight="auto"),o.attachments?.enabled&&ke&&et){Mt=nr.fromConfig(o.attachments),Mt.setPreviewsContainer(et),ke.addEventListener("change",x=>{let C=x.target;Mt?.handleFileSelect(C.files),C.value=""});let i=o.attachments.dropOverlay,m=Zg(i);ue.appendChild(m)}let Uh=()=>on?.prefetch();if(o.contextMentions?.enabled&&ge&&(on=km({config:o,textarea:ge,anchor:Q??ge,getMessages:()=>z.getMessages(),liveRegionHost:ue}),on)){let i=ge;i.parentElement?.insertBefore(on.contextRow,i);let m=on.affordanceButtons;for(let x=m.length-1;x>=0;x--){let C=m[x];Me?Me.insertBefore(C,Me.firstChild):Q?.appendChild(C)}}(()=>{let i=o.layout?.slots??{},m=C=>{switch(C){case"body-top":return ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ye;case"footer-top":return bt;case"composer":return Q;case"footer-bottom":return I;default:return null}},x=(C,P)=>{switch(C){case"header-left":case"header-center":case"header-right":if(C==="header-left")_.insertBefore(P,_.firstChild);else if(C==="header-right")_.appendChild(P);else{let H=_.querySelector(".persona-flex-col");H?H.parentNode?.insertBefore(P,H.nextSibling):_.appendChild(P)}break;case"body-top":{let H=se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(P):se.insertBefore(P,se.firstChild);break}case"body-bottom":se.appendChild(P);break;case"footer-top":bt.replaceWith(P);break;case"footer-bottom":I.replaceWith(P);break;default:break}};for(let[C,P]of Object.entries(i))if(P)try{let H=P({config:o,defaultContent:()=>m(C)});H&&x(C,H)}catch(H){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${C}":`,H)}})();let gu=i=>{let x=i.target.closest('button[data-expand-header="true"]');if(!x)return;let C=x.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!C)return;let P=C.getAttribute("data-message-id");if(!P)return;let H=x.getAttribute("data-bubble-type");if(H==="reasoning")$r.has(P)?$r.delete(P):$r.add(P),wg(P,C);else if(H==="tool")jr.has(P)?jr.delete(P):jr.add(P),Ag(P,C,o);else if(H==="approval"){let V=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",X=lr.get(P)??V;lr.set(P,!X),Eg(P,C,o)}No.delete(P)};ye.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),gu(i))}),ye.addEventListener("keydown",i=>{let m=i.target;(i.key==="Enter"||i.key===" ")&&m.closest('button[data-expand-header="true"]')&&(i.preventDefault(),gu(i))}),ye.addEventListener("copy",i=>{let{clipboardData:m}=i;if(!m)return;let x=ye.getRootNode(),C=typeof x.getSelection=="function"?x.getSelection():window.getSelection();if(!C||C.isCollapsed)return;let P=C.toString(),H=Zm(P);!H||H===P||(m.setData("text/plain",H),i.preventDefault())});let ul=new Map,hu=null,yu="idle",qh={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Vh=(i,m)=>{let{icon:x,label:C}=qh[m];i.setAttribute("aria-label",C),i.title=C,i.setAttribute("aria-pressed",m==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",m!=="idle"),i.classList.toggle("persona-message-action-loading",m==="loading");let P=te(x,14,"currentColor",2);P&&(i.innerHTML="",i.appendChild(P))},xu=()=>{ye.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{let C=m.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Vh(m,C&&C===hu?yu:"idle")})};ye.addEventListener("click",i=>{let x=i.target.closest(".persona-message-action-btn[data-action]");if(!x)return;i.preventDefault(),i.stopPropagation();let C=x.closest("[data-actions-for]");if(!C)return;let P=C.getAttribute("data-actions-for");if(!P)return;let H=x.getAttribute("data-action");if(H==="copy"){let V=z.getMessages().find(X=>X.id===P);if(V&&Se.onCopy){let X=V.content||"";navigator.clipboard.writeText(X).then(()=>{x.classList.add("persona-message-action-success");let oe=te("check",14,"currentColor",2);oe&&(x.innerHTML="",x.appendChild(oe)),setTimeout(()=>{x.classList.remove("persona-message-action-success");let ie=te("copy",14,"currentColor",2);ie&&(x.innerHTML="",x.appendChild(ie))},2e3)}).catch(oe=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",oe)}),Se.onCopy(V)}}else if(H==="read-aloud")z.toggleReadAloud(P);else if(H==="upvote"||H==="downvote"){let V=(ul.get(P)??null)===H,X=H==="upvote"?"thumbs-up":"thumbs-down";if(V){ul.delete(P),x.classList.remove("persona-message-action-active");let oe=te(X,14,"currentColor",2);oe&&(x.innerHTML="",x.appendChild(oe))}else{let oe=H==="upvote"?"downvote":"upvote",ie=C.querySelector(`[data-action="${oe}"]`);if(ie){ie.classList.remove("persona-message-action-active");let it=te(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);it&&(ie.innerHTML="",ie.appendChild(it))}ul.set(P,H),x.classList.add("persona-message-action-active");let re=te(X,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),x.innerHTML="",x.appendChild(re)),x.classList.remove("persona-message-action-pop"),x.offsetWidth,x.classList.add("persona-message-action-pop");let je=z.getMessages().find(gt=>gt.id===P);je&&Se.onFeedback&&Se.onFeedback({type:H,messageId:je.id,message:je})}}}),ye.addEventListener("click",i=>{let x=i.target.closest("button[data-approval-action]");if(!x)return;i.preventDefault(),i.stopPropagation();let C=x.closest(".persona-approval-bubble");if(!C)return;let P=C.getAttribute("data-message-id");if(!P)return;let H=x.getAttribute("data-approval-action");if(!H)return;let J=H==="approve"?"approved":"denied",X=z.getMessages().find(ie=>ie.id===P);if(!X?.approval)return;let oe=C.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),X.approval.toolType==="webmcp"?z.resolveWebMcpApproval(P,J):z.resolveApproval(X.approval,J)});let tt=null,ea=null,ta=()=>{},na="none",cs=null,bn={artifacts:[],selectedId:null},Nn=!1,Cn=!1,oa=!1,fr=!1,bu=()=>fr||bn.artifacts.some(i=>Jo(o.features?.artifacts,i.artifactType)==="panel"),ps=()=>bn.artifacts.length>0&&!Nn&&bu(),ft={current:null},fl=(i,m)=>{let x=z.getArtifactById(m),C=x?.markdown,P=x?.title||"artifact",H=x?.file,J=x?.artifactType??"markdown";if(!C){let oe=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(oe){let re=z.getMessages().find(xe=>xe.id===oe);if(re?.rawContent)try{let xe=JSON.parse(re.rawContent);C=xe?.props?.markdown,P=xe?.props?.title||P,xe?.props?.file&&typeof xe.props.file=="object"&&(H=xe.props.file),!x&&typeof xe?.props?.artifactType=="string"&&(J=xe.props.artifactType)}catch{}}}return{markdown:C,title:P,file:H,artifactType:J}};ye.addEventListener("click",i=>{let x=i.target.closest("[data-download-artifact]");if(!x)return;i.preventDefault(),i.stopPropagation();let C=x.getAttribute("data-download-artifact");if(!C||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:C})===!0)return;let{markdown:H,title:J,file:V}=fl(x,C);if(!H)return;let{filename:X,mime:oe,content:ie}=Bm({title:J,markdown:H,file:V}),re=new Blob([ie],{type:oe}),xe=URL.createObjectURL(re),je=document.createElement("a");je.href=xe,je.download=X,je.click(),URL.revokeObjectURL(xe)}),ye.addEventListener("click",i=>{let x=i.target.closest("[data-artifact-custom-action]");if(!x)return;i.preventDefault(),i.stopPropagation();let C=x.getAttribute("data-artifact-custom-action");if(!C)return;let P=x.closest("[data-artifact-inline]"),H=P?null:x.closest("[data-open-artifact]"),J=P?P.getAttribute("data-artifact-inline"):H?.getAttribute("data-open-artifact")??null,X=(P?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(gt=>gt.id===C);if(!X)return;let{markdown:oe,title:ie,file:re,artifactType:xe}=fl(x,J??""),je={artifactId:J,title:ie,artifactType:xe,markdown:oe,file:re};try{Promise.resolve(X.onClick(je)).catch(()=>{})}catch{}}),ye.addEventListener("click",i=>{let x=i.target.closest("[data-copy-artifact]");if(!x)return;i.preventDefault(),i.stopPropagation();let C=x.getAttribute("data-copy-artifact");if(!C)return;let P=z.getArtifactById(C),H="";if(P)H=za(P);else{let{markdown:J,file:V,artifactType:X}=fl(x,C);X==="markdown"&&(H=za({id:C,artifactType:"markdown",status:"complete",markdown:J??"",...V?{file:V}:{}}))}H&&navigator.clipboard.writeText(H).then(()=>{let J=te("check",16,"currentColor",2);J&&(x.replaceChildren(J),setTimeout(()=>{let V=te("copy",16,"currentColor",2);V&&x.replaceChildren(V)},1500))}).catch(()=>{})}),ye.addEventListener("click",i=>{let x=i.target.closest("[data-expand-artifact-inline]");if(!x)return;i.preventDefault(),i.stopPropagation();let C=x.getAttribute("data-expand-artifact-inline");!C||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:C})===!0||(Nn=!1,fr=!0,Cn=!0,oa=!0,z.selectArtifact(C),On())}),ye.addEventListener("click",i=>{let m=i.target;if(m.closest("[data-download-artifact]")||m.closest("[data-artifact-custom-action]"))return;let x=m.closest("[data-open-artifact]");if(!x)return;let C=x.getAttribute("data-open-artifact");!C||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:C})===!0||(i.preventDefault(),i.stopPropagation(),Nn=!1,fr=!0,z.selectArtifact(C),On())}),ye.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let m=i.target;!m.hasAttribute("data-open-artifact")&&!m.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),m.click())});let mr=Ee.composerOverlay,gr=(i,m,x)=>{let C=m.trim();if(!C||!ft.current)return;let P=i.getAttribute("data-tool-call-id")??"",H=x.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:P,answer:C,answers:x.structured,values:x.values??(x.source==="multi"?C.split(", "):[C]),isFreeText:H,source:x.source},bubbles:!0,composed:!0})),go(mr,P);let J=ft.current.getMessages().find(V=>V.toolCall?.id===P);J?.agentMetadata?.awaitingLocalTool?ft.current.resolveAskUserQuestion(J,x.structured??C):ft.current.sendMessage(C)},Bo=i=>{let m=ft.current;if(!m)return;let x=i.getAttribute("data-tool-call-id")??"",C=m.getMessages().find(P=>P.toolCall?.id===x);C&&m.persistAskUserQuestionProgress(C,{answers:qs(i,C),currentIndex:yn(i)})},Cu=i=>Object.entries(i).map(([m,x])=>`${m}: ${Array.isArray(x)?x.join(", "):x}`).join(" | "),ml=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let m=yn(i),x=Lr(i);if(m>=x-1)return;let C=ft.current?.getMessages().find(P=>P.toolCall?.id===i.getAttribute("data-tool-call-id"));C&&(Vs(i,C,o,m+1),Bo(i))};mr.addEventListener("click",i=>{let x=i.target.closest("[data-ask-user-action]");if(!x)return;let C=x.closest("[data-persona-ask-sheet-for]");if(!C)return;let P=x.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),P==="dismiss"){let H=C.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:H},bubbles:!0,composed:!0})),go(mr,H);let J=ft.current?.getMessages().find(V=>V.toolCall?.id===H);J?.agentMetadata?.awaitingLocalTool&&(ft.current?.markAskUserQuestionResolved(J),ft.current?.resolveAskUserQuestion(J,"(dismissed)"));return}if(P==="pick"){let H=x.getAttribute("data-option-label");if(!H)return;let J=C.getAttribute("data-multi-select")==="true",V=mo(C);if(V&&J){let X=Qo(C)[yn(C)],oe=new Set(Array.isArray(X)?X:[]);oe.has(H)?oe.delete(H):oe.add(H),ho(C,Array.from(oe)),Bo(C);return}if(V){ho(C,H),Bo(C),ml(C);return}if(J){let X=x.getAttribute("aria-pressed")==="true";x.setAttribute("aria-pressed",X?"false":"true"),x.classList.toggle("persona-ask-pill-selected",!X);let oe=C.querySelector('[data-ask-user-action="submit-multi"]');oe&&(oe.disabled=Yl(C).length===0);return}gr(C,H,{source:"pick",values:[H]});return}if(P==="submit-multi"){let H=Yl(C);if(H.length===0)return;gr(C,H.join(", "),{source:"multi",values:H});return}if(P==="open-free-text"){let H=C.querySelector('[data-ask-free-text-row="true"]');H&&(H.classList.remove("persona-hidden"),H.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(P==="focus-free-text"){C.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(P==="submit-free-text"){let J=C.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!J.trim())return;if(mo(C)){ho(C,J.trim()),Bo(C),ml(C);return}gr(C,J,{source:"free-text"});return}if(P==="next"||P==="back"){if(!ft.current)return;let H=C.getAttribute("data-tool-call-id")??"",J=ft.current.getMessages().find(re=>re.toolCall?.id===H);if(!J)return;let X=C.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(X){let re=Qo(C)[yn(C)];(typeof re!="string"||re!==X)&&ho(C,X)}let oe=P==="next"?1:-1,ie=yn(C)+oe;Vs(C,J,o,ie),Bo(C);return}if(P==="submit-all"){if(!ft.current)return;let H=C.getAttribute("data-tool-call-id")??"",J=ft.current.getMessages().find(re=>re.toolCall?.id===H);if(!J)return;let X=C.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";X&&ho(C,X);let oe=qs(C,J);ft.current.persistAskUserQuestionProgress(J,{answers:oe,currentIndex:yn(C)});let ie=Cu(oe);gr(C,ie||"(submitted)",{source:"submit-all",structured:oe});return}if(P==="skip"){if(!ft.current)return;let H=C.getAttribute("data-tool-call-id")??"",J=ft.current.getMessages().find(xe=>xe.toolCall?.id===H);if(!J)return;let V=mo(C),X=yn(C),oe=Lr(C),ie=X>=oe-1;if(!V){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:H},bubbles:!0,composed:!0})),go(mr,H),J.agentMetadata?.awaitingLocalTool&&(ft.current.markAskUserQuestionResolved(J),ft.current.resolveAskUserQuestion(J,"(dismissed)"));return}ho(C,"");let re=C.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),ie){let xe=qs(C,J),je=Cu(xe);gr(C,je||"(skipped)",{source:"submit-all",structured:xe});return}Vs(C,J,o,X+1),Bo(C);return}}),mr.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let x=i.target;if(!x.matches?.('[data-ask-free-text-input="true"]'))return;let C=x.closest("[data-persona-ask-sheet-for]");if(!C)return;i.preventDefault();let P=x.value;if(P.trim()){if(mo(C)){ho(C,P.trim()),Bo(C),ml(C);return}gr(C,P,{source:"free-text"})}});let vu=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let m=i.target;if(m?.tagName==="INPUT"||m?.tagName==="TEXTAREA"||m?.isContentEditable)return;let x=mr.querySelector("[data-persona-ask-sheet-for]");if(!x||x.getAttribute("data-ask-layout")!=="rows"||x.getAttribute("data-multi-select")==="true")return;let C=Number(i.key),H=x.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[C-1];H&&(i.preventDefault(),H.click())};document.addEventListener("keydown",vu);let to=null,Ct=null,ra=null,us=null,gl=()=>{},wu=!1,fs="",ms="";function hl(){us?.(),us=null}let Au=()=>{if(!to||!Ct)return;let i=e.classList.contains("persona-artifact-welded-split"),m=e.ownerDocument.defaultView??window,x=m.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||x){Ct.style.removeProperty("position"),Ct.style.removeProperty("left"),Ct.style.removeProperty("top"),Ct.style.removeProperty("bottom"),Ct.style.removeProperty("width"),Ct.style.removeProperty("z-index");return}let C=to.firstElementChild;if(!C||C===Ct)return;let P=10;Ct.style.position="absolute",Ct.style.top="0",Ct.style.bottom="0",Ct.style.width=`${P}px`,Ct.style.zIndex="5";let H=_p(to,m),J=C.offsetWidth+H/2-P/2;Ct.style.left=`${Math.max(0,J)}px`},gs=()=>{},zh=()=>{let i=e.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,x=o.launcher?.mobileBreakpoint??640;return!m||i.innerWidth>x?!1:A||Rt(o)},hs=()=>!Qt(o)||!ps()||e.classList.contains("persona-artifact-narrow-host")||zh()||(e.ownerDocument.defaultView??window).innerWidth<yv?"none":Op(o)?"detached":"welded",On=()=>{if(!tt||!Qt(o))return;es(e,o),ts(e,o),gs();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,m=me.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=i);let x=ps();tt.setVisible(x),tt.update(bn),Nn?(tt.setMobileOpen(!1),tt.element.classList.add("persona-hidden"),tt.backdrop?.classList.add("persona-hidden"),Cn=!1,oa=!1):bn.artifacts.length>0&&bu()?(tt.element.classList.remove("persona-hidden"),tt.setMobileOpen(!0)):(tt.setMobileOpen(!1),tt.element.classList.add("persona-hidden"),tt.backdrop?.classList.add("persona-hidden"),Cn=!1,oa=!1);let C=o.features?.artifacts?.layout?.showExpandToggle===!0;if(tt.setExpandToggleVisible(C),tt.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),tt.setCustomActions(o.features?.artifacts?.toolbarActions??[]),tt.setTabFade(o.features?.artifacts?.layout?.tabFade),tt.setRenderTabBar(o.features?.artifacts?.renderTabBar),!C&&!oa&&(Cn=!1),Cn!==wu){let H=tt.element;Cn?(fs=H.style.width,ms=H.style.maxWidth,H.style.removeProperty("width"),H.style.removeProperty("max-width")):(fs&&(H.style.width=fs),ms&&(H.style.maxWidth=ms),fs="",ms=""),wu=Cn}e.classList.toggle("persona-artifact-expanded",Cn),tt.setExpanded(Cn);let P=hs();P!==na&&(na=P,ta()),gl()};if(Qt(o)){me.style.position="relative";let i=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(ue),tt=Ng(o,{onSelect:x=>ft.current?.selectArtifact(x),onDismiss:()=>{Nn=!0,On()},onToggleExpand:()=>{let x=!Cn,C=bn.selectedId??bn.artifacts[bn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:C,expanded:x})!==!0&&(Cn=x,x||(oa=!1),On())}}),tt.element.classList.add("persona-hidden"),to=m,m.appendChild(i),m.appendChild(tt.element),tt.backdrop&&me.appendChild(tt.backdrop),me.appendChild(m),gl=()=>{if(!to||!tt)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){ra?.(),ra=null,hl(),Ct&&(Ct.remove(),Ct=null),tt.element.style.removeProperty("width"),tt.element.style.removeProperty("maxWidth");return}if(!Ct){let C=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");C.setAttribute("role","separator"),C.setAttribute("aria-orientation","vertical"),C.setAttribute("aria-label","Resize artifacts panel"),C.tabIndex=0;let P=e.ownerDocument,H=P.defaultView??window,J=V=>{if(!tt||V.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||H.innerWidth<=640)return;V.preventDefault(),hl();let X=V.clientX,oe=tt.element.getBoundingClientRect().width,ie=o.features?.artifacts?.layout,re=je=>{let gt=to.getBoundingClientRect().width,it=e.classList.contains("persona-artifact-welded-split"),jt=_p(to,H),Bt=it?0:C.getBoundingClientRect().width||6,D=oe-(je.clientX-X),Fe=qg(D,gt,jt,Bt,ie?.resizableMinWidth,ie?.resizableMaxWidth);tt.element.style.width=`${Fe}px`,tt.element.style.maxWidth="none",Au()},xe=()=>{P.removeEventListener("pointermove",re),P.removeEventListener("pointerup",xe),P.removeEventListener("pointercancel",xe),us=null;try{C.releasePointerCapture(V.pointerId)}catch{}};us=xe,P.addEventListener("pointermove",re),P.addEventListener("pointerup",xe),P.addEventListener("pointercancel",xe);try{C.setPointerCapture(V.pointerId)}catch{}};C.addEventListener("pointerdown",J),Ct=C,to.insertBefore(C,tt.element),ra=()=>{C.removeEventListener("pointerdown",J)}}if(Ct){let C=ps();Ct.classList.toggle("persona-hidden",!C),Au()}},gs=()=>{if(!A||!tt||(o.launcher?.sidebarMode??!1)||Rt(o)&&nn(o).reveal==="emerge")return;let C=e.ownerDocument.defaultView??window,P=o.launcher?.mobileFullscreen??!0,H=o.launcher?.mobileBreakpoint??640;if(P&&C.innerWidth<=H||!Ug(o,A))return;let J=o.launcher?.width??o.launcherWidth??cn,V=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";ps()?(me.style.width=V,me.style.maxWidth=V):(me.style.width=J,me.style.maxWidth=J)},typeof ResizeObserver<"u"&&(ea=new ResizeObserver(()=>{On()}),ea.observe(me))}else me.appendChild(ue);$()&&Je&&(Ee.peekBanner&&Je.appendChild(Ee.peekBanner),Je.appendChild(j)),e.appendChild(Re),Je&&e.appendChild(Je);let ys=()=>{if($()){me.style.width="100%",me.style.maxWidth="100%";let Pt=o.launcher?.composerBar??{},en=Re.dataset.state==="expanded",Ps=Pt.expandedSize??"anchored";if(!(en&&Ps!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let xa=o.theme?.components?.panel,Rs=wo(o),Ar=(Vn,jo)=>Vn==null||Vn===""?jo:Xt(Rs,Vn)??Vn,ba="1px solid var(--persona-border)",Ul="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",$o="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Ar(xa?.border,ba),ue.style.borderRadius=Ar(xa?.borderRadius,$o),ue.style.boxShadow=Ar(xa?.shadow,Ul),ue.style.overflow="hidden";return}let i=Rt(o),m=o.launcher?.sidebarMode??!1,x=i||m||(o.launcher?.fullHeight??!1),C=o.launcher?.enabled===!1,P=o.launcher?.detachedPanel===!0,H=o.theme?.components?.panel,J=wo(o),V=(Pt,en)=>Pt==null||Pt===""?en:Xt(J,Pt)??Pt,X=e.ownerDocument.defaultView??window,oe=o.launcher?.mobileFullscreen??!0,ie=o.launcher?.mobileBreakpoint??640,re=X.innerWidth<=ie,xe=oe&&re&&A,je=i&&oe&&re,gt=o.launcher?.position??"bottom-left",it=gt==="bottom-left"||gt==="top-left",jt=o.launcher?.zIndex??zt,Bt="var(--persona-panel-border, 1px solid var(--persona-border))",D="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",Fe="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",we=P&&!xe&&!je;we?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let _e=we?Bt:m||xe?"none":Bt,St=we?D:xe?"none":m?it?"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))":C?"none":D;i&&!xe&&!we&&(St="none",_e="none");let pt=we?Fe:m||xe?"0":Fe,wt=V(H?.border,_e),yt=V(H?.shadow,St),qt=V(H?.borderRadius,pt),Vo=hs(),ut=Vo==="detached",de=Vo==="welded";e.classList.toggle("persona-artifact-detached-split",ut),e.classList.toggle("persona-artifact-welded-split",de);let At="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)))))",rt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Qt(o)&&Op(o)&&C&&!i;e.classList.toggle("persona-artifact-chat-flush",rt);let Ve=ut||rt?"none":yt,nt=ut?Bt:de?"none":wt,Lt=ut?Fe:qt;rt&&(nt="none",Lt="0");let We=H?.borderRadius!=null&&H.borderRadius!=="",ot=rt&&!We?"0":qt,sn=se.scrollTop;e.style.cssText="",Re.style.cssText="",me.style.cssText="",ue.style.cssText="",se.style.cssText="",j.style.cssText="",lt&&(se.style.display="none"),(x||C)&&(e.style.minWidth="0");let zo=()=>{if(sn<=0)return;(se.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(se.scrollTop===sn)return;let en=se.scrollHeight-se.clientHeight;en<=0||(se.scrollTop=Math.min(sn,en))})};if(xe){Re.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"),Re.style.cssText=`
|
|
49
|
+
`,C.addEventListener("click",()=>{u=H,E.forEach((B,F)=>{let q=F<H;B.classList.toggle("selected",q),B.setAttribute("aria-checked",F===H-1?"true":"false")})}),E.push(C),L.appendChild(C)}g.appendChild(L);let M=null;if(p){let H=document.createElement("div");H.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=a,M.rows=3,M.setAttribute("aria-label","Additional comments"),H.appendChild(M),g.appendChild(H)}let A=document.createElement("div");A.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=l,w.addEventListener("click",()=>{n?.(),c.remove()});let T=document.createElement("button");return T.type="button",T.className="persona-feedback-btn persona-feedback-btn-submit",T.textContent=s,T.addEventListener("click",async()=>{if(u===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let H=M?.value.trim()||void 0;await t(u,H),c.remove()}catch(H){T.disabled=!1,T.textContent=s,console.error("[CSAT Feedback] Failed to submit:",H)}}),A.appendChild(w),A.appendChild(T),g.appendChild(A),c.appendChild(g),c}function el(e){let{onSubmit:t,onDismiss:n,title:o="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:s="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let S=document.createElement("h3");S.className="persona-feedback-title",S.textContent=o,h.appendChild(S);let L=document.createElement("p");L.className="persona-feedback-subtitle",L.textContent=r,h.appendChild(L),f.appendChild(h);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let A=document.createElement("span");A.className="persona-feedback-label-low",A.textContent=d;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=c,M.appendChild(A),M.appendChild(w);let T=document.createElement("div");T.className="persona-feedback-numbers";let H=[];for(let D=0;D<=10;D++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${D} out of 10`),U.textContent=String(D),U.dataset.rating=String(D),D<=6?U.classList.add("persona-feedback-detractor"):D<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{g=D,H.forEach((se,le)=>{se.classList.toggle("selected",le===D),se.setAttribute("aria-checked",le===D?"true":"false")})}),H.push(U),T.appendChild(U)}E.appendChild(M),E.appendChild(T),f.appendChild(E);let C=null;if(p){let D=document.createElement("div");D.className="persona-feedback-comment-container",C=document.createElement("textarea"),C.className="persona-feedback-comment",C.placeholder=a,C.rows=3,C.setAttribute("aria-label","Additional comments"),D.appendChild(C),f.appendChild(D)}let B=document.createElement("div");B.className="persona-feedback-actions";let F=document.createElement("button");F.type="button",F.className="persona-feedback-btn persona-feedback-btn-skip",F.textContent=l,F.addEventListener("click",()=>{n?.(),u.remove()});let q=document.createElement("button");return q.type="button",q.className="persona-feedback-btn persona-feedback-btn-submit",q.textContent=s,q.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}q.disabled=!0,q.textContent="Submitting...";try{let D=C?.value.trim()||void 0;await t(g,D),u.remove()}catch(D){q.disabled=!1,q.textContent=s,console.error("[NPS Feedback] Failed to submit:",D)}}),B.appendChild(F),B.appendChild(q),f.appendChild(B),u.appendChild(f),u}var $r="persona-chat-history",MC=30*1e3,TC=641,EC={"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 kC(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let a=EC[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 o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function tl(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 LC(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 PC(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var $p=e=>!e||typeof e!="object"?{}:{...e},oh=e=>e.map(t=>({...t,streaming:!1})),rh=(e,t,n)=>{let o=e?.markdown?$o(e.markdown):null,r=wr(e?.sanitize);return 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."),a=>{let s=a.text??"",l=a.message.rawContent??null;if(t){let c=t.process({text:s,raw:l??s,message:a.message,streaming:a.streaming});c!==null&&(s=c.text,c.persist||(a.message.__skipPersist=!0),c.resubmit&&!a.streaming&&n&&n())}let p=Vn()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...a,text:s,raw:l??a.text??""});d=r?r(c):c}else if(o){let c=a.streaming?Lf(s):s,u=o(c);d=r&&p?r(u):u}else d=In(s);return d}};function ah(e){let t=x("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 n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",a=e?.iconStrokeWidth??.5,s=te(n,o,r,a);if(s&&t.appendChild(s),e?.label){let l=x("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var RC=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];n[o]=a?{...a,...r}:r}return n},IC=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:RC(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),nl=(e,t,n)=>{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 o=Rr(t),r=Ja.getForInstance(o.plugins),{plugin:a,teardown:s}=Fg();o.components&&En.registerAll(o.components);let l=Yg(),d=o.persistState===!1?null:o.storageAdapter??Xi(),c={},u=null,g=!1,f=i=>{if(o.onStateLoaded)try{let m=o.onStateLoaded(i);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:v}=m;return v&&(g=!0),y}return m}catch(m){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return i};if(d?.load)try{let i=d.load();if(i&&typeof i.then=="function")u=i.then(m=>f(m??{messages:[],metadata:{}}));else{let y=f(i??{messages:[],metadata:{}});y.metadata&&(c=$p(y.metadata)),y.messages?.length&&(o={...o,initialMessages:y.messages}),y.artifacts?.length&&(o={...o,initialArtifacts:y.artifacts,initialSelectedArtifactId:y.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=f({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let h=()=>c,S=i=>{c=i({...c})??{},wl()},L=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Qa],E=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ir.message,ir.messageAndClick],M=Ya({parsers:L,handlers:E,getSessionMetadata:h,updateSessionMetadata:S,emit:l.emit,documentRef:typeof document<"u"?document:null});M.syncFromMetadata();let A=o.launcher?.enabled??!0,w=o.launcher?.autoExpand??!1,T=o.autoFocusInput??!1,H=w,C=A,B=o.layout?.header?.layout,F=!1,q=()=>Lo(o),D=()=>A||q(),U=q()?!1:A?w:!0,se=!1,le=null,Ce=()=>{se=!0,le&&clearTimeout(le),le=setTimeout(()=>{se&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),se=!1)},1e4)},Le=rh(o,M,Ce),ae=o.features?.showReasoning??!0,me=o.features?.showToolCalls??!0,Z=o.features?.showEventStreamToggle??!1,de=o.features?.scrollToBottom??{},Y=o.features?.scrollBehavior??{},Ae=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,xe=Z?new ja(Ae):null,Be=o.features?.eventStream?.maxEvents??2e3,Oe=Z?new $a(Be,xe):null,Ve=Z?new Ga:null,Ne=null,rt=!1,Xe=null,Pe=0;xe?.open().then(()=>Oe?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Se={onCopy:i=>{l.emit("message:copy",i),$?.isClientTokenMode()&&$.submitMessageFeedback(i.id,"copy").catch(m=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",m)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{l.emit("message:feedback",i),$?.isClientTokenMode()&&$.submitMessageFeedback(i.messageId,i.type).catch(m=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",m)}),o.messageActions?.onFeedback?.(i)}},Je=o.statusIndicator??{},cn=i=>i==="idle"?Je.idleText??Ht.idle:i==="connecting"?Je.connectingText??Ht.connecting:i==="connected"?Je.connectedText??Ht.connected:i==="error"?Je.errorText??Ht.error:i==="paused"?Je.pausedText??Ht.paused:i==="resuming"?Je.resumingText??Ht.resuming:Ht[i];function Et(i,m,y,v){if(v==="idle"&&y.idleLink){i.textContent="";let k=document.createElement("a");k.href=y.idleLink,k.target="_blank",k.rel="noopener noreferrer",k.textContent=m,k.style.color="inherit",k.style.textDecoration="none",i.appendChild(k)}else i.textContent=m}let xt=wg({config:o,showClose:D()}),{wrapper:Re,panel:fe,pillRoot:Ge}=xt.shell,Te=xt.panelElements,{container:pe,body:ie,messagesWrapper:ge,suggestions:bt,textarea:he,sendButton:ce,sendButtonWrapper:yn,composerForm:Q,statusText:R,introTitle:z,introSubtitle:b,closeButton:P,iconHolder:I,headerTitle:N,headerSubtitle:G,header:_,footer:j,actionsRow:re,rightActions:$e}=Te,Me=Te.leftActions,at=Te.setSendButtonMode,K=Te.micButton,Ue=Te.micButtonWrapper,we=Te.attachmentButton,ke=Te.attachmentButtonWrapper,Ee=Te.attachmentInput,Qe=Te.attachmentPreviewsContainer;pe.classList.add("persona-relative"),ie.classList.add("persona-relative");let Po=12,Ro=()=>de.label??"",sl=()=>de.iconName??"arrow-down",ns=()=>de.enabled!==!1,Yt=()=>Y.mode??"anchor-top",Qn=()=>Yt()==="follow"||Yt()==="anchor-top"&&ta,iu=()=>Y.anchorTopOffset??16,zh=()=>Y.restorePosition??"bottom",lu=()=>Y.pauseOnInteraction===!0,du=()=>Y.showActivityWhilePinned!==!1,cu=()=>Y.announce===!0,Pt=x("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");Pt.type="button",Pt.style.display="none",Pt.setAttribute("data-persona-scroll-to-bottom","true");let Gr=x("span","persona-flex persona-items-center"),il=x("span",""),Io=x("span","");Io.setAttribute("data-persona-scroll-to-bottom-count",""),Io.style.display="none",Pt.append(Gr,il,Io),pe.appendChild(Pt);let Yn=x("div","persona-stream-anchor-spacer");Yn.setAttribute("aria-hidden","true"),Yn.setAttribute("data-persona-anchor-spacer",""),Yn.style.flexShrink="0",Yn.style.pointerEvents="none",Yn.style.height="0px",ie.appendChild(Yn);let Wo=x("div","persona-sr-only");Wo.setAttribute("aria-live","polite"),Wo.setAttribute("aria-atomic","true"),Wo.setAttribute("role","status"),Wo.setAttribute("data-persona-live-region",""),Object.assign(Wo.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(Wo);let Kr=null,os=null,pu=i=>{!cu()||!i||(os=i,Kr===null&&(Kr=setTimeout(()=>{Kr=null,os&&cu()&&(Wo.textContent=os),os=null},400)))},lr=()=>{let m=j.style.display==="none"?0:j.offsetHeight;Pt.style.bottom=`${m+Po}px`};lr();let uu=()=>{let i=!!Ro();Pt.setAttribute("aria-label",Ro()||"Jump to latest"),Pt.title=Ro(),Pt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Gr.innerHTML="";let m=te(sl(),"14px","currentColor",2);m?(Gr.appendChild(m),Gr.style.display=""):Gr.style.display="none",il.textContent=Ro(),il.style.display=i?"":"none"};uu();let At=null,nn=null,fu=null,mu=r.find(i=>i.renderHeader);if(mu?.renderHeader){let i=mu.renderHeader({config:o,defaultRenderer:()=>{let m=Jn({config:o,showClose:D()});return nr(pe,m,o),m.header},onClose:()=>pt(!1,"user")});if(i){let m=pe.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(i),_=i,xt.header.element=i)}}let ll=()=>{if(!Oe)return;if(rt=!0,!Ne&&Oe&&(Ne=qg({buffer:Oe,getFullHistory:()=>Oe.getAllFromStore(),onClose:()=>Xr(),config:o,plugins:r,getThroughput:()=>Ve?.getMetric()??{status:"idle"}})),Ne&&(ie.style.display="none",j.parentNode?.insertBefore(Ne.element,j),Ne.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Xt.actionIconColor}`;let m=o.features?.eventStream?.classNames?.toggleButtonActive;m&&m.split(/\s+/).forEach(y=>y&&tt.classList.add(y))}let i=()=>{if(!rt)return;let m=Date.now();m-Pe>=200&&(Ne?.update(),Pe=m),Xe=requestAnimationFrame(i)};Pe=0,Xe=requestAnimationFrame(i),rn(),l.emit("eventStream:opened",{timestamp:Date.now()})},Xr=()=>{if(rt){if(rt=!1,Ne&&Ne.element.remove(),ie.style.display="",tt){tt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(m=>m&&tt.classList.remove(m))}Xe!==null&&(cancelAnimationFrame(Xe),Xe=null),rn(),l.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(Z){let i=o.features?.eventStream?.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");tt=x("button",m),tt.style.width="28px",tt.style.height="28px",tt.style.color=Xt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let y=te("activity","18px","currentColor",1.5);y&&tt.appendChild(y);let v=Te.clearChatButtonWrapper,k=Te.closeButtonWrapper,W=v||k;W&&W.parentNode===_?_.insertBefore(tt,W):_.appendChild(tt),tt.addEventListener("click",()=>{rt?Xr():ll()})}let $h=i=>{let m=o.attachments;if(!m?.enabled)return;let y=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!y){y=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.setAttribute("data-persona-composer-attachment-previews",""),y.style.display="none";let k=i.querySelector("[data-persona-composer-form]");k?.parentNode?k.parentNode.insertBefore(y,k):i.insertBefore(y,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let k=x("input");k.type="file",k.setAttribute("data-persona-composer-attachment-input",""),k.accept=(m.allowedTypes??Kn).join(","),k.multiple=(m.maxFiles??4)>1,k.style.display="none",k.setAttribute("aria-label",m.buttonTooltipText??"Attach files"),i.appendChild(k)}},gu=r.find(i=>i.renderComposer);if(gu?.renderComposer){let i=o.composer,m=gu.renderComposer({config:o,defaultRenderer:()=>Nr({config:o}).footer,onSubmit:y=>{if(!$||$.isStreaming())return;let v=y.trim(),k=At?.hasAttachments()??!1;if(!v&&!k)return;zu();let W;k&&(W=[],W.push(...At.getContentParts()),v&&W.push(bo(v))),$.sendMessage(v,{contentParts:W}),k&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ee?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:y=>{o.composer={...o.composer,selectedModelId:y},o.agent&&(o.agent={...o.agent,model:y})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{fu?.()}:void 0});m&&(xt.replaceComposer(m),j=xt.composer.footer)}let jh=i=>{let m=(...ue)=>{for(let ne of ue){let be=i.querySelector(ne);if(be)return be}return null},y=i.querySelector("[data-persona-composer-form]"),v=i.querySelector("[data-persona-composer-input]"),k=i.querySelector("[data-persona-composer-submit]"),W=i.querySelector("[data-persona-composer-mic]"),J=i.querySelector("[data-persona-composer-status]");y&&(Q=y),v&&(he=v),k&&(ce=k),W&&(K=W,Ue=W.parentElement),J&&(R=J);let V=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(bt=V);let X=m("[data-persona-composer-attachment-button]",".persona-attachment-button");X&&(we=X,ke=X.parentElement),Ee=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Qe=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let oe=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");oe&&(re=oe),Me=m(".persona-widget-composer__left-actions")};$h(j),jh(j);let Zn=o.layout?.contentMaxWidth??(q()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Zn&&(ge.style.maxWidth=Zn,ge.style.marginLeft="auto",ge.style.marginRight="auto",ge.style.width="100%"),Zn&&Q&&!q()&&(Q.style.maxWidth=Zn,Q.style.marginLeft="auto",Q.style.marginRight="auto"),Zn&&bt&&!q()&&(bt.style.maxWidth=Zn,bt.style.marginLeft="auto",bt.style.marginRight="auto"),Zn&&Qe&&!q()&&(Qe.style.maxWidth=Zn,Qe.style.marginLeft="auto",Qe.style.marginRight="auto"),o.attachments?.enabled&&Ee&&Qe){At=Yo.fromConfig(o.attachments),At.setPreviewsContainer(Qe),Ee.addEventListener("change",y=>{let v=y.target;At?.handleFileSelect(v.files),v.value=""});let i=o.attachments.dropOverlay,m=ah(i);pe.appendChild(m)}let Gh=()=>nn?.prefetch();if(o.contextMentions?.enabled&&he&&(nn=Hm({config:o,textarea:he,anchor:Q??he,getMessages:()=>$.getMessages(),liveRegionHost:pe}),nn)){let i=he;i.parentElement?.insertBefore(nn.contextRow,i);let m=nn.affordanceButtons;for(let y=m.length-1;y>=0;y--){let v=m[y];Me?Me.insertBefore(v,Me.firstChild):Q?.appendChild(v)}}(()=>{let i=o.layout?.slots??{},m=v=>{switch(v){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ge;case"footer-top":return bt;case"composer":return Q;case"footer-bottom":return R;default:return null}},y=(v,k)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")_.insertBefore(k,_.firstChild);else if(v==="header-right")_.appendChild(k);else{let W=_.querySelector(".persona-flex-col");W?W.parentNode?.insertBefore(k,W.nextSibling):_.appendChild(k)}break;case"body-top":{let W=ie.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");W?W.replaceWith(k):ie.insertBefore(k,ie.firstChild);break}case"body-bottom":ie.appendChild(k);break;case"footer-top":bt.replaceWith(k);break;case"footer-bottom":R.replaceWith(k);break;default:break}};for(let[v,k]of Object.entries(i))if(k)try{let W=k({config:o,defaultContent:()=>m(v)});W&&y(v,W)}catch(W){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,W)}})();let hu=i=>{let y=i.target.closest('button[data-expand-header="true"]');if(!y)return;let v=y.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let k=v.getAttribute("data-message-id");if(!k)return;let W=y.getAttribute("data-bubble-type");if(W==="reasoning")Ur.has(k)?Ur.delete(k):Ur.add(k),kg(k,v);else if(W==="tool")qr.has(k)?qr.delete(k):qr.add(k),Lg(k,v,o);else if(W==="approval"){let V=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",X=rr.get(k)??V;rr.set(k,!X),Wg(k,v,o)}Fo.delete(k)};ge.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),hu(i))}),ge.addEventListener("keydown",i=>{let m=i.target;(i.key==="Enter"||i.key===" ")&&m.closest('button[data-expand-header="true"]')&&(i.preventDefault(),hu(i))}),ge.addEventListener("copy",i=>{let{clipboardData:m}=i;if(!m)return;let y=ge.getRootNode(),v=typeof y.getSelection=="function"?y.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let k=v.toString(),W=ag(k);!W||W===k||(m.setData("text/plain",W),i.preventDefault())});let dl=new Map,yu=null,xu="idle",Kh={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Xh=(i,m)=>{let{icon:y,label:v}=Kh[m];i.setAttribute("aria-label",v),i.title=v,i.setAttribute("aria-pressed",m==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",m!=="idle"),i.classList.toggle("persona-message-action-loading",m==="loading");let k=te(y,14,"currentColor",2);k&&(i.innerHTML="",i.appendChild(k))},bu=()=>{ge.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{let v=m.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Xh(m,v&&v===yu?xu:"idle")})};ge.addEventListener("click",i=>{let y=i.target.closest(".persona-message-action-btn[data-action]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.closest("[data-actions-for]");if(!v)return;let k=v.getAttribute("data-actions-for");if(!k)return;let W=y.getAttribute("data-action");if(W==="copy"){let V=$.getMessages().find(X=>X.id===k);if(V&&Se.onCopy){let X=V.content||"";navigator.clipboard.writeText(X).then(()=>{y.classList.add("persona-message-action-success");let oe=te("check",14,"currentColor",2);oe&&(y.innerHTML="",y.appendChild(oe)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ue=te("copy",14,"currentColor",2);ue&&(y.innerHTML="",y.appendChild(ue))},2e3)}).catch(oe=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",oe)}),Se.onCopy(V)}}else if(W==="read-aloud")$.toggleReadAloud(k);else if(W==="upvote"||W==="downvote"){let V=(dl.get(k)??null)===W,X=W==="upvote"?"thumbs-up":"thumbs-down";if(V){dl.delete(k),y.classList.remove("persona-message-action-active");let oe=te(X,14,"currentColor",2);oe&&(y.innerHTML="",y.appendChild(oe))}else{let oe=W==="upvote"?"downvote":"upvote",ue=v.querySelector(`[data-action="${oe}"]`);if(ue){ue.classList.remove("persona-message-action-active");let nt=te(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(ue.innerHTML="",ue.appendChild(nt))}dl.set(k,W),y.classList.add("persona-message-action-active");let ne=te(X,14,"currentColor",2);ne&&(ne.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(ne)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let ze=$.getMessages().find(ut=>ut.id===k);ze&&Se.onFeedback&&Se.onFeedback({type:W,messageId:ze.id,message:ze})}}}),ge.addEventListener("click",i=>{let y=i.target.closest("button[data-approval-action]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.closest(".persona-approval-bubble");if(!v)return;let k=v.getAttribute("data-message-id");if(!k)return;let W=y.getAttribute("data-approval-action");if(!W)return;let J=W==="approve"?"approved":"denied",X=$.getMessages().find(ue=>ue.id===k);if(!X?.approval)return;let oe=v.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(ne=>{ne.disabled=!0,ne.style.opacity="0.5",ne.style.cursor="not-allowed"}),X.approval.toolType==="webmcp"?$.resolveWebMcpApproval(k,J):$.resolveApproval(X.approval,J)});let Ye=null,Jr=null,Qr=()=>{},Yr="none",rs=null,xn={artifacts:[],selectedId:null},Dn=!1,bn=!1,Zr=!1,dr=!1,vu=()=>dr||xn.artifacts.some(i=>jo(o.features?.artifacts,i.artifactType)==="panel"),as=()=>xn.artifacts.length>0&&!Dn&&vu(),dt={current:null},cl=(i,m)=>{let y=$.getArtifactById(m),v=y?.markdown,k=y?.title||"artifact",W=y?.file,J=y?.artifactType??"markdown";if(!v){let oe=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(oe){let ne=$.getMessages().find(be=>be.id===oe);if(ne?.rawContent)try{let be=JSON.parse(ne.rawContent);v=be?.props?.markdown,k=be?.props?.title||k,be?.props?.file&&typeof be.props.file=="object"&&(W=be.props.file),!y&&typeof be?.props?.artifactType=="string"&&(J=be.props.artifactType)}catch{}}}return{markdown:v,title:k,file:W,artifactType:J}};ge.addEventListener("click",i=>{let y=i.target.closest("[data-download-artifact]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.getAttribute("data-download-artifact");if(!v||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:v})===!0)return;let{markdown:W,title:J,file:V}=cl(y,v);if(!W)return;let{filename:X,mime:oe,content:ue}=Um({title:J,markdown:W,file:V}),ne=new Blob([ue],{type:oe}),be=URL.createObjectURL(ne),ze=document.createElement("a");ze.href=be,ze.download=X,ze.click(),URL.revokeObjectURL(be)}),ge.addEventListener("click",i=>{let y=i.target.closest("[data-artifact-custom-action]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.getAttribute("data-artifact-custom-action");if(!v)return;let k=y.closest("[data-artifact-inline]"),W=k?null:y.closest("[data-open-artifact]"),J=k?k.getAttribute("data-artifact-inline"):W?.getAttribute("data-open-artifact")??null,X=(k?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ut=>ut.id===v);if(!X)return;let{markdown:oe,title:ue,file:ne,artifactType:be}=cl(y,J??""),ze={artifactId:J,title:ue,artifactType:be,markdown:oe,file:ne};try{Promise.resolve(X.onClick(ze)).catch(()=>{})}catch{}}),ge.addEventListener("click",i=>{let y=i.target.closest("[data-copy-artifact]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.getAttribute("data-copy-artifact");if(!v)return;let k=$.getArtifactById(v),W="";if(k)W=Oa(k);else{let{markdown:J,file:V,artifactType:X}=cl(y,v);X==="markdown"&&(W=Oa({id:v,artifactType:"markdown",status:"complete",markdown:J??"",...V?{file:V}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let J=te("check",16,"currentColor",2);J&&(y.replaceChildren(J),setTimeout(()=>{let V=te("copy",16,"currentColor",2);V&&y.replaceChildren(V)},1500))}).catch(()=>{})}),ge.addEventListener("click",i=>{let y=i.target.closest("[data-expand-artifact-inline]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.getAttribute("data-expand-artifact-inline");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(Dn=!1,dr=!0,bn=!0,Zr=!0,$.selectArtifact(v),Fn())}),ge.addEventListener("click",i=>{let m=i.target;if(m.closest("[data-download-artifact]")||m.closest("[data-artifact-custom-action]"))return;let y=m.closest("[data-open-artifact]");if(!y)return;let v=y.getAttribute("data-open-artifact");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(i.preventDefault(),i.stopPropagation(),Dn=!1,dr=!0,$.selectArtifact(v),Fn())}),ge.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let m=i.target;!m.hasAttribute("data-open-artifact")&&!m.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),m.click())});let cr=Te.composerOverlay,pr=(i,m,y)=>{let v=m.trim();if(!v||!dt.current)return;let k=i.getAttribute("data-tool-call-id")??"",W=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:k,answer:v,answers:y.structured,values:y.values??(y.source==="multi"?v.split(", "):[v]),isFreeText:W,source:y.source},bubbles:!0,composed:!0})),go(cr,k);let J=dt.current.getMessages().find(V=>V.toolCall?.id===k);J?.agentMetadata?.awaitingLocalTool?dt.current.resolveAskUserQuestion(J,y.structured??v):dt.current.sendMessage(v)},Ho=i=>{let m=dt.current;if(!m)return;let y=i.getAttribute("data-tool-call-id")??"",v=m.getMessages().find(k=>k.toolCall?.id===y);v&&m.persistAskUserQuestionProgress(v,{answers:Os(i,v),currentIndex:hn(i)})},Cu=i=>Object.entries(i).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),pl=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let m=hn(i),y=Mr(i);if(m>=y-1)return;let v=dt.current?.getMessages().find(k=>k.toolCall?.id===i.getAttribute("data-tool-call-id"));v&&(Ns(i,v,o,m+1),Ho(i))};cr.addEventListener("click",i=>{let y=i.target.closest("[data-ask-user-action]");if(!y)return;let v=y.closest("[data-persona-ask-sheet-for]");if(!v)return;let k=y.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),k==="dismiss"){let W=v.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:W},bubbles:!0,composed:!0})),go(cr,W);let J=dt.current?.getMessages().find(V=>V.toolCall?.id===W);J?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(J),dt.current?.resolveAskUserQuestion(J,"(dismissed)"));return}if(k==="pick"){let W=y.getAttribute("data-option-label");if(!W)return;let J=v.getAttribute("data-multi-select")==="true",V=mo(v);if(V&&J){let X=Go(v)[hn(v)],oe=new Set(Array.isArray(X)?X:[]);oe.has(W)?oe.delete(W):oe.add(W),ho(v,Array.from(oe)),Ho(v);return}if(V){ho(v,W),Ho(v),pl(v);return}if(J){let X=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",X?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!X);let oe=v.querySelector('[data-ask-user-action="submit-multi"]');oe&&(oe.disabled=Jl(v).length===0);return}pr(v,W,{source:"pick",values:[W]});return}if(k==="submit-multi"){let W=Jl(v);if(W.length===0)return;pr(v,W.join(", "),{source:"multi",values:W});return}if(k==="open-free-text"){let W=v.querySelector('[data-ask-free-text-row="true"]');W&&(W.classList.remove("persona-hidden"),W.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(k==="focus-free-text"){v.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(k==="submit-free-text"){let J=v.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!J.trim())return;if(mo(v)){ho(v,J.trim()),Ho(v),pl(v);return}pr(v,J,{source:"free-text"});return}if(k==="next"||k==="back"){if(!dt.current)return;let W=v.getAttribute("data-tool-call-id")??"",J=dt.current.getMessages().find(ne=>ne.toolCall?.id===W);if(!J)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(X){let ne=Go(v)[hn(v)];(typeof ne!="string"||ne!==X)&&ho(v,X)}let oe=k==="next"?1:-1,ue=hn(v)+oe;Ns(v,J,o,ue),Ho(v);return}if(k==="submit-all"){if(!dt.current)return;let W=v.getAttribute("data-tool-call-id")??"",J=dt.current.getMessages().find(ne=>ne.toolCall?.id===W);if(!J)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";X&&ho(v,X);let oe=Os(v,J);dt.current.persistAskUserQuestionProgress(J,{answers:oe,currentIndex:hn(v)});let ue=Cu(oe);pr(v,ue||"(submitted)",{source:"submit-all",structured:oe});return}if(k==="skip"){if(!dt.current)return;let W=v.getAttribute("data-tool-call-id")??"",J=dt.current.getMessages().find(be=>be.toolCall?.id===W);if(!J)return;let V=mo(v),X=hn(v),oe=Mr(v),ue=X>=oe-1;if(!V){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:W},bubbles:!0,composed:!0})),go(cr,W),J.agentMetadata?.awaitingLocalTool&&(dt.current.markAskUserQuestionResolved(J),dt.current.resolveAskUserQuestion(J,"(dismissed)"));return}ho(v,"");let ne=v.querySelector('[data-ask-free-text-input="true"]');if(ne&&(ne.value=""),ue){let be=Os(v,J),ze=Cu(be);pr(v,ze||"(skipped)",{source:"submit-all",structured:be});return}Ns(v,J,o,X+1),Ho(v);return}}),cr.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let y=i.target;if(!y.matches?.('[data-ask-free-text-input="true"]'))return;let v=y.closest("[data-persona-ask-sheet-for]");if(!v)return;i.preventDefault();let k=y.value;if(k.trim()){if(mo(v)){ho(v,k.trim()),Ho(v),pl(v);return}pr(v,k,{source:"free-text"})}});let wu=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let m=i.target;if(m?.tagName==="INPUT"||m?.tagName==="TEXTAREA"||m?.isContentEditable)return;let y=cr.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let v=Number(i.key),W=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];W&&(i.preventDefault(),W.click())};document.addEventListener("keydown",wu);let eo=null,vt=null,ea=null,ss=null,ul=()=>{},Au=!1,is="",ls="";function fl(){ss?.(),ss=null}let Su=()=>{if(!eo||!vt)return;let i=e.classList.contains("persona-artifact-welded-split"),m=e.ownerDocument.defaultView??window,y=m.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||y){vt.style.removeProperty("position"),vt.style.removeProperty("left"),vt.style.removeProperty("top"),vt.style.removeProperty("bottom"),vt.style.removeProperty("width"),vt.style.removeProperty("z-index");return}let v=eo.firstElementChild;if(!v||v===vt)return;let k=10;vt.style.position="absolute",vt.style.top="0",vt.style.bottom="0",vt.style.width=`${k}px`,vt.style.zIndex="5";let W=Up(eo,m),J=v.offsetWidth+W/2-k/2;vt.style.left=`${Math.max(0,J)}px`},ds=()=>{},Jh=()=>{let i=e.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640;return!m||i.innerWidth>y?!1:A||Lt(o)},cs=()=>!Jt(o)||!as()||e.classList.contains("persona-artifact-narrow-host")||Jh()||(e.ownerDocument.defaultView??window).innerWidth<TC?"none":_p(o)?"detached":"welded",Fn=()=>{if(!Ye||!Jt(o))return;Ka(e,o),Xa(e,o),ds();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,m=fe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=i);let y=as();Ye.setVisible(y),Ye.update(xn),Dn?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),bn=!1,Zr=!1):xn.artifacts.length>0&&vu()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),bn=!1,Zr=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(v),Ye.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ye.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ye.setTabFade(o.features?.artifacts?.layout?.tabFade),Ye.setRenderTabBar(o.features?.artifacts?.renderTabBar),!v&&!Zr&&(bn=!1),bn!==Au){let W=Ye.element;bn?(is=W.style.width,ls=W.style.maxWidth,W.style.removeProperty("width"),W.style.removeProperty("max-width")):(is&&(W.style.width=is),ls&&(W.style.maxWidth=ls),is="",ls=""),Au=bn}e.classList.toggle("persona-artifact-expanded",bn),Ye.setExpanded(bn);let k=cs();k!==Yr&&(Yr=k,Qr()),ul()};if(Jt(o)){fe.style.position="relative";let i=x("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=x("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(pe),Ye=zg(o,{onSelect:y=>dt.current?.selectArtifact(y),onDismiss:()=>{Dn=!0,Fn()},onToggleExpand:()=>{let y=!bn,v=xn.selectedId??xn.artifacts[xn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:v,expanded:y})!==!0&&(bn=y,y||(Zr=!1),Fn())}}),Ye.element.classList.add("persona-hidden"),eo=m,m.appendChild(i),m.appendChild(Ye.element),Ye.backdrop&&fe.appendChild(Ye.backdrop),fe.appendChild(m),ul=()=>{if(!eo||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){ea?.(),ea=null,fl(),vt&&(vt.remove(),vt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!vt){let v=x("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");v.setAttribute("role","separator"),v.setAttribute("aria-orientation","vertical"),v.setAttribute("aria-label","Resize artifacts panel"),v.tabIndex=0;let k=e.ownerDocument,W=k.defaultView??window,J=V=>{if(!Ye||V.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||W.innerWidth<=640)return;V.preventDefault(),fl();let X=V.clientX,oe=Ye.element.getBoundingClientRect().width,ue=o.features?.artifacts?.layout,ne=ze=>{let ut=eo.getBoundingClientRect().width,nt=e.classList.contains("persona-artifact-welded-split"),an=Up(eo,W),St=nt?0:v.getBoundingClientRect().width||6,It=oe-(ze.clientX-X),O=Kg(It,ut,an,St,ue?.resizableMinWidth,ue?.resizableMaxWidth);Ye.element.style.width=`${O}px`,Ye.element.style.maxWidth="none",Su()},be=()=>{k.removeEventListener("pointermove",ne),k.removeEventListener("pointerup",be),k.removeEventListener("pointercancel",be),ss=null;try{v.releasePointerCapture(V.pointerId)}catch{}};ss=be,k.addEventListener("pointermove",ne),k.addEventListener("pointerup",be),k.addEventListener("pointercancel",be);try{v.setPointerCapture(V.pointerId)}catch{}};v.addEventListener("pointerdown",J),vt=v,eo.insertBefore(v,Ye.element),ea=()=>{v.removeEventListener("pointerdown",J)}}if(vt){let v=as();vt.classList.toggle("persona-hidden",!v),Su()}},ds=()=>{if(!A||!Ye||(o.launcher?.sidebarMode??!1)||Lt(o)&&tn(o).reveal==="emerge")return;let v=e.ownerDocument.defaultView??window,k=o.launcher?.mobileFullscreen??!0,W=o.launcher?.mobileBreakpoint??640;if(k&&v.innerWidth<=W||!Gg(o,A))return;let J=o.launcher?.width??o.launcherWidth??ln,V=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";as()?(fe.style.width=V,fe.style.maxWidth=V):(fe.style.width=J,fe.style.maxWidth=J)},typeof ResizeObserver<"u"&&(Jr=new ResizeObserver(()=>{Fn()}),Jr.observe(fe))}else fe.appendChild(pe);q()&&Ge&&(Te.peekBanner&&Ge.appendChild(Te.peekBanner),Ge.appendChild(j)),e.appendChild(Re),Ge&&e.appendChild(Ge);let ps=()=>{if(q()){fe.style.width="100%",fe.style.maxWidth="100%";let kt=o.launcher?.composerBar??{},en=Re.dataset.state==="expanded",Ms=kt.expandedSize??"anchored";if(!(en&&Ms!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let ga=o.theme?.components?.panel,Ts=wo(o),br=(Un,zo)=>Un==null||Un===""?zo:Kt(Ts,Un)??Un,Es="1px solid var(--persona-border)",Ol="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Vo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=br(ga?.border,Es),pe.style.borderRadius=br(ga?.borderRadius,Vo),pe.style.boxShadow=br(ga?.shadow,Ol),pe.style.overflow="hidden";return}let i=Lt(o),m=o.launcher?.sidebarMode??!1,y=i||m||(o.launcher?.fullHeight??!1),v=o.launcher?.enabled===!1,k=o.launcher?.detachedPanel===!0,W=o.theme?.components?.panel,J=wo(o),V=(kt,en)=>kt==null||kt===""?en:Kt(J,kt)??kt,X=e.ownerDocument.defaultView??window,oe=o.launcher?.mobileFullscreen??!0,ue=o.launcher?.mobileBreakpoint??640,ne=X.innerWidth<=ue,be=oe&&ne&&A,ze=i&&oe&&ne,ut=o.launcher?.position??"bottom-left",nt=ut==="bottom-left"||ut==="top-left",an=o.launcher?.zIndex??Vt,St="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)))",O="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ie=k&&!be&&!ze;Ie?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let We=Ie?St:m||be?"none":St,_e=Ie?It:be?"none":m?nt?"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))":v?"none":It;i&&!be&&!Ie&&(_e="none",We="none");let Mt=Ie?O:m||be?"0":O,ft=V(W?.border,We),$t=V(W?.shadow,_e),mt=V(W?.borderRadius,Mt),Zt=cs(),Wt=Zt==="detached",He=Zt==="welded";e.classList.toggle("persona-artifact-detached-split",Wt),e.classList.toggle("persona-artifact-welded-split",He);let et="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)))))",st=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Jt(o)&&_p(o)&&v&&!i;e.classList.toggle("persona-artifact-chat-flush",st);let ct=Wt||st?"none":$t,gt=Wt?St:He?"none":ft,Ze=Wt?O:mt;st&&(gt="none",Ze="0");let De=W?.borderRadius!=null&&W.borderRadius!=="",yt=st&&!De?"0":mt,_t=ie.scrollTop;e.style.cssText="",Re.style.cssText="",fe.style.cssText="",pe.style.cssText="",ie.style.cssText="",j.style.cssText="",rt&&(ie.style.display="none"),(y||v)&&(e.style.minWidth="0");let gn=()=>{if(_t<=0)return;(ie.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ie.scrollTop===_t)return;let en=ie.scrollHeight-ie.clientHeight;en<=0||(ie.scrollTop=Math.min(_t,en))})};if(be){Re.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"),Re.style.cssText=`
|
|
50
50
|
position: fixed !important;
|
|
51
51
|
inset: 0 !important;
|
|
52
52
|
width: 100% !important;
|
|
@@ -56,9 +56,9 @@ _Details: ${n.message}_`:o}var Da=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
56
56
|
padding: 0 !important;
|
|
57
57
|
display: flex !important;
|
|
58
58
|
flex-direction: column !important;
|
|
59
|
-
z-index: ${
|
|
59
|
+
z-index: ${an} !important;
|
|
60
60
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
61
|
-
`,
|
|
61
|
+
`,fe.style.cssText=`
|
|
62
62
|
position: relative !important;
|
|
63
63
|
display: flex !important;
|
|
64
64
|
flex-direction: column !important;
|
|
@@ -71,7 +71,7 @@ _Details: ${n.message}_`:o}var Da=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
71
71
|
padding: 0 !important;
|
|
72
72
|
box-shadow: none !important;
|
|
73
73
|
border-radius: 0 !important;
|
|
74
|
-
`,
|
|
74
|
+
`,pe.style.cssText=`
|
|
75
75
|
display: flex !important;
|
|
76
76
|
flex-direction: column !important;
|
|
77
77
|
flex: 1 1 0% !important;
|
|
@@ -82,33 +82,33 @@ _Details: ${n.message}_`:o}var Da=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
82
82
|
overflow: hidden !important;
|
|
83
83
|
border-radius: 0 !important;
|
|
84
84
|
border: none !important;
|
|
85
|
-
`,
|
|
85
|
+
`,ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",j.style.flexShrink="0",F=!0,gn();return}let Ss=o?.launcher?.width??o?.launcherWidth??ln;if(!m&&!i)v&&y?(fe.style.width="100%",fe.style.maxWidth="100%"):(fe.style.width=Ss,fe.style.maxWidth=Ss);else if(i)if(tn(o).reveal==="emerge"&&!k){let en=tn(o).width;fe.style.width=en,fe.style.maxWidth=en}else fe.style.width="100%",fe.style.maxWidth="100%";if(ds(),fe.style.boxShadow=ct,fe.style.borderRadius=yt,Wt?fe.style.border="none":He&&(fe.style.border=ft),pe.style.border=gt,pe.style.borderRadius=Ze,pe.style.boxShadow=Wt&&!st?et:"",st&&(pe.style.background="transparent",ie.style.background="transparent",j.style.background="transparent",j.style.borderTop="none"),He){let kt=o.features?.artifacts?.layout;rs=kt?.unifiedSplitOuterRadius?.trim()||kt?.paneBorderRadius?.trim()||mt}else rs=null;if(i&&!be&&!Ie&&!Wt&&!He&&W?.border===void 0&&(pe.style.border="none",tn(o).side==="right"?pe.style.borderLeft="1px solid var(--persona-border)":pe.style.borderRight="1px solid var(--persona-border)"),i&&!be&&He&&W?.border===void 0&&(tn(o).side==="right"?fe.style.borderLeft="1px solid var(--persona-border)":fe.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",v&&(e.style.width="100%"),Re.style.display="flex",Re.style.flexDirection="column",Re.style.flex="1 1 0%",Re.style.minHeight="0",Re.style.maxHeight="100%",Re.style.height="100%",v&&(Re.style.overflow="hidden"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.height="100%",Wt||(fe.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",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",j.style.flexShrink="0"),v&&(Ie||Wt||st)&&!i&&(st||(Re.style.padding="var(--persona-panel-inset)"),Re.style.background="var(--persona-panel-canvas-bg)"),Re.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"),!m&&!v&&!i&&(kn[ut]??kn["bottom-right"]).split(" ").forEach(en=>Re.classList.add(en)),m){let kt=o.launcher?.sidebarWidth??"420px";k?Re.style.cssText=`
|
|
86
86
|
position: fixed !important;
|
|
87
87
|
top: var(--persona-panel-inset) !important;
|
|
88
88
|
bottom: var(--persona-panel-inset) !important;
|
|
89
|
-
width: ${
|
|
89
|
+
width: ${kt} !important;
|
|
90
90
|
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
91
91
|
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
92
92
|
margin: 0 !important;
|
|
93
93
|
padding: 0 !important;
|
|
94
94
|
display: flex !important;
|
|
95
95
|
flex-direction: column !important;
|
|
96
|
-
z-index: ${
|
|
97
|
-
${
|
|
96
|
+
z-index: ${an} !important;
|
|
97
|
+
${nt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
98
98
|
`:Re.style.cssText=`
|
|
99
99
|
position: fixed !important;
|
|
100
100
|
top: 0 !important;
|
|
101
101
|
bottom: 0 !important;
|
|
102
|
-
width: ${
|
|
102
|
+
width: ${kt} !important;
|
|
103
103
|
height: 100vh !important;
|
|
104
104
|
max-height: 100vh !important;
|
|
105
105
|
margin: 0 !important;
|
|
106
106
|
padding: 0 !important;
|
|
107
107
|
display: flex !important;
|
|
108
108
|
flex-direction: column !important;
|
|
109
|
-
z-index: ${
|
|
110
|
-
${
|
|
111
|
-
`,
|
|
109
|
+
z-index: ${an} !important;
|
|
110
|
+
${nt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
111
|
+
`,fe.style.cssText=`
|
|
112
112
|
position: relative !important;
|
|
113
113
|
display: flex !important;
|
|
114
114
|
flex-direction: column !important;
|
|
@@ -119,10 +119,10 @@ _Details: ${n.message}_`:o}var Da=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
119
119
|
min-height: 0 !important;
|
|
120
120
|
margin: 0 !important;
|
|
121
121
|
padding: 0 !important;
|
|
122
|
-
box-shadow: ${
|
|
123
|
-
border-radius: ${
|
|
124
|
-
${
|
|
125
|
-
`,
|
|
122
|
+
box-shadow: ${ct} !important;
|
|
123
|
+
border-radius: ${yt} !important;
|
|
124
|
+
${Wt?"border: none !important;":He?`border: ${ft} !important;`:""}
|
|
125
|
+
`,fe.style.setProperty("width","100%","important"),fe.style.setProperty("max-width","100%","important"),pe.style.cssText=`
|
|
126
126
|
display: flex !important;
|
|
127
127
|
flex-direction: column !important;
|
|
128
128
|
flex: 1 1 0% !important;
|
|
@@ -131,32 +131,32 @@ _Details: ${n.message}_`:o}var Da=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
131
131
|
min-height: 0 !important;
|
|
132
132
|
max-height: 100% !important;
|
|
133
133
|
overflow: hidden !important;
|
|
134
|
-
border-radius: ${
|
|
135
|
-
border: ${
|
|
136
|
-
${
|
|
137
|
-
${
|
|
134
|
+
border-radius: ${Ze} !important;
|
|
135
|
+
border: ${gt} !important;
|
|
136
|
+
${Wt&&!st?`box-shadow: ${et} !important;`:""}
|
|
137
|
+
${st?"background: transparent !important;":""}
|
|
138
138
|
`,j.style.cssText=`
|
|
139
139
|
flex-shrink: 0 !important;
|
|
140
140
|
border-top: none !important;
|
|
141
141
|
padding: 8px 16px 12px 16px !important;
|
|
142
|
-
${
|
|
143
|
-
`}if(!C&&!i){let Pt="max-height: -moz-available !important; max-height: stretch !important;",en=m?"":"padding-top: 1.25em !important;",Ps=m?"":`z-index: ${o.launcher?.zIndex??zt} !important;`;Re.style.cssText+=Pt+en+Ps}zo()};ys(),or(e,o),es(e,o),ts(e,o),ta=()=>{ys(),or(e,o),es(e,o),ts(e,o),cs?e.style.setProperty("--persona-artifact-welded-outer-radius",cs):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let $e=[];$e.push(()=>{document.removeEventListener("keydown",vu)}),$e.push(()=>{Yr!==null&&clearTimeout(Yr)});let Pn=null,Rn=null;$e.push(()=>{Pn?.(),Pn=null,Rn?.(),Rn=null}),ea&&$e.push(()=>{ea?.disconnect(),ea=null}),$e.push(()=>{ra?.(),ra=null,hl(),Ct&&(Ct.remove(),Ct=null),tt?.element.style.removeProperty("width"),tt?.element.style.removeProperty("maxWidth")}),ee&&$e.push(()=>{Ye!==null&&(cancelAnimationFrame(Ye),Ye=null),Oe?.destroy(),Oe=null,Ne?.destroy(),Ne=null,be=null});let Do=null,Su=()=>{Do&&(Do(),Do=null),o.colorScheme==="auto"&&(Do=Dr(()=>{or(e,o)}))};Su(),$e.push(()=>{Do&&(Do(),Do=null)}),$e.push(s);let xs=o.features?.streamAnimation;if(xs?.type&&xs.type!=="none"){let i=Ur(xs.type,xs.plugins);i&&(Ni(i,e),$e.push(()=>pg(e)))}let bs=Ig(bt),Fo=null,z,yl=i=>{if(!z)return;let m=i??z.getMessages(),x=o.features?.suggestReplies?.enabled!==!1?$s(m):null;x?bs.render(x,z,ge,m,o.suggestionChipsConfig,{agentPushed:!0}):m.some(C=>C.role==="user")?bs.render([],z,ge,m):bs.render(o.suggestionChips,z,ge,m,o.suggestionChipsConfig)},vn=!1,No=ng(),hr=new Map,Oo=new Map,no=new Map,xl=0,$h=zn()!==null,rn=Ii(),fn=0,oo=null,mn=!1,Cs=!1,ro=0,wn=null,_o=null,bl=!1,vs=!1,Cl=null,aa=!0,vl=!1,wl=null,jh=4,ws=24,Gh=80,Al=new Map,Qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Mu=o.voiceRecognition?.autoResume??!1,_n=i=>{l.emit("voice:state",{active:Qe.active,source:i,timestamp:Date.now()})},An=()=>{S(i=>({...i,voiceState:{active:Qe.active,timestamp:Date.now(),manuallyDeactivated:Qe.manuallyDeactivated}}))},Kh=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=zp(d.voiceState),m=!!i.active,x=Number(i.timestamp??0);Qe.manuallyDeactivated=!!i.manuallyDeactivated,m&&Date.now()-x<hv&&setTimeout(()=>{Qe.active||(Qe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?z.toggleVoice().then(()=>{Qe.active=z.isVoiceActive(),_n("restore"),z.isVoiceActive()&&vr()}):Ms("restore"))},1e3)},Xh=()=>z?Qg(z.getMessages()).filter(i=>!i.__skipPersist):[],As=null,Tu=(i,m)=>{typeof console<"u"&&console.error(i,m)},Sl=(i,m)=>{let x=()=>{try{let J=i();return!J||typeof J.then!="function"?null:Promise.resolve(J).catch(V=>{Tu(m,V)})}catch(J){return Tu(m,J),null}},C=As,P=C?C.then(()=>x()??void 0):x();if(!P)return;let H=P.finally(()=>{As===H&&(As=null)});As=H};function Ml(i){if(!c?.save)return;let x={messages:i?Qg(i):z?Xh():[],metadata:d,artifacts:bn.artifacts,selectedArtifactId:bn.selectedId};Sl(()=>c.save(x),"[AgentWidget] Failed to persist state:")}let yr=null,Eu=()=>Re.querySelector("#persona-scroll-container")||se,sa=()=>{yr!==null&&(cancelAnimationFrame(yr),yr=null),mn=!1},ku=()=>{oo!==null&&(cancelAnimationFrame(oo),oo=null),Cs=!1,sa()},Jh=()=>vn&&El()&&(Zt()!=="anchor-top"||lu()),Tl=()=>{let i=Io()||"Jump to latest",m=Jh();It.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),ro>0?(Wo.textContent=String(ro),Wo.style.display="",It.setAttribute("aria-label",`${i} (${ro} new)`)):(Wo.textContent="",Wo.style.display="none",It.setAttribute("aria-label",m?`${i} (response streaming below)`:i))},Lu=()=>{ro!==0&&(ro=0,Tl())},El=()=>Yn()?!rn.isFollowing():!ko(se,ws),an=()=>{if(!ls()||lt){It.parentNode&&It.remove(),It.style.display="none";return}It.parentNode!==ue&&ue.appendChild(It),ur();let m=Dn(se)>0&&El();m?Tl():Lu(),It.style.display=m?"":"none"},ia=()=>{rn.pause()&&(ku(),an())},ao=()=>{rn.resume(),Lu(),an()},so=(i=!1)=>{Yn()&&rn.isFollowing()&&(!i&&!vn||(oo!==null&&(cancelAnimationFrame(oo),oo=null),Cs=!0,oo=requestAnimationFrame(()=>{oo=null,Cs=!1,rn.isFollowing()&&Qh(Eu(),i?220:140)})))},Pu=(i,m,x,C=()=>!0)=>{let P=i.scrollTop,H=m(),J=H-P;if(sa(),Math.abs(J)<1){mn=!0,i.scrollTop=H,fn=i.scrollTop,mn=!1;return}let V=performance.now();mn=!0;let X=ie=>1-Math.pow(1-ie,3),oe=ie=>{if(!C()){sa();return}let re=m();re!==H&&(H=re,J=H-P);let xe=ie-V,je=Math.min(xe/x,1),gt=X(je),it=P+J*gt;i.scrollTop=it,fn=i.scrollTop,je<1?yr=requestAnimationFrame(oe):(i.scrollTop=H,fn=i.scrollTop,yr=null,mn=!1)};yr=requestAnimationFrame(oe)},Qh=(i,m=500)=>{let x=Dn(i)-i.scrollTop;if(Math.abs(x)<1){fn=i.scrollTop;return}if(Math.abs(x)>=Gh){sa(),mn=!0,i.scrollTop=Dn(i),fn=i.scrollTop,mn=!1;return}Pu(i,()=>Dn(i),m,()=>rn.isFollowing())},Ru=()=>{let i=Eu();mn=!0,i.scrollTop=Dn(i),fn=i.scrollTop,mn=!1,an()},Iu=i=>{let m=0,x=i;for(;x&&x!==se;)m+=x.offsetTop,x=x.offsetParent;return m},Wu=()=>{if(Nh()!=="last-user-turn")return!1;let i=z?.getMessages()??[];if(i.length<2)return!1;let m=[...i].reverse().find(H=>H.role==="user");if(!m)return!1;let x=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),C=se.querySelector(`[data-message-id="${x}"]`);if(!C)return!1;let P=Math.min(Math.max(0,Iu(C)-su()),Dn(se));return mn=!0,se.scrollTop=P,fn=se.scrollTop,mn=!1,Zt()==="follow"&&!ko(se,ws)&&rn.pause(),an(),!0},Hu=i=>{Zn.style.height=`${Math.max(0,Math.round(i))}px`,wn&&(wn.spacerHeight=Math.max(0,i))},la=()=>{_o!==null&&(cancelAnimationFrame(_o),_o=null),sa(),wn=null,Zn.style.height="0px"},Yh=i=>{_o!==null&&cancelAnimationFrame(_o),_o=requestAnimationFrame(()=>{_o=null;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=se.querySelector(`[data-message-id="${m}"]`);if(!x)return;let C=Iu(x),P=wn?.spacerHeight??0,H=se.scrollHeight-P,{targetScrollTop:J,spacerHeight:V}=ig({anchorOffsetTop:C,topOffset:su(),viewportHeight:se.clientHeight,contentHeight:H});wn={initialSpacerHeight:V,contentHeightAtAnchor:H,spacerHeight:V},Hu(V),Pu(se,()=>J,220)})},Zh=()=>{if(Yn()){if(!rn.isFollowing()||ko(se,1))return;so(!vn);return}if(wn&&wn.initialSpacerHeight>0){let i=se.scrollHeight-wn.spacerHeight,m=lg({initialSpacerHeight:wn.initialSpacerHeight,contentHeightAtAnchor:wn.contentHeightAtAnchor,currentContentHeight:i});m!==wn.spacerHeight&&Hu(m)}an()},ey=i=>{let m=Zt();m==="follow"?(ao(),so(!0)):m==="anchor-top"&&(aa=!1,vl=!0,Yh(i))},ty=()=>{if(Zt()==="anchor-top"){if(vl){aa=!1;return}aa=!0,la(),ao(),so(!0)}},ny=i=>{let m=new Map;i.forEach(x=>{let C=Al.get(x.id);m.set(x.id,{streaming:x.streaming,role:x.role}),!C&&x.role==="assistant"&&(l.emit("assistant:message",x),!vs&&(Zt()!=="anchor-top"||lu())&&El()&&(ro+=1,Tl(),an(),cu(ro===1?"1 new message below.":`${ro} new messages below.`))),x.role==="assistant"&&C?.streaming&&x.streaming===!1&&l.emit("assistant:complete",x),x.variant==="approval"&&x.approval&&(C?x.approval.status!=="pending"&&l.emit("approval:resolved",{approval:x.approval,decision:x.approval.status}):l.emit("approval:requested",{approval:x.approval,message:x}))}),Al.clear(),m.forEach((x,C)=>{Al.set(C,x)})},oy=(i,m,x)=>{let C=document.createElement("div"),H=(()=>{let D=r.find(Fe=>Fe.renderLoadingIndicator);if(D?.renderLoadingIndicator)return D.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),J=(D,Fe)=>Fe==null?!1:typeof Fe=="string"?(D.textContent=Fe,!0):(D.appendChild(Fe),!0),V=new Set,X=new Set,oe=r.some(D=>D.renderAskUserQuestion),ie=[],re=[],xe=o.enableComponentStreaming!==!1,je=o.approval!==!1,gt=[];if(m.forEach(D=>{V.add(D.id);let Fe=oe&&jn(D),we=je&&D.variant==="approval"&&!!D.approval,_e=!Fe&&D.role==="assistant"&&!D.variant&&xe&&as(D);!we&&no.has(D.id)&&(i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),no.delete(D.id)),!_e&&Oo.has(D.id)&&(i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),Oo.delete(D.id));let St=jn(D)?`:${D.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${D.agentMetadata?.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",pt=tg(D,xl)+St,wt=Fe||we||_e?null:og(No,D.id,pt);if(wt){C.appendChild(wt.cloneNode(!0)),jn(D)&&D.toolCall?.id&&D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(X.add(D.toolCall.id),Pr(D,o,Ee.composerOverlay));return}let yt=null,qt=r.find(de=>!!(D.variant==="reasoning"&&de.renderReasoning||D.variant==="tool"&&de.renderToolCall||!D.variant&&de.renderMessage)),Vo=o.layout?.messages;if(jn(D)&&D.agentMetadata?.askUserQuestionAnswered===!0){hr.delete(D.id),i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime");return}if(Pa(D)&&o.features?.suggestReplies?.enabled!==!1)return;if(jn(D)&&o.features?.askUserQuestion?.enabled!==!1){let de=r.find(At=>typeof At.renderAskUserQuestion=="function");if(de&&ft.current){let At=hr.get(D.id),Gt=At!==pt,Dt=null;if(Gt){let{payload:nt,complete:Lt}=Gn(D),We=D.id,ot=()=>ft.current?.getMessages().find(sn=>sn.id===We);Dt=de.renderAskUserQuestion({message:D,payload:nt,complete:Lt,resolve:sn=>{let zo=ot();zo&&ft.current?.resolveAskUserQuestion(zo,sn)},dismiss:()=>{let sn=ot();sn?.agentMetadata?.awaitingLocalTool&&(ft.current?.markAskUserQuestionResolved(sn),ft.current?.resolveAskUserQuestion(sn,"(dismissed)"))},config:o})}let rt=At!=null;if(Gt&&Dt===null&&!rt){D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(X.add(D.toolCall.id),Pr(D,o,Ee.composerOverlay));return}let Ve=document.createElement("div");Ve.className="persona-flex",Ve.id=`wrapper-${D.id}`,Ve.setAttribute("data-wrapper-id",D.id),Ve.setAttribute("data-ask-plugin-stub","true"),Ve.setAttribute("data-preserve-runtime","true"),C.appendChild(Ve),ie.push({messageId:D.id,fingerprint:pt,bubble:Dt});return}else{D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(X.add(D.toolCall.id),Pr(D,o,Ee.composerOverlay));return}}else if(we){let de=r.find(rt=>typeof rt.renderApproval=="function")??a,Gt=no.get(D.id)!==pt,Dt=null;if(Gt&&de?.renderApproval){let rt=D.id,Ve=(nt,Lt)=>{let We=ft.current?.getMessages().find(ot=>ot.id===rt);We?.approval&&(We.approval.toolType==="webmcp"?ft.current?.resolveWebMcpApproval(We.id,nt):ft.current?.resolveApproval(We.approval,nt,Lt))};Dt=de.renderApproval({message:D,defaultRenderer:()=>Xi(D,o),config:o,approve:nt=>Ve("approved",nt),deny:nt=>Ve("denied",nt)})}if(Gt&&Dt===null)i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),no.delete(D.id),yt=Xi(D,o);else{let rt=document.createElement("div");rt.className="persona-flex",rt.id=`wrapper-${D.id}`,rt.setAttribute("data-wrapper-id",D.id),rt.setAttribute("data-approval-plugin-stub","true"),rt.setAttribute("data-preserve-runtime","true"),C.appendChild(rt),gt.push({messageId:D.id,fingerprint:pt,bubble:Dt});return}}else if(qt)if(D.variant==="reasoning"&&D.reasoning&&qt.renderReasoning){if(!ae)return;yt=qt.renderReasoning({message:D,defaultRenderer:()=>Ip(D,o),config:o})}else if(D.variant==="tool"&&D.toolCall&&qt.renderToolCall){if(!Ce)return;yt=qt.renderToolCall({message:D,defaultRenderer:()=>Hp(D,o),config:o})}else qt.renderMessage&&(yt=qt.renderMessage({message:D,defaultRenderer:()=>{let de=zr(D,x,Vo,o.messageActions,Se,{loadingIndicatorRenderer:H,widgetConfig:o});return D.role!=="user"&&Up(de,D,o,z),de},config:o}));if(!yt&&_e){let de=tl(D);if(de){let At=Oo.get(D.id),Gt=At!==pt,Dt=o.wrapComponentDirectiveInBubble!==!1&&kn.getOptions(de.component)?.bubbleChrome!==!1,rt=null;if(Gt){let Ve=el(de,{config:o,message:D,transform:x});if(Ve&&de.component==="PersonaArtifactInline"){let nt=Ve.hasAttribute("data-artifact-inline")?Ve:Ve.querySelector("[data-artifact-inline]"),Lt=nt?.getAttribute("data-artifact-inline")??"",We=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Lt):Lt,ot=Lt?i.querySelector(`#wrapper-${D.id}`)?.querySelector(`[data-artifact-inline="${We}"]`)??null:null;nt&&ot&&ot!==nt&&Xm(ot)&&(nt===Ve?Ve=ot:nt.replaceWith(ot))}if(Ve)if(Dt){let nt=document.createElement("div");if(nt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),nt.id=`bubble-${D.id}`,nt.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let Lt=document.createElement("div");Lt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Lt.innerHTML=x({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),nt.appendChild(Lt)}nt.appendChild(Ve),rt=nt}else{let nt=document.createElement("div");if(nt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",nt.id=`bubble-${D.id}`,nt.setAttribute("data-message-id",D.id),nt.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let Lt=document.createElement("div");Lt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Lt.innerHTML=x({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),nt.appendChild(Lt)}nt.appendChild(Ve),rt=nt}}if(rt||At!=null){let Ve=document.createElement("div");Ve.className="persona-flex",Ve.id=`wrapper-${D.id}`,Ve.setAttribute("data-wrapper-id",D.id),Ve.setAttribute("data-component-directive-stub","true"),Ve.setAttribute("data-preserve-runtime","true"),Dt||Ve.classList.add("persona-w-full"),C.appendChild(Ve),re.push({messageId:D.id,fingerprint:pt,bubble:rt});return}}}if(!yt)if(D.variant==="reasoning"&&D.reasoning){if(!ae)return;yt=Ip(D,o)}else if(D.variant==="tool"&&D.toolCall){if(!Ce)return;yt=Hp(D,o)}else if(D.variant==="approval"&&D.approval){if(o.approval===!1)return;yt=Xi(D,o)}else{let de=o.layout?.messages;de?.renderUserMessage&&D.role==="user"?yt=de.renderUserMessage({message:D,config:o,streaming:!!D.streaming}):de?.renderAssistantMessage&&D.role==="assistant"?yt=de.renderAssistantMessage({message:D,config:o,streaming:!!D.streaming}):yt=zr(D,x,de,o.messageActions,Se,{loadingIndicatorRenderer:H,widgetConfig:o}),D.role!=="user"&&yt&&Up(yt,D,o,z)}let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-${D.id}`,ut.setAttribute("data-wrapper-id",D.id),D.role==="user"&&ut.classList.add("persona-justify-end"),yt?.getAttribute("data-persona-component-directive")==="true"&&ut.classList.add("persona-w-full"),ut.appendChild(yt),rg(No,D.id,pt,ut),C.appendChild(ut)}),Ee.composerOverlay&&Ee.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Fe=>{let we=Fe.getAttribute("data-persona-ask-sheet-for");we&&!X.has(we)&&go(Ee.composerOverlay,we)}),o.features?.toolCallDisplay?.grouped){let D=[],Fe=[];m.forEach(we=>{if(we.variant==="tool"&&we.toolCall&&Ce){Fe.push(we);return}we.variant==="reasoning"&&!ae||(Fe.length>1&&D.push(Fe),Fe=[])}),Fe.length>1&&D.push(Fe),D.forEach((we,_e)=>{let St=we.map(At=>Array.from(C.children).find(Gt=>Gt instanceof HTMLElement&&Gt.getAttribute("data-wrapper-id")===At.id)).filter(At=>!!At);if(St.length<2)return;let pt=document.createElement("div");pt.className="persona-flex",pt.id=`wrapper-tool-group-${_e}-${we[0].id}`,pt.setAttribute("data-wrapper-id",`tool-group-${_e}-${we[0].id}`);let wt=document.createElement("div");wt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",wt.setAttribute("data-persona-tool-group","true");let yt=document.createElement("div");yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let qt=`Called ${we.length} tools`,Vo=o.toolCall?.renderGroupedSummary?.({messages:we,toolCalls:we.map(At=>At.toolCall).filter(At=>!!At),defaultSummary:qt,config:o});J(yt,Vo)||(yt.textContent=qt);let ut=document.createElement("div");ut.className="persona-tool-group-stack persona-flex persona-flex-col";let de=o.features?.toolCallDisplay?.groupedMode==="summary";wt.appendChild(yt),de||wt.appendChild(ut),pt.appendChild(wt),St[0].before(pt),St.forEach((At,Gt)=>{if(de){At.remove();return}let Dt=document.createElement("div");Dt.className="persona-tool-group-item persona-relative",Dt.setAttribute("data-persona-tool-group-item","true"),Gt<St.length-1&&Dt.setAttribute("data-persona-tool-group-connector","true"),Dt.appendChild(At),ut.appendChild(Dt)})})}ag(No,V);let it=m.some(D=>D.role==="assistant"&&D.streaming),jt=m[m.length-1],Bt=jt?.role==="assistant"&&!jt.streaming&&jt.variant!=="approval";if(vn&&m.some(D=>D.role==="user")&&!it&&!Bt){let D={config:o,streaming:!0,location:"standalone",defaultRenderer:ir},Fe=r.find(_e=>_e.renderLoadingIndicator),we=null;if(Fe?.renderLoadingIndicator&&(we=Fe.renderLoadingIndicator(D)),we===null&&o.loadingIndicator?.render&&(we=o.loadingIndicator.render(D)),we===null&&(we=ir()),we){let _e=document.createElement("div"),St=o.loadingIndicator?.showBubble!==!1;_e.className=St?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),_e.setAttribute("data-typing-indicator","true"),_e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",_e.appendChild(we);let pt=document.createElement("div");pt.className="persona-flex",pt.id="wrapper-typing-indicator",pt.setAttribute("data-wrapper-id","typing-indicator"),pt.appendChild(_e),C.appendChild(pt)}}if(!vn&&m.length>0){let D=m[m.length-1],Fe={config:o,lastMessage:D,messageCount:m.length},we=r.find(St=>St.renderIdleIndicator),_e=null;if(we?.renderIdleIndicator&&(_e=we.renderIdleIndicator(Fe)),_e===null&&o.loadingIndicator?.renderIdle&&(_e=o.loadingIndicator.renderIdle(Fe)),_e){let St=document.createElement("div"),pt=o.loadingIndicator?.showBubble!==!1;St.className=pt?["persona-max-w-[85%]","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-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),St.setAttribute("data-idle-indicator","true"),St.appendChild(_e);let wt=document.createElement("div");wt.className="persona-flex",wt.id="wrapper-idle-indicator",wt.setAttribute("data-wrapper-id","idle-indicator"),wt.appendChild(St),C.appendChild(wt)}}if(Ri(i,C),ie.length>0)for(let{messageId:D,fingerprint:Fe,bubble:we}of ie){let _e=i.querySelector(`#wrapper-${D}`);_e&&we!==null&&(_e.replaceChildren(we),_e.setAttribute("data-bubble-fp",Fe),hr.set(D,Fe))}if(hr.size>0)for(let D of hr.keys())V.has(D)||hr.delete(D);if(re.length>0)for(let{messageId:D,fingerprint:Fe,bubble:we}of re){let _e=i.querySelector(`#wrapper-${D}`);_e&&we!==null&&(_e.replaceChildren(we),_e.setAttribute("data-bubble-fp",Fe),Oo.set(D,Fe))}if(Oo.size>0)for(let D of Oo.keys())V.has(D)||Oo.delete(D);if(gt.length>0)for(let{messageId:D,fingerprint:Fe,bubble:we}of gt){let _e=i.querySelector(`#wrapper-${D}`);_e&&we!==null&&(_e.replaceChildren(we),_e.setAttribute("data-bubble-fp",Fe),no.set(D,Fe))}if(no.size>0)for(let D of no.keys())V.has(D)||no.delete(D)},da=(i,m,x)=>{oy(i,m,x),xu()},ca=null,ry=()=>{if(ca)return;let i=x=>{let C=x.composedPath();C.includes(Re)||Je&&C.includes(Je)||mt(!1,"user")};ca=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},Bu=()=>{if(!ca)return;(e.ownerDocument??document).removeEventListener("pointerdown",ca,!0),ca=null};$e.push(()=>Bu());let pa=null,ay=()=>{if(pa)return;let i=x=>{x.key==="Escape"&&(x.isComposing||mt(!1,"user"))};pa=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Du=()=>{if(!pa)return;(e.ownerDocument??document).removeEventListener("keydown",pa,!0),pa=null};$e.push(()=>Du());let ua=!1,Fu=new Set,sy=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},xr=()=>{if(!$())return;let i=Ee.peekBanner,m=Ee.peekTextNode;if(!i||!m)return;if(U){i.classList.remove("persona-pill-peek--visible");return}let x=z?.getMessages()??[],C;for(let Bt=x.length-1;Bt>=0;Bt--){let D=x[Bt];if(D.role==="assistant"&&D.content){C=D;break}}if(!C){i.classList.remove("persona-pill-peek--visible");return}let P=C.content,H=!!C.streaming,J=sy(),V=Bi(J),X=V.type!=="none"?Ur(V.type,J?.plugins):null,oe=X?.isAnimating?.(C)===!0,ie=X!==null&&(H||oe);ie&&X&&!Fu.has(X.name)&&(Ni(X,e),Fu.add(X.name));let re=ie&&X?.containerClass?X.containerClass:null,xe=m.dataset.personaPeekStreamClass??null;xe&&xe!==re&&(m.classList.remove(xe),delete m.dataset.personaPeekStreamClass),re&&xe!==re&&(m.classList.add(re),m.dataset.personaPeekStreamClass=re),ie?(m.style.setProperty("--persona-stream-step",`${V.speed}ms`),m.style.setProperty("--persona-stream-duration",`${V.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let je=ie?Di(P,V.buffer,X,C,H):P;if(ie&&V.placeholder==="skeleton"&&H&&(!je||!je.trim())){let Bt=document.createElement("div"),D=Ka();D.classList.add("persona-pill-peek__skeleton"),Bt.appendChild(D),Ri(m,Bt)}else{let Bt=Math.max(0,je.length-100),D=je.length>100?je.slice(-100):je,Fe=Wn(D);if(!ie||!X){let we=je.length>100?`\u2026${D}`:D;m.textContent!==we&&(m.textContent=we)}else{let we=Fe;(X.wrap==="char"||X.wrap==="word")&&(we=Ga(Fe,X.wrap,`peek-${C.id}`,{skipTags:X.skipTags,startIndex:Bt}));let _e=document.createElement("div");if(_e.innerHTML=we,X.useCaret&&D.length>0){let St=Fi(),pt=_e.querySelectorAll(".persona-stream-char, .persona-stream-word"),wt=pt[pt.length-1];wt?.parentNode?wt.parentNode.insertBefore(St,wt.nextSibling):_e.appendChild(St)}Ri(m,_e),X.onAfterRender?.({container:m,bubble:i,messageId:C.id,message:C,speed:V.speed,duration:V.duration})}}let jt=vn||ua;i.classList.toggle("persona-pill-peek--visible",jt)};if($()){let i=Ee.peekBanner;if(i){let C=P=>{P.preventDefault(),P.stopPropagation(),mt(!0,"user")};i.addEventListener("pointerdown",C),$e.push(()=>{i.removeEventListener("pointerdown",C)})}let m=()=>{ua||(ua=!0,xr())},x=()=>{ua&&(ua=!1,xr())};me.addEventListener("pointerenter",m),me.addEventListener("pointerleave",x),$e.push(()=>{me.removeEventListener("pointerenter",m),me.removeEventListener("pointerleave",x)}),Je&&(Je.addEventListener("pointerenter",m),Je.addEventListener("pointerleave",x),$e.push(()=>{Je.removeEventListener("pointerenter",m),Je.removeEventListener("pointerleave",x)}))}let iy=i=>{let m=o.launcher?.composerBar??{},x=m.expandedSize??"anchored",C=m.bottomOffset??"16px",P=m.collapsedMaxWidth,H=m.expandedMaxWidth??"880px",J=m.expandedTopOffset??"5vh",V=m.modalMaxWidth??"880px",X=m.modalMaxHeight??"min(90vh, 800px)",oe="calc(100vw - 32px)",ie="var(--persona-pill-area-height, 80px)",re=Re.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",Je){let xe=Je.style;xe.bottom=C,xe.width=P??""}if(i&&x!=="fullscreen"){if(x==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=V,re.maxWidth=oe,re.maxHeight=X,re.height=X;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${C} + ${ie})`,re.top=J,re.width=H,re.maxWidth=oe}},fa=()=>{if(!N())return;if($()){let oe=(o.launcher?.composerBar??{}).expandedSize??"anchored",ie=U?"expanded":"collapsed";Re.dataset.state=ie,Re.dataset.expandedSize=oe,Je&&(Je.dataset.state=ie,Je.dataset.expandedSize=oe),Re.style.removeProperty("display"),Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),iy(U),ue.style.display=U?"flex":"none",ys(),U?(ry(),ay()):(Bu(),Du()),xr();return}let i=Rt(o),m=e.ownerDocument.defaultView??window,x=o.launcher?.mobileBreakpoint??640,C=o.launcher?.mobileFullscreen??!0,P=m.innerWidth<=x,H=C&&P&&A,J=nn(o).reveal;U?(Re.style.removeProperty("display"),Re.style.display=i?"flex":"",Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0"),me.classList.add("persona-scale-100","persona-opacity-100"),Ot?Ot.element.style.display="none":$t&&($t.style.display="none")):(i?i&&(J==="overlay"||J==="push")&&!H?(Re.style.removeProperty("display"),Re.style.display="flex",Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Re.style.setProperty("display","none","important"),Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Re.style.display="",Re.classList.add("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100"),me.classList.add("persona-scale-95","persona-opacity-0")),Ot?Ot.element.style.display=i?"none":"":$t&&($t.style.display=i?"none":""))},mt=(i,m="user")=>{if(!N()||U===i)return;let x=U;U=i,fa();let C=(()=>{let H=o.launcher?.sidebarMode??!1,J=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,oe=J.innerWidth<=X,ie=Rt(o)&&V&&oe,re=$()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return H||V&&oe&&A||ie||re})();if(U&&C){if(!Pn){let H=e.getRootNode(),J=H instanceof ShadowRoot?H.host:e.closest(".persona-host");J&&(Pn=vp(J,o.launcher?.zIndex??zt))}Rn||(Rn=wp(e.ownerDocument))}else U||(Pn?.(),Pn=null,Rn?.(),Rn=null);U&&(ha(),Wu()||(Zt()==="follow"?so(!0):Ru()));let P={open:U,source:m,timestamp:Date.now()};U&&!x?l.emit("widget:opened",P):!U&&x&&l.emit("widget:closed",P),l.emit("widget:state",{open:U,launcherEnabled:A,voiceActive:Qe.active,streaming:z.isStreaming()})},kl=i=>{dt(i?"stop":"send"),K&&(K.disabled=i),bs.buttons.forEach(m=>{m.disabled=i}),j.dataset.personaComposerStreaming=i?"true":"false",j.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=i)})},Ll=()=>{Qe.active||ge&&ge.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Ll(),200)});let Nu=()=>{q.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",b.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",ge.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=se.querySelector("[data-persona-intro-card]");if(i){let x=o.copy?.showWelcomeCard!==!1;i.style.display=x?"":"none",x?(se.classList.remove("persona-gap-3"),se.classList.add("persona-gap-6")):(se.classList.remove("persona-gap-6"),se.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!z?.isStreaming()&&(pe.textContent=o.copy?.sendButtonLabel??"Send"),ge.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ge.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=d.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{S(m=>({...m,sessionId:i}))}});let Uo=null,ly=()=>{Uo==null&&(Uo=setInterval(()=>{let i=ye.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Uo),Uo=null;return}let m=Date.now();i.forEach(x=>{let C=Number(x.getAttribute("data-tool-elapsed"));C&&(x.textContent=Gs(m-C))})},100))},Pl=(i,m)=>{if(Object.is(i,m))return!0;if(i===null||m===null||typeof i!="object"||typeof m!="object")return!1;if(Array.isArray(i)||Array.isArray(m))return!Array.isArray(i)||!Array.isArray(m)||i.length!==m.length?!1:i.every((J,V)=>Pl(J,m[V]));let x=i,C=m,P=Object.keys(x),H=Object.keys(C);return P.length===H.length&&P.every(J=>Object.prototype.hasOwnProperty.call(C,J)&&Pl(x[J],C[J]))},Ou=i=>{let{content:m,rawContent:x,llmContent:C,...P}=i;return P},Rl=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!as(i),dy=(i,m,x)=>{if(i.length!==m.length)return!1;let C=i[x.index],P=m[x.index];return!C||!P||C.id!==x.id||P.id!==x.id?!1:(!Object.is(C.content,P.content)||!Object.is(C.rawContent,P.rawContent)||!Object.is(C.llmContent,P.llmContent))&&Rl(C)&&Rl(P)&&Pl(Ou(C),Ou(P))},_u=null,br=null,qo=null,Un=null,Ss=i=>{_u=i;let m,x;br=null;for(let P=i.length-1;P>=0;P-=1){let H=i[P];if(!m&&H.role==="user"&&(m=H),!x&&H.role==="assistant"&&(x=H),!br&&Rl(H)&&(br={index:P,id:H.id}),m&&x&&br)break}da(ye,i,De),fp(ye,bn.artifacts,{suppressTransition:vn}),ly(),yl(i),so(!vn),ny(i),i.length===0&&(la(),aa=!0,vl=!1),!bl||vs?(bl=!0,Cl=m?.id??null,wl=x?.id??null):m&&m.id!==Cl?(Cl=m.id,ey(m.id)):x&&x.id!==wl&&ty(),x&&(wl=x.id);let C=Qe.lastUserMessageId;m&&m.id!==C&&(Qe.lastUserMessageId=m.id,l.emit("user:message",m)),Qe.lastUserMessageWasVoice=!!m?.viaVoice,Ml(i),xr()},Il=()=>{Un!==null&&(cancelAnimationFrame(Un),Un=null);let i=qo;qo=null,i&&Ss(i)},Uu=()=>{Un!==null&&cancelAnimationFrame(Un),Un=null,qo=null},cy=i=>{let m=qo??_u;if(vn&&m&&br&&dy(m,i,br)){qo=i,Un===null&&(Un=requestAnimationFrame(()=>{Un=null;let x=qo;qo=null,x&&Ss(x)}));return}if(i.length===0){Uu(),Ss(i);return}Il(),Ss(i)};z=new Hr(o,{onMessagesChanged(i){cy(i)},onStatusChanged(i){let m=o.statusIndicator??{};kt(I,(C=>C==="idle"?m.idleText??Ht.idle:C==="connecting"?m.connectingText??Ht.connecting:C==="connected"?m.connectedText??Ht.connected:C==="error"?m.errorText??Ht.error:C==="paused"?m.pausedText??Ht.paused:C==="resuming"?m.resumingText??Ht.resuming:Ht[C])(i),m,i)},onStreamingChanged(i){i||(z?.getMessages().length===0?Uu():Il()),vn=i,kl(i),z&&da(ye,z.getMessages(),De),i||so(!0),an(),cu(i?"Responding\u2026":"Response complete."),xr()},onVoiceStatusChanged(i){if(l.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":qn(),vr();break;case"processing":qn(),vy();break;case"speaking":qn(),wy();break;default:i==="idle"&&z.isBargeInActive()?(qn(),vr(),K?.setAttribute("aria-label","End voice session")):(Qe.active=!1,qn(),_n("system"),An());break}},onArtifactsState(i){bn=i,i.artifacts.length===0&&(fr=!1),fp(ye,i.artifacts,{suppressTransition:vn}),On(),Ml()},onReconnect(i){let{executionId:m,lastEventId:x}=i.handle;i.phase==="paused"?l.emit("stream:paused",{executionId:m,after:x}):i.phase==="resuming"?l.emit("stream:resuming",{executionId:m,after:x,attempt:i.attempt??1}):l.emit("stream:resumed",{executionId:m,after:x})}}),ft.current=z,$e.push(()=>z.cancel());let Wl=null;if(z.onReadAloudChange((i,m)=>{hu=i,yu=m,xu();let x=i??Wl;i&&(Wl=i);let C=x?z.getMessages().find(P=>P.id===x)??null:null;l.emit("message:read-aloud",{messageId:x,message:C,state:m,timestamp:Date.now()}),m==="idle"&&(Wl=null)}),bl=!0,o.voiceRecognition?.provider?.type==="runtype")try{z.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&z.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Ne||o.onSSEEvent)&&z.setSSEEventCallback((i,m)=>{o.onSSEEvent?.(i,m),Xe?.processEvent(i,m),Ne?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(m)})});let qu=()=>{o.resume&&typeof o.reconnectStream=="function"&&z.resumeFromHandle(o.resume)};u?u.then(i=>{if(i){if(i.metadata&&(d=zp(i.metadata),M.syncFromMetadata()),i.messages?.length){vs=!0;try{z.hydrateMessages(i.messages)}finally{vs=!1}}i.artifacts?.length&&z.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>qu()):qu();let Vu=()=>{!$()||U||!(o.launcher?.composerBar?.expandOnSubmit??!0)||mt(!0,"auto")},py=(i,m)=>i?m?{refs:[...i.refs,...m.refs],finalize:async()=>{let[x,C]=await Promise.allSettled([i.finalize(),m.finalize()]),P=[];return x.status==="fulfilled"?P.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),C.status==="fulfilled"?P.push(C.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",C.reason),Av(P)}}:i:m,uy=()=>{let m=ge.getInlineMessageFields?.();return m&&m.contentSegments.some(C=>C.kind==="mention")?m.contentSegments:void 0},ma=!1,fy=async i=>{let m=ge.value.trim(),x=Mt?.hasAttachments()??!1,C=m?await(on?.takeInlineCommand(m)??Promise.resolve(null)):null;if(C?.kind==="action"){ge.value="",ge.style.height="auto",ga(),on?.clear();return}let P=on?.collectForSubmit()??null,H=C?.kind==="server"?C.mentions:null,J=py(P,H),V=C?.kind==="prompt"?C.sendText:m,X=!!P&&P.refs.length>0;if(!V&&!x&&!X&&!H)return;Vu();let oe;x&&(oe=[],oe.push(...Mt.getContentParts()),V&&oe.push(bo(V)));let ie=C?.kind==="prompt"?void 0:uy();ge.value="",ge.style.height="auto",ga(),z.sendMessage(V,{contentParts:oe,mentions:J??void 0,contentSegments:ie,viaVoice:i?.viaVoice}),x&&Mt.clearAttachments(),P&&on?.clear()},Hl=async i=>{if(!ma){ma=!0;try{await fy(i)}finally{ma=!1}}},zu=i=>{if(i.preventDefault(),z.isStreaming()){z.cancel(),Xe?.reset(),Oe?.update();return}ma||Hl()},my=()=>o.features?.composerHistory!==!1,Bl={...hp},Dl=!1,ga=()=>{Bl={...hp}},gy=()=>z.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),hy=i=>{if(!ge)return;Dl=!0,ge.value=i,ge.dispatchEvent(new Event("input",{bubbles:!0})),Dl=!1;let m=ge.value.length;ge.setSelectionRange(m,m)},yy=i=>{Dl||(i.isComposing||on?.handleInput(i.inputType??void 0),ga())},xy=i=>{if(ge&&!(!i.isComposing&&on?.handleKeydown(i))){if(my()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let m=ge.selectionStart===0&&ge.selectionEnd===0,x=eg({direction:i.key==="ArrowUp"?"up":"down",history:gy(),currentValue:ge.value,atStart:m,state:Bl});if(Bl=x.state,x.handled){i.preventDefault(),x.value!==void 0&&hy(x.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(z.isStreaming()){i.preventDefault();return}if(ma){i.preventDefault();return}ga(),i.preventDefault(),pe.click()}}},$u=i=>{i.key!=="Escape"||i.isComposing||z.isStreaming()&&i.composedPath().includes(ue)&&(z.cancel(),Xe?.reset(),Oe?.update(),ga(),i.preventDefault(),i.stopImmediatePropagation())},by=async i=>{if(o.attachments?.enabled!==!0||!Mt)return;let m=bv(i.clipboardData);m.length!==0&&(i.preventDefault(),await Mt.handleFiles(m))},gn=null,In=!1,Cr=null,vt=null,ju=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ms=(i="user")=>{if(In||z.isStreaming())return;let m=ju();if(!m)return;gn=new m;let C=(o.voiceRecognition??{}).pauseDuration??2e3;gn.continuous=!0,gn.interimResults=!0,gn.lang="en-US";let P=ge.value;gn.onresult=H=>{let J="",V="";for(let oe=0;oe<H.results.length;oe++){let ie=H.results[oe],re=ie[0].transcript;ie.isFinal?J+=re+" ":V=re}let X=P+J+V;ge.value=X,Cr&&clearTimeout(Cr),(J||V)&&(Cr=window.setTimeout(()=>{ge.value.trim()&&gn&&In&&(io(),Hl({viaVoice:!0}))},C))},gn.onerror=H=>{H.error!=="no-speech"&&io()},gn.onend=()=>{if(In){let H=ge.value.trim();H&&H!==P.trim()&&Hl({viaVoice:!0}),io()}};try{if(gn.start(),In=!0,Qe.active=!0,i!=="system"&&(Qe.manuallyDeactivated=!1),_n(i),An(),K){let H=o.voiceRecognition??{};vt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:H.iconName??"mic",iconSize:parseFloat(H.iconSize??o.sendButton?.size??"40")||24};let J=H.recordingBackgroundColor,V=H.recordingIconColor,X=H.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=J??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=V??"var(--persona-voice-recording-indicator, #ffffff)",V){let oe=K.querySelector("svg");oe&&oe.setAttribute("stroke",V)}X&&(K.style.borderColor=X),K.setAttribute("aria-label","Stop voice recognition")}}catch{io("system")}},io=(i="user")=>{if(In){if(In=!1,Cr&&(clearTimeout(Cr),Cr=null),gn){try{gn.stop()}catch{}gn=null}if(Qe.active=!1,_n(i),An(),K){if(K.classList.remove("persona-voice-recording"),vt){K.style.backgroundColor=vt.backgroundColor,K.style.color=vt.color,K.style.borderColor=vt.borderColor;let m=K.querySelector("svg");m&&m.setAttribute("stroke",vt.color||"currentColor"),vt=null}K.setAttribute("aria-label","Start voice recognition")}}},Cy=(i,m)=>{let x=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),C=i?.provider?.type==="runtype",P=i?.provider?.type==="custom";if(!(x||C||P))return null;let J=y("div","persona-send-button-wrapper"),V=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");V.type="button",V.setAttribute("aria-label","Start voice recognition");let X=i?.iconName??"mic",oe=m?.size??"40px",ie=i?.iconSize??oe,re=parseFloat(ie)||24,xe=i?.backgroundColor??m?.backgroundColor,je=i?.iconColor??m?.textColor;V.style.width=ie,V.style.height=ie,V.style.minWidth=ie,V.style.minHeight=ie,V.style.fontSize="18px",V.style.lineHeight="1",je?V.style.color=je:V.style.color="var(--persona-text, #111827)";let it=te(X,re,je||"currentColor",1.5);it?V.appendChild(it):V.textContent="\u{1F3A4}",xe?V.style.backgroundColor=xe:V.style.backgroundColor="",i?.borderWidth&&(V.style.borderWidth=i.borderWidth,V.style.borderStyle="solid"),i?.borderColor&&(V.style.borderColor=i.borderColor),i?.paddingX&&(V.style.paddingLeft=i.paddingX,V.style.paddingRight=i.paddingX),i?.paddingY&&(V.style.paddingTop=i.paddingY,V.style.paddingBottom=i.paddingY),J.appendChild(V);let jt=i?.tooltipText??"Start voice recognition";if((i?.showTooltip??!1)&&jt){let D=y("div","persona-send-button-tooltip");D.textContent=jt,J.appendChild(D)}return{micButton:V,micButtonWrapper:J}},Fl=()=>{if(!K||vt)return;let i=o.voiceRecognition??{};vt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Nl=(i,m)=>{if(!K)return;let x=K.querySelector("svg");x&&x.remove();let C=vt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),P=te(i,C,m,1.5);P&&K.appendChild(P)},Ts=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},vr=()=>{if(!K)return;Fl();let i=o.voiceRecognition??{},m=i.recordingBackgroundColor,x=i.recordingIconColor,C=i.recordingBorderColor;if(Ts(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=m??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=x??"var(--persona-voice-recording-indicator, #ffffff)",x){let P=K.querySelector("svg");P&&P.setAttribute("stroke",x)}C&&(K.style.borderColor=C),K.setAttribute("aria-label","Stop voice recognition")},vy=()=>{if(!K)return;Fl();let i=o.voiceRecognition??{},m=z.getVoiceInterruptionMode(),x=i.processingIconName??"loader",C=i.processingIconColor??vt?.color??"",P=i.processingBackgroundColor??vt?.backgroundColor??"",H=i.processingBorderColor??vt?.borderColor??"";Ts(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=P,K.style.borderColor=H;let J=C||"currentColor";K.style.color=J,Nl(x,J),K.setAttribute("aria-label","Processing voice input"),m==="none"&&(K.style.cursor="default")},wy=()=>{if(!K)return;Fl();let i=o.voiceRecognition??{},m=z.getVoiceInterruptionMode(),x=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",C=i.speakingIconName??x,P=i.speakingIconColor??(m==="barge-in"?i.recordingIconColor??vt?.color??"":vt?.color??""),H=i.speakingBackgroundColor??(m==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),J=i.speakingBorderColor??(m==="barge-in"?i.recordingBorderColor??"":vt?.borderColor??"");Ts(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=H,K.style.borderColor=J;let V=P||"currentColor";K.style.color=V,Nl(C,V);let X=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",X),m==="none"&&(K.style.cursor="default"),m==="barge-in"&&K.classList.add("persona-voice-recording")},qn=()=>{K&&(Ts(),vt&&(K.style.backgroundColor=vt.backgroundColor??"",K.style.color=vt.color??"",K.style.borderColor=vt.borderColor??"",Nl(vt.iconName,vt.color||"currentColor"),vt=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},Es=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=z.getVoiceStatus(),m=z.getVoiceInterruptionMode();if(m==="none"&&(i==="processing"||i==="speaking"))return;if(m==="cancel"&&(i==="processing"||i==="speaking")){z.stopVoicePlayback();return}if(z.isBargeInActive()){z.stopVoicePlayback(),z.deactivateBargeIn().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,An(),_n("user"),qn()});return}z.toggleVoice().then(()=>{Qe.active=z.isVoiceActive(),Qe.manuallyDeactivated=!z.isVoiceActive(),An(),_n("user"),z.isVoiceActive()?vr():qn()});return}if(In){let i=ge.value.trim();Qe.manuallyDeactivated=!0,An(),io("user"),i&&(ge.value="",ge.style.height="auto",z.sendMessage(i))}else Qe.manuallyDeactivated=!1,An(),Ms("user")};uu=Es,K&&(K.addEventListener("click",Es),$e.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(z.isVoiceActive()&&z.toggleVoice(),qn()):io("system"),K&&K.removeEventListener("click",Es)}));let Ay=l.on("assistant:complete",()=>{Mu&&(Qe.active||Qe.manuallyDeactivated||Mu==="assistant"&&!Qe.lastUserMessageWasVoice||setTimeout(()=>{!Qe.active&&!Qe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?z.toggleVoice().then(()=>{Qe.active=z.isVoiceActive(),_n("auto"),z.isVoiceActive()&&vr()}):Ms("auto"))},600))});$e.push(Ay);let Sy=l.on("action:resubmit",()=>{setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)});$e.push(Sy);let Gu=()=>{mt(!U,"user")},Ot=null,$t=null;if(A&&!$()){let{instance:i,element:m}=Ep({config:o,plugins:r,onToggle:Gu});Ot=i,i||($t=m)}Ot?e.appendChild(Ot.element):$t&&e.appendChild($t),fa(),yl(),Nu(),kl(z.isStreaming()),Wu()||(Zt()==="follow"?so(!0):Ru()),Kh(),T&&(!A||$()?setTimeout(()=>Ll(),0):U&&setTimeout(()=>Ll(),200));let ha=()=>{if($()){ur(),fa();return}let i=Rt(o),m=o.launcher?.sidebarMode??!1,x=i||m||(o.launcher?.fullHeight??!1),C=e.ownerDocument.defaultView??window,P=o.launcher?.mobileFullscreen??!0,H=o.launcher?.mobileBreakpoint??640,J=C.innerWidth<=H,V=P&&J&&A;try{if(V){ta(),na=hs();return}let X=!1;F&&(F=!1,ta(),X=!0);let oe=hs();if(!X&&oe!==na&&(ta(),X=!0),na=oe,X&&gl(),!A&&!i){me.style.height="",me.style.width="";return}if(!m&&!i){let re=o?.launcher?.width??o?.launcherWidth??cn;me.style.width=re,me.style.maxWidth=re}if(gs(),!x){let ie=C.innerHeight,re=64,xe=o.launcher?.heightOffset??0,je=Math.max(200,ie-re),gt=Math.min(640,je),it=Math.max(200,gt-xe);me.style.height=`${it}px`}}finally{if(ur(),fa(),U&&A){let oe=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ie=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,xe=Rt(o)&&re&&oe,je=ie||re&&oe&&A||xe;if(je&&!Rn){let gt=e.getRootNode(),it=gt instanceof ShadowRoot?gt.host:e.closest(".persona-host");it&&!Pn&&(Pn=vp(it,o.launcher?.zIndex??zt)),Rn=wp(e.ownerDocument)}else je||(Pn?.(),Pn=null,Rn?.(),Rn=null)}}};ha();let Ku=e.ownerDocument.defaultView??window;if(Ku.addEventListener("resize",ha),$e.push(()=>Ku.removeEventListener("resize",ha)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{ur()});i.observe(j),$e.push(()=>i.disconnect())}fn=se.scrollTop;let Xu=Dn(se),My=()=>{let i=se.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??se.ownerDocument.getSelection()},Ol=()=>sg(My(),se),Ju=()=>{let i=se.scrollTop,m=Dn(se),x=m<Xu;if(Xu=m,!Yn()){fn=i,an();return}let{action:C,nextLastScrollTop:P}=Wi({following:rn.isFollowing(),currentScrollTop:i,lastScrollTop:fn,nearBottom:ko(se,ws),userScrollThreshold:jh,isAutoScrolling:mn||Cs||x,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(fn=P,C==="resume"){Ol()||ao();return}C==="pause"&&ia()};if(se.addEventListener("scroll",Ju,{passive:!0}),$e.push(()=>se.removeEventListener("scroll",Ju)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Zh()});i.observe(ye),i.observe(se),$e.push(()=>i.disconnect())}let Qu=()=>{Yn()&&rn.isFollowing()&&Ol()&&ia()},Yu=se.ownerDocument;Yu.addEventListener("selectionchange",Qu),$e.push(()=>{Yu.removeEventListener("selectionchange",Qu)});let Ty=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Zu=i=>{iu()&&Yn()&&rn.isFollowing()&&Ty.has(i.key)&&ia()},ef=i=>{if(!iu()||!Yn()||!rn.isFollowing())return;let m=i.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&ia()};se.addEventListener("keydown",Zu),se.addEventListener("focusin",ef),$e.push(()=>{se.removeEventListener("keydown",Zu),se.removeEventListener("focusin",ef)});let tf=i=>{if(!Yn())return;let m=Hi({following:rn.isFollowing(),deltaY:i.deltaY,nearBottom:ko(se,ws),resumeWhenNearBottom:!0});m==="pause"?ia():m==="resume"&&!Ol()&&ao()};se.addEventListener("wheel",tf,{passive:!0}),$e.push(()=>se.removeEventListener("wheel",tf)),It.addEventListener("click",()=>{la(),se.scrollTop=se.scrollHeight,fn=se.scrollTop,ao(),so(!0),an()}),$e.push(()=>It.remove()),$e.push(()=>{ku(),la()});let nf=()=>{L&&(Fo&&(L.removeEventListener("click",Fo),Fo=null),N()?(L.style.display="",Fo=()=>{mt(!1,"user")},L.addEventListener("click",Fo)):L.style.display="none")};nf(),(()=>{let{clearChatButton:i}=Ee;i&&i.addEventListener("click",()=>{z.clearMessages(),No.clear(),ao(),go(Ee.composerOverlay);try{localStorage.removeItem(Xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xr}`)}catch(x){console.error("[AgentWidget] Failed to clear default localStorage:",x)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Xr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(x){console.error("[AgentWidget] Failed to clear custom localStorage:",x)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(m),c?.clear&&Sl(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),d={},M.syncFromMetadata(),Ne?.clear(),Xe?.reset(),Oe?.update()})})(),Q&&Q.addEventListener("submit",zu);let of=[["keydown",xy],["input",yy],["paste",by],["focus",Uh]],rf=i=>{if(i)for(let[m,x]of of)i.addEventListener(m,x)},af=i=>{if(i)for(let[m,x]of of)i.removeEventListener(m,x)};rf(ge),on?.onComposerSwap((i,m)=>{af(m),ge=i,rf(i)});let sf=e.ownerDocument??document;sf.addEventListener("keydown",$u,!0);let lf="persona-attachment-drop-active",ya=0,_l=()=>{ya=0,ue.classList.remove(lf)},wr=()=>o.attachments?.enabled===!0&&Mt!==null,df=i=>{!rl(i.dataTransfer)||!wr()||(ya++,ya===1&&ue.classList.add(lf))},cf=i=>{!rl(i.dataTransfer)||!wr()||(ya--,ya<=0&&_l())},pf=i=>{!rl(i.dataTransfer)||!wr()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},uf=i=>{if(!rl(i.dataTransfer)||!wr())return;i.preventDefault(),i.stopPropagation(),_l();let m=Array.from(i.dataTransfer.files??[]);m.length!==0&&Mt.handleFiles(m)},lo=!0;ue.addEventListener("dragenter",df,lo),ue.addEventListener("dragleave",cf,lo),e.addEventListener("dragover",pf,lo),e.addEventListener("drop",uf,lo);let ks=e.ownerDocument,ff=i=>{wr()&&i.preventDefault()},mf=i=>{wr()&&i.preventDefault()};ks.addEventListener("dragover",ff),ks.addEventListener("drop",mf),$e.push(()=>{Q&&Q.removeEventListener("submit",zu),af(ge),sf.removeEventListener("keydown",$u,!0),on?.destroy()}),$e.push(()=>{ue.removeEventListener("dragenter",df,lo),ue.removeEventListener("dragleave",cf,lo),e.removeEventListener("dragover",pf,lo),e.removeEventListener("drop",uf,lo),ks.removeEventListener("dragover",ff),ks.removeEventListener("drop",mf),_l()}),$e.push(()=>{z.cancel()}),Ot?$e.push(()=>{Ot?.destroy()}):$t&&$e.push(()=>{$t?.remove()});let Wt={update(i){let m=o.toolCall,x=o.messageActions,C=o.layout?.messages,P=o.colorScheme,H=o.loadingIndicator,J=o.iterationDisplay,V=o.features?.showReasoning,X=o.features?.showToolCalls,oe=o.features?.toolCallDisplay,ie=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o=Qi(o,i),ys(),or(e,o),es(e,o),ts(e,o),On(),o.colorScheme!==P&&Su();let xe=ns.getForInstance(o.plugins);r.length=0,r.push(...xe),A=o.launcher?.enabled??!0,w=o.launcher?.autoExpand??!1,ae=o.features?.showReasoning??!0,Ce=o.features?.showToolCalls??!0,le=o.features?.scrollToBottom??{};let je=Zt();Y=o.features?.scrollBehavior??{},je!==Zt()&&(la(),ao()),pu(),an();let gt=ee;if(ee=o.features?.showEventStreamToggle??!1,ee&&!gt){if(Ne||(be=new Ya(Ae),Ne=new Qa(He,be),Xe=Xe??new Za,be.open().then(()=>Ne?.restore()).catch(()=>{}),z.setSSEEventCallback((Z,Ke)=>{o.onSSEEvent?.(Z,Ke),Xe?.processEvent(Z,Ke),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Z,timestamp:Date.now(),payload:JSON.stringify(Ke)})})),!st&&_){let Z=o.features?.eventStream?.classNames,Ke="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:"");st=y("button",Ke),st.style.width="28px",st.style.height="28px",st.style.color=Jt.actionIconColor,st.type="button",st.setAttribute("aria-label","Event Stream"),st.title="Event Stream";let ht=te("activity","18px","currentColor",1.5);ht&&st.appendChild(ht);let ze=Ee.clearChatButtonWrapper,at=Ee.closeButtonWrapper,Vt=ze||at;Vt&&Vt.parentNode===_?_.insertBefore(st,Vt):_.appendChild(st),st.addEventListener("click",()=>{lt?Zr():pl()})}}else!ee&>&&(Zr(),st&&(st.remove(),st=null),Ne?.clear(),be?.destroy(),Ne=null,be=null,Xe?.reset(),Xe=null);if(o.launcher?.enabled===!1&&Ot&&(Ot.destroy(),Ot=null),o.launcher?.enabled===!1&&$t&&($t.remove(),$t=null),o.launcher?.enabled!==!1&&!Ot&&!$t){let{instance:Z,element:Ke}=Ep({config:o,plugins:r,onToggle:Gu});Ot=Z,Z||($t=Ke),e.appendChild(Ke)}Ot&&Ot.update(o),O&&o.launcher?.title!==void 0&&(O.textContent=o.launcher.title),G&&o.launcher?.subtitle!==void 0&&(G.textContent=o.launcher.subtitle);let it=o.layout?.header;if(it?.layout!==B&&_){let Z=it?qr(o,it,{showClose:N(),onClose:()=>mt(!1,"user")}):Qn({config:o,showClose:N(),onClose:()=>mt(!1,"user")});xt.replaceHeader(Z),_=xt.header.element,W=xt.header.iconHolder,O=xt.header.headerTitle,G=xt.header.headerSubtitle,L=xt.header.closeButton,B=it?.layout}else if(it){if(W&&(W.style.display=it.showIcon===!1?"none":""),O&&(O.style.display=it.showTitle===!1?"none":""),G&&(G.style.display=it.showSubtitle===!1?"none":""),L){let Z=N()&&it.showCloseButton!==!1;L.style.display=Z?"":"none"}if(Ee.clearChatButtonWrapper){let Z=it.showClearChat;if(Z!==void 0){Ee.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:Ke}=Ee;Ke&&!Ke.classList.contains("persona-absolute")&&(Z?Ke.classList.remove("persona-ml-auto"):Ke.classList.add("persona-ml-auto"))}}}let Bt=o.layout?.showHeader!==!1;_&&(_.style.display=Bt?"":"none");let D=o.layout?.showFooter!==!1;j&&(j.style.display=D?"":"none"),ur(),an(),A!==v?A?mt(w,"auto"):(U=!0,fa()):w!==R&&mt(w,"auto"),R=w,v=A,ha(),nf();let _e=JSON.stringify(o.toolCall)!==JSON.stringify(m),St=JSON.stringify(o.messageActions)!==JSON.stringify(x),pt=JSON.stringify(o.layout?.messages)!==JSON.stringify(C),wt=o.loadingIndicator?.render!==H?.render||o.loadingIndicator?.renderIdle!==H?.renderIdle||o.loadingIndicator?.showBubble!==H?.showBubble,yt=o.iterationDisplay!==J,qt=(o.features?.showReasoning??!0)!==(V??!0)||(o.features?.showToolCalls??!0)!==(X??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(oe)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ie);(_e||St||pt||wt||yt||qt)&&z&&(xl++,da(ye,z.getMessages(),De));let ut=o.features?.streamAnimation?.type;if(ut!==re&&ut&&ut!=="none"){let Z=Ur(ut,o.features?.streamAnimation?.plugins);Z&&Ni(Z,e)}let de=o.launcher??{},At=de.headerIconHidden??!1,Gt=o.layout?.header?.showIcon,Dt=At||Gt===!1,rt=de.headerIconName,Ve=de.headerIconSize??"48px";if(W){let Z=ue.querySelector(".persona-border-b-persona-divider"),Ke=Z?.querySelector(".persona-flex-col");if(Dt)W.style.display="none",Z&&Ke&&!Z.contains(Ke)&&Z.insertBefore(Ke,Z.firstChild);else{if(W.style.display="",W.style.height=Ve,W.style.width=Ve,Z&&Ke&&(Z.contains(W)?W.nextSibling!==Ke&&(W.remove(),Z.insertBefore(W,Ke)):Z.insertBefore(W,Ke)),rt){let ze=parseFloat(Ve)||24,at=te(rt,ze*.6,"currentColor",1);at?W.replaceChildren(at):W.textContent=de.agentIconText??"\u{1F4AC}"}else if(de.iconUrl){let ze=W.querySelector("img");if(ze)ze.src=de.iconUrl,ze.style.height=Ve,ze.style.width=Ve;else{let at=document.createElement("img");at.src=de.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=Ve,at.style.width=Ve,W.replaceChildren(at)}}else{let ze=W.querySelector("svg"),at=W.querySelector("img");(ze||at)&&W.replaceChildren(),W.textContent=de.agentIconText??"\u{1F4AC}"}let ht=W.querySelector("img");ht&&(ht.style.height=Ve,ht.style.width=Ve)}}let nt=o.layout?.header?.showTitle,Lt=o.layout?.header?.showSubtitle;if(O&&(O.style.display=nt===!1?"none":""),G&&(G.style.display=Lt===!1?"none":""),L){let Z=N()&&o.layout?.header?.showCloseButton!==!1;L.style.display=Z?"":"none";let Ke=de.closeButtonSize??"32px",ht=de.closeButtonPlacement??"inline";L.style.height=Ke,L.style.width=Ke;let{closeButtonWrapper:ze}=Ee,at=ht==="top-right",Vt=ze?.classList.contains("persona-absolute");if(ze&&at!==Vt)if(ze.remove(),at)ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(ze);else{let qe=de.clearChat?.placement??"inline",Nt=de.clearChat?.enabled??!0;ze.className=Nt&&qe==="inline"?"":"persona-ml-auto";let tn=ue.querySelector(".persona-border-b-persona-divider");tn&&tn.appendChild(ze)}if(L.style.color=de.closeButtonColor||Jt.actionIconColor,de.closeButtonBackgroundColor?(L.style.backgroundColor=de.closeButtonBackgroundColor,L.classList.remove("hover:persona-bg-gray-100")):(L.style.backgroundColor="",L.classList.add("hover:persona-bg-gray-100")),de.closeButtonBorderWidth||de.closeButtonBorderColor){let qe=de.closeButtonBorderWidth||"0px",Nt=de.closeButtonBorderColor||"transparent";L.style.border=`${qe} solid ${Nt}`,L.classList.remove("persona-border-none")}else L.style.border="",L.classList.add("persona-border-none");de.closeButtonBorderRadius?(L.style.borderRadius=de.closeButtonBorderRadius,L.classList.remove("persona-rounded-full")):(L.style.borderRadius="",L.classList.add("persona-rounded-full")),de.closeButtonPaddingX?(L.style.paddingLeft=de.closeButtonPaddingX,L.style.paddingRight=de.closeButtonPaddingX):(L.style.paddingLeft="",L.style.paddingRight=""),de.closeButtonPaddingY?(L.style.paddingTop=de.closeButtonPaddingY,L.style.paddingBottom=de.closeButtonPaddingY):(L.style.paddingTop="",L.style.paddingBottom="");let ln=de.closeButtonIconName??"x",Sn=de.closeButtonIconText??"\xD7";L.innerHTML="";let _t=te(ln,"28px","currentColor",1);_t?(_t.style.display="block",L.appendChild(_t)):L.textContent=Sn;let Tt=de.closeButtonTooltipText??"Close chat",dn=de.closeButtonShowTooltip??!0;if(L.setAttribute("aria-label",Tt),ze&&(ze._cleanupTooltip&&(ze._cleanupTooltip(),delete ze._cleanupTooltip),dn&&Tt)){let qe=null,Nt=()=>{if(qe||!L)return;let Go=L.ownerDocument,va=Go.body;if(!va)return;qe=Hn(Go,"div","persona-clear-chat-tooltip"),qe.textContent=Tt;let wa=Hn(Go,"div");wa.className="persona-clear-chat-tooltip-arrow",qe.appendChild(wa);let Ko=L.getBoundingClientRect();qe.style.position="fixed",qe.style.zIndex=String(Mo),qe.style.left=`${Ko.left+Ko.width/2}px`,qe.style.top=`${Ko.top-8}px`,qe.style.transform="translate(-50%, -100%)",va.appendChild(qe)},tn=()=>{qe&&qe.parentNode&&(qe.parentNode.removeChild(qe),qe=null)};ze.addEventListener("mouseenter",Nt),ze.addEventListener("mouseleave",tn),L.addEventListener("focus",Nt),L.addEventListener("blur",tn),ze._cleanupTooltip=()=>{tn(),ze&&(ze.removeEventListener("mouseenter",Nt),ze.removeEventListener("mouseleave",tn)),L&&(L.removeEventListener("focus",Nt),L.removeEventListener("blur",tn))}}}let{clearChatButton:We,clearChatButtonWrapper:ot}=Ee;if(We){let Z=de.clearChat??{},Ke=Z.enabled??!0,ht=o.layout?.header?.showClearChat,ze=ht!==void 0?ht:Ke,at=Z.placement??"inline";if(ot){ot.style.display=ze?"":"none";let{closeButtonWrapper:Vt}=Ee;!$()&&Vt&&!Vt.classList.contains("persona-absolute")&&(ze?Vt.classList.remove("persona-ml-auto"):Vt.classList.add("persona-ml-auto"));let ln=at==="top-right",Sn=ot.classList.contains("persona-absolute");if(!$()&&ln!==Sn&&ze){if(ot.remove(),ln)ot.className="persona-absolute persona-top-4 persona-z-50",ot.style.right="48px",ue.style.position="relative",ue.appendChild(ot);else{ot.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ot.style.right="";let Tt=ue.querySelector(".persona-border-b-persona-divider"),dn=Ee.closeButtonWrapper;Tt&&dn&&dn.parentElement===Tt?Tt.insertBefore(ot,dn):Tt&&Tt.appendChild(ot)}let _t=Ee.closeButtonWrapper;_t&&!_t.classList.contains("persona-absolute")&&(ln?_t.classList.add("persona-ml-auto"):_t.classList.remove("persona-ml-auto"))}}if(ze){if(!$()){let qe=Z.size??"32px";We.style.height=qe,We.style.width=qe}let Vt=Z.iconName??"refresh-cw",ln=Z.iconColor??"";We.style.color=ln||Jt.actionIconColor,We.innerHTML="";let Sn=$()?"14px":"20px",_t=te(Vt,Sn,"currentColor",1);if(_t&&(_t.style.display="block",We.appendChild(_t)),Z.backgroundColor?(We.style.backgroundColor=Z.backgroundColor,We.classList.remove("hover:persona-bg-gray-100")):(We.style.backgroundColor="",We.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let qe=Z.borderWidth||"0px",Nt=Z.borderColor||"transparent";We.style.border=`${qe} solid ${Nt}`,We.classList.remove("persona-border-none")}else We.style.border="",We.classList.add("persona-border-none");Z.borderRadius?(We.style.borderRadius=Z.borderRadius,We.classList.remove("persona-rounded-full")):(We.style.borderRadius="",We.classList.add("persona-rounded-full")),Z.paddingX?(We.style.paddingLeft=Z.paddingX,We.style.paddingRight=Z.paddingX):(We.style.paddingLeft="",We.style.paddingRight=""),Z.paddingY?(We.style.paddingTop=Z.paddingY,We.style.paddingBottom=Z.paddingY):(We.style.paddingTop="",We.style.paddingBottom="");let Tt=Z.tooltipText??"Clear chat",dn=Z.showTooltip??!0;if(We.setAttribute("aria-label",Tt),ot&&(ot._cleanupTooltip&&(ot._cleanupTooltip(),delete ot._cleanupTooltip),dn&&Tt)){let qe=null,Nt=()=>{if(qe||!We)return;let Go=We.ownerDocument,va=Go.body;if(!va)return;qe=Hn(Go,"div","persona-clear-chat-tooltip"),qe.textContent=Tt;let wa=Hn(Go,"div");wa.className="persona-clear-chat-tooltip-arrow",qe.appendChild(wa);let Ko=We.getBoundingClientRect();qe.style.position="fixed",qe.style.zIndex=String(Mo),qe.style.left=`${Ko.left+Ko.width/2}px`,qe.style.top=`${Ko.top-8}px`,qe.style.transform="translate(-50%, -100%)",va.appendChild(qe)},tn=()=>{qe&&qe.parentNode&&(qe.parentNode.removeChild(qe),qe=null)};ot.addEventListener("mouseenter",Nt),ot.addEventListener("mouseleave",tn),We.addEventListener("focus",Nt),We.addEventListener("blur",tn),ot._cleanupTooltip=()=>{tn(),ot&&(ot.removeEventListener("mouseenter",Nt),ot.removeEventListener("mouseleave",tn)),We&&(We.removeEventListener("focus",Nt),We.removeEventListener("blur",tn))}}}}let sn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[os],zo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[pr.message,pr.messageAndClick];M=rs({parsers:sn,handlers:zo,getSessionMetadata:h,updateSessionMetadata:S,emit:l.emit,documentRef:typeof document<"u"?document:null}),De=Yg(o,M,Le),z.updateConfig(o),da(ye,z.getMessages(),De),yl(),Nu(),kl(z.isStreaming());let gf=o.voiceRecognition?.enabled===!0,Ls=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Pt=o.voiceRecognition?.provider?.type==="runtype";if(gf&&(Ls||Pt))if(!K||!Ue){let Z=Cy(o.voiceRecognition,o.sendButton);Z&&(K=Z.micButton,Ue=Z.micButtonWrapper,Ge.insertBefore(Ue,xn),K.addEventListener("click",Es),K.disabled=z.isStreaming())}else{let Z=o.voiceRecognition??{},Ke=o.sendButton??{},ht=Z.iconName??"mic",ze=Ke.size??"40px",at=Z.iconSize??ze,Vt=parseFloat(at)||24;K.style.width=at,K.style.height=at,K.style.minWidth=at,K.style.minHeight=at;let ln=Z.iconColor??Ke.textColor;K.innerHTML="";let Sn=te(ht,Vt,ln||"currentColor",1.5);Sn?K.appendChild(Sn):K.textContent="\u{1F3A4}";let _t=Z.backgroundColor??Ke.backgroundColor;_t?K.style.backgroundColor=_t:K.style.backgroundColor="",ln?K.style.color=ln:K.style.color="var(--persona-text, #111827)",Z.borderWidth?(K.style.borderWidth=Z.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),Z.borderColor?K.style.borderColor=Z.borderColor:K.style.borderColor="",Z.paddingX?(K.style.paddingLeft=Z.paddingX,K.style.paddingRight=Z.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),Z.paddingY?(K.style.paddingTop=Z.paddingY,K.style.paddingBottom=Z.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let Tt=Ue?.querySelector(".persona-send-button-tooltip"),dn=Z.tooltipText??"Start voice recognition";if((Z.showTooltip??!1)&&dn)if(Tt)Tt.textContent=dn,Tt.style.display="";else{let Nt=document.createElement("div");Nt.className="persona-send-button-tooltip",Nt.textContent=dn,Ue?.insertBefore(Nt,K)}else Tt&&(Tt.style.display="none");Ue.style.display="",K.disabled=z.isStreaming()}else K&&Ue&&(Ue.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?z.isVoiceActive()&&z.toggleVoice():In&&io());if(o.attachments?.enabled===!0){if(!Ie||!Te){let Z=o.attachments??{},ht=(o.sendButton??{}).size??"40px";et||(et=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),et.style.display="none",Q.insertBefore(et,ge)),ke||(ke=document.createElement("input"),ke.type="file",ke.accept=(Z.allowedTypes??Xn).join(","),ke.multiple=(Z.maxFiles??4)>1,ke.style.display="none",ke.setAttribute("aria-label","Attach files"),Q.insertBefore(ke,ge)),Ie=y("div","persona-send-button-wrapper"),Te=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Te.type="button",Te.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let ze=Z.buttonIconName??"paperclip",at=ht,Vt=parseFloat(at)||40,ln=Math.round(Vt*.6);Te.style.width=at,Te.style.height=at,Te.style.minWidth=at,Te.style.minHeight=at,Te.style.fontSize="18px",Te.style.lineHeight="1";let Sn=te(ze,ln,"currentColor",1.5);Sn?Te.appendChild(Sn):Te.textContent="\u{1F4CE}",Te.addEventListener("click",dn=>{dn.preventDefault(),ke?.click()}),Ie.appendChild(Te);let _t=Z.buttonTooltipText??"Attach file",Tt=y("div","persona-send-button-tooltip");Tt.textContent=_t,Ie.appendChild(Tt),Me?Me.append(Ie):Q.appendChild(Ie),!Mt&&ke&&et&&(Mt=nr.fromConfig(Z),Mt.setPreviewsContainer(et),ke.addEventListener("change",async()=>{Mt&&ke?.files&&(await Mt.handleFileSelect(ke.files),ke.value="")}))}else{Ie.style.display="";let Z=o.attachments??{};ke&&(ke.accept=(Z.allowedTypes??Xn).join(","),ke.multiple=(Z.maxFiles??4)>1),Mt&&Mt.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(Zg(o.attachments?.dropOverlay)),Te){let Z=o.attachments??{},Ke=Z.buttonTooltipText??"Attach file";Te.setAttribute("aria-label",Ke),Te.textContent="";let ht=parseFloat(o.sendButton?.size??"40px")||40,ze=te(Z.buttonIconName??"paperclip",Math.round(ht*.6),"currentColor",1.5);ze?Te.appendChild(ze):Te.textContent="\u{1F4CE}";let at=Ie?.querySelector(".persona-send-button-tooltip");at&&(at.textContent=Ke)}}else Ie&&(Ie.style.display="none"),Mt&&Mt.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Ft=o.sendButton??{},xa=Ft.useIcon??!1,Rs=Ft.iconText??"\u2191",Ar=Ft.iconName,ba=Ft.tooltipText??"Send message",Ul=Ft.showTooltip??!1,$o=Ft.size??"40px",Vn=Ft.backgroundColor,jo=Ft.textColor;if(xa){if(pe.style.width=$o,pe.style.height=$o,pe.style.minWidth=$o,pe.style.minHeight=$o,pe.style.fontSize="18px",pe.style.lineHeight="1",jo?pe.style.color=jo:pe.style.color="var(--persona-button-primary-fg, #ffffff)",!z.isStreaming())if(pe.innerHTML="",Ar){let Z=parseFloat($o)||24,Ke=jo?.trim()||"currentColor",ht=te(Ar,Z,Ke,2);ht?pe.appendChild(ht):pe.textContent=Rs}else pe.textContent=Rs;pe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Vn?(pe.style.backgroundColor=Vn,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=o.copy?.sendButtonLabel??"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.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",Vn?(pe.style.backgroundColor=Vn,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),jo?pe.style.color=jo:pe.classList.add("persona-text-white");Ft.borderWidth?(pe.style.borderWidth=Ft.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),Ft.borderColor?pe.style.borderColor=Ft.borderColor:pe.style.borderColor="",Ft.paddingX?(pe.style.paddingLeft=Ft.paddingX,pe.style.paddingRight=Ft.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),Ft.paddingY?(pe.style.paddingTop=Ft.paddingY,pe.style.paddingBottom=Ft.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom="");let Ca=xn?.querySelector(".persona-send-button-tooltip");if(Ul&&ba)if(Ca)Ca.textContent=ba,Ca.style.display="";else{let Z=document.createElement("div");Z.className="persona-send-button-tooltip",Z.textContent=ba,xn?.insertBefore(Z,pe)}else Ca&&(Ca.style.display="none");let Is=o.layout?.contentMaxWidth??($()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);Is?(ye.style.maxWidth=Is,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%",Q&&(Q.style.maxWidth=Is,Q.style.marginLeft="auto",Q.style.marginRight="auto"),bt&&(bt.style.maxWidth=Is,bt.style.marginLeft="auto",bt.style.marginRight="auto")):(ye.style.maxWidth="",ye.style.marginLeft="",ye.style.marginRight="",ye.style.width="",Q&&(Q.style.maxWidth="",Q.style.marginLeft="",Q.style.marginRight=""),bt&&(bt.style.maxWidth="",bt.style.marginLeft="",bt.style.marginRight=""));let co=o.statusIndicator??{},Ey=co.visible??!0;if(I.style.display=Ey?"":"none",z){let Z=z.getStatus();kt(I,(ht=>ht==="idle"?co.idleText??Ht.idle:ht==="connecting"?co.connectingText??Ht.connecting:ht==="connected"?co.connectedText??Ht.connected:ht==="error"?co.errorText??Ht.error:Ht[ht])(Z),co,Z)}I.classList.remove("persona-text-left","persona-text-center","persona-text-right");let ky=co.align==="left"?"persona-text-left":co.align==="center"?"persona-text-center":"persona-text-right";I.classList.add(ky)},open(){N()&&mt(!0,"api")},close(){N()&&mt(!1,"api")},toggle(){N()&&mt(!U,"api")},reconnect(){z.reconnectNow()},clearChat(){Nn=!1,z.clearMessages(),No.clear(),ao();try{localStorage.removeItem(Xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xr}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Xr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),c?.clear&&Sl(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),d={},M.syncFromMetadata(),Ne?.clear(),Xe?.reset(),Oe?.update()},setMessage(i){return!ge||z.isStreaming()?!1:(!U&&N()&&mt(!0,"system"),ge.value=i,ge.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(z.isStreaming())return!1;let m=i?.trim()||ge.value.trim();return m?(!U&&N()&&mt(!0,"system"),ge.value="",ge.style.height="auto",z.sendMessage(m),!0):!1},startVoiceRecognition(){return z.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(z.isVoiceActive()||(!U&&N()&&mt(!0,"system"),Qe.manuallyDeactivated=!1,An(),z.toggleVoice().then(()=>{Qe.active=z.isVoiceActive(),_n("user"),z.isVoiceActive()&&vr()})),!0):In?!0:ju()?(!U&&N()&&mt(!0,"system"),Qe.manuallyDeactivated=!1,An(),Ms("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?z.isVoiceActive()?(z.toggleVoice().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,An(),_n("user"),qn()}),!0):!1:In?(Qe.manuallyDeactivated=!0,An(),io("user"),!0):!1},injectMessage(i){return!U&&N()&&mt(!0,"system"),z.injectMessage(i)},injectAssistantMessage(i){!U&&N()&&mt(!0,"system");let m=z.injectAssistantMessage(i);return fe&&(fe=!1,ce&&(clearTimeout(ce),ce=null),setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)),m},injectUserMessage(i){return!U&&N()&&mt(!0,"system"),z.injectUserMessage(i)},injectSystemMessage(i){return!U&&N()&&mt(!0,"system"),z.injectSystemMessage(i)},injectMessageBatch(i){return!U&&N()&&mt(!0,"system"),z.injectMessageBatch(i)},injectComponentDirective(i){return!U&&N()&&mt(!0,"system"),z.injectComponentDirective(i)},injectTestMessage(i){!U&&N()&&mt(!0,"system"),z.injectTestEvent(i)},async connectStream(i,m){return z.connectStream(i,m)},__pushEventStreamEvent(i){Ne&&(Xe?.processEvent(i.type,i.payload),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!ee||!Ne||pl()},hideEventStream(){lt&&Zr()},isEventStreamVisible(){return lt},showArtifacts(){Qt(o)&&(Nn=!1,fr=!0,On(),tt?.setMobileOpen(!0))},hideArtifacts(){Qt(o)&&(Nn=!0,On())},upsertArtifact(i){return Qt(o)?(Jo(o.features?.artifacts,i.artifactType)==="panel"&&(Nn=!1,fr=!0),z.upsertArtifact(i)):null},selectArtifact(i){Qt(o)&&z.selectArtifact(i)},clearArtifacts(){Qt(o)&&z.clearArtifacts()},getArtifacts(){return z?.getArtifacts()??[]},getSelectedArtifactId(){return z?.getSelectedArtifactId()??null},focusInput(){return A&&!U&&!$()||!ge?!1:(ge.focus(),!0)},async resolveApproval(i,m,x){let P=z.getMessages().find(H=>H.variant==="approval"&&H.approval?.id===i);if(!P?.approval)throw new Error(`Approval not found: ${i}`);if(P.approval.toolType==="webmcp"){z.resolveWebMcpApproval(P.id,m);return}return z.resolveApproval(P.approval,m,x)},getMessages(){return z.getMessages()},getStatus(){return z.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(i){S(i)},on(i,m){return l.on(i,m)},off(i,m){l.off(i,m)},isOpen(){return N()&&U},isVoiceActive(){return Qe.active},toggleReadAloud(i){z.toggleReadAloud(i)},stopReadAloud(){z.stopSpeaking()},getReadAloudState(i){return z.getReadAloudState(i)},onReadAloudChange(i){return z.onReadAloudChange(i)},getState(){return{open:N()&&U,launcherEnabled:A,voiceActive:Qe.active,streaming:z.isStreaming()}},showCSATFeedback(i){!U&&N()&&mt(!0,"system");let m=ye.querySelector(".persona-feedback-container");m&&m.remove();let x=nl({onSubmit:async(C,P)=>{z.isClientTokenMode()&&await z.submitCSATFeedback(C,P),i?.onSubmit?.(C,P)},onDismiss:i?.onDismiss,...i});ye.appendChild(x),x.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!U&&N()&&mt(!0,"system");let m=ye.querySelector(".persona-feedback-container");m&&m.remove();let x=ol({onSubmit:async(C,P)=>{z.isClientTokenMode()&&await z.submitNPSFeedback(C,P),i?.onSubmit?.(C,P)},onDismiss:i?.onDismiss,...i});ye.appendChild(x),x.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,m){return z.submitCSATFeedback(i,m)},async submitNPSFeedback(i,m){return z.submitNPSFeedback(i,m)},destroy(){Il(),Uo!=null&&(clearInterval(Uo),Uo=null),$e.forEach(i=>i()),Re.remove(),Je?.remove(),Ot?.destroy(),$t?.remove(),Fo&&L.removeEventListener("click",Fo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,m={controller:Wt,getMessages:Wt.getMessages,getStatus:Wt.getStatus,getMetadata:Wt.getPersistentMetadata,updateMetadata:Wt.updatePersistentMetadata,clearHistory:()=>Wt.clearChat(),setVoiceActive:x=>x?Wt.startVoiceRecognition():Wt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,$e.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Wt.focusInput()};if(window.addEventListener("persona:focusInput",m),$e.push(()=>{window.removeEventListener("persona:focusInput",m)}),ee){let V=oe=>{let ie=oe.detail;(!ie?.instanceId||ie.instanceId===i)&&Wt.showEventStream()},X=oe=>{let ie=oe.detail;(!ie?.instanceId||ie.instanceId===i)&&Wt.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",X),$e.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",X)})}let x=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Wt.showArtifacts()},C=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Wt.hideArtifacts()},P=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||X?.artifact&&Wt.upsertArtifact(X.artifact)},H=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||typeof X?.id=="string"&&Wt.selectArtifact(X.id)},J=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Wt.clearArtifacts()};window.addEventListener("persona:showArtifacts",x),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",P),window.addEventListener("persona:selectArtifact",H),window.addEventListener("persona:clearArtifacts",J),$e.push(()=>{window.removeEventListener("persona:showArtifacts",x),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",P),window.removeEventListener("persona:selectArtifact",H),window.removeEventListener("persona:clearArtifacts",J)})}let hn=Cv(o.persistState);if(hn&&N()){let i=vv(hn.storage),m=`${hn.keyPrefix}widget-open`,x=`${hn.keyPrefix}widget-voice`,C=`${hn.keyPrefix}widget-voice-mode`;if(i){let P=hn.persist?.openState&&i.getItem(m)==="true",H=hn.persist?.voiceState&&i.getItem(x)==="true",J=hn.persist?.voiceState&&i.getItem(C)==="true";if(P&&setTimeout(()=>{Wt.open(),setTimeout(()=>{if(H||J)Wt.startVoiceRecognition();else if(hn.persist?.focusInput){let V=e.querySelector("textarea");V&&V.focus()}},100)},0),hn.persist?.openState&&(l.on("widget:opened",()=>{i.setItem(m,"true")}),l.on("widget:closed",()=>{i.setItem(m,"false")})),hn.persist?.voiceState&&(l.on("voice:state",V=>{i.setItem(x,V.active?"true":"false")}),l.on("user:message",V=>{i.setItem(C,V.viaVoice?"true":"false")})),hn.clearOnChatClear){let V=()=>{i.removeItem(m),i.removeItem(x),i.removeItem(C)},X=()=>V();window.addEventListener("persona:clear-chat",X),$e.push(()=>{window.removeEventListener("persona:clear-chat",X)})}}}if(g&&N()&&setTimeout(()=>{Wt.open()},0),xr(),!$h){let i=Mr(()=>{z&&(xl++,No.clear(),da(ye,z.getMessages(),De))});$e.push(i)}return Wt};var eh=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},Sv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Mv=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Tv=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.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.")},th=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},Kp=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=""},nh=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Kp(e)},$p=e=>{e.style.transition=""},jp=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=""},Gp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},sl=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ev=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},kv=(e,t,n,o,r,a)=>{let s=a?t:e;r==="left"?s.firstElementChild!==o&&s.replaceChildren(o,n):s.lastElementChild!==o&&s.replaceChildren(n,o)},Lv=e=>{let t=wo(e),n=t.components?.panel,o=(r,a)=>r==null||r===""?a:Xt(t,r)??r;return{inset:o(n?.inset,bi),canvasBackground:o(n?.canvasBackground,Ci)}},oh=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},Pv=(e,t,n,o,r,a,s,l)=>{let p=nn(a),c=p.reveal==="push",d=l!=null,u=l?.inset??"",g=l?.canvasBackground??"";Ev(e,t,n,o,c),kv(e,t,n,o,p.side,c),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=s?"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",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,h=a?.launcher?.mobileFullscreen??!0,S=a?.launcher?.mobileBreakpoint??640,E=f!=null?f.innerWidth<=S:!1;if(h&&E&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),jp(t),$p(o),nh(o),Gp(n),sl(r,o),oh(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(a?.launcher?.zIndex??zt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",c&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),nh(o),Sv(o,p.maxHeight),oh(o,d&&s,u,g),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",jp(t),$p(o),Gp(n),sl(r,o);let M=p.animate?"transform 180ms ease":"none",A=p.side==="right"?"translateX(100%)":"translateX(-100%)",w=s?"translateX(0)":A;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=M,o.style.transform=w,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",$p(o),Kp(o),sl(r,o);let M=eh(p.width,e.clientWidth),A=Math.max(0,e.clientWidth),w=p.animate?"margin-left 180ms ease":"none",T=p.side==="right"?s?-M:0:s?0:-M;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=`${A+M}px`,t.style.transition=w,t.style.marginLeft=`${T}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${A}px`,n.style.maxWidth=`${A}px`,n.style.minWidth=`${A}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",jp(t),Kp(o),Gp(n),sl(r,o);let M=p.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let A=s?p.width:"0px",w=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${d?", padding 180ms ease":""}`:"none",T=!s;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${A}`,o.style.width=A,o.style.maxWidth=A,o.style.minWidth=A,o.style.minHeight="0",Mv(o,p.maxHeight),o.style.overflow=M||T?"hidden":"visible",o.style.transition=w,M){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let R=d?`calc(${eh(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=R,r.style.minWidth=R,r.style.maxWidth=R,r.style.boxSizing="border-box"}}},Rv=(e,t)=>{let n=e.ownerDocument.createElement("div");return th(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){th(n,o)},destroy(){n.remove()}}},Iv=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)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,s=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),c=n.createElement("aside"),d=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",c.appendChild(d),o.insertBefore(s,e),p.appendChild(e);let g=null,f=()=>{g?.disconnect(),g=null},h=null,S=()=>{h=t?.launcher?.detachedPanel===!0?Lv(t):null};S();let E=()=>{Pv(s,l,p,c,d,t,u,h)},k=null,M=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=Dr(()=>{S(),E()}))},A=()=>{f(),nn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{E()}),g.observe(s)))},w=!1,T=()=>{E(),A(),u&&!w&&s.dataset.personaDockMobileFullscreen!=="true"&&(w=!0,Tv(s,nn(t)))},R=s.ownerDocument.defaultView,v=()=>{T()};return R?.addEventListener("resize",v),nn(t).reveal==="push"?(l.appendChild(p),l.appendChild(c),s.appendChild(l)):(s.appendChild(p),s.appendChild(c)),T(),M(),{mode:"docked",host:d,shell:s,syncWidgetState(B){let F=B.launcherEnabled?B.open:!0;u!==F&&(u=F,T())},updateConfig(B){t=B,(t?.launcher?.enabled??!0)===!1&&(u=!0),S(),T(),M()},destroy(){R?.removeEventListener("resize",v),k?.(),k=null,f(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},ss=(e,t)=>Rt(t)?Iv(e,t):Rv(e,t);var Wv=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},rh=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},ah=e=>{let t=Wv(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,a=ss(t,r),s,l=[],p=(E,k)=>{let A=!(k?.launcher?.enabled??!0)||Rt(k),w=o.createElement("div");if(w.setAttribute("data-persona-root","true"),A&&(w.style.height="100%",w.style.display="flex",w.style.flexDirection="column",w.style.flex="1",w.style.minHeight="0",w.style.minWidth="0"),n){let T=E.attachShadow({mode:"open"});T.appendChild(w),rh(T,o)}else E.appendChild(w),rh(E,o);return t.id&&w.setAttribute("data-persona-instance",t.id),w},c=()=>{a.syncWidgetState(s.getState())},d=()=>{l.forEach(E=>E()),l=[s.on("widget:opened",c),s.on("widget:closed",c)],c()},u=()=>{let E=p(a.host,r);s=al(E,r,{debugTools:e.debugTools}),d()},g=()=>{l.forEach(E=>E()),l=[],s.destroy()};u(),e.onChatReady?.();let f=E=>{g(),a.destroy(),a=ss(t,E),r=E,u()},h={update(E){let k=Qi(r??{},E),M=Rt(r),A=Rt(k),w=Po(r),T=Po(k);if(M!==A||w!==T){f(k);return}r=k,a.updateConfig(r),s.update(E),c()},destroy(){g(),a.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},S=new Proxy(h,{get(E,k,M){if(k==="host")return a.host;if(k in E)return Reflect.get(E,k,M);let A=s[k];return typeof A=="function"?A.bind(s):A}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=S),S};function Hv(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function Bv(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(a=>a.toLowerCase().startsWith(o))?1:Hv(o,n)?2:3}function sh(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function il(e,t){let n=t.trim();if(!n)return[...e].sort(sh);let o=[];for(let r of e){let a=Bv(r.label,n);a!==3&&o.push({item:r,tier:a})}return o.sort((r,a)=>r.tier!==a.tier?r.tier-a.tier:sh(r.item,a.item)),o.map(r=>r.item)}function Dv(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function ih(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>il(e.items,t),resolve:e.resolve}}function lh(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>il(t,Dv(r).name),resolve:(r,a)=>{let s=n.get(r.id);return s?s.kind==="server"?{context:(typeof s.data=="function"?s.data(a.args):s.data)??{}}:{insertText:typeof s.prompt=="function"?s.prompt(a.args):s.prompt??""}:{}}}}var fh=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Fv=new Set(["button","a","input","select","textarea","details","summary"]),Nv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Xp=/\b(product|card|item|listing|result)\b/i,Qp=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Ov=3e3,_v=100;function mh(e){let t=typeof e.className=="string"?e.className:"";if(Xp.test(t)||e.id&&Xp.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Xp.test(o.value))return!0}return!1}function gh(e){return Qp.test((e.textContent??"").trim())}function hh(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Uv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function dh(e){let t=e.match(Qp);return t?t[0]:null}function ch(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 o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function qv(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var Vv="commerce-card",zv="result-card";function ph(e){return!mh(e)||!gh(e)||!hh(e)&&!Uv(e)?0:5200}function uh(e){return!mh(e)||gh(e)||!hh(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Yp=[{id:Vv,scoreElement(e){return ph(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||Qp.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(ph(e)===0)return null;let{title:n,href:o}=ch(e),r=dh((e.textContent??"").trim())??dh(t.text)??"",a=qv(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
144
|
-
`)}},{id:
|
|
145
|
-
`)}}];function
|
|
142
|
+
${st?"background: transparent !important;":""}
|
|
143
|
+
`}if(!v&&!i){let kt="max-height: -moz-available !important; max-height: stretch !important;",en=m?"":"padding-top: 1.25em !important;",Ms=m?"":`z-index: ${o.launcher?.zIndex??Vt} !important;`;Re.style.cssText+=kt+en+Ms}gn()};ps(),Zo(e,o),Ka(e,o),Xa(e,o),Qr=()=>{ps(),Zo(e,o),Ka(e,o),Xa(e,o),rs?e.style.setProperty("--persona-artifact-welded-outer-radius",rs):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let qe=[];qe.push(()=>{document.removeEventListener("keydown",wu)}),qe.push(()=>{Kr!==null&&clearTimeout(Kr)});let Ln=null,Pn=null;qe.push(()=>{Ln?.(),Ln=null,Pn?.(),Pn=null}),Jr&&qe.push(()=>{Jr?.disconnect(),Jr=null}),qe.push(()=>{ea?.(),ea=null,fl(),vt&&(vt.remove(),vt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),Z&&qe.push(()=>{Xe!==null&&(cancelAnimationFrame(Xe),Xe=null),Ne?.destroy(),Ne=null,Oe?.destroy(),Oe=null,xe=null});let Bo=null,Mu=()=>{Bo&&(Bo(),Bo=null),o.colorScheme==="auto"&&(Bo=Ir(()=>{Zo(e,o)}))};Mu(),qe.push(()=>{Bo&&(Bo(),Bo=null)}),qe.push(s);let us=o.features?.streamAnimation;if(us?.type&&us.type!=="none"){let i=Fr(us.type,us.plugins);i&&(Bi(i,e),qe.push(()=>yg(e)))}let fs=Og(bt),Do=null,$,ml=i=>{if(!$)return;let m=i??$.getMessages(),y=o.features?.suggestReplies?.enabled!==!1?Us(m):null;y?fs.render(y,$,he,m,o.suggestionChipsConfig,{agentPushed:!0}):m.some(v=>v.role==="user")?fs.render([],$,he,m):fs.render(o.suggestionChips,$,he,m,o.suggestionChipsConfig)},vn=!1,Fo=lg(),ur=new Map,Oo=new Map,to=new Map,gl=0,Qh=Vn()!==null,on=Li(),pn=0,no=null,un=!1,ms=!1,oo=0,Cn=null,No=null,hl=!1,gs=!1,yl=null,ta=!0,xl=!1,bl=null,Yh=4,hs=24,Zh=80,vl=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Tu=o.voiceRecognition?.autoResume??!1,On=i=>{l.emit("voice:state",{active:Ke.active,source:i,timestamp:Date.now()})},wn=()=>{S(i=>({...i,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},ey=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=$p(c.voiceState),m=!!i.active,y=Number(i.timestamp??0);Ke.manuallyDeactivated=!!i.manuallyDeactivated,m&&Date.now()-y<MC&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Ke.active=$.isVoiceActive(),On("restore"),$.isVoiceActive()&&yr()}):vs("restore"))},1e3)},ty=()=>$?oh($.getMessages()).filter(i=>!i.__skipPersist):[],ys=null,Eu=(i,m)=>{typeof console<"u"&&console.error(i,m)},Cl=(i,m)=>{let y=()=>{try{let J=i();return!J||typeof J.then!="function"?null:Promise.resolve(J).catch(V=>{Eu(m,V)})}catch(J){return Eu(m,J),null}},v=ys,k=v?v.then(()=>y()??void 0):y();if(!k)return;let W=k.finally(()=>{ys===W&&(ys=null)});ys=W};function wl(i){if(!d?.save)return;let y={messages:i?oh(i):$?ty():[],metadata:c,artifacts:xn.artifacts,selectedArtifactId:xn.selectedId};Cl(()=>d.save(y),"[AgentWidget] Failed to persist state:")}let fr=null,ku=()=>Re.querySelector("#persona-scroll-container")||ie,na=()=>{fr!==null&&(cancelAnimationFrame(fr),fr=null),un=!1},Lu=()=>{no!==null&&(cancelAnimationFrame(no),no=null),ms=!1,na()},ny=()=>vn&&Sl()&&(Yt()!=="anchor-top"||du()),Al=()=>{let i=Ro()||"Jump to latest",m=ny();Pt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),oo>0?(Io.textContent=String(oo),Io.style.display="",Pt.setAttribute("aria-label",`${i} (${oo} new)`)):(Io.textContent="",Io.style.display="none",Pt.setAttribute("aria-label",m?`${i} (response streaming below)`:i))},Pu=()=>{oo!==0&&(oo=0,Al())},Sl=()=>Qn()?!on.isFollowing():!Eo(ie,hs),rn=()=>{if(!ns()||rt){Pt.parentNode&&Pt.remove(),Pt.style.display="none";return}Pt.parentNode!==pe&&pe.appendChild(Pt),lr();let m=Hn(ie)>0&&Sl();m?Al():Pu(),Pt.style.display=m?"":"none"},oa=()=>{on.pause()&&(Lu(),rn())},ro=()=>{on.resume(),Pu(),rn()},ao=(i=!1)=>{Qn()&&on.isFollowing()&&(!i&&!vn||(no!==null&&(cancelAnimationFrame(no),no=null),ms=!0,no=requestAnimationFrame(()=>{no=null,ms=!1,on.isFollowing()&&oy(ku(),i?220:140)})))},Ru=(i,m,y,v=()=>!0)=>{let k=i.scrollTop,W=m(),J=W-k;if(na(),Math.abs(J)<1){un=!0,i.scrollTop=W,pn=i.scrollTop,un=!1;return}let V=performance.now();un=!0;let X=ue=>1-Math.pow(1-ue,3),oe=ue=>{if(!v()){na();return}let ne=m();ne!==W&&(W=ne,J=W-k);let be=ue-V,ze=Math.min(be/y,1),ut=X(ze),nt=k+J*ut;i.scrollTop=nt,pn=i.scrollTop,ze<1?fr=requestAnimationFrame(oe):(i.scrollTop=W,pn=i.scrollTop,fr=null,un=!1)};fr=requestAnimationFrame(oe)},oy=(i,m=500)=>{let y=Hn(i)-i.scrollTop;if(Math.abs(y)<1){pn=i.scrollTop;return}if(Math.abs(y)>=Zh){na(),un=!0,i.scrollTop=Hn(i),pn=i.scrollTop,un=!1;return}Ru(i,()=>Hn(i),m,()=>on.isFollowing())},Iu=()=>{let i=ku();un=!0,i.scrollTop=Hn(i),pn=i.scrollTop,un=!1,rn()},Wu=i=>{let m=0,y=i;for(;y&&y!==ie;)m+=y.offsetTop,y=y.offsetParent;return m},Hu=()=>{if(zh()!=="last-user-turn")return!1;let i=$?.getMessages()??[];if(i.length<2)return!1;let m=[...i].reverse().find(W=>W.role==="user");if(!m)return!1;let y=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),v=ie.querySelector(`[data-message-id="${y}"]`);if(!v)return!1;let k=Math.min(Math.max(0,Wu(v)-iu()),Hn(ie));return un=!0,ie.scrollTop=k,pn=ie.scrollTop,un=!1,Yt()==="follow"&&!Eo(ie,hs)&&on.pause(),rn(),!0},Bu=i=>{Yn.style.height=`${Math.max(0,Math.round(i))}px`,Cn&&(Cn.spacerHeight=Math.max(0,i))},ra=()=>{No!==null&&(cancelAnimationFrame(No),No=null),na(),Cn=null,Yn.style.height="0px"},ry=i=>{No!==null&&cancelAnimationFrame(No),No=requestAnimationFrame(()=>{No=null;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=ie.querySelector(`[data-message-id="${m}"]`);if(!y)return;let v=Wu(y),k=Cn?.spacerHeight??0,W=ie.scrollHeight-k,{targetScrollTop:J,spacerHeight:V}=fg({anchorOffsetTop:v,topOffset:iu(),viewportHeight:ie.clientHeight,contentHeight:W});Cn={initialSpacerHeight:V,contentHeightAtAnchor:W,spacerHeight:V},Bu(V),Ru(ie,()=>J,220)})},ay=()=>{if(Qn()){if(!on.isFollowing()||Eo(ie,1))return;ao(!vn);return}if(Cn&&Cn.initialSpacerHeight>0){let i=ie.scrollHeight-Cn.spacerHeight,m=mg({initialSpacerHeight:Cn.initialSpacerHeight,contentHeightAtAnchor:Cn.contentHeightAtAnchor,currentContentHeight:i});m!==Cn.spacerHeight&&Bu(m)}rn()},sy=i=>{let m=Yt();m==="follow"?(ro(),ao(!0)):m==="anchor-top"&&(ta=!1,xl=!0,ry(i))},iy=()=>{if(Yt()==="anchor-top"){if(xl){ta=!1;return}ta=!0,ra(),ro(),ao(!0)}},ly=i=>{let m=new Map;i.forEach(y=>{let v=vl.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!v&&y.role==="assistant"&&(l.emit("assistant:message",y),!gs&&(Yt()!=="anchor-top"||du())&&Sl()&&(oo+=1,Al(),rn(),pu(oo===1?"1 new message below.":`${oo} new messages below.`))),y.role==="assistant"&&v?.streaming&&y.streaming===!1&&l.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(v?y.approval.status!=="pending"&&l.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):l.emit("approval:requested",{approval:y.approval,message:y}))}),vl.clear(),m.forEach((y,v)=>{vl.set(v,y)})},xs=(i,m)=>{let y=m==="user"?"user":"assistant",v=o.layout?.messages?.[y],k=v?.width??"content",W=v?.maxWidth??(k==="full"?"100%":"85%");i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${m}`,`persona-message-width-${k}`),i.classList.toggle("persona-justify-end",m==="user"),i.setAttribute("data-message-role",m),i.setAttribute("data-message-width",k),i.style.setProperty("--persona-message-row-max-width",W)},_o=(i,m)=>{let y=document.createElement("div");return y.className="persona-flex",y.id=`wrapper-${i}`,y.setAttribute("data-wrapper-id",i),xs(y,m),y},dy=(i,m,y)=>{let v=document.createElement("div"),W=(()=>{let O=r.find(Ie=>Ie.renderLoadingIndicator);if(O?.renderLoadingIndicator)return O.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),J=(O,Ie)=>Ie==null?!1:typeof Ie=="string"?(O.textContent=Ie,!0):(O.appendChild(Ie),!0),V=new Set,X=new Map,oe=new Set,ue=r.some(O=>O.renderAskUserQuestion),ne=[],be=[],ze=o.enableComponentStreaming!==!1,ut=o.approval!==!1,nt=[];if(m.forEach(O=>{V.add(O.id),X.set(O.id,O.role);let Ie=ue&&$n(O),We=ut&&O.variant==="approval"&&!!O.approval,_e=!Ie&&O.role==="assistant"&&!O.variant&&ze&&Za(O);!We&&to.has(O.id)&&(i.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),to.delete(O.id)),!_e&&Oo.has(O.id)&&(i.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),Oo.delete(O.id));let Mt=$n(O)?`:${O.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${O.agentMetadata?.askUserQuestionAnswers?Object.keys(O.agentMetadata.askUserQuestionAnswers).length:0}`:"",ft=ig(O,gl)+Mt,$t=Ie||We||_e?null:dg(Fo,O.id,ft);if($t){v.appendChild($t.cloneNode(!0)),$n(O)&&O.toolCall?.id&&O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(oe.add(O.toolCall.id),Tr(O,o,Te.composerOverlay));return}let mt=null,Zt=r.find(et=>!!(O.variant==="reasoning"&&et.renderReasoning||O.variant==="tool"&&et.renderToolCall||!O.variant&&et.renderMessage)),Wt=o.layout?.messages;if($n(O)&&O.agentMetadata?.askUserQuestionAnswered===!0){ur.delete(O.id),i.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime");return}if(Sa(O)&&o.features?.suggestReplies?.enabled!==!1)return;if($n(O)&&o.features?.askUserQuestion?.enabled!==!1){let et=r.find(wt=>typeof wt.renderAskUserQuestion=="function");if(et&&dt.current){let wt=ur.get(O.id),jt=wt!==ft,st=null;if(jt){let{payload:Ze,complete:De}=jn(O),yt=O.id,_t=()=>dt.current?.getMessages().find(gn=>gn.id===yt);st=et.renderAskUserQuestion({message:O,payload:Ze,complete:De,resolve:gn=>{let ma=_t();ma&&dt.current?.resolveAskUserQuestion(ma,gn)},dismiss:()=>{let gn=_t();gn?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(gn),dt.current?.resolveAskUserQuestion(gn,"(dismissed)"))},config:o})}let ct=wt!=null;if(jt&&st===null&&!ct){O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(oe.add(O.toolCall.id),Tr(O,o,Te.composerOverlay));return}let gt=_o(O.id,O.role);gt.setAttribute("data-ask-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),v.appendChild(gt),ne.push({messageId:O.id,fingerprint:ft,bubble:st});return}else{O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(oe.add(O.toolCall.id),Tr(O,o,Te.composerOverlay));return}}else if(We){let et=r.find(ct=>typeof ct.renderApproval=="function")??a,jt=to.get(O.id)!==ft,st=null;if(jt&&et?.renderApproval){let ct=O.id,gt=(Ze,De)=>{let yt=dt.current?.getMessages().find(_t=>_t.id===ct);yt?.approval&&(yt.approval.toolType==="webmcp"?dt.current?.resolveWebMcpApproval(yt.id,Ze):dt.current?.resolveApproval(yt.approval,Ze,De))};st=et.renderApproval({message:O,defaultRenderer:()=>ji(O,o),config:o,approve:Ze=>gt("approved",Ze),deny:Ze=>gt("denied",Ze)})}if(jt&&st===null)i.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),to.delete(O.id),mt=ji(O,o);else{let ct=_o(O.id,O.role);ct.setAttribute("data-approval-plugin-stub","true"),ct.setAttribute("data-preserve-runtime","true"),v.appendChild(ct),nt.push({messageId:O.id,fingerprint:ft,bubble:st});return}}else if(Zt)if(O.variant==="reasoning"&&O.reasoning&&Zt.renderReasoning){if(!ae)return;mt=Zt.renderReasoning({message:O,defaultRenderer:()=>Wp(O,o),config:o})}else if(O.variant==="tool"&&O.toolCall&&Zt.renderToolCall){if(!me)return;mt=Zt.renderToolCall({message:O,defaultRenderer:()=>Bp(O,o),config:o})}else Zt.renderMessage&&(mt=Zt.renderMessage({message:O,defaultRenderer:()=>{let et=_r(O,y,Wt,o.messageActions,Se,{loadingIndicatorRenderer:W,widgetConfig:o});return O.role!=="user"&&qp(et,O,o,$),et},config:o}));if(!mt&&_e){let et=Yi(O);if(et){let wt=Oo.get(O.id),jt=wt!==ft,st=o.wrapComponentDirectiveInBubble!==!1&&En.getOptions(et.component)?.bubbleChrome!==!1,ct=null;if(jt){let gt=Qi(et,{config:o,message:O,transform:y});if(gt&&et.component==="PersonaArtifactInline"){let Ze=gt.hasAttribute("data-artifact-inline")?gt:gt.querySelector("[data-artifact-inline]"),De=Ze?.getAttribute("data-artifact-inline")??"",yt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(De):De,_t=De?i.querySelector(`#wrapper-${O.id}`)?.querySelector(`[data-artifact-inline="${yt}"]`)??null:null;Ze&&_t&&_t!==Ze&&tg(_t)&&(Ze===gt?gt=_t:Ze.replaceWith(_t))}if(gt)if(st){let Ze=document.createElement("div");if(Ze.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ze.id=`bubble-${O.id}`,Ze.setAttribute("data-message-id",O.id),O.content&&O.content.trim()){let De=document.createElement("div");De.className="persona-mb-3 persona-text-sm persona-leading-relaxed",De.innerHTML=y({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ze.appendChild(De)}Ze.appendChild(gt),ct=Ze}else{let Ze=document.createElement("div");if(Ze.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ze.id=`bubble-${O.id}`,Ze.setAttribute("data-message-id",O.id),Ze.setAttribute("data-persona-component-directive","true"),O.content&&O.content.trim()){let De=document.createElement("div");De.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",De.innerHTML=y({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ze.appendChild(De)}Ze.appendChild(gt),ct=Ze}}if(ct||wt!=null){let gt=_o(O.id,O.role);gt.setAttribute("data-component-directive-stub","true"),gt.setAttribute("data-preserve-runtime","true"),v.appendChild(gt),be.push({messageId:O.id,fingerprint:ft,bubble:ct});return}}}if(!mt)if(O.variant==="reasoning"&&O.reasoning){if(!ae)return;mt=Wp(O,o)}else if(O.variant==="tool"&&O.toolCall){if(!me)return;mt=Bp(O,o)}else if(O.variant==="approval"&&O.approval){if(o.approval===!1)return;mt=ji(O,o)}else{let et=o.layout?.messages;et?.renderUserMessage&&O.role==="user"?mt=et.renderUserMessage({message:O,config:o,streaming:!!O.streaming}):et?.renderAssistantMessage&&O.role==="assistant"?mt=et.renderAssistantMessage({message:O,config:o,streaming:!!O.streaming}):mt=_r(O,y,et,o.messageActions,Se,{loadingIndicatorRenderer:W,widgetConfig:o}),O.role!=="user"&&mt&&qp(mt,O,o,$)}let He=_o(O.id,O.role);He.appendChild(mt),cg(Fo,O.id,ft,He),v.appendChild(He)}),Te.composerOverlay&&Te.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ie=>{let We=Ie.getAttribute("data-persona-ask-sheet-for");We&&!oe.has(We)&&go(Te.composerOverlay,We)}),o.features?.toolCallDisplay?.grouped){let O=[],Ie=[];m.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&me){Ie.push(We);return}We.variant==="reasoning"&&!ae||(Ie.length>1&&O.push(Ie),Ie=[])}),Ie.length>1&&O.push(Ie),O.forEach((We,_e)=>{let Mt=We.map(wt=>Array.from(v.children).find(jt=>jt instanceof HTMLElement&&jt.getAttribute("data-wrapper-id")===wt.id)).filter(wt=>!!wt);if(Mt.length<2)return;let ft=_o(`tool-group-${_e}-${We[0].id}`,"assistant");ft.setAttribute("data-persona-tool-group-row","true");let $t=document.createElement("div");$t.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",$t.setAttribute("data-persona-tool-group","true");let mt=document.createElement("div");mt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Zt=`Called ${We.length} tools`,Wt=o.toolCall?.renderGroupedSummary?.({messages:We,toolCalls:We.map(wt=>wt.toolCall).filter(wt=>!!wt),defaultSummary:Zt,config:o});J(mt,Wt)||(mt.textContent=Zt);let He=document.createElement("div");He.className="persona-tool-group-stack persona-flex persona-flex-col";let et=o.features?.toolCallDisplay?.groupedMode==="summary";$t.appendChild(mt),et||$t.appendChild(He),ft.appendChild($t),Mt[0].before(ft),Mt.forEach((wt,jt)=>{if(et){wt.remove();return}wt.style.setProperty("--persona-message-row-max-width","100%");let st=document.createElement("div");st.className="persona-tool-group-item persona-relative",st.setAttribute("data-persona-tool-group-item","true"),jt<Mt.length-1&&st.setAttribute("data-persona-tool-group-connector","true"),st.appendChild(wt),He.appendChild(st)})})}pg(Fo,V);let an=m.some(O=>O.role==="assistant"&&O.streaming),St=m[m.length-1],It=St?.role==="assistant"&&!St.streaming&&St.variant!=="approval";if(vn&&m.some(O=>O.role==="user")&&!an&&!It){let O={config:o,streaming:!0,location:"standalone",defaultRenderer:or},Ie=r.find(_e=>_e.renderLoadingIndicator),We=null;if(Ie?.renderLoadingIndicator&&(We=Ie.renderLoadingIndicator(O)),We===null&&o.loadingIndicator?.render&&(We=o.loadingIndicator.render(O)),We===null&&(We=or()),We){let _e=document.createElement("div"),Mt=o.loadingIndicator?.showBubble!==!1;_e.className=Mt?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),_e.setAttribute("data-typing-indicator","true"),_e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",_e.appendChild(We);let ft=_o("typing-indicator","assistant");ft.appendChild(_e),v.appendChild(ft)}}if(!vn&&m.length>0){let O=m[m.length-1],Ie={config:o,lastMessage:O,messageCount:m.length},We=r.find(Mt=>Mt.renderIdleIndicator),_e=null;if(We?.renderIdleIndicator&&(_e=We.renderIdleIndicator(Ie)),_e===null&&o.loadingIndicator?.renderIdle&&(_e=o.loadingIndicator.renderIdle(Ie)),_e){let Mt=document.createElement("div"),ft=o.loadingIndicator?.showBubble!==!1;Mt.className=ft?["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(" "),Mt.setAttribute("data-idle-indicator","true"),Mt.appendChild(_e);let $t=_o("idle-indicator","assistant");$t.appendChild(Mt),v.appendChild($t)}}if(Wf(v),ki(i,v),ql(i),ne.length>0)for(let{messageId:O,fingerprint:Ie,bubble:We}of ne){let _e=i.querySelector(`#wrapper-${O}`);_e&&(xs(_e,X.get(O)??"assistant"),We!==null&&(_e.replaceChildren(We),_e.setAttribute("data-bubble-fp",Ie),ur.set(O,Ie)))}if(ur.size>0)for(let O of ur.keys())V.has(O)||ur.delete(O);if(be.length>0)for(let{messageId:O,fingerprint:Ie,bubble:We}of be){let _e=i.querySelector(`#wrapper-${O}`);_e&&(xs(_e,X.get(O)??"assistant"),We!==null&&(_e.replaceChildren(We),_e.setAttribute("data-bubble-fp",Ie),Oo.set(O,Ie)))}if(Oo.size>0)for(let O of Oo.keys())V.has(O)||Oo.delete(O);if(nt.length>0)for(let{messageId:O,fingerprint:Ie,bubble:We}of nt){let _e=i.querySelector(`#wrapper-${O}`);_e&&(xs(_e,X.get(O)??"assistant"),We!==null&&(_e.replaceChildren(We),_e.setAttribute("data-bubble-fp",Ie),to.set(O,Ie)))}if(to.size>0)for(let O of to.keys())V.has(O)||to.delete(O)},aa=(i,m,y)=>{dy(i,m,y),bu()},sa=null,cy=()=>{if(sa)return;let i=y=>{let v=y.composedPath();v.includes(Re)||Ge&&v.includes(Ge)||pt(!1,"user")};sa=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},Du=()=>{if(!sa)return;(e.ownerDocument??document).removeEventListener("pointerdown",sa,!0),sa=null};qe.push(()=>Du());let ia=null,py=()=>{if(ia)return;let i=y=>{y.key==="Escape"&&(y.isComposing||pt(!1,"user"))};ia=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Fu=()=>{if(!ia)return;(e.ownerDocument??document).removeEventListener("keydown",ia,!0),ia=null};qe.push(()=>Fu());let la=!1,Ou=new Set,uy=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},mr=()=>{if(!q())return;let i=Te.peekBanner,m=Te.peekTextNode;if(!i||!m)return;if(U){i.classList.remove("persona-pill-peek--visible");return}let y=$?.getMessages()??[],v;for(let St=y.length-1;St>=0;St--){let It=y[St];if(It.role==="assistant"&&It.content){v=It;break}}if(!v){i.classList.remove("persona-pill-peek--visible");return}let k=v.content,W=!!v.streaming,J=uy(),V=Ii(J),X=V.type!=="none"?Fr(V.type,J?.plugins):null,oe=X?.isAnimating?.(v)===!0,ue=X!==null&&(W||oe);ue&&X&&!Ou.has(X.name)&&(Bi(X,e),Ou.add(X.name));let ne=ue&&X?.containerClass?X.containerClass:null,be=m.dataset.personaPeekStreamClass??null;be&&be!==ne&&(m.classList.remove(be),delete m.dataset.personaPeekStreamClass),ne&&be!==ne&&(m.classList.add(ne),m.dataset.personaPeekStreamClass=ne),ue?(m.style.setProperty("--persona-stream-step",`${V.speed}ms`),m.style.setProperty("--persona-stream-duration",`${V.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let ze=ue?Wi(k,V.buffer,X,v,W):k;if(ue&&V.placeholder==="skeleton"&&W&&(!ze||!ze.trim())){let St=document.createElement("div"),It=qa();It.classList.add("persona-pill-peek__skeleton"),St.appendChild(It),ki(m,St)}else{let St=Math.max(0,ze.length-100),It=ze.length>100?ze.slice(-100):ze,O=In(It);if(!ue||!X){let Ie=ze.length>100?`\u2026${It}`:It;m.textContent!==Ie&&(m.textContent=Ie)}else{let Ie=O;(X.wrap==="char"||X.wrap==="word")&&(Ie=Ua(O,X.wrap,`peek-${v.id}`,{skipTags:X.skipTags,startIndex:St}));let We=document.createElement("div");if(We.innerHTML=Ie,X.useCaret&&It.length>0){let _e=Hi(),Mt=We.querySelectorAll(".persona-stream-char, .persona-stream-word"),ft=Mt[Mt.length-1];ft?.parentNode?ft.parentNode.insertBefore(_e,ft.nextSibling):We.appendChild(_e)}ki(m,We),X.onAfterRender?.({container:m,bubble:i,messageId:v.id,message:v,speed:V.speed,duration:V.duration})}}let an=vn||la;i.classList.toggle("persona-pill-peek--visible",an)};if(q()){let i=Te.peekBanner;if(i){let v=k=>{k.preventDefault(),k.stopPropagation(),pt(!0,"user")};i.addEventListener("pointerdown",v),qe.push(()=>{i.removeEventListener("pointerdown",v)})}let m=()=>{la||(la=!0,mr())},y=()=>{la&&(la=!1,mr())};fe.addEventListener("pointerenter",m),fe.addEventListener("pointerleave",y),qe.push(()=>{fe.removeEventListener("pointerenter",m),fe.removeEventListener("pointerleave",y)}),Ge&&(Ge.addEventListener("pointerenter",m),Ge.addEventListener("pointerleave",y),qe.push(()=>{Ge.removeEventListener("pointerenter",m),Ge.removeEventListener("pointerleave",y)}))}let fy=i=>{let m=o.launcher?.composerBar??{},y=m.expandedSize??"anchored",v=m.bottomOffset??"16px",k=m.collapsedMaxWidth,W=m.expandedMaxWidth??"880px",J=m.expandedTopOffset??"5vh",V=m.modalMaxWidth??"880px",X=m.modalMaxHeight??"min(90vh, 800px)",oe="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",ne=Re.style;if(ne.left="",ne.right="",ne.top="",ne.bottom="",ne.transform="",ne.width="",ne.maxWidth="",ne.height="",ne.maxHeight="",Ge){let be=Ge.style;be.bottom=v,be.width=k??""}if(i&&y!=="fullscreen"){if(y==="modal"){ne.top="50%",ne.left="50%",ne.transform="translate(-50%, -50%)",ne.bottom="auto",ne.right="auto",ne.width=V,ne.maxWidth=oe,ne.maxHeight=X,ne.height=X;return}ne.left="50%",ne.transform="translateX(-50%)",ne.bottom=`calc(${v} + ${ue})`,ne.top=J,ne.width=W,ne.maxWidth=oe}},da=()=>{if(!D())return;if(q()){let oe=(o.launcher?.composerBar??{}).expandedSize??"anchored",ue=U?"expanded":"collapsed";Re.dataset.state=ue,Re.dataset.expandedSize=oe,Ge&&(Ge.dataset.state=ue,Ge.dataset.expandedSize=oe),Re.style.removeProperty("display"),Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),fy(U),pe.style.display=U?"flex":"none",ps(),U?(cy(),py()):(Du(),Fu()),mr();return}let i=Lt(o),m=e.ownerDocument.defaultView??window,y=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,k=m.innerWidth<=y,W=v&&k&&A,J=tn(o).reveal;U?(Re.style.removeProperty("display"),Re.style.display=i?"flex":"",Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0"),fe.classList.add("persona-scale-100","persona-opacity-100"),Dt?Dt.element.style.display="none":zt&&(zt.style.display="none")):(i?i&&(J==="overlay"||J==="push")&&!W?(Re.style.removeProperty("display"),Re.style.display="flex",Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Re.style.setProperty("display","none","important"),Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Re.style.display="",Re.classList.add("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100"),fe.classList.add("persona-scale-95","persona-opacity-0")),Dt?Dt.element.style.display=i?"none":"":zt&&(zt.style.display=i?"none":""))},pt=(i,m="user")=>{if(!D()||U===i)return;let y=U;U=i,da();let v=(()=>{let W=o.launcher?.sidebarMode??!1,J=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,oe=J.innerWidth<=X,ue=Lt(o)&&V&&oe,ne=q()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return W||V&&oe&&A||ue||ne})();if(U&&v){if(!Ln){let W=e.getRootNode(),J=W instanceof ShadowRoot?W.host:e.closest(".persona-host");J&&(Ln=wp(J,o.launcher?.zIndex??Vt))}Pn||(Pn=Ap(e.ownerDocument))}else U||(Ln?.(),Ln=null,Pn?.(),Pn=null);U&&(ua(),Hu()||(Yt()==="follow"?ao(!0):Iu()));let k={open:U,source:m,timestamp:Date.now()};U&&!y?l.emit("widget:opened",k):!U&&y&&l.emit("widget:closed",k),l.emit("widget:state",{open:U,launcherEnabled:A,voiceActive:Ke.active,streaming:$.isStreaming()})},Ml=i=>{at(i?"stop":"send"),K&&(K.disabled=i),fs.buttons.forEach(m=>{m.disabled=i}),j.dataset.personaComposerStreaming=i?"true":"false",j.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=i)})},Tl=()=>{Ke.active||he&&he.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Tl(),200)});let Nu=()=>{z.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",b.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",he.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=ie.querySelector("[data-persona-intro-card]");if(i){let y=o.copy?.showWelcomeCard!==!1;i.style.display=y?"":"none",y?(ie.classList.remove("persona-gap-3"),ie.classList.add("persona-gap-6")):(ie.classList.remove("persona-gap-6"),ie.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!$?.isStreaming()&&(ce.textContent=o.copy?.sendButtonLabel??"Send"),he.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',he.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=c.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{S(m=>({...m,sessionId:i}))}});let Uo=null,my=()=>{Uo==null&&(Uo=setInterval(()=>{let i=ge.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Uo),Uo=null;return}let m=Date.now();i.forEach(y=>{let v=Number(y.getAttribute("data-tool-elapsed"));v&&(y.textContent=Vs(m-v))})},100))},El=(i,m)=>{if(Object.is(i,m))return!0;if(i===null||m===null||typeof i!="object"||typeof m!="object")return!1;if(Array.isArray(i)||Array.isArray(m))return!Array.isArray(i)||!Array.isArray(m)||i.length!==m.length?!1:i.every((J,V)=>El(J,m[V]));let y=i,v=m,k=Object.keys(y),W=Object.keys(v);return k.length===W.length&&k.every(J=>Object.prototype.hasOwnProperty.call(v,J)&&El(y[J],v[J]))},_u=i=>{let{content:m,rawContent:y,llmContent:v,...k}=i;return k},kl=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Za(i),gy=(i,m,y)=>{if(i.length!==m.length)return!1;let v=i[y.index],k=m[y.index];return!v||!k||v.id!==y.id||k.id!==y.id?!1:(!Object.is(v.content,k.content)||!Object.is(v.rawContent,k.rawContent)||!Object.is(v.llmContent,k.llmContent))&&kl(v)&&kl(k)&&El(_u(v),_u(k))},Uu=null,gr=null,qo=null,Nn=null,bs=i=>{Uu=i;let m,y;gr=null;for(let k=i.length-1;k>=0;k-=1){let W=i[k];if(!m&&W.role==="user"&&(m=W),!y&&W.role==="assistant"&&(y=W),!gr&&kl(W)&&(gr={index:k,id:W.id}),m&&y&&gr)break}aa(ge,i,Le),mp(ge,xn.artifacts,{suppressTransition:vn}),my(),ml(i),ao(!vn),ly(i),i.length===0&&(ra(),ta=!0,xl=!1),!hl||gs?(hl=!0,yl=m?.id??null,bl=y?.id??null):m&&m.id!==yl?(yl=m.id,sy(m.id)):y&&y.id!==bl&&iy(),y&&(bl=y.id);let v=Ke.lastUserMessageId;m&&m.id!==v&&(Ke.lastUserMessageId=m.id,l.emit("user:message",m)),Ke.lastUserMessageWasVoice=!!m?.viaVoice,wl(i),mr()},Ll=()=>{Nn!==null&&(cancelAnimationFrame(Nn),Nn=null);let i=qo;qo=null,i&&bs(i)},qu=()=>{Nn!==null&&cancelAnimationFrame(Nn),Nn=null,qo=null},hy=i=>{let m=qo??Uu;if(vn&&m&&gr&&gy(m,i,gr)){qo=i,Nn===null&&(Nn=requestAnimationFrame(()=>{Nn=null;let y=qo;qo=null,y&&bs(y)}));return}if(i.length===0){qu(),bs(i);return}Ll(),bs(i)};$=new Pr(o,{onMessagesChanged(i){hy(i)},onStatusChanged(i){let m=o.statusIndicator??{};Et(R,(v=>v==="idle"?m.idleText??Ht.idle:v==="connecting"?m.connectingText??Ht.connecting:v==="connected"?m.connectedText??Ht.connected:v==="error"?m.errorText??Ht.error:v==="paused"?m.pausedText??Ht.paused:v==="resuming"?m.resumingText??Ht.resuming:Ht[v])(i),m,i)},onStreamingChanged(i){i||($?.getMessages().length===0?qu():Ll()),vn=i,Ml(i),$&&aa(ge,$.getMessages(),Le),i||ao(!0),rn(),pu(i?"Responding\u2026":"Response complete."),mr()},onVoiceStatusChanged(i){if(l.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":_n(),yr();break;case"processing":_n(),Ey();break;case"speaking":_n(),ky();break;default:i==="idle"&&$.isBargeInActive()?(_n(),yr(),K?.setAttribute("aria-label","End voice session")):(Ke.active=!1,_n(),On("system"),wn());break}},onArtifactsState(i){xn=i,i.artifacts.length===0&&(dr=!1),mp(ge,i.artifacts,{suppressTransition:vn}),Fn(),wl()},onReconnect(i){let{executionId:m,lastEventId:y}=i.handle;i.phase==="paused"?l.emit("stream:paused",{executionId:m,after:y}):i.phase==="resuming"?l.emit("stream:resuming",{executionId:m,after:y,attempt:i.attempt??1}):l.emit("stream:resumed",{executionId:m,after:y})}}),dt.current=$,qe.push(()=>$.cancel());let Pl=null;if($.onReadAloudChange((i,m)=>{yu=i,xu=m,bu();let y=i??Pl;i&&(Pl=i);let v=y?$.getMessages().find(k=>k.id===y)??null:null;l.emit("message:read-aloud",{messageId:y,message:v,state:m,timestamp:Date.now()}),m==="idle"&&(Pl=null)}),hl=!0,o.voiceRecognition?.provider?.type==="runtype")try{$.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&$.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Oe||o.onSSEEvent)&&$.setSSEEventCallback((i,m)=>{o.onSSEEvent?.(i,m),Ve?.processEvent(i,m),Oe?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(m)})});let Vu=()=>{o.resume&&typeof o.reconnectStream=="function"&&$.resumeFromHandle(o.resume)};u?u.then(i=>{if(i){if(i.metadata&&(c=$p(i.metadata),M.syncFromMetadata()),i.messages?.length){gs=!0;try{$.hydrateMessages(i.messages)}finally{gs=!1}}i.artifacts?.length&&$.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>Vu()):Vu();let zu=()=>{!q()||U||!(o.launcher?.composerBar?.expandOnSubmit??!0)||pt(!0,"auto")},yy=(i,m)=>i?m?{refs:[...i.refs,...m.refs],finalize:async()=>{let[y,v]=await Promise.allSettled([i.finalize(),m.finalize()]),k=[];return y.status==="fulfilled"?k.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),v.status==="fulfilled"?k.push(v.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",v.reason),IC(k)}}:i:m,xy=()=>{let m=he.getInlineMessageFields?.();return m&&m.contentSegments.some(v=>v.kind==="mention")?m.contentSegments:void 0},ca=!1,by=async i=>{let m=he.value.trim(),y=At?.hasAttachments()??!1,v=m?await(nn?.takeInlineCommand(m)??Promise.resolve(null)):null;if(v?.kind==="action"){he.value="",he.style.height="auto",pa(),nn?.clear();return}let k=nn?.collectForSubmit()??null,W=v?.kind==="server"?v.mentions:null,J=yy(k,W),V=v?.kind==="prompt"?v.sendText:m,X=!!k&&k.refs.length>0;if(!V&&!y&&!X&&!W)return;zu();let oe;y&&(oe=[],oe.push(...At.getContentParts()),V&&oe.push(bo(V)));let ue=v?.kind==="prompt"?void 0:xy();he.value="",he.style.height="auto",pa(),$.sendMessage(V,{contentParts:oe,mentions:J??void 0,contentSegments:ue,viaVoice:i?.viaVoice}),y&&At.clearAttachments(),k&&nn?.clear()},Rl=async i=>{if(!ca){ca=!0;try{await by(i)}finally{ca=!1}}},$u=i=>{if(i.preventDefault(),$.isStreaming()){$.cancel(),Ve?.reset(),Ne?.update();return}ca||Rl()},vy=()=>o.features?.composerHistory!==!1,Il={...yp},Wl=!1,pa=()=>{Il={...yp}},Cy=()=>$.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),wy=i=>{if(!he)return;Wl=!0,he.value=i,he.dispatchEvent(new Event("input",{bubbles:!0})),Wl=!1;let m=he.value.length;he.setSelectionRange(m,m)},Ay=i=>{Wl||(i.isComposing||nn?.handleInput(i.inputType??void 0),pa())},Sy=i=>{if(he&&!(!i.isComposing&&nn?.handleKeydown(i))){if(vy()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let m=he.selectionStart===0&&he.selectionEnd===0,y=sg({direction:i.key==="ArrowUp"?"up":"down",history:Cy(),currentValue:he.value,atStart:m,state:Il});if(Il=y.state,y.handled){i.preventDefault(),y.value!==void 0&&wy(y.value);return}}if(i.key==="Enter"&&!i.shiftKey){if($.isStreaming()){i.preventDefault();return}if(ca){i.preventDefault();return}pa(),i.preventDefault(),ce.click()}}},ju=i=>{i.key!=="Escape"||i.isComposing||$.isStreaming()&&i.composedPath().includes(pe)&&($.cancel(),Ve?.reset(),Ne?.update(),pa(),i.preventDefault(),i.stopImmediatePropagation())},My=async i=>{if(o.attachments?.enabled!==!0||!At)return;let m=kC(i.clipboardData);m.length!==0&&(i.preventDefault(),await At.handleFiles(m))},fn=null,Rn=!1,hr=null,Ct=null,Gu=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,vs=(i="user")=>{if(Rn||$.isStreaming())return;let m=Gu();if(!m)return;fn=new m;let v=(o.voiceRecognition??{}).pauseDuration??2e3;fn.continuous=!0,fn.interimResults=!0,fn.lang="en-US";let k=he.value;fn.onresult=W=>{let J="",V="";for(let oe=0;oe<W.results.length;oe++){let ue=W.results[oe],ne=ue[0].transcript;ue.isFinal?J+=ne+" ":V=ne}let X=k+J+V;he.value=X,hr&&clearTimeout(hr),(J||V)&&(hr=window.setTimeout(()=>{he.value.trim()&&fn&&Rn&&(so(),Rl({viaVoice:!0}))},v))},fn.onerror=W=>{W.error!=="no-speech"&&so()},fn.onend=()=>{if(Rn){let W=he.value.trim();W&&W!==k.trim()&&Rl({viaVoice:!0}),so()}};try{if(fn.start(),Rn=!0,Ke.active=!0,i!=="system"&&(Ke.manuallyDeactivated=!1),On(i),wn(),K){let W=o.voiceRecognition??{};Ct={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:W.iconName??"mic",iconSize:parseFloat(W.iconSize??o.sendButton?.size??"40")||24};let J=W.recordingBackgroundColor,V=W.recordingIconColor,X=W.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=J??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=V??"var(--persona-voice-recording-indicator, #ffffff)",V){let oe=K.querySelector("svg");oe&&oe.setAttribute("stroke",V)}X&&(K.style.borderColor=X),K.setAttribute("aria-label","Stop voice recognition")}}catch{so("system")}},so=(i="user")=>{if(Rn){if(Rn=!1,hr&&(clearTimeout(hr),hr=null),fn){try{fn.stop()}catch{}fn=null}if(Ke.active=!1,On(i),wn(),K){if(K.classList.remove("persona-voice-recording"),Ct){K.style.backgroundColor=Ct.backgroundColor,K.style.color=Ct.color,K.style.borderColor=Ct.borderColor;let m=K.querySelector("svg");m&&m.setAttribute("stroke",Ct.color||"currentColor"),Ct=null}K.setAttribute("aria-label","Start voice recognition")}}},Ty=(i,m)=>{let y=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),v=i?.provider?.type==="runtype",k=i?.provider?.type==="custom";if(!(y||v||k))return null;let J=x("div","persona-send-button-wrapper"),V=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");V.type="button";let X=i?.tooltipText??"Start voice recognition";V.setAttribute("aria-label",X);let oe=i?.iconName??"mic",ue=m?.size??"40px",ne=i?.iconSize??ue,be=parseFloat(ne)||24,ze=i?.backgroundColor??m?.backgroundColor,ut=i?.iconColor??m?.textColor;V.style.width=ne,V.style.height=ne,V.style.minWidth=ne,V.style.minHeight=ne,V.style.fontSize="18px",V.style.lineHeight="1",ut?V.style.color=ut:V.style.color="var(--persona-text, #111827)";let an=te(oe,be,ut||"currentColor",1.5);an?V.appendChild(an):V.textContent="\u{1F3A4}",ze?V.style.backgroundColor=ze:V.style.backgroundColor="",i?.borderWidth&&(V.style.borderWidth=i.borderWidth,V.style.borderStyle="solid"),i?.borderColor&&(V.style.borderColor=i.borderColor),i?.paddingX&&(V.style.paddingLeft=i.paddingX,V.style.paddingRight=i.paddingX),i?.paddingY&&(V.style.paddingTop=i.paddingY,V.style.paddingBottom=i.paddingY),J.appendChild(V);let St=i?.showTooltip??!1;return Nt({anchor:V,trigger:J,text:()=>V.getAttribute("aria-label")??X,enabled:St}),{micButton:V,micButtonWrapper:J}},Hl=()=>{if(!K||Ct)return;let i=o.voiceRecognition??{};Ct={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Bl=(i,m)=>{if(!K)return;let y=K.querySelector("svg");y&&y.remove();let v=Ct?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),k=te(i,v,m,1.5);k&&K.appendChild(k)},Cs=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},yr=()=>{if(!K)return;Hl();let i=o.voiceRecognition??{},m=i.recordingBackgroundColor,y=i.recordingIconColor,v=i.recordingBorderColor;if(Cs(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=m??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=y??"var(--persona-voice-recording-indicator, #ffffff)",y){let k=K.querySelector("svg");k&&k.setAttribute("stroke",y)}v&&(K.style.borderColor=v),K.setAttribute("aria-label","Stop voice recognition")},Ey=()=>{if(!K)return;Hl();let i=o.voiceRecognition??{},m=$.getVoiceInterruptionMode(),y=i.processingIconName??"loader",v=i.processingIconColor??Ct?.color??"",k=i.processingBackgroundColor??Ct?.backgroundColor??"",W=i.processingBorderColor??Ct?.borderColor??"";Cs(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=k,K.style.borderColor=W;let J=v||"currentColor";K.style.color=J,Bl(y,J),K.setAttribute("aria-label","Processing voice input"),m==="none"&&(K.style.cursor="default")},ky=()=>{if(!K)return;Hl();let i=o.voiceRecognition??{},m=$.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",v=i.speakingIconName??y,k=i.speakingIconColor??(m==="barge-in"?i.recordingIconColor??Ct?.color??"":Ct?.color??""),W=i.speakingBackgroundColor??(m==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Ct?.backgroundColor??""),J=i.speakingBorderColor??(m==="barge-in"?i.recordingBorderColor??"":Ct?.borderColor??"");Cs(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=W,K.style.borderColor=J;let V=k||"currentColor";K.style.color=V,Bl(v,V);let X=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",X),m==="none"&&(K.style.cursor="default"),m==="barge-in"&&K.classList.add("persona-voice-recording")},_n=()=>{K&&(Cs(),Ct&&(K.style.backgroundColor=Ct.backgroundColor??"",K.style.color=Ct.color??"",K.style.borderColor=Ct.borderColor??"",Bl(Ct.iconName,Ct.color||"currentColor"),Ct=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},ws=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=$.getVoiceStatus(),m=$.getVoiceInterruptionMode();if(m==="none"&&(i==="processing"||i==="speaking"))return;if(m==="cancel"&&(i==="processing"||i==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,wn(),On("user"),_n()});return}$.toggleVoice().then(()=>{Ke.active=$.isVoiceActive(),Ke.manuallyDeactivated=!$.isVoiceActive(),wn(),On("user"),$.isVoiceActive()?yr():_n()});return}if(Rn){let i=he.value.trim();Ke.manuallyDeactivated=!0,wn(),so("user"),i&&(he.value="",he.style.height="auto",$.sendMessage(i))}else Ke.manuallyDeactivated=!1,wn(),vs("user")};fu=ws,K&&(K.addEventListener("click",ws),qe.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()&&$.toggleVoice(),_n()):so("system"),K&&K.removeEventListener("click",ws)}));let Ly=l.on("assistant:complete",()=>{Tu&&(Ke.active||Ke.manuallyDeactivated||Tu==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Ke.active=$.isVoiceActive(),On("auto"),$.isVoiceActive()&&yr()}):vs("auto"))},600))});qe.push(Ly);let Py=l.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});qe.push(Py);let Ku=()=>{pt(!U,"user")},Dt=null,zt=null;if(A&&!q()){let{instance:i,element:m}=kp({config:o,plugins:r,onToggle:Ku});Dt=i,i||(zt=m)}Dt?e.appendChild(Dt.element):zt&&e.appendChild(zt),da(),ml(),Nu(),Ml($.isStreaming()),Hu()||(Yt()==="follow"?ao(!0):Iu()),ey(),T&&(!A||q()?setTimeout(()=>Tl(),0):U&&setTimeout(()=>Tl(),200));let ua=()=>{if(q()){lr(),da();return}let i=Lt(o),m=o.launcher?.sidebarMode??!1,y=i||m||(o.launcher?.fullHeight??!1),v=e.ownerDocument.defaultView??window,k=o.launcher?.mobileFullscreen??!0,W=o.launcher?.mobileBreakpoint??640,J=v.innerWidth<=W,V=k&&J&&A;try{if(V){Qr(),Yr=cs();return}let X=!1;F&&(F=!1,Qr(),X=!0);let oe=cs();if(!X&&oe!==Yr&&(Qr(),X=!0),Yr=oe,X&&ul(),!A&&!i){fe.style.height="",fe.style.width="";return}if(!m&&!i){let ne=o?.launcher?.width??o?.launcherWidth??ln;fe.style.width=ne,fe.style.maxWidth=ne}if(ds(),!y){let ue=v.innerHeight,ne=64,be=o.launcher?.heightOffset??0,ze=Math.max(200,ue-ne),ut=Math.min(640,ze),nt=Math.max(200,ut-be);fe.style.height=`${nt}px`}}finally{if(lr(),da(),U&&A){let oe=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ue=o.launcher?.sidebarMode??!1,ne=o.launcher?.mobileFullscreen??!0,be=Lt(o)&&ne&&oe,ze=ue||ne&&oe&&A||be;if(ze&&!Pn){let ut=e.getRootNode(),nt=ut instanceof ShadowRoot?ut.host:e.closest(".persona-host");nt&&!Ln&&(Ln=wp(nt,o.launcher?.zIndex??Vt)),Pn=Ap(e.ownerDocument)}else ze||(Ln?.(),Ln=null,Pn?.(),Pn=null)}}};ua();let Xu=e.ownerDocument.defaultView??window;if(Xu.addEventListener("resize",ua),qe.push(()=>Xu.removeEventListener("resize",ua)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{lr()});i.observe(j),qe.push(()=>i.disconnect())}pn=ie.scrollTop;let Ju=Hn(ie),Ry=()=>{let i=ie.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ie.ownerDocument.getSelection()},Dl=()=>ug(Ry(),ie),Qu=()=>{let i=ie.scrollTop,m=Hn(ie),y=m<Ju;if(Ju=m,!Qn()){pn=i,rn();return}let{action:v,nextLastScrollTop:k}=Pi({following:on.isFollowing(),currentScrollTop:i,lastScrollTop:pn,nearBottom:Eo(ie,hs),userScrollThreshold:Yh,isAutoScrolling:un||ms||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(pn=k,v==="resume"){Dl()||ro();return}v==="pause"&&oa()};if(ie.addEventListener("scroll",Qu,{passive:!0}),qe.push(()=>ie.removeEventListener("scroll",Qu)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{ay(),ql(ge)});i.observe(ge),i.observe(ie),qe.push(()=>i.disconnect())}let Yu=()=>{Qn()&&on.isFollowing()&&Dl()&&oa()},Zu=ie.ownerDocument;Zu.addEventListener("selectionchange",Yu),qe.push(()=>{Zu.removeEventListener("selectionchange",Yu)});let Iy=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),ef=i=>{lu()&&Qn()&&on.isFollowing()&&Iy.has(i.key)&&oa()},tf=i=>{if(!lu()||!Qn()||!on.isFollowing())return;let m=i.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&oa()};ie.addEventListener("keydown",ef),ie.addEventListener("focusin",tf),qe.push(()=>{ie.removeEventListener("keydown",ef),ie.removeEventListener("focusin",tf)});let nf=i=>{if(!Qn())return;let m=Ri({following:on.isFollowing(),deltaY:i.deltaY,nearBottom:Eo(ie,hs),resumeWhenNearBottom:!0});m==="pause"?oa():m==="resume"&&!Dl()&&ro()};ie.addEventListener("wheel",nf,{passive:!0}),qe.push(()=>ie.removeEventListener("wheel",nf)),Pt.addEventListener("click",()=>{ra(),ie.scrollTop=ie.scrollHeight,pn=ie.scrollTop,ro(),ao(!0),rn()}),qe.push(()=>Pt.remove()),qe.push(()=>{Lu(),ra()});let of=()=>{P&&(Do&&(P.removeEventListener("click",Do),Do=null),D()?(P.style.display="",Do=()=>{pt(!1,"user")},P.addEventListener("click",Do)):P.style.display="none")};of(),(()=>{let{clearChatButton:i}=Te;i&&i.addEventListener("click",()=>{$.clearMessages(),Fo.clear(),ro(),go(Te.composerOverlay);try{localStorage.removeItem($r),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${$r}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==$r)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(m),d?.clear&&Cl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},M.syncFromMetadata(),Oe?.clear(),Ve?.reset(),Ne?.update()})})(),Q&&Q.addEventListener("submit",$u);let rf=[["keydown",Sy],["input",Ay],["paste",My],["focus",Gh]],af=i=>{if(i)for(let[m,y]of rf)i.addEventListener(m,y)},sf=i=>{if(i)for(let[m,y]of rf)i.removeEventListener(m,y)};af(he),nn?.onComposerSwap((i,m)=>{sf(m),he=i,af(i)});let lf=e.ownerDocument??document;lf.addEventListener("keydown",ju,!0);let df="persona-attachment-drop-active",fa=0,Fl=()=>{fa=0,pe.classList.remove(df)},xr=()=>o.attachments?.enabled===!0&&At!==null,cf=i=>{!tl(i.dataTransfer)||!xr()||(fa++,fa===1&&pe.classList.add(df))},pf=i=>{!tl(i.dataTransfer)||!xr()||(fa--,fa<=0&&Fl())},uf=i=>{!tl(i.dataTransfer)||!xr()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},ff=i=>{if(!tl(i.dataTransfer)||!xr())return;i.preventDefault(),i.stopPropagation(),Fl();let m=Array.from(i.dataTransfer.files??[]);m.length!==0&&At.handleFiles(m)},io=!0;pe.addEventListener("dragenter",cf,io),pe.addEventListener("dragleave",pf,io),e.addEventListener("dragover",uf,io),e.addEventListener("drop",ff,io);let As=e.ownerDocument,mf=i=>{xr()&&i.preventDefault()},gf=i=>{xr()&&i.preventDefault()};As.addEventListener("dragover",mf),As.addEventListener("drop",gf),qe.push(()=>{Q&&Q.removeEventListener("submit",$u),sf(he),lf.removeEventListener("keydown",ju,!0),nn?.destroy()}),qe.push(()=>{pe.removeEventListener("dragenter",cf,io),pe.removeEventListener("dragleave",pf,io),e.removeEventListener("dragover",uf,io),e.removeEventListener("drop",ff,io),As.removeEventListener("dragover",mf),As.removeEventListener("drop",gf),Fl()}),qe.push(()=>{$.cancel()}),Dt?qe.push(()=>{Dt?.destroy()}):zt&&qe.push(()=>{zt?.remove()});let Rt={update(i){let m=o.toolCall,y=o.messageActions,v=o.layout?.messages,k=o.colorScheme,W=o.loadingIndicator,J=o.iterationDisplay,V=o.features?.showReasoning,X=o.features?.showToolCalls,oe=o.features?.toolCallDisplay,ue=o.features?.reasoningDisplay,ne=o.features?.streamAnimation?.type;o=Ki(o,i),ps(),Zo(e,o),Ka(e,o),Xa(e,o),Fn(),o.colorScheme!==k&&Mu();let be=Ja.getForInstance(o.plugins);r.length=0,r.push(...be),A=o.launcher?.enabled??!0,w=o.launcher?.autoExpand??!1,ae=o.features?.showReasoning??!0,me=o.features?.showToolCalls??!0,de=o.features?.scrollToBottom??{};let ze=Yt();Y=o.features?.scrollBehavior??{},ze!==Yt()&&(ra(),ro()),uu(),rn();let ut=Z;if(Z=o.features?.showEventStreamToggle??!1,Z&&!ut){if(Oe||(xe=new ja(Ae),Oe=new $a(Be,xe),Ve=Ve??new Ga,xe.open().then(()=>Oe?.restore()).catch(()=>{}),$.setSSEEventCallback((ee,je)=>{o.onSSEEvent?.(ee,je),Ve?.processEvent(ee,je),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(je)})})),!tt&&_){let ee=o.features?.eventStream?.classNames,je="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=x("button",je),tt.style.width="28px",tt.style.height="28px",tt.style.color=Xt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let ht=te("activity","18px","currentColor",1.5);ht&&tt.appendChild(ht);let ot=Te.clearChatButtonWrapper,it=Te.closeButtonWrapper,Ut=ot||it;Ut&&Ut.parentNode===_?_.insertBefore(tt,Ut):_.appendChild(tt),tt.addEventListener("click",()=>{rt?Xr():ll()})}}else!Z&&ut&&(Xr(),tt&&(tt.remove(),tt=null),Oe?.clear(),xe?.destroy(),Oe=null,xe=null,Ve?.reset(),Ve=null);if(o.launcher?.enabled===!1&&Dt&&(Dt.destroy(),Dt=null),o.launcher?.enabled===!1&&zt&&(zt.remove(),zt=null),o.launcher?.enabled!==!1&&!Dt&&!zt){let{instance:ee,element:je}=kp({config:o,plugins:r,onToggle:Ku});Dt=ee,ee||(zt=je),e.appendChild(je)}Dt&&Dt.update(o),N&&o.launcher?.title!==void 0&&(N.textContent=o.launcher.title),G&&o.launcher?.subtitle!==void 0&&(G.textContent=o.launcher.subtitle);let nt=o.layout?.header;if(nt?.layout!==B&&_){let ee=nt?Or(o,nt,{showClose:D(),onClose:()=>pt(!1,"user")}):Jn({config:o,showClose:D(),onClose:()=>pt(!1,"user")});xt.replaceHeader(ee),_=xt.header.element,I=xt.header.iconHolder,N=xt.header.headerTitle,G=xt.header.headerSubtitle,P=xt.header.closeButton,B=nt?.layout}else if(nt){if(I&&(I.style.display=nt.showIcon===!1?"none":""),N&&(N.style.display=nt.showTitle===!1?"none":""),G&&(G.style.display=nt.showSubtitle===!1?"none":""),P){let ee=D()&&nt.showCloseButton!==!1;P.style.display=ee?"":"none"}if(Te.clearChatButtonWrapper){let ee=nt.showClearChat;if(ee!==void 0){Te.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:je}=Te;je&&!je.classList.contains("persona-absolute")&&(ee?je.classList.remove("persona-ml-auto"):je.classList.add("persona-ml-auto"))}}}let St=o.layout?.showHeader!==!1;_&&(_.style.display=St?"":"none");let It=o.layout?.showFooter!==!1;j&&(j.style.display=It?"":"none"),lr(),rn(),A!==C?A?pt(w,"auto"):(U=!0,da()):w!==H&&pt(w,"auto"),H=w,C=A,ua(),of();let We=JSON.stringify(o.toolCall)!==JSON.stringify(m),_e=JSON.stringify(o.messageActions)!==JSON.stringify(y),Mt=JSON.stringify(o.layout?.messages)!==JSON.stringify(v),ft=o.loadingIndicator?.render!==W?.render||o.loadingIndicator?.renderIdle!==W?.renderIdle||o.loadingIndicator?.showBubble!==W?.showBubble,$t=o.iterationDisplay!==J,mt=(o.features?.showReasoning??!0)!==(V??!0)||(o.features?.showToolCalls??!0)!==(X??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(oe)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ue);(We||_e||Mt||ft||$t||mt)&&$&&(gl++,aa(ge,$.getMessages(),Le));let Wt=o.features?.streamAnimation?.type;if(Wt!==ne&&Wt&&Wt!=="none"){let ee=Fr(Wt,o.features?.streamAnimation?.plugins);ee&&Bi(ee,e)}let He=o.launcher??{},et=He.headerIconHidden??!1,wt=o.layout?.header?.showIcon,jt=et||wt===!1,st=He.headerIconName,ct=He.headerIconSize??"48px";if(I){let ee=pe.querySelector(".persona-border-b-persona-divider"),je=ee?.querySelector(".persona-flex-col");if(jt)I.style.display="none",ee&&je&&!ee.contains(je)&&ee.insertBefore(je,ee.firstChild);else{if(I.style.display="",I.style.height=ct,I.style.width=ct,ee&&je&&(ee.contains(I)?I.nextSibling!==je&&(I.remove(),ee.insertBefore(I,je)):ee.insertBefore(I,je)),st){let ot=parseFloat(ct)||24,it=te(st,ot*.6,"currentColor",1);it?I.replaceChildren(it):I.textContent=He.agentIconText??"\u{1F4AC}"}else if(He.iconUrl){let ot=I.querySelector("img");if(ot)ot.src=He.iconUrl,ot.style.height=ct,ot.style.width=ct;else{let it=document.createElement("img");it.src=He.iconUrl,it.alt="",it.className="persona-rounded-xl persona-object-cover",it.style.height=ct,it.style.width=ct,I.replaceChildren(it)}}else{let ot=I.querySelector("svg"),it=I.querySelector("img");(ot||it)&&I.replaceChildren(),I.textContent=He.agentIconText??"\u{1F4AC}"}let ht=I.querySelector("img");ht&&(ht.style.height=ct,ht.style.width=ct)}}let gt=o.layout?.header?.showTitle,Ze=o.layout?.header?.showSubtitle;if(N&&(N.style.display=gt===!1?"none":""),G&&(G.style.display=Ze===!1?"none":""),P){let ee=D()&&o.layout?.header?.showCloseButton!==!1;P.style.display=ee?"":"none";let je=He.closeButtonSize??"32px",ht=He.closeButtonPlacement??"inline";P.style.height=je,P.style.width=je;let{closeButtonWrapper:ot}=Te,it=ht==="top-right",Ut=ot?.classList.contains("persona-absolute");if(ot&&it!==Ut)if(ot.remove(),it)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(ot);else{let co=He.clearChat?.placement??"inline",ha=He.clearChat?.enabled??!0;ot.className=ha&&co==="inline"?"":"persona-ml-auto";let hf=pe.querySelector(".persona-border-b-persona-divider");hf&&hf.appendChild(ot)}if(P.style.color=He.closeButtonColor||Xt.actionIconColor,He.closeButtonBackgroundColor?(P.style.backgroundColor=He.closeButtonBackgroundColor,P.classList.remove("hover:persona-bg-gray-100")):(P.style.backgroundColor="",P.classList.add("hover:persona-bg-gray-100")),He.closeButtonBorderWidth||He.closeButtonBorderColor){let co=He.closeButtonBorderWidth||"0px",ha=He.closeButtonBorderColor||"transparent";P.style.border=`${co} solid ${ha}`,P.classList.remove("persona-border-none")}else P.style.border="",P.classList.add("persona-border-none");He.closeButtonBorderRadius?(P.style.borderRadius=He.closeButtonBorderRadius,P.classList.remove("persona-rounded-full")):(P.style.borderRadius="",P.classList.add("persona-rounded-full")),He.closeButtonPaddingX?(P.style.paddingLeft=He.closeButtonPaddingX,P.style.paddingRight=He.closeButtonPaddingX):(P.style.paddingLeft="",P.style.paddingRight=""),He.closeButtonPaddingY?(P.style.paddingTop=He.closeButtonPaddingY,P.style.paddingBottom=He.closeButtonPaddingY):(P.style.paddingTop="",P.style.paddingBottom="");let sn=He.closeButtonIconName??"x",An=He.closeButtonIconText??"\xD7";P.innerHTML="";let Ft=te(sn,"28px","currentColor",1);Ft?(Ft.style.display="block",P.appendChild(Ft)):P.textContent=An;let qt=He.closeButtonTooltipText??"Close chat",qn=He.closeButtonShowTooltip??!0;P.setAttribute("aria-label",qt),ot&&Nt({anchor:P,trigger:ot,text:()=>P?.getAttribute("aria-label")??qt,enabled:qn})}let{clearChatButton:De,clearChatButtonWrapper:yt}=Te;if(De){let ee=He.clearChat??{},je=ee.enabled??!0,ht=o.layout?.header?.showClearChat,ot=ht!==void 0?ht:je,it=ee.placement??"inline";if(yt){yt.style.display=ot?"":"none";let{closeButtonWrapper:Ut}=Te;!q()&&Ut&&!Ut.classList.contains("persona-absolute")&&(ot?Ut.classList.remove("persona-ml-auto"):Ut.classList.add("persona-ml-auto"));let sn=it==="top-right",An=yt.classList.contains("persona-absolute");if(!q()&&sn!==An&&ot){if(yt.remove(),sn)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",pe.style.position="relative",pe.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let qt=pe.querySelector(".persona-border-b-persona-divider"),qn=Te.closeButtonWrapper;qt&&qn&&qn.parentElement===qt?qt.insertBefore(yt,qn):qt&&qt.appendChild(yt)}let Ft=Te.closeButtonWrapper;Ft&&!Ft.classList.contains("persona-absolute")&&(sn?Ft.classList.add("persona-ml-auto"):Ft.classList.remove("persona-ml-auto"))}}if(ot){if(!q()){let co=ee.size??"32px";De.style.height=co,De.style.width=co}let Ut=ee.iconName??"refresh-cw",sn=ee.iconColor??"";De.style.color=sn||Xt.actionIconColor,De.innerHTML="";let An=q()?"14px":"20px",Ft=te(Ut,An,"currentColor",1);if(Ft&&(Ft.style.display="block",De.appendChild(Ft)),ee.backgroundColor?(De.style.backgroundColor=ee.backgroundColor,De.classList.remove("hover:persona-bg-gray-100")):(De.style.backgroundColor="",De.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let co=ee.borderWidth||"0px",ha=ee.borderColor||"transparent";De.style.border=`${co} solid ${ha}`,De.classList.remove("persona-border-none")}else De.style.border="",De.classList.add("persona-border-none");ee.borderRadius?(De.style.borderRadius=ee.borderRadius,De.classList.remove("persona-rounded-full")):(De.style.borderRadius="",De.classList.add("persona-rounded-full")),ee.paddingX?(De.style.paddingLeft=ee.paddingX,De.style.paddingRight=ee.paddingX):(De.style.paddingLeft="",De.style.paddingRight=""),ee.paddingY?(De.style.paddingTop=ee.paddingY,De.style.paddingBottom=ee.paddingY):(De.style.paddingTop="",De.style.paddingBottom="");let qt=ee.tooltipText??"Clear chat",qn=ee.showTooltip??!0;De.setAttribute("aria-label",qt),yt&&Nt({anchor:De,trigger:yt,text:()=>De?.getAttribute("aria-label")??qt,enabled:qn})}}let _t=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Qa],gn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ir.message,ir.messageAndClick];M=Ya({parsers:_t,handlers:gn,getSessionMetadata:h,updateSessionMetadata:S,emit:l.emit,documentRef:typeof document<"u"?document:null}),Le=rh(o,M,Ce),$.updateConfig(o),aa(ge,$.getMessages(),Le),ml(),Nu(),Ml($.isStreaming());let ma=o.voiceRecognition?.enabled===!0,Ss=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),kt=o.voiceRecognition?.provider?.type==="runtype";if(ma&&(Ss||kt))if(!K||!Ue){let ee=Ty(o.voiceRecognition,o.sendButton);ee&&(K=ee.micButton,Ue=ee.micButtonWrapper,$e.insertBefore(Ue,yn),K.addEventListener("click",ws),K.disabled=$.isStreaming())}else{let ee=o.voiceRecognition??{},je=o.sendButton??{},ht=ee.iconName??"mic",ot=je.size??"40px",it=ee.iconSize??ot,Ut=parseFloat(it)||24;K.style.width=it,K.style.height=it,K.style.minWidth=it,K.style.minHeight=it;let sn=ee.iconColor??je.textColor;K.innerHTML="";let An=te(ht,Ut,sn||"currentColor",1.5);An?K.appendChild(An):K.textContent="\u{1F3A4}";let Ft=ee.backgroundColor??je.backgroundColor;Ft?K.style.backgroundColor=Ft:K.style.backgroundColor="",sn?K.style.color=sn:K.style.color="var(--persona-text, #111827)",ee.borderWidth?(K.style.borderWidth=ee.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),ee.borderColor?K.style.borderColor=ee.borderColor:K.style.borderColor="",ee.paddingX?(K.style.paddingLeft=ee.paddingX,K.style.paddingRight=ee.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),ee.paddingY?(K.style.paddingTop=ee.paddingY,K.style.paddingBottom=ee.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let qt=ee.tooltipText??"Start voice recognition",qn=ee.showTooltip??!1;K.setAttribute("aria-label",qt),Ue&&Nt({anchor:K,trigger:Ue,text:()=>K?.getAttribute("aria-label")??qt,enabled:qn}),Ue.style.display="",K.disabled=$.isStreaming()}else K&&Ue&&(Ue.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()&&$.toggleVoice():Rn&&so());if(o.attachments?.enabled===!0){if(!ke||!we){let ee=o.attachments??{},ht=(o.sendButton??{}).size??"40px";Qe||(Qe=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Qe.style.display="none",Q.insertBefore(Qe,he)),Ee||(Ee=document.createElement("input"),Ee.type="file",Ee.accept=(ee.allowedTypes??Kn).join(","),Ee.multiple=(ee.maxFiles??4)>1,Ee.style.display="none",Ee.setAttribute("aria-label","Attach files"),Q.insertBefore(Ee,he)),ke=x("div","persona-send-button-wrapper"),we=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),we.type="button",we.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let ot=ee.buttonIconName??"paperclip",it=ht,Ut=parseFloat(it)||40,sn=Math.round(Ut*.6);we.style.width=it,we.style.height=it,we.style.minWidth=it,we.style.minHeight=it,we.style.fontSize="18px",we.style.lineHeight="1";let An=te(ot,sn,"currentColor",1.5);An?we.appendChild(An):we.textContent="\u{1F4CE}",we.addEventListener("click",qt=>{qt.preventDefault(),Ee?.click()}),ke.appendChild(we);let Ft=ee.buttonTooltipText??"Attach file";Nt({anchor:we,trigger:ke,text:()=>we?.getAttribute("aria-label")??Ft}),Me?Me.append(ke):Q.appendChild(ke),!At&&Ee&&Qe&&(At=Yo.fromConfig(ee),At.setPreviewsContainer(Qe),Ee.addEventListener("change",async()=>{At&&Ee?.files&&(await At.handleFileSelect(Ee.files),Ee.value="")}))}else{ke.style.display="";let ee=o.attachments??{};Ee&&(Ee.accept=(ee.allowedTypes??Kn).join(","),Ee.multiple=(ee.maxFiles??4)>1),At&&At.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}if(pe.querySelector(".persona-attachment-drop-overlay")?.remove(),pe.appendChild(ah(o.attachments?.dropOverlay)),we){let ee=o.attachments??{},je=ee.buttonTooltipText??"Attach file";we.setAttribute("aria-label",je),we.textContent="";let ht=parseFloat(o.sendButton?.size??"40px")||40,ot=te(ee.buttonIconName??"paperclip",Math.round(ht*.6),"currentColor",1.5);ot?we.appendChild(ot):we.textContent="\u{1F4CE}",ke&&Nt({anchor:we,trigger:ke,text:()=>we?.getAttribute("aria-label")??je})}}else ke&&(ke.style.display="none"),At&&At.clearAttachments(),pe.querySelector(".persona-attachment-drop-overlay")?.remove();let Bt=o.sendButton??{},ga=Bt.useIcon??!1,Ts=Bt.iconText??"\u2191",br=Bt.iconName,Es=Bt.tooltipText??"Send message",Ol=Bt.showTooltip??!1,Vo=Bt.size??"40px",Un=Bt.backgroundColor,zo=Bt.textColor;if(ga){if(ce.style.width=Vo,ce.style.height=Vo,ce.style.minWidth=Vo,ce.style.minHeight=Vo,ce.style.fontSize="18px",ce.style.lineHeight="1",zo?ce.style.color=zo:ce.style.color="var(--persona-button-primary-fg, #ffffff)",!$.isStreaming())if(ce.innerHTML="",br){let ee=parseFloat(Vo)||24,je=zo?.trim()||"currentColor",ht=te(br,ee,je,2);ht?ce.appendChild(ht):ce.textContent=Ts}else ce.textContent=Ts;ce.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Un?(ce.style.backgroundColor=Un,ce.classList.remove("persona-bg-persona-primary")):(ce.style.backgroundColor="",ce.classList.add("persona-bg-persona-primary"))}else ce.textContent=o.copy?.sendButtonLabel??"Send",ce.style.width="",ce.style.height="",ce.style.minWidth="",ce.style.minHeight="",ce.style.fontSize="",ce.style.lineHeight="",ce.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",Un?(ce.style.backgroundColor=Un,ce.classList.remove("persona-bg-persona-accent")):ce.classList.add("persona-bg-persona-accent"),zo?ce.style.color=zo:ce.classList.add("persona-text-white");Bt.borderWidth?(ce.style.borderWidth=Bt.borderWidth,ce.style.borderStyle="solid"):(ce.style.borderWidth="",ce.style.borderStyle=""),Bt.borderColor?ce.style.borderColor=Bt.borderColor:ce.style.borderColor="",Bt.paddingX?(ce.style.paddingLeft=Bt.paddingX,ce.style.paddingRight=Bt.paddingX):(ce.style.paddingLeft="",ce.style.paddingRight=""),Bt.paddingY?(ce.style.paddingTop=Bt.paddingY,ce.style.paddingBottom=Bt.paddingY):(ce.style.paddingTop="",ce.style.paddingBottom=""),$.isStreaming()||ce.setAttribute("aria-label",Es),yn&&Nt({anchor:ce,trigger:yn,text:()=>ce.getAttribute("aria-label")??Es,enabled:Ol});let ks=o.layout?.contentMaxWidth??(q()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);ks?(ge.style.maxWidth=ks,ge.style.marginLeft="auto",ge.style.marginRight="auto",ge.style.width="100%",Q&&(Q.style.maxWidth=ks,Q.style.marginLeft="auto",Q.style.marginRight="auto"),bt&&(bt.style.maxWidth=ks,bt.style.marginLeft="auto",bt.style.marginRight="auto")):(ge.style.maxWidth="",ge.style.marginLeft="",ge.style.marginRight="",ge.style.width="",Q&&(Q.style.maxWidth="",Q.style.marginLeft="",Q.style.marginRight=""),bt&&(bt.style.maxWidth="",bt.style.marginLeft="",bt.style.marginRight=""));let lo=o.statusIndicator??{},Wy=lo.visible??!0;if(R.style.display=Wy?"":"none",$){let ee=$.getStatus();Et(R,(ht=>ht==="idle"?lo.idleText??Ht.idle:ht==="connecting"?lo.connectingText??Ht.connecting:ht==="connected"?lo.connectedText??Ht.connected:ht==="error"?lo.errorText??Ht.error:Ht[ht])(ee),lo,ee)}R.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Hy=lo.align==="left"?"persona-text-left":lo.align==="center"?"persona-text-center":"persona-text-right";R.classList.add(Hy)},open(){D()&&pt(!0,"api")},close(){D()&&pt(!1,"api")},toggle(){D()&&pt(!U,"api")},reconnect(){$.reconnectNow()},clearChat(){Dn=!1,$.clearMessages(),Fo.clear(),ro();try{localStorage.removeItem($r),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${$r}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==$r)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),d?.clear&&Cl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},M.syncFromMetadata(),Oe?.clear(),Ve?.reset(),Ne?.update()},setMessage(i){return!he||$.isStreaming()?!1:(!U&&D()&&pt(!0,"system"),he.value=i,he.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if($.isStreaming())return!1;let m=i?.trim()||he.value.trim();return m?(!U&&D()&&pt(!0,"system"),he.value="",he.style.height="auto",$.sendMessage(m),!0):!1},startVoiceRecognition(){return $.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()||(!U&&D()&&pt(!0,"system"),Ke.manuallyDeactivated=!1,wn(),$.toggleVoice().then(()=>{Ke.active=$.isVoiceActive(),On("user"),$.isVoiceActive()&&yr()})),!0):Rn?!0:Gu()?(!U&&D()&&pt(!0,"system"),Ke.manuallyDeactivated=!1,wn(),vs("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,wn(),On("user"),_n()}),!0):!1:Rn?(Ke.manuallyDeactivated=!0,wn(),so("user"),!0):!1},injectMessage(i){return!U&&D()&&pt(!0,"system"),$.injectMessage(i)},injectAssistantMessage(i){!U&&D()&&pt(!0,"system");let m=$.injectAssistantMessage(i);return se&&(se=!1,le&&(clearTimeout(le),le=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),m},injectUserMessage(i){return!U&&D()&&pt(!0,"system"),$.injectUserMessage(i)},injectSystemMessage(i){return!U&&D()&&pt(!0,"system"),$.injectSystemMessage(i)},injectMessageBatch(i){return!U&&D()&&pt(!0,"system"),$.injectMessageBatch(i)},injectComponentDirective(i){return!U&&D()&&pt(!0,"system"),$.injectComponentDirective(i)},injectTestMessage(i){!U&&D()&&pt(!0,"system"),$.injectTestEvent(i)},async connectStream(i,m){return $.connectStream(i,m)},__pushEventStreamEvent(i){Oe&&(Ve?.processEvent(i.type,i.payload),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!Z||!Oe||ll()},hideEventStream(){rt&&Xr()},isEventStreamVisible(){return rt},showArtifacts(){Jt(o)&&(Dn=!1,dr=!0,Fn(),Ye?.setMobileOpen(!0))},hideArtifacts(){Jt(o)&&(Dn=!0,Fn())},upsertArtifact(i){return Jt(o)?(jo(o.features?.artifacts,i.artifactType)==="panel"&&(Dn=!1,dr=!0),$.upsertArtifact(i)):null},selectArtifact(i){Jt(o)&&$.selectArtifact(i)},clearArtifacts(){Jt(o)&&$.clearArtifacts()},getArtifacts(){return $?.getArtifacts()??[]},getSelectedArtifactId(){return $?.getSelectedArtifactId()??null},focusInput(){return A&&!U&&!q()||!he?!1:(he.focus(),!0)},async resolveApproval(i,m,y){let k=$.getMessages().find(W=>W.variant==="approval"&&W.approval?.id===i);if(!k?.approval)throw new Error(`Approval not found: ${i}`);if(k.approval.toolType==="webmcp"){$.resolveWebMcpApproval(k.id,m);return}return $.resolveApproval(k.approval,m,y)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(i){S(i)},on(i,m){return l.on(i,m)},off(i,m){l.off(i,m)},isOpen(){return D()&&U},isVoiceActive(){return Ke.active},toggleReadAloud(i){$.toggleReadAloud(i)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(i){return $.getReadAloudState(i)},onReadAloudChange(i){return $.onReadAloudChange(i)},getState(){return{open:D()&&U,launcherEnabled:A,voiceActive:Ke.active,streaming:$.isStreaming()}},showCSATFeedback(i){!U&&D()&&pt(!0,"system");let m=ge.querySelector(".persona-feedback-container");m&&m.remove();let y=Zi({onSubmit:async(v,k)=>{$.isClientTokenMode()&&await $.submitCSATFeedback(v,k),i?.onSubmit?.(v,k)},onDismiss:i?.onDismiss,...i});ge.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!U&&D()&&pt(!0,"system");let m=ge.querySelector(".persona-feedback-container");m&&m.remove();let y=el({onSubmit:async(v,k)=>{$.isClientTokenMode()&&await $.submitNPSFeedback(v,k),i?.onSubmit?.(v,k)},onDismiss:i?.onDismiss,...i});ge.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,m){return $.submitCSATFeedback(i,m)},async submitNPSFeedback(i,m){return $.submitNPSFeedback(i,m)},destroy(){Ll(),Uo!=null&&(clearInterval(Uo),Uo=null),qe.forEach(i=>i()),Re.remove(),Ge?.remove(),Dt?.destroy(),zt?.remove(),Do&&P.removeEventListener("click",Do)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,m={controller:Rt,getMessages:Rt.getMessages,getStatus:Rt.getStatus,getMetadata:Rt.getPersistentMetadata,updateMetadata:Rt.updatePersistentMetadata,clearHistory:()=>Rt.clearChat(),setVoiceActive:y=>y?Rt.startVoiceRecognition():Rt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,qe.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Rt.focusInput()};if(window.addEventListener("persona:focusInput",m),qe.push(()=>{window.removeEventListener("persona:focusInput",m)}),Z){let V=oe=>{let ue=oe.detail;(!ue?.instanceId||ue.instanceId===i)&&Rt.showEventStream()},X=oe=>{let ue=oe.detail;(!ue?.instanceId||ue.instanceId===i)&&Rt.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",X),qe.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",X)})}let y=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Rt.showArtifacts()},v=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Rt.hideArtifacts()},k=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||X?.artifact&&Rt.upsertArtifact(X.artifact)},W=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||typeof X?.id=="string"&&Rt.selectArtifact(X.id)},J=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Rt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",J),qe.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",J)})}let mn=LC(o.persistState);if(mn&&D()){let i=PC(mn.storage),m=`${mn.keyPrefix}widget-open`,y=`${mn.keyPrefix}widget-voice`,v=`${mn.keyPrefix}widget-voice-mode`;if(i){let k=mn.persist?.openState&&i.getItem(m)==="true",W=mn.persist?.voiceState&&i.getItem(y)==="true",J=mn.persist?.voiceState&&i.getItem(v)==="true";if(k&&setTimeout(()=>{Rt.open(),setTimeout(()=>{if(W||J)Rt.startVoiceRecognition();else if(mn.persist?.focusInput){let V=e.querySelector("textarea");V&&V.focus()}},100)},0),mn.persist?.openState&&(l.on("widget:opened",()=>{i.setItem(m,"true")}),l.on("widget:closed",()=>{i.setItem(m,"false")})),mn.persist?.voiceState&&(l.on("voice:state",V=>{i.setItem(y,V.active?"true":"false")}),l.on("user:message",V=>{i.setItem(v,V.viaVoice?"true":"false")})),mn.clearOnChatClear){let V=()=>{i.removeItem(m),i.removeItem(y),i.removeItem(v)},X=()=>V();window.addEventListener("persona:clear-chat",X),qe.push(()=>{window.removeEventListener("persona:clear-chat",X)})}}}if(g&&D()&&setTimeout(()=>{Rt.open()},0),mr(),!Qh){let i=Cr(()=>{$&&(gl++,Fo.clear(),aa(ge,$.getMessages(),Le))});qe.push(i)}return Rt};var sh=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},WC=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},HC=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},BC=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.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.")},ih=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},Xp=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=""},lh=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Xp(e)},jp=e=>{e.style.transition=""},Gp=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=""},Kp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ol=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},DC=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},FC=(e,t,n,o,r,a)=>{let s=a?t:e;r==="left"?s.firstElementChild!==o&&s.replaceChildren(o,n):s.lastElementChild!==o&&s.replaceChildren(n,o)},OC=e=>{let t=wo(e),n=t.components?.panel,o=(r,a)=>r==null||r===""?a:Kt(t,r)??r;return{inset:o(n?.inset,hi),canvasBackground:o(n?.canvasBackground,yi)}},dh=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},NC=(e,t,n,o,r,a,s,l)=>{let p=tn(a),d=p.reveal==="push",c=l!=null,u=l?.inset??"",g=l?.canvasBackground??"";DC(e,t,n,o,d),FC(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=s?"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",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,h=a?.launcher?.mobileFullscreen??!0,S=a?.launcher?.mobileBreakpoint??640,L=f!=null?f.innerWidth<=S:!1;if(h&&L&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Gp(t),jp(o),lh(o),Kp(n),ol(r,o),dh(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(a?.launcher?.zIndex??Vt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(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",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),lh(o),WC(o,p.maxHeight),dh(o,c&&s,u,g),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Gp(t),jp(o),Kp(n),ol(r,o);let M=p.animate?"transform 180ms ease":"none",A=p.side==="right"?"translateX(100%)":"translateX(-100%)",w=s?"translateX(0)":A;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=M,o.style.transform=w,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",jp(o),Xp(o),ol(r,o);let M=sh(p.width,e.clientWidth),A=Math.max(0,e.clientWidth),w=p.animate?"margin-left 180ms ease":"none",T=p.side==="right"?s?-M:0:s?0:-M;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=`${A+M}px`,t.style.transition=w,t.style.marginLeft=`${T}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${A}px`,n.style.maxWidth=`${A}px`,n.style.minWidth=`${A}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Gp(t),Xp(o),Kp(n),ol(r,o);let M=p.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let A=s?p.width:"0px",w=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",T=!s;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${A}`,o.style.width=A,o.style.maxWidth=A,o.style.minWidth=A,o.style.minHeight="0",HC(o,p.maxHeight),o.style.overflow=M||T?"hidden":"visible",o.style.transition=w,M){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let H=c?`calc(${sh(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=H,r.style.minWidth=H,r.style.maxWidth=H,r.style.boxSizing="border-box"}}},_C=(e,t)=>{let n=e.ownerDocument.createElement("div");return ih(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){ih(n,o)},destroy(){n.remove()}}},UC=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)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,s=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(s,e),p.appendChild(e);let g=null,f=()=>{g?.disconnect(),g=null},h=null,S=()=>{h=t?.launcher?.detachedPanel===!0?OC(t):null};S();let L=()=>{NC(s,l,p,d,c,t,u,h)},E=null,M=()=>{E?.(),E=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(E=Ir(()=>{S(),L()}))},A=()=>{f(),tn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{L()}),g.observe(s)))},w=!1,T=()=>{L(),A(),u&&!w&&s.dataset.personaDockMobileFullscreen!=="true"&&(w=!0,BC(s,tn(t)))},H=s.ownerDocument.defaultView,C=()=>{T()};return H?.addEventListener("resize",C),tn(t).reveal==="push"?(l.appendChild(p),l.appendChild(d),s.appendChild(l)):(s.appendChild(p),s.appendChild(d)),T(),M(),{mode:"docked",host:c,shell:s,syncWidgetState(B){let F=B.launcherEnabled?B.open:!0;u!==F&&(u=F,T())},updateConfig(B){t=B,(t?.launcher?.enabled??!0)===!1&&(u=!0),S(),T(),M()},destroy(){H?.removeEventListener("resize",C),E?.(),E=null,f(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},es=(e,t)=>Lt(t)?UC(e,t):_C(e,t);var qC=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},ch=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},ph=e=>{let t=qC(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,a=es(t,r),s,l=[],p=(L,E)=>{let A=!(E?.launcher?.enabled??!0)||Lt(E),w=o.createElement("div");if(w.setAttribute("data-persona-root","true"),A&&(w.style.height="100%",w.style.display="flex",w.style.flexDirection="column",w.style.flex="1",w.style.minHeight="0",w.style.minWidth="0"),n){let T=L.attachShadow({mode:"open"});T.appendChild(w),ch(T,o)}else L.appendChild(w),ch(L,o);return t.id&&w.setAttribute("data-persona-instance",t.id),w},d=()=>{a.syncWidgetState(s.getState())},c=()=>{l.forEach(L=>L()),l=[s.on("widget:opened",d),s.on("widget:closed",d)],d()},u=()=>{let L=p(a.host,r);s=nl(L,r,{debugTools:e.debugTools}),c()},g=()=>{l.forEach(L=>L()),l=[],s.destroy()};u(),e.onChatReady?.();let f=L=>{g(),a.destroy(),a=es(t,L),r=L,u()},h={update(L){let E=Ki(r??{},L),M=Lt(r),A=Lt(E),w=Lo(r),T=Lo(E);if(M!==A||w!==T){f(E);return}r=E,a.updateConfig(r),s.update(L),d()},destroy(){g(),a.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},S=new Proxy(h,{get(L,E,M){if(E==="host")return a.host;if(E in L)return Reflect.get(L,E,M);let A=s[E];return typeof A=="function"?A.bind(s):A}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=S),S};function VC(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function zC(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(a=>a.toLowerCase().startsWith(o))?1:VC(o,n)?2:3}function uh(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function rl(e,t){let n=t.trim();if(!n)return[...e].sort(uh);let o=[];for(let r of e){let a=zC(r.label,n);a!==3&&o.push({item:r,tier:a})}return o.sort((r,a)=>r.tier!==a.tier?r.tier-a.tier:uh(r.item,a.item)),o.map(r=>r.item)}function $C(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function fh(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>rl(e.items,t),resolve:e.resolve}}function mh(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>rl(t,$C(r).name),resolve:(r,a)=>{let s=n.get(r.id);return s?s.kind==="server"?{context:(typeof s.data=="function"?s.data(a.args):s.data)??{}}:{insertText:typeof s.prompt=="function"?s.prompt(a.args):s.prompt??""}:{}}}}var bh=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),jC=new Set(["button","a","input","select","textarea","details","summary"]),GC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Jp=/\b(product|card|item|listing|result)\b/i,Yp=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,KC=3e3,XC=100;function vh(e){let t=typeof e.className=="string"?e.className:"";if(Jp.test(t)||e.id&&Jp.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Jp.test(o.value))return!0}return!1}function Ch(e){return Yp.test((e.textContent??"").trim())}function wh(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function JC(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function gh(e){let t=e.match(Yp);return t?t[0]:null}function hh(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 o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function QC(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var YC="commerce-card",ZC="result-card";function yh(e){return!vh(e)||!Ch(e)||!wh(e)&&!JC(e)?0:5200}function xh(e){return!vh(e)||Ch(e)||!wh(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Zp=[{id:YC,scoreElement(e){return yh(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||Yp.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(yh(e)===0)return null;let{title:n,href:o}=hh(e),r=gh((e.textContent??"").trim())??gh(t.text)??"",a=QC(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
144
|
+
`)}},{id:ZC,scoreElement(e){return xh(e)},formatSummary(e,t){if(xh(e)===0)return null;let{title:n,href:o}=hh(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
145
|
+
`)}}];function ew(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function tw(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,s=t.root??e.root,l=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),d=e.rules??Zp;return l==="simple"&&e.rules&&e.rules.length>0?(ew(),d=[]):l==="simple"&&(d=[]),{mode:l,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:a,root:s,rules:d}}function Qp(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var nw=["data-testid","data-product","data-action","data-id","data-name","data-type"];function ow(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||jC.has(t)||n&&GC.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Ah(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 rw(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let l=e.getAttribute("name");l&&(t.name=l);let p=e.getAttribute("role");p&&(t.role=p);for(let d=0;d<e.attributes.length;d++){let c=e.attributes[d];c.name.startsWith("data-")&&(t[c.name]=c.value)}return t}function eu(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${Qp(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of nw){let a=e.getAttribute(r);if(a){let s=`${t}[${r}="${Qp(a)}"]`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(s=>Qp(s)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let a=e.parentElement;if(a){let l=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(l>=0){let p=`${r}:nth-of-type(${l+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let a=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function aw(e){return e==="static"?XC:KC}function Sh(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:eu(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:ow(e),attributes:rw(e)}}function sw(e,t,n,o){let r=aw(t.interactivity),a=null;for(let s of n){let l=s.scoreElement(e,t,o);l>0&&(r+=l,s.formatSummary&&!a&&(a=s))}return{score:r,formattingRule:a}}function iw(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function lw(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=s.currentNode;for(;l&&r.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let d=l,c=d.tagName.toLowerCase();if(bh.has(c)){l=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){l=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Ah(d)){l=s.nextNode();continue}let u=Sh(d,e.maxTextLength),g=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(L=>L==="role");if(!g&&!f){l=s.nextNode();continue}if(o.has(u.selector)){l=s.nextNode();continue}o.add(u.selector);let{score:h,formattingRule:S}=sw(d,u,e.rules,n);r.push({el:d,domIndex:a,enriched:u,score:h,formattingRule:S}),a+=1}l=s.nextNode()}r.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,g=c.enriched.interactivity==="static"?1:0;return u!==g?u-g:c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex});let p=[];for(let d of r){if(p.length>=e.maxElements)break;iw(p,d)||p.push(d)}return p.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,g=c.enriched.interactivity==="static"?1:0;return u!==g?u-g:u===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let g=d.formattingRule.formatSummary(d.el,d.enriched,n);g&&(c=g)}let u={...d.enriched};return c&&(u.formattedSummary=c),u})}function dw(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=r.currentNode;for(;a&&n.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let p=a,d=p.tagName.toLowerCase();if(bh.has(d)){a=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Ah(p)){a=r.nextNode();continue}let c=Sh(p,e.maxTextLength),u=c.text.length>0,g=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(f=>f==="role");if(!u&&!g){a=r.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}a=r.nextNode()}let s=[],l=[];for(let p of n)p.interactivity!=="static"?s.push(p):l.push(p);return[...s,...l].slice(0,e.maxElements)}function Mh(e={}){let t=tw(e),n=t.root??document.body;return n?t.mode==="simple"?dw(t,n):lw(t,n):[]}var al=100;function Th(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let a=e.map(s=>s.formattedSummary).filter(s=>!!s&&s.length>0);a.length>0&&o.push(`Structured summaries:
|
|
146
146
|
${a.map(s=>`- ${s.split(`
|
|
147
147
|
`).join(`
|
|
148
148
|
`)}`).join(`
|
|
149
|
-
`)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||r[a.interactivity].push(a);if(r.clickable.length>0){let a=r.clickable.map(s=>`- ${s.selector}: "${s.text.substring(0,
|
|
149
|
+
`)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||r[a.interactivity].push(a);if(r.clickable.length>0){let a=r.clickable.map(s=>`- ${s.selector}: "${s.text.substring(0,al)}" (clickable)`);o.push(`Interactive elements:
|
|
150
150
|
${a.join(`
|
|
151
|
-
`)}`)}if(r.navigable.length>0){let a=r.navigable.map(s=>`- ${s.selector}${s.attributes.href?`[href="${s.attributes.href}"]`:""}: "${s.text.substring(0,
|
|
151
|
+
`)}`)}if(r.navigable.length>0){let a=r.navigable.map(s=>`- ${s.selector}${s.attributes.href?`[href="${s.attributes.href}"]`:""}: "${s.text.substring(0,al)}" (navigable)`);o.push(`Navigation links:
|
|
152
152
|
${a.join(`
|
|
153
|
-
`)}`)}if(r.input.length>0){let a=r.input.map(s=>`- ${s.selector}${s.attributes.type?`[type="${s.attributes.type}"]`:""}: "${s.text.substring(0,
|
|
153
|
+
`)}`)}if(r.input.length>0){let a=r.input.map(s=>`- ${s.selector}${s.attributes.type?`[type="${s.attributes.type}"]`:""}: "${s.text.substring(0,al)}" (input)`);o.push(`Form inputs:
|
|
154
154
|
${a.join(`
|
|
155
|
-
`)}`)}if(r.static.length>0){let a=r.static.map(s=>`- ${s.selector}: "${s.text.substring(0,
|
|
155
|
+
`)}`)}if(r.static.length>0){let a=r.static.map(s=>`- ${s.selector}: "${s.text.substring(0,al)}"`);o.push(`Content:
|
|
156
156
|
${a.join(`
|
|
157
157
|
`)}`)}return o.join(`
|
|
158
158
|
|
|
159
|
-
`)}function
|
|
159
|
+
`)}function Eh(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function kh(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Lh(e){return{name:"@persona/brand",version:"1.0.0",transform(t){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:Bn(e.colors.primary,.95),100:Bn(e.colors.primary,.9),200:Bn(e.colors.primary,.8),300:Bn(e.colors.primary,.7),400:Bn(e.colors.primary,.6),500:e.colors.primary,600:Bn(e.colors.primary,.8),700:Bn(e.colors.primary,.7),800:Bn(e.colors.primary,.6),900:Bn(e.colors.primary,.5),950:Bn(e.colors.primary,.45)}}),{...t,palette:n}}}}function Ph(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Rh(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Bn(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),a=Math.round(n+(255-n)*(1-t)),s=Math.round(o+(255-o)*(1-t)),l=Math.round(r+(255-r)*(1-t));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}function Ih(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var cw={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"}}},Wh={components:{panel:{borderRadius:"0",shadow:"none"}}},tu={id:"shop",label:"Shopping Assistant",config:{theme:cw,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:ln},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},nu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Wh}},ou={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Wh}},ru={shop:tu,minimal:nu,fullscreen:ou};function Hh(e){return ru[e]}var pw=`
|
|
160
160
|
@keyframes persona-stream-wipe {
|
|
161
161
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
162
162
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|
|
@@ -192,7 +192,7 @@ ${a.join(`
|
|
|
192
192
|
mask-image: none !important;
|
|
193
193
|
}
|
|
194
194
|
}
|
|
195
|
-
`.trim(),
|
|
195
|
+
`.trim(),uw={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:pw};tr(uw);var fw=`
|
|
196
196
|
[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
197
197
|
animation: persona-stream-glyph-cycle-fade
|
|
198
198
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
@@ -210,7 +210,7 @@ ${a.join(`
|
|
|
210
210
|
opacity: 1 !important;
|
|
211
211
|
}
|
|
212
212
|
}
|
|
213
|
-
`.trim(),
|
|
213
|
+
`.trim(),ts="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",mw=10,gw=120,au=120,hw=.4,yw=50,xw=e=>{if(!e)return au;let n=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):au},qh=e=>{let t=e.closest(".persona-stream-glyph-cycle"),n=xw(t);return gw*n/au},su=e=>{let t=ts[Math.floor(Math.random()*ts.length)];return e&&t===e&&(t=ts[(ts.indexOf(t)+1)%ts.length]),t},bw=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let n=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===e){o=!0;continue}o&&Math.random()<hw&&(r.textContent=su())}},Bh=new WeakMap,Dh=25,Fh=.5,vw=6,Oh=.25,Nh=new WeakMap,_h=new WeakMap,Cw=(e,t)=>{if(!e)return Dh*Fh;let n=Nh.get(e);Nh.set(e,t);let o=_h.get(e)??Dh;if(n!==void 0){let r=t-n;r>1&&(o=o*(1-Oh)+r*Oh,_h.set(e,o))}return Math.max(vw,o*Fh)},jr=new Map,ww=e=>e.closest("[data-message-id]")?.dataset.messageId??null,Aw=e=>{e&&jr.set(e,(jr.get(e)??0)+1)},Sw=e=>{if(!e)return;let t=jr.get(e)??0;t<=1?jr.delete(e):jr.set(e,t-1)},Vh=e=>{if(e.dataset.glyphCycleScheduled==="true")return;let t=e.textContent??"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=su();let n=ww(e);n&&(e.dataset.glyphCycleMessageId=n),Aw(n);let o=e.closest(".persona-stream-glyph-cycle"),r=Date.now(),a=Cw(o,r),s=qh(e),l=mw*s,p=r+l;if(o){let d=Bh.get(o);d!==void 0&&(p=Math.max(p,d)),Bh.set(o,p+a)}Mw(e,t,p)},Mw=(e,t,n)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=qh(e),r=e.textContent??void 0,a=()=>{if(!e.isConnected)return;if(Date.now()>=n){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,Sw(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let s=su(r);e.textContent=s,r=s,bw(e),setTimeout(a,o)};setTimeout(a,o)},Uh=e=>{let t=e.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let n of Array.from(t))Vh(n)},Tw=e=>e.nodeType===1,Ew={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:fw,bufferContent(e){if(e.length<yw)return"";let t=0,n=-1,o=0;for(;o<e.length;){if(e[o]==="*"&&e[o+1]==="*"){t+=1,o+=2;continue}/\s/.test(e[o])&&t%2===0&&(n=o),o+=1}return n<0?"":e.slice(0,n)},isAnimating(e){return(jr.get(e.id)??0)>0},onAttach(e){Uh(e);let t=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))Tw(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?Vh(r):Uh(r))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};tr(Ew);var Qt=typeof document<"u"?document.currentScript?.src??null:null;Df(()=>{let e=Qt?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===Qt?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${Qt??"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)});vf(()=>{let e=Qt?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===Qt?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${Qt??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});xa().catch(e=>{typeof console<"u"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});vm(()=>{let e=Qt?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===Qt?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${Qt??"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)});Rm(()=>{let e=Qt?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===Qt?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${Qt??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});Im(()=>{let e=Qt?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===Qt?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${Qt??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});return Uy(kw);})();
|
|
214
214
|
/*! Bundled license information:
|
|
215
215
|
|
|
216
216
|
lucide/dist/esm/icons/activity.mjs:
|