@runtypelabs/persona 4.13.0 → 4.14.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/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/context-mentions.d.cts +98 -6
- package/dist/context-mentions.d.ts +98 -6
- package/dist/index.cjs +64 -64
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +183 -8
- package/dist/index.d.ts +183 -8
- package/dist/index.global.js +54 -54
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +67 -67
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +1 -1
- package/dist/launcher.global.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +98 -6
- package/dist/smart-dom-reader.d.ts +98 -6
- package/dist/theme-editor-preview.cjs +66 -66
- package/dist/theme-editor-preview.d.cts +100 -6
- package/dist/theme-editor-preview.d.ts +100 -6
- package/dist/theme-editor-preview.js +75 -75
- package/dist/theme-editor.cjs +10 -10
- package/dist/theme-editor.d.cts +134 -7
- package/dist/theme-editor.d.ts +134 -7
- package/dist/theme-editor.js +10 -10
- package/dist/theme-reference.cjs +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/artifacts-session.test.ts +106 -0
- package/src/client.test.ts +2 -2
- package/src/client.ts +4 -1
- package/src/components/artifact-card.ts +13 -2
- package/src/components/artifact-inline.ts +11 -2
- package/src/components/composer-builder.test.ts +2 -0
- package/src/components/composer-builder.ts +1 -1
- package/src/components/composer-parts.test.ts +2 -0
- package/src/components/composer-parts.ts +1 -1
- package/src/components/message-bubble.test.ts +7 -1
- package/src/components/message-bubble.ts +11 -8
- package/src/index-core.ts +34 -0
- package/src/session.ts +45 -4
- package/src/styles/widget.css +10 -1
- package/src/theme-editor/index.ts +5 -0
- package/src/theme-editor/presets.test.ts +43 -0
- package/src/theme-editor/presets.ts +101 -87
- package/src/theme-editor/sections.test.ts +39 -7
- package/src/theme-editor/sections.ts +60 -8
- package/src/theme-editor/state-preferences.test.ts +15 -0
- package/src/theme-editor/state.ts +46 -0
- package/src/theme-editor/types.ts +15 -1
- package/src/theme-editor/webmcp/tools.test.ts +13 -0
- package/src/theme-editor/webmcp/tools.ts +5 -0
- package/src/types.ts +139 -9
- package/src/ui.artifact-pane-gating.test.ts +5 -5
- package/src/ui.config-preferences.test.ts +166 -0
- package/src/ui.ts +43 -25
- package/src/ui.typing-indicator.test.ts +135 -0
- package/src/utils/artifact-display.test.ts +180 -16
- package/src/utils/artifact-display.ts +155 -14
- package/src/utils/config-merge.test.ts +60 -0
- package/src/utils/config-merge.ts +6 -1
- package/src/utils/feature-preferences.test.ts +326 -0
- package/src/utils/feature-preferences.ts +498 -0
- package/src/utils/theme.test.ts +92 -0
- package/src/utils/tokens.ts +7 -7
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 lb=Object.create;var js=Object.defineProperty;var db=Object.getOwnPropertyDescriptor;var cb=Object.getOwnPropertyNames;var pb=Object.getPrototypeOf,ub=Object.prototype.hasOwnProperty;var Ea=(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 fb=(e,t)=>()=>(e&&(t=e(e=0)),t);var Of=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Nf=(e,t)=>{for(var n in t)js(e,n,{get:t[n],enumerable:!0})},_f=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of cb(t))!ub.call(e,r)&&r!==n&&js(e,r,{get:()=>t[r],enumerable:!(o=db(t,r))||o.enumerable});return e};var ho=(e,t,n)=>(n=e!=null?lb(pb(e)):{},_f(t||!e||!e.__esModule?js(n,"default",{value:e,enumerable:!0}):n,e)),mb=e=>_f(js({},"__esModule",{value:!0}),e);var id=Of(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 Ys=Of(_t=>{"use strict";var Db=_t&&_t.__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]})),Fb=_t&&_t.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&Db(t,e,n)};Object.defineProperty(_t,"__esModule",{value:!0});_t.Allow=_t.MalformedJSON=_t.PartialJSON=_t.parseJSON=_t.parse=void 0;var Jt=id();Object.defineProperty(_t,"Allow",{enumerable:!0,get:function(){return Jt.Allow}});Fb(id(),_t);var Js=class extends Error{};_t.PartialJSON=Js;var Qs=class extends Error{};_t.MalformedJSON=Qs;function im(e,t=Jt.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return Ob(e.trim(),t)}_t.parseJSON=im;var Ob=(e,t)=>{let n=e.length,o=0,r=g=>{throw new Js(`${g} at position ${o}`)},a=g=>{throw new Qs(`${g} at position ${o}`)},s=()=>(u(),o>=n&&r("Unexpected end of input"),e[o]==='"'?l():e[o]==="{"?p():e[o]==="["?c():e.substring(o,o+4)==="null"||Jt.Allow.NULL&t&&n-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Jt.Allow.BOOL&t&&n-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Jt.Allow.BOOL&t&&n-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Jt.Allow.INFINITY&t&&n-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Jt.Allow._INFINITY&t&&1<n-o&&n-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Jt.Allow.NAN&t&&n-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):d()),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(Jt.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&&Jt.Allow.OBJ&t)return g;let f=l();u(),o++;try{let h=s();g[f]=h}catch(h){if(Jt.Allow.OBJ&t)return g;throw h}u(),e[o]===","&&o++}}catch{if(Jt.Allow.OBJ&t)return g;r("Expected '}' at end of object")}return o++,g},c=()=>{o++;let g=[];try{for(;e[o]!=="]";)g.push(s()),u(),e[o]===","&&o++}catch{if(Jt.Allow.ARR&t)return g;r("Expected ']' at end of array")}return o++,g},d=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(f){if(Jt.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&&!(Jt.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()},Nb=im;_t.parse=Nb});var qm={};Nf(qm,{createReconnectController:()=>Mx});function Mx(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()},c=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",p),r=!0)},d=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},u=h=>new Promise(A=>{n=A,o=setTimeout(()=>{o=null,n=null,A()},h)}),g=()=>{let h=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,d(),e.setAbortController(null);let A=!1;for(let k of e.getMessages())k.streaming&&(k.streaming=!1,A=!0);let E=e.buildErrorContent("Connection lost and the response could not be resumed.");E?e.appendMessage({id:`reconnect-failed-${h?.executionId??e.nextSequence()}`,role:"assistant",content:E,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):A&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},f=async()=>{let h=e.config.reconnect?.backoffMs??Sx,A=e.config.reconnect?.maxAttempts??h.length,E=e.config.reconnectStream;if(!E){e.setReconnecting(!1);return}for(;e.getResumable()&&t<A;){t+=1,e.setStatus("resuming");let k=e.getResumable(),M=k.lastEventId,S=new AbortController;e.setAbortController(S),e.emitReconnect({phase:"resuming",handle:k,attempt:t});let C=null;try{let T=await E({executionId:k.executionId,after:k.lastEventId,signal:S.signal});T&&T.ok&&T.body&&(C=T.body)}catch{C=null}if(S.signal.aborted)return;if(C){let T=e.getMessages().find(w=>w.id===k.assistantMessageId)?.content,W=typeof T=="string"?T:"";try{await e.resumeConnect(C,k.assistantMessageId,W)}catch{}if(S.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,d(),e.emitReconnect({phase:"resumed",handle:k});return}e.getResumable().lastEventId!==M&&(t=0)}if(e.getResumable()&&t<A&&(e.setStatus("paused"),await u(h[Math.min(t-1,h.length-1)]??1e3),S.signal.aborted))return}e.getResumable()&&g()};return{begin(){t=0,c(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,d()},wake:a}}var Sx,Vm=fb(()=>{"use strict";Sx=[1e3,2e3,4e3,8e3,8e3]});var pA={};Nf(pA,{ASK_USER_QUESTION_CLIENT_TOOL:()=>yd,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>hd,ASK_USER_QUESTION_TOOL_NAME:()=>Wa,AgentWidgetClient:()=>er,AgentWidgetSession:()=>Fr,AttachmentManager:()=>or,BrowserSpeechEngine:()=>Eo,DEFAULT_COMPONENTS:()=>Mp,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Ri,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>pn,DEFAULT_PALETTE:()=>Ap,DEFAULT_SEMANTIC:()=>Sp,DEFAULT_WIDGET_CONFIG:()=>st,PRESETS:()=>Su,PRESET_FULLSCREEN:()=>Au,PRESET_MINIMAL:()=>wu,PRESET_SHOP:()=>Cu,ReadAloudController:()=>nr,SUGGEST_REPLIES_CLIENT_TOOL:()=>ni,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>fd,SUGGEST_REPLIES_TOOL_NAME:()=>kn,THEME_ZONES:()=>ag,VERSION:()=>Zo,WEBMCP_TOOL_PREFIX:()=>En,WebMcpBridge:()=>Pr,accessibilityPlugin:()=>ey,animationsPlugin:()=>ty,applyFeaturePreferences:()=>su,applyThemeVariables:()=>rr,attachHeaderToContainer:()=>ir,brandPlugin:()=>ny,buildComposer:()=>jr,buildDefaultHeader:()=>_p,buildHeader:()=>eo,buildHeaderWithLayout:()=>$r,buildMinimalHeader:()=>Up,builtInClientToolsForDispatch:()=>Hr,canonicalArtifactDisplayMode:()=>on,collectEnrichedPageContext:()=>Yh,componentRegistry:()=>Ln,createActionManager:()=>cs,createAgentExperience:()=>vl,createAskUserQuestionBubble:()=>Cm,createBestAvailableVoiceProvider:()=>yi,createBubbleWithLayout:()=>Xg,createCSATFeedback:()=>yl,createComboButton:()=>_i,createComponentMiddleware:()=>kh,createComponentStreamParser:()=>ml,createDefaultSanitizer:()=>nd,createDirectivePostprocessor:()=>$f,createDropdownMenu:()=>Ro,createFlexibleJsonStreamParser:()=>Mm,createIconButton:()=>Mt,createImagePart:()=>Im,createJsonStreamParser:()=>ci,createLabelButton:()=>Zn,createLocalStorageAdapter:()=>fl,createMarkdownProcessor:()=>La,createMarkdownProcessorFromConfig:()=>Qo,createMessageActions:()=>Xp,createNPSFeedback:()=>bl,createPlainTextParser:()=>li,createPlugin:()=>ay,createRegexJsonParser:()=>di,createSlashCommandsSource:()=>Uh,createStandardBubble:()=>Gr,createStaticMentionSource:()=>_h,createTextPart:()=>Mo,createTheme:()=>za,createThemeObserver:()=>Nr,createToggleGroup:()=>qr,createTypingIndicator:()=>lr,createVoiceProvider:()=>To,createWidgetHostLayout:()=>us,createXmlParser:()=>pi,defaultActionHandlers:()=>mr,defaultJsonActionParser:()=>ds,defaultMentionFilter:()=>wl,defaultParseRules:()=>xu,detectColorScheme:()=>$a,directivePostprocessor:()=>jf,ensureAskUserQuestionSheet:()=>Wr,escapeHtml:()=>Hn,extractComponentDirectiveFromMessage:()=>hl,fileToImagePart:()=>Wm,formatEnrichedContext:()=>Zh,generateAssistantMessageId:()=>So,generateMessageId:()=>km,generateStableSelector:()=>vu,generateUserMessageId:()=>Br,getActiveTheme:()=>ko,getColorScheme:()=>Di,getDisplayText:()=>Pm,getHeaderLayout:()=>qp,getImageParts:()=>Rm,getPreset:()=>iy,hasComponentDirective:()=>ps,hasImages:()=>mi,headerLayouts:()=>el,highContrastPlugin:()=>ry,initAgentWidget:()=>Oh,isAskUserQuestionMessage:()=>Xn,isComponentDirectiveType:()=>Eh,isDockedMountMode:()=>Et,isSuggestRepliesMessage:()=>Ba,isVoiceSupported:()=>_a,isWebMcpToolName:()=>yo,latestAgentSuggestions:()=>oi,listRegisteredStreamAnimations:()=>Fp,loadMarkdownParsers:()=>ka,markdownPostprocessor:()=>td,mergeWithDefaults:()=>Or,normalizeContent:()=>Lm,normalizeMediaType:()=>bo,onMarkdownParsersReady:()=>kr,parseAskUserQuestionPayload:()=>Jn,parseSuggestRepliesPayload:()=>gd,parseWidgetPreferenceSlice:()=>au,pickBestVoice:()=>Dr,pluginRegistry:()=>ls,reducedMotionPlugin:()=>oy,registerStreamAnimationPlugin:()=>sr,removeAskUserQuestionSheet:()=>Co,renderComponentDirective:()=>gl,renderLoadingIndicatorWithFallback:()=>Gp,renderLucideIcon:()=>oe,resolveArtifactDisplay:()=>sd,resolveArtifactDisplayMode:()=>Bn,resolveConfigPreferences:()=>is,resolveDockConfig:()=>rn,resolveSanitizer:()=>Lr,resolveTokens:()=>Hi,stripWebMcpPrefix:()=>Xs,themeToCssVariables:()=>Bi,unregisterStreamAnimationPlugin:()=>Dp,validateImageFile:()=>Hm,validateTheme:()=>Tp});var Er=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,a=null;return{setLoader:d=>{o=d,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:d=>{r=d},getSync:()=>r}};var{setLoader:gb,load:hb,provide:bA,getSync:ed}=Er({fallbackImport:()=>import("./markdown-parsers-entry")}),Gs=new Set,yb=()=>{let e=[...Gs];Gs.clear();for(let t of e)try{t()}catch{}},Uf=gb,ka=()=>{let e=ed();return e?Promise.resolve(e):hb().then(t=>(yb(),t))},kr=e=>ed()?()=>{}:(Gs.add(e),ka().catch(()=>{}),()=>{Gs.delete(e)});var Gn=ed;var bb=e=>{if(e)return e},La=e=>{let t=null;return n=>{let o=Gn();if(!o)return Hn(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=bb(e?.renderer);s&&t.use({renderer:s})}return t.parse(n)}},Qo=e=>e?La({markedOptions:e.options,renderer:e.renderer}):La(),xb=La(),td=e=>xb(e),Hn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Vf=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),qf=e=>`%%FORM_PLACEHOLDER_${e}%%`,zf=(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=qf(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=qf(t.length);return t.push({token:a,type:r}),a}),n},$f=e=>{let t=Qo(e);return n=>{let o=[],r=zf(n,o),a=t(r);return o.forEach(({token:s,type:l})=>{let p=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Vf(l)}"></div>`;a=a.replace(p,d)}),a}},jf=e=>{let t=[],n=zf(e,t),o=td(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="${Vf(a)}"></div>`;o=o.replace(s,p)}),o};var vb={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"]},Cb=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,nd=()=>{let e=null;return t=>{let n=Gn();if(!n)return Hn(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:")&&!Cb.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,vb)}},Lr=e=>e===!1?null:typeof e=="function"?e:nd();var Gf=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Kf=e=>e.includes("|"),Xf=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())},wb=e=>`| ${e.join(" | ")} |`,Ab=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Sb=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Jf=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(!Kf(r)||Gf.test(r)||!Gf.test(a))continue;let s=Xf(r).length;if(s<1)continue;let l=Ab(s);t[o+1]!==l&&(t[o+1]=l,n=!0);let p=o+2;for(;p<t.length;p++){let c=t[p];if(c.trim()===""||!Kf(c))break;let d=wb(Sb(Xf(c),s));t[p]!==d&&(t[p]=d,n=!0)}o=p-1}return n?t.join(`
|
|
4
|
+
`):e};var Qf="var(--persona-md-table-scroll-fade, 24px)",Yf=new WeakSet;function em(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 Zf(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":Qf),e.style.setProperty("--persona-fade-r",r<=1?"0px":Qf)}function od(e){Yf.has(e)||(Yf.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Zf(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Zf)}var En="webmcp:",rd=new Map,tm=e=>{rd.clear();for(let t of e){let n=t.title?.trim();n&&rd.set(t.name,n)}},Pa=e=>rd.get(Xs(e)),Ks={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},ad=null,om=e=>{ad=e};function rm(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}:${Mb(t.join(""))}`}function nm(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 Mb(e){let t=nm(e,0).toString(36),n=nm(e,2654435761).toString(36);return`${t}.${n}`}var Pr=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 Ks.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}tm(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=Eb(r.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Tn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let h=typeof document<"u"&&!!document.modelContext;return Tn(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=Xs(t),s;try{s=await r.getTools()}catch(h){let A=h instanceof Error?h.message:String(h);return Tn(`Failed to read WebMCP registry: ${A}`)}tm(s);let l=s.find(h=>h.name===a);if(!l)return Tn(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return Tn(`WebMCP tool not allowed by client allowlist: ${a}`);if(o?.aborted)return Tn("Aborted by cancel()");let p=Pa(a),c={toolName:a,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(c))return Tn("User declined the tool call.");if(o?.aborted)return Tn("Aborted by cancel()");let d=new AbortController,u=!1,g=setTimeout(()=>{u=!0,d.abort()},this.timeoutMs),f=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",f,{once:!0}));try{let h=await r.executeTool(l,Rb(n),{signal:d.signal});return kb(h)}catch(h){if(u)return Tn(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Tn("Aborted by cancel()");let A=h instanceof Error?h.message:String(h);return Tn(A)}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}(ad?await ad():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ks.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,Ks.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??Lb;try{return await n(t)}catch(o){return Ks.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=>Tb(t,o))}},Xs=e=>e.startsWith(En)?e.slice(En.length):e,yo=e=>e.startsWith(En),Tb=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Eb=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},kb=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:Ib(t)}]}},Tn=e=>({isError:!0,content:[{type:"text",text:e}]}),Lb=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=Pb(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)},lx=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)}},dx=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},cx=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function Go(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function Ns(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 px="agent_",ux="flow_";function qf(e){return e.startsWith(px)?{kind:"agentId",agentId:e}:e.startsWith(ux)?{kind:"flowId",flowId:e}:null}function Vf(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=qf(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=qf(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(qs(),1);var x=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var $f=()=>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 Sa="ask_user_question",Aa=8,Mr="data-persona-ask-sheet-for",yx="Other",xx="Other\u2026",Gf="Type your own answer here",Kf="Send",bx="Next",vx="Back",Cx="Submit all",wx="Skip",Ax=3,Xl="data-ask-current-index",Jl="data-ask-question-count",Xf="data-ask-answers",Ql="data-ask-grouped",Jf="data-ask-layout",Sx=e=>e.layout==="pills"?"pills":"rows",Mx=e=>e.getAttribute(Jf)==="pills"?"pills":"rows",jf=!1,Qf=e=>e.replace(/["\\]/g,"\\$&"),$n=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Sa,Vs=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}},Ma=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Aa&&!jf&&(jf=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Aa}.`)),t.slice(0,Aa)},Tx=e=>Ma(e)[0]??null,Ex=(e,t)=>Ma(e)[t]??null,Yf=(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=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},kx=(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=Zf(n,o,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Lx=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},Px=(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<Ax;c++)a.appendChild(Lx(o));return a}if(p.forEach((c,u)=>{a.appendChild(kx(c,u,o,s))}),e?.allowFreeText!==!1){let c=o==="rows"?yx:xx;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??Gf,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),g.appendChild(f),u.appendChild(g);let h=Zf(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},em=(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??Gf,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??Kf,a.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(a)}return o},Rx=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??Kf,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Ix=(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??vx,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??wx,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??Cx:n.nextLabel??bx,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,a.appendChild(l),o.appendChild(a),o},Ko=e=>{let t=e.getAttribute(Xf);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},tm=(e,t)=>{e.setAttribute(Xf,JSON.stringify(t))},hn=e=>{let t=Number(e.getAttribute(Xl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Wx=(e,t)=>{e.setAttribute(Xl,String(Math.max(0,Math.floor(t))))},Tr=e=>{let t=Number(e.getAttribute(Jl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},mo=e=>e.getAttribute(Ql)==="true",Hx=(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},Bx=(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)))},zs=(e,t)=>{let{payload:n}=jn(t),o=Ma(n),r=Ko(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},nm=e=>{let t=Ko(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="")},om=e=>{if(!mo(e))return;let t=Ko(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}},Yl=(e,t,n)=>{let o=Vs(n),r=Mx(e),{payload:a,complete:s}=jn(t),l=mo(e),p=hn(e),d=Tr(e),c=l?Ex(a,p):Tx(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=Px(c,o,s,r);S.replaceWith(M)}if(r!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(em(o,r))}let L=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!L?e.appendChild(Rx(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=Ix(p,d,o);E?E.replaceWith(M):e.appendChild(M)}else E&&E.remove();nm(e),om(e)},Dx=(e,t,n)=>{let o=Vs(t),r=Sx(o),a=e.toolCall.id,s=Ma(n),l=Math.max(1,s.length),p=l>1,d=Hx(e,s),c=p?Bx(e,l):0,u=x("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Mr,a),u.setAttribute("data-tool-call-id",a),u.setAttribute("data-message-id",e.id),u.setAttribute(Jl,String(l)),u.setAttribute(Xl,String(c)),u.setAttribute(Ql,p?"true":"false"),u.setAttribute(Jf,r),tm(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`),Yf(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(em(o,r)),Yl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Fx=(e,t,n)=>{let{payload:o}=jn(t),r=Math.max(1,Ma(o).length);r>Tr(e)&&(e.setAttribute(Jl,String(r)),r>1&&!mo(e)&&e.setAttribute(Ql,"true")),Yl(e,t,n)},rm=(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=Vs(t);Yf(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},Er=(e,t,n)=>{if(!n||!$n(e)||Vs(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Mr}]`).forEach(d=>{d.getAttribute(Mr)!==r&&d.remove()});let s=n.querySelector(`[${Mr}="${Qf(r)}"]`);if(s){Fx(s,e,t);return}let{payload:l}=jn(e),p=Dx(e,t,l);n.appendChild(p)},go=(e,t)=>{if(!e)return;let n=t?`[${Mr}="${Qf(t)}"]`:`[${Mr}]`;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)})},Zl=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=Ko(e),o=hn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,tm(e,n),nm(e),om(e)},$s=(e,t,n,o)=>{let r=Tr(e),a=Math.max(0,Math.min(r-1,o));Wx(e,a),Yl(e,t,n)};var Tn="suggest_replies";var ed={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},js={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:ed,origin:"sdk",annotations:{readOnlyHint:!0}},td=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ta=e=>e.variant==="tool"&&e.toolCall?.name===Tn,nd=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},Gs=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ta(n))continue;let o=nd(n.toolCall?.args);return o.length>0?o:null}return null},am=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var od={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Aa,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},rd={name:Sa,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:od,origin:"sdk",annotations:{readOnlyHint:!0}},kr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(rd),am(e)&&t.push(js),t};var Gn=po(qs(),1),Ks=e=>e.replace(/\\n/g,`
|
|
10
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
9
|
+
${e.description}`:"");return window.confirm(n)},Pb=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)}},Rb=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ib=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function on(e){return e==="card"?"collapsed":e}function bo(e){return e.split(";",1)[0].trim().toLowerCase()}function Wb(e,t){if(!e)return;let n=Object.entries(e);for(let[r,a]of n)if(bo(r)===t)return{mode:on(a),selector:bo(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,a]of n)if(bo(r)===o)return{mode:on(a),selector:o}}function sd(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:on(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?bo(t.file.mimeType):void 0,p=l?Wb(o.files.byMediaType,l):void 0;if(l&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:l,selector:p.selector}};if(o.files.default)return{mode:on(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:on(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=o.byType?.[t.artifactType];if(a)return{mode:on(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:on(s),matchedBy:{type:"preferredMode"}}:o.default?{mode:on(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Bn(e,t){return sd(e,t).mode}function Ra(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var Hb="agent_",Bb="flow_";function am(e){return e.startsWith(Hb)?{kind:"agentId",agentId:e}:e.startsWith(Bb)?{kind:"flowId",flowId:e}:null}function sm(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=am(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=am(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 xo=ho(Ys(),1);var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var lm=()=>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},Kn=(...e)=>e.filter(Boolean).join(" ");var Wa="ask_user_question",Ia=8,Rr="data-persona-ask-sheet-for",_b="Other",Ub="Other\u2026",cm="Type your own answer here",pm="Send",qb="Next",Vb="Back",zb="Submit all",$b="Skip",jb=3,ld="data-ask-current-index",dd="data-ask-question-count",um="data-ask-answers",cd="data-ask-grouped",fm="data-ask-layout",Gb=e=>e.layout==="pills"?"pills":"rows",Kb=e=>e.getAttribute(fm)==="pills"?"pills":"rows",dm=!1,mm=e=>e.replace(/["\\]/g,"\\$&"),Xn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Wa,Zs=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,xo.parse)(r,xo.STR|xo.OBJ|xo.ARR);if(a&&typeof a=="object")return{payload:a,complete:n}}catch{}return{payload:null,complete:n}},Ha=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ia&&!dm&&(dm=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ia}.`)),t.slice(0,Ia)},Xb=e=>Ha(e)[0]??null,Jb=(e,t)=>Ha(e)[t]??null,gm=(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))},hm=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Qb=(e,t,n,o)=>{let a=b("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=b("span","persona-ask-row-content"),l=b("span","persona-ask-row-label");if(l.textContent=e.label,s.appendChild(l),e.description){let c=b("span","persona-ask-row-description");c.textContent=e.description,s.appendChild(c)}a.appendChild(s);let p=hm(n,o,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Yb=e=>{let n=b("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},Zb=(e,t,n,o)=>{let a=b("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<jb;d++)a.appendChild(Yb(o));return a}if(p.forEach((d,u)=>{a.appendChild(Qb(d,u,o,s))}),e?.allowFreeText!==!1){let d=o==="rows"?_b:Ub;if(o==="rows"){let u=b("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=b("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??cm,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??d),g.appendChild(f),u.appendChild(g);let h=hm(o,s,p.length);h&&u.appendChild(h),a.appendChild(u)}else{let u=b("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},ym=(e,t)=>{let o=b("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??cm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let a=b("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??pm,a.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(a)}return o},ex=e=>{let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??pm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},tx=(e,t,n)=>{let o=b("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=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Vb,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let a=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=b("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=n.skipLabel??$b,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let l=b("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??zb:n.nextLabel??qb,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,a.appendChild(l),o.appendChild(a),o},Yo=e=>{let t=e.getAttribute(um);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},bm=(e,t)=>{e.setAttribute(um,JSON.stringify(t))},xn=e=>{let t=Number(e.getAttribute(ld)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},nx=(e,t)=>{e.setAttribute(ld,String(Math.max(0,Math.floor(t))))},Ir=e=>{let t=Number(e.getAttribute(dd)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},vo=e=>e.getAttribute(cd)==="true",ox=(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},rx=(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)))},ei=(e,t)=>{let{payload:n}=Jn(t),o=Ha(n),r=Yo(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},xm=e=>{let t=Yo(e),n=xn(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="")},vm=e=>{if(!vo(e))return;let t=Yo(e),n=xn(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}},pd=(e,t,n)=>{let o=Zs(n),r=Kb(e),{payload:a,complete:s}=Jn(t),l=vo(e),p=xn(e),c=Ir(e),d=l?Jb(a,p):Xb(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 A=e.querySelector('[data-ask-pill-list="true"]');if(A){let M=Zb(d,o,s,r);A.replaceWith(M)}if(r!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(ym(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!E?e.appendChild(ex(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=tx(p,c,o);k?k.replaceWith(M):e.appendChild(M)}else k&&k.remove();xm(e),vm(e)},ax=(e,t,n)=>{let o=Zs(t),r=Gb(o),a=e.toolCall.id,s=Ha(n),l=Math.max(1,s.length),p=l>1,c=ox(e,s),d=p?rx(e,l):0,u=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Rr,a),u.setAttribute("data-tool-call-id",a),u.setAttribute("data-message-id",e.id),u.setAttribute(dd,String(l)),u.setAttribute(ld,String(d)),u.setAttribute(cd,p?"true":"false"),u.setAttribute(fm,r),bm(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`),gm(u,o);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=b("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let h=b("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",g.appendChild(h),u.appendChild(g);let E=b("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(ym(o,r)),pd(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},sx=(e,t,n)=>{let{payload:o}=Jn(t),r=Math.max(1,Ha(o).length);r>Ir(e)&&(e.setAttribute(dd,String(r)),r>1&&!vo(e)&&e.setAttribute(cd,"true")),pd(e,t,n)},Cm=(e,t)=>{let n=b("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=Zs(t);gm(n,o);let r=b("span","persona-ask-stub-label"),{complete:a}=Jn(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Wr=(e,t,n)=>{if(!n||!Xn(e)||Zs(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Rr}]`).forEach(c=>{c.getAttribute(Rr)!==r&&c.remove()});let s=n.querySelector(`[${Rr}="${mm(r)}"]`);if(s){sx(s,e,t);return}let{payload:l}=Jn(e),p=ax(e,t,l);n.appendChild(p)},Co=(e,t)=>{if(!e)return;let n=t?`[${Rr}="${mm(t)}"]`:`[${Rr}]`;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)})},ud=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),wo=(e,t)=>{let n=Yo(e),o=xn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,bm(e,n),xm(e),vm(e)},ti=(e,t,n,o)=>{let r=Ir(e),a=Math.max(0,Math.min(r-1,o));nx(e,a),pd(e,t,n)};var kn="suggest_replies";var fd={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},ni={name:kn,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:fd,origin:"sdk",annotations:{readOnlyHint:!0}},md=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ba=e=>e.variant==="tool"&&e.toolCall?.name===kn,gd=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},oi=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ba(n))continue;let o=gd(n.toolCall?.args);return o.length>0?o:null}return null},wm=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var hd={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ia,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},yd={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:hd,origin:"sdk",annotations:{readOnlyHint:!0}},Hr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(yd),wm(e)&&t.push(ni),t};var Qn=ho(Ys(),1),ri=e=>e.replace(/\\n/g,`
|
|
10
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ao=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)}},ix=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`},Am=e=>e.status==="complete"?ix(e):e.status==="pending"?"Waiting":"",lx=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 Sm=e=>e.status==="complete"?lx(e):"Using tool...",ai=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Fa=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 ai(t)},si=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return ai(t)},bd=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Fa(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ii=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=r.exec(n))!==null;)s.index>a&&Da(o,n.slice(a,s.index),[]),s[1]!==void 0?Da(o,s[1],["bold"]):s[2]!==void 0?Da(o,s[2],["italic"]):s[3]!==void 0&&Da(o,s[3],["dim"]),a=s.index+s[0].length;return a<n.length&&Da(o,n.slice(a),[]),o},Da=(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})},dx=()=>{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()=>{}}},La=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ys=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Zs=()=>{let e=_x();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)}},ei=()=>{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"?Ks(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Ks(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},lm=e=>{let t=null,n=0,r=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?Ks(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?Ks(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:()=>{}}},ti=()=>{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 dm="4.13.0";var Xo=dm;var qx="https://api.runtype.com/v1/dispatch",ni="https://api.runtype.com";function Vx(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 sd=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 zx(e){switch(e){case"json":return ei;case"regex-json":return Zs;case"xml":return ti;default:return Ys}}var cm=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=cm(n);if(!cm(o))return e;if(!r||o===n||o.startsWith(n))return t;let s=La(e);return La(t)!==null&&s===null?t:e}var Jo=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??qx,this.headers={"Content-Type":"application/json","X-Persona-Version":Xo,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??zx(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 Sr(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=Vf(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$/,"")||ni}/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":Xo},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$/,"")||ni}/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":Xo},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(sd).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":Xo},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$/,"")||ni}/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?Uf(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(/\/+$/,"")||ni}/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=[...kr(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(sd).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=[...kr(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(sd).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=[...kr(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),ie=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,Ie=()=>{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=ie(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},ze=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)}},Je=new Map,We=new Map,Me=new Map,Qe=(R,z,b)=>{let P=Me.get(R);P||(P=[],Me.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=We.get(R.id),I=$x(P,b);R.rawContent=I;let N=Je.get(R.id),G=Te=>{let at=R.content??"";Te.trim()!==""&&(at.trim().length===0||Te.startsWith(at)||Te.trimStart().startsWith(at.trim()))&&(R.content=Te)},_=()=>{if(N){let Te=N.close?.();Te instanceof Promise&&Te.catch(()=>{})}Je.delete(R.id),We.delete(R.id),R.streaming=!1,f(R)};if(!N){G(b),_();return}let j=La(I);if(j!==null&&j.trim()!==""){G(j),_();return}let re=Te=>{let at=typeof Te=="string"?Te:Te?.text??null;if(at!==null&&at.trim()!=="")return at;let K=N.getExtractedText();return K!==null&&K.trim()!==""?K:b},je;try{je=N.processChunk(I)}catch{G(b),_();return}if(je instanceof Promise){je.then(Te=>{G(re(Te)),_()}).catch(()=>{G(b),_()});return}G(re(je)),_()},Tt=null,yt=(R,z,b,P)=>{R.rawContent=z,Je.has(R.id)||Je.set(R.id,this.createStreamParser());let I=Je.get(R.id),N=z.trim().startsWith("{")||z.trim().startsWith("[");if(N&&We.set(R.id,z),I.__isPlainTextParser===!0){R.content=P!==void 0?z:R.content+b,We.delete(R.id),Je.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,We.delete(R.id),Je.delete(R.id),R.rawContent=void 0,f(R))}).catch(()=>{R.content=P!==void 0?z:R.content+b,We.delete(R.id),Je.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,We.delete(R.id),Je.delete(R.id),R.rawContent=void 0,f(R))}},He=(R,z)=>{let b=z??R.content;if(b==null||b===""){R.streaming=!1,f(R);return}let I=We.get(R.id)??rt(b);R.rawContent=I;let N=Je.get(R.id),G=null,_=!1;if(N&&(G=N.getExtractedText(),G===null&&(G=La(I)),G===null)){let j=N.processChunk(I);j instanceof Promise?(_=!0,j.then(re=>{let je=typeof re=="string"?re:re?.text??null;je!==null&&(R.content=je,R.streaming=!1,Je.delete(R.id),We.delete(R.id),f(R))}).catch(()=>{})):G=typeof j=="string"?j:j?.text??null}if(!_){G!==null&&G.trim()!==""?R.content=G:We.has(R.id)||(R.content=rt(b));let j=Je.get(R.id);if(j){let re=j.close?.();re instanceof Promise&&re.catch(()=>{}),Je.delete(R.id)}We.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},Ke=[],Ee,pe=new Map,se=0,ge="agent",xt=!1,he=null,ce=null,yn=new Map,Q=this.config.iterationDisplay??"separate";for(Ee=()=>{for(let R=0;R<Ke.length;R++){let z=Ke[R].payloadType,b=Ke[R].payload;if(!xt&&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=Qe(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"&&(se=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(ie(b),P);let N=ze(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=ze(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=ze(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=ie(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=ze(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"?(He(N),Tt=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},yt(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 _=Ie();_.agentMetadata={executionId:b.executionId,iteration:b.iteration},yt(_,A,G,void 0),S=_;continue}let N=Ie();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&&He(N),w.delete(P),H.delete(P),T.delete(P);continue}let I=h;I&&(ge==="flow"?(He(I),Tt=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=Tt;Tt=null;let G=b.stopReason,_=b.result?.response;if(N)G&&(N.stopReason=G),_!=null?cn(N,_):N.streaming!==!1&&(Je.delete(N.id),We.delete(N.id),N.streaming=!1,f(N));else{let j=_!=null&&_!=="";if(j||G){let re=Ie();G&&(re.stopReason=G),j?He(re,_):(re.streaming=!1,f(re))}}continue}}else if(z==="execution_start")ge=b.kind==="flow"?"flow":"agent",xt=!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:se;if(P!==se){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)}se=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,je=j?[j]:[],Te=[];for(let at of je){if(!at||typeof at!="object")continue;let K=at,qe=typeof K.type=="string"?K.type:void 0,we=typeof K.mediaType=="string"?K.mediaType.toLowerCase():"",Re=null,ke="";if(qe==="media"){let Ye=typeof K.data=="string"?K.data:void 0;if(!Ye)continue;ke=we.length>0?we:"application/octet-stream",Re=`data:${ke};base64,${Ye}`}else if(qe==="image-url"){let Ye=typeof K.url=="string"?K.url:void 0;if(!Ye)continue;ke=we,Re=Ye}else if(qe==="file-url"){let Ye=typeof K.url=="string"?K.url:void 0;if(!Ye)continue;ke=we,Re=Ye}else continue;if(Re)if(qe==="image-url"||ke.startsWith("image/"))Te.push({type:"image",image:Re,...ke.includes("/")?{mimeType:ke}:{}});else if(ke.startsWith("audio/"))Te.push({type:"audio",audio:Re,mimeType:ke});else if(ke.startsWith("video/"))Te.push({type:"video",video:Re,mimeType:ke});else{let Ye=ke||"application/octet-stream";Te.push({type:"file",data:Re,mimeType:Ye,filename:Vx(Ye)})}}if(Te.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:Te,createdAt:new Date().toISOString(),streaming:!1,sequence:at,agentMetadata:{executionId:b.executionId,iteration:typeof b.iteration=="number"?b.iteration:se}};f(we);let Re=h;Re&&(Re.streaming=!1,f(Re)),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?He(I):(I.streaming=!1,f(I)),h=null),M=null,A="",Tt=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=Go(this.config.features?.artifacts,P),je=typeof b.component=="string"?b.component:void 0,Te={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Ns(re,{artifactId:I,title:N,artifactType:P,status:"streaming",..._?{file:_}:{},...je?{component:je}:{}})};ve.set(I,Te),f(Te)}}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,Je.delete(I),We.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"})}}}}}Ke.length=0};;){let{done:R,value:z}=await a.read();if(R)break;l+=s.decode(z,{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()=>{}}},Oa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},li=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{let e=dx();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)}},ci=()=>{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,Qn.parse)(n,Qn.STR|Qn.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?ri(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=ri(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Mm=e=>{let t=null,n=0,r=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?ri(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?ri(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,Qn.parse)(a,Qn.STR|Qn.OBJ),p=r(l);p!==null&&(t=p)}catch{}return n=a.length,{text:t||"",raw:a}},close:()=>{}}},pi=()=>{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 Tm="4.14.0";var Zo=Tm;var px="https://api.runtype.com/v1/dispatch",ui="https://api.runtype.com";function ux(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 xd=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 fx(e){switch(e){case"json":return ci;case"regex-json":return di;case"xml":return pi;default:return li}}var Em=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function mx(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=Em(n);if(!Em(o))return e;if(!r||o===n||o.startsWith(n))return t;let s=Oa(e);return Oa(t)!==null&&s===null?t:e}var er=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??px,this.headers={"Content-Type":"application/json","X-Persona-Version":Zo,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??fx(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 Pr(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=sm(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$/,"")||ui}/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":Zo},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$/,"")||ui}/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":Zo},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(xd).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":Zo},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$/,"")||ui}/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?rm(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(/\/+$/,"")||ui}/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=[...Hr(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(xd).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=[...Hr(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(xd).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=[...Hr(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=P=>{let U=P.reasoning?{...P.reasoning,chunks:[...P.reasoning.chunks]}:void 0,x=P.toolCall?{...P.toolCall,chunks:P.toolCall.chunks?[...P.toolCall.chunks]:void 0}:void 0,H=P.tools?P.tools.map(R=>({...R,chunks:R.chunks?[...R.chunks]:void 0})):void 0;return{...P,reasoning:U,toolCall:x,tools:H}},g=P=>{if(P.role!=="assistant"||P.variant)return!0;let U=Array.isArray(P.contentParts)&&P.contentParts.length>0,x=typeof P.rawContent=="string"&&P.rawContent.trim()!=="";return typeof P.content=="string"&&P.content.trim()!==""||U||x||!!P.stopReason},f=P=>{g(P)&&n({type:"message",message:u(P)})},h=null,A=null,E={current:null},k={current:null},M=null,S="",C=new Map,T=new Map,W=new Map,w=new Map,D=new Map,F={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},O=P=>{if(P==null)return null;try{return String(P)}catch{return null}},q=P=>O(P.stepId??P.step_id??P.step??P.parentId??P.flowStepId??P.flow_step_id),Q=P=>O(P.callId??P.call_id??P.requestId??P.request_id??P.toolCallId??P.tool_call_id??P.stepId??P.step_id),de=o,be=!1,De=()=>{if(h)return h;let P,U="",x=M;return!be&&de?(P=de,be=!0,U=r??""):de&&x?P=`${de}_${x}`:P=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:P,role:"assistant",content:U,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},f(h),h},ie=(P,U)=>{F.lastId=U,P&&F.byStep.set(P,U)},ge=(P,U)=>{let x=P.reasoningId??P.id,H=q(P);if(x){let B=String(x);return ie(H,B),B}if(H){let B=F.byStep.get(H);if(B)return F.lastId=B,B}if(F.lastId&&!U)return F.lastId;if(!U)return null;let R=`reason-${d()}`;return ie(H,R),R},ne=P=>{let U=w.get(P);if(U)return U;let x={id:`reason-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:P,status:"streaming",chunks:[]}};return w.set(P,x),f(x),x},le=(P,U)=>{j.lastId=U,P&&j.byCall.set(P,U)},Z=new Set,me=new Map,Ae=new Set,we=new Map,Se=P=>{if(!P)return!1;let U=P.replace(/_+/g,"_").replace(/^_|_$/g,"");return U==="emit_artifact_markdown"||U==="emit_artifact_component"},mt=(P,U)=>{let x=P.toolId??P.id,H=Q(P);if(x){let B=String(x);return le(H,B),B}if(H){let B=j.byCall.get(H);if(B)return j.lastId=B,B}if(j.lastId&&!U)return j.lastId;if(!U)return null;let R=`tool-${d()}`;return le(H,R),R},We=P=>{let U=D.get(P);if(U)return U;let x={id:`tool-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:P,status:"pending"}};return D.set(P,x),f(x),x},_e=P=>{if(typeof P=="number"&&Number.isFinite(P))return P;if(typeof P=="string"){let U=Number(P);if(!Number.isNaN(U)&&Number.isFinite(U))return U;let x=Date.parse(P);if(!Number.isNaN(x))return x}return Date.now()},Xe=P=>{if(typeof P=="string")return P;if(P==null)return"";try{return JSON.stringify(P)}catch{return String(P)}},$e=new Map,Me=new Map,ke=new Map,Je=(P,U,x)=>{let H=ke.get(P);H||(H=[],ke.set(P,H));let R=0,B=H.length;for(;R<B;){let _=R+B>>>1;H[_].seq<U?R=_+1:B=_}H[R]?.seq===U?H[R]={seq:U,text:x}:H.splice(R,0,{seq:U,text:x});let K="";for(let _=0;_<H.length;_++)K+=H[_].text;return K},Dt=(P,U)=>{let x=Xe(U),H=Me.get(P.id),R=mx(H,x);P.rawContent=R;let B=$e.get(P.id),K=Re=>{let Qe=P.content??"";Re.trim()!==""&&(Qe.trim().length===0||Re.startsWith(Qe)||Re.trimStart().startsWith(Qe.trim()))&&(P.content=Re)},_=()=>{if(B){let Re=B.close?.();Re instanceof Promise&&Re.catch(()=>{})}$e.delete(P.id),Me.delete(P.id),P.streaming=!1,f(P)};if(!B){K(x),_();return}let $=Oa(R);if($!==null&&$.trim()!==""){K($),_();return}let Y=Re=>{let Qe=typeof Re=="string"?Re:Re?.text??null;if(Qe!==null&&Qe.trim()!=="")return Qe;let rt=B.getExtractedText();return rt!==null&&rt.trim()!==""?rt:x},je;try{je=B.processChunk(R)}catch{K(x),_();return}if(je instanceof Promise){je.then(Re=>{K(Y(Re)),_()}).catch(()=>{K(x),_()});return}K(Y(je)),_()},Wt=null,Kt=(P,U,x,H)=>{P.rawContent=U,$e.has(P.id)||$e.set(P.id,this.createStreamParser());let R=$e.get(P.id),B=U.trim().startsWith("{")||U.trim().startsWith("[");if(B&&Me.set(P.id,U),R.__isPlainTextParser===!0){P.content=H!==void 0?U:P.content+x,Me.delete(P.id),$e.delete(P.id),P.rawContent=void 0,f(P);return}let _=R.processChunk(U);if(_ instanceof Promise)_.then($=>{let Y=typeof $=="string"?$:$?.text??null;Y!==null&&Y.trim()!==""?(P.content=Y,f(P)):!B&&!U.trim().startsWith("<")&&(P.content=H!==void 0?U:P.content+x,Me.delete(P.id),$e.delete(P.id),P.rawContent=void 0,f(P))}).catch(()=>{P.content=H!==void 0?U:P.content+x,Me.delete(P.id),$e.delete(P.id),P.rawContent=void 0,f(P)});else{let $=typeof _=="string"?_:_?.text??null;$!==null&&$.trim()!==""?(P.content=$,f(P)):!B&&!U.trim().startsWith("<")&&(P.content=H!==void 0?U:P.content+x,Me.delete(P.id),$e.delete(P.id),P.rawContent=void 0,f(P))}},wt=(P,U)=>{let x=U??P.content;if(x==null||x===""){P.streaming=!1,f(P);return}let R=Me.get(P.id)??Xe(x);P.rawContent=R;let B=$e.get(P.id),K=null,_=!1;if(B&&(K=B.getExtractedText(),K===null&&(K=Oa(R)),K===null)){let $=B.processChunk(R);$ instanceof Promise?(_=!0,$.then(Y=>{let je=typeof Y=="string"?Y:Y?.text??null;je!==null&&(P.content=je,P.streaming=!1,$e.delete(P.id),Me.delete(P.id),f(P))}).catch(()=>{})):K=typeof $=="string"?$:$?.text??null}if(!_){K!==null&&K.trim()!==""?P.content=K:Me.has(P.id)||(P.content=Xe(x));let $=$e.get(P.id);if($){let Y=$.close?.();Y instanceof Promise&&Y.catch(()=>{}),$e.delete(P.id)}Me.delete(P.id),P.streaming=!1,f(P)}},He=(P,U,x)=>{let H=T.get(P);if(H)return H;let R={id:`nested-${U}-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...x?{variant:x}:{},...x==="reasoning"?{reasoning:{id:P,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:U}};return T.set(P,R),f(R),R},ce=[],et,Pe=new Map,ue=0,ae="agent",Le=!1,it=null,pe=null,ve=new Map,ee=this.config.iterationDisplay??"separate";for(et=()=>{for(let P=0;P<ce.length;P++){let U=ce[P].payloadType,x=ce[P].payload;if(!Le&&ae!=="flow"&&typeof x.stepType=="string"&&(ae="flow"),U==="reasoning_start"){let H=typeof x.id=="string"?x.id:null,R=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(H&&R){C.set(H,R),He(H,R,"reasoning");continue}let B=ge(x,!0)??`reason-${d()}`,K=ne(B);K.reasoning=K.reasoning??{id:B,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??_e(x.startedAt??x.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),K.streaming=!0,K.reasoning.status="streaming",f(K)}else if(U==="reasoning_delta"){let H=typeof x.id=="string"?x.id:null;if(H&&C.has(H)&&T.has(H)){let _=T.get(H),$=x.reasoningText??x.text??x.delta??"";$&&x.hidden!==!0&&_.reasoning&&(_.reasoning.chunks.push(String($)),f(_));continue}let R=ge(x,!1)??ge(x,!0)??`reason-${d()}`,B=ne(R);B.reasoning=B.reasoning??{id:R,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??_e(x.startedAt??x.timestamp);let K=x.reasoningText??x.text??x.delta??"";if(K&&x.hidden!==!0){let _=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(_!==void 0){let $=Je(R,_,String(K));B.reasoning.chunks=[$]}else B.reasoning.chunks.push(String(K))}if(B.reasoning.status=x.done?"complete":"streaming",x.done){B.reasoning.completedAt=_e(x.completedAt??x.timestamp);let _=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-_)}B.streaming=B.reasoning.status!=="complete",f(B)}else if(U==="reasoning_complete"){let H=typeof x.id=="string"?x.id:null;if(H&&C.has(H)&&T.has(H)){let $=T.get(H);if($.reasoning){let Y=typeof x.text=="string"?x.text:"";Y&&$.reasoning.chunks.length===0&&$.reasoning.chunks.push(Y),$.reasoning.status="complete",$.streaming=!1,f($)}C.delete(H),T.delete(H);continue}let R=ge(x,!1)??ge(x,!0)??`reason-${d()}`,B=typeof x.text=="string"?x.text:"";!w.get(R)&&(B||x.scope==="loop")&&ne(R);let K=w.get(R);if(K?.reasoning){(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),B&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(B),K.reasoning.status="complete",K.reasoning.completedAt=_e(x.completedAt??x.timestamp);let $=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-$),K.streaming=!1,f(K)}let _=q(x);_&&F.byStep.delete(_)}else if(U==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof x.iteration=="number"&&(ue=x.iteration);let H=(typeof x.toolCallId=="string"?x.toolCallId:void 0)??mt(x,!0)??`tool-${d()}`,R=x.toolName??x.name;if(Se(R)){Z.add(H);continue}le(Q(x),H);let B=We(H),K=B.toolCall??{id:H,status:"pending"};K.name=R??K.name,K.status="running",x.parameters!==void 0?K.args=x.parameters:x.args!==void 0&&(K.args=x.args),K.startedAt=K.startedAt??_e(x.startedAt??x.timestamp),K.completedAt=void 0,K.durationMs=void 0,B.toolCall=K,B.streaming=!0,x.executionId&&(B.agentMetadata={executionId:x.executionId,iteration:x.iteration}),f(B)}else if(U==="tool_output_delta"){let H=mt(x,!1)??mt(x,!0)??`tool-${d()}`;if(Z.has(H))continue;let R=We(H),B=R.toolCall??{id:H,status:"running"};B.startedAt=B.startedAt??_e(x.startedAt??x.timestamp);let K=x.text??x.delta??x.message??"";K&&(B.chunks=B.chunks??[],B.chunks.push(String(K))),B.status="running",R.toolCall=B,R.streaming=!0;let _=x.agentContext;(_||x.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:_?.executionId??x.executionId,iteration:_?.iteration??x.iteration}),f(R)}else if(U==="tool_complete"){let H=mt(x,!1)??mt(x,!0)??`tool-${d()}`;if(Z.has(H)){Z.delete(H);continue}let R=We(H),B=R.toolCall??{id:H,status:"running"};B.status="complete",x.result!==void 0&&(B.result=x.result),typeof x.duration=="number"&&(B.duration=x.duration),B.completedAt=_e(x.completedAt??x.timestamp);let K=x.duration??x.executionTime;if(typeof K=="number")B.durationMs=K;else{let Y=B.startedAt??Date.now();B.durationMs=Math.max(0,(B.completedAt??Date.now())-Y)}R.toolCall=B,R.streaming=!1;let _=x.agentContext;(_||x.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:_?.executionId??x.executionId,iteration:_?.iteration??x.iteration}),f(R);let $=Q(x);$&&j.byCall.delete($)}else if(U==="await"&&x.toolName){let H=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,R=H??x.toolId??`local-${d()}`,B=We(R),K=x.toolName,_=x.origin==="webmcp"&&!yo(K)?`webmcp:${K}`:K,$=yo(_),Y=B.toolCall??{id:R,status:"pending"};Y.name=_,Y.args=x.parameters,Y.status=$?"running":"complete",Y.chunks=Y.chunks??[],Y.startedAt=Y.startedAt??_e(x.startedAt??x.timestamp??x.awaitedAt),$?(Y.completedAt=void 0,Y.duration=void 0,Y.durationMs=void 0):Y.completedAt=Y.completedAt??Y.startedAt,B.toolCall=Y,B.streaming=!1,B.agentMetadata={...B.agentMetadata,executionId:x.executionId??B.agentMetadata?.executionId,awaitingLocalTool:!0,...H?{webMcpToolCallId:H}:{}},f(B)}else if(U==="text_start"){let H=typeof x.id=="string"?x.id:null,R=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(H&&R){C.set(H,R);continue}let B=h;B&&(ae==="flow"?(wt(B),Wt=B):(B.streaming=!1,f(B)),h=null),M=typeof x.id=="string"?x.id:M,S=""}else if(U==="text_delta"){let H=typeof x.id=="string"?x.id:null,R=H?C.get(H):void 0;if(H&&R){let K=typeof x.delta=="string"?x.delta:"",_=(W.get(H)??"")+K;if(W.set(H,_),_.trim()==="")continue;let $=He(H,R);$.agentMetadata={...$.agentMetadata,executionId:x.executionId,parentToolId:R},Kt($,_,K,void 0);continue}if(M=typeof x.id=="string"?x.id:M,ae==="flow"){let K=typeof x.delta=="string"?x.delta:"";if(S+=K,S.trim()==="")continue;let _=De();_.agentMetadata={executionId:x.executionId,iteration:x.iteration},Kt(_,S,K,void 0),A=_;continue}let B=De();B.content+=x.delta??"",B.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:it??void 0,agentName:pe?.agentName},A=B,f(B)}else if(U==="text_complete"){let H=typeof x.id=="string"?x.id:null;if(H&&C.has(H)){let B=T.get(H);B&&wt(B),C.delete(H),W.delete(H),T.delete(H);continue}let R=h;R&&(ae==="flow"?(wt(R),Wt=R):((R.content??"")===""&&typeof x.text=="string"&&(R.content=x.text),R.streaming=!1,f(R)),h=null),M=null,S=""}else if(U==="step_complete"){let H=x.stepType,R=x.executionType;if(H==="tool"||R==="context")continue;if(x.success===!1){let B=x.error,K=typeof B=="string"&&B!==""?B:B!=null&&typeof B=="object"&&Reflect.has(B,"message")?String(B.message??"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let _=h;_&&_.streaming&&(_.streaming=!1,f(_)),n({type:"status",status:"idle"});continue}{let B=Wt;Wt=null;let K=x.stopReason,_=x.result?.response;if(B)K&&(B.stopReason=K),_!=null?Dt(B,_):B.streaming!==!1&&($e.delete(B.id),Me.delete(B.id),B.streaming=!1,f(B));else{let $=_!=null&&_!=="";if($||K){let Y=De();K&&(Y.stopReason=K),$?wt(Y,_):(Y.streaming=!1,f(Y))}}continue}}else if(U==="execution_start")ae=x.kind==="flow"?"flow":"agent",Le=!0,ae==="agent"&&(pe={executionId:x.executionId,agentId:x.agentId??"virtual",agentName:x.agentName??"",status:"running",currentIteration:0,maxTurns:x.maxTurns??1,startedAt:_e(x.startedAt)});else if(U==="turn_start"){let H=typeof x.iteration=="number"?x.iteration:ue;if(H!==ue){if(pe&&(pe.currentIteration=H),ee==="separate"&&H>1){let R=h;R&&(R.streaming=!1,f(R),ve.set(H-1,R),h=null)}ue=H}it=typeof x.id=="string"?x.id:null,A=null}else if(U==="tool_input_delta"){let H=x.toolCallId??j.lastId;if(H){let R=D.get(H);R?.toolCall&&(R.toolCall.chunks=R.toolCall.chunks??[],R.toolCall.chunks.push(x.delta??""),f(R))}}else{if(U==="tool_input_complete")continue;if(U==="turn_complete"){let H=x.stopReason,R=h??A;if(H&&R!==null){let B=x.id;(!B||R.agentMetadata?.turnId===B)&&(R.stopReason=H,f(R))}it===x.id&&(it=null)}else if(U==="media_start"){let H=String(x.id);Pe.set(H,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(U==="media_delta"){let H=Pe.get(String(x.id));H&&typeof x.delta=="string"&&H.parts.push(x.delta)}else if(U==="media_complete"){let H=String(x.id),R=Pe.get(H);Pe.delete(H);let B=(typeof x.mediaType=="string"?x.mediaType:void 0)??R?.mediaType??"application/octet-stream",K=typeof x.data=="string"?x.data:void 0,_=typeof x.url=="string"?x.url:R&&R.parts.length>0?R.parts.join(""):void 0,$=null;if(K)$={type:"media",data:K,mediaType:B};else if(_){let Qe=B.toLowerCase();$={type:Qe==="image"||Qe.startsWith("image/")?"image-url":"file-url",url:_,mediaType:B}}let Y=x.toolCallId??R?.toolCallId,je=$?[$]:[],Re=[];for(let Qe of je){if(!Qe||typeof Qe!="object")continue;let rt=Qe,G=typeof rt.type=="string"?rt.type:void 0,Ue=typeof rt.mediaType=="string"?rt.mediaType.toLowerCase():"",he=null,qe="";if(G==="media"){let Fe=typeof rt.data=="string"?rt.data:void 0;if(!Fe)continue;qe=Ue.length>0?Ue:"application/octet-stream",he=`data:${qe};base64,${Fe}`}else if(G==="image-url"){let Fe=typeof rt.url=="string"?rt.url:void 0;if(!Fe)continue;qe=Ue,he=Fe}else if(G==="file-url"){let Fe=typeof rt.url=="string"?rt.url:void 0;if(!Fe)continue;qe=Ue,he=Fe}else continue;if(he)if(G==="image-url"||qe.startsWith("image/"))Re.push({type:"image",image:he,...qe.includes("/")?{mimeType:qe}:{}});else if(qe.startsWith("audio/"))Re.push({type:"audio",audio:he,mimeType:qe});else if(qe.startsWith("video/"))Re.push({type:"video",video:he,mimeType:qe});else{let Fe=qe||"application/octet-stream";Re.push({type:"file",data:he,mimeType:Fe,filename:ux(Fe)})}}if(Re.length>0){let Qe=d(),rt=Y,Ue={id:`agent-media-${typeof rt=="string"&&rt.length>0?`${rt}-${Qe}`:String(Qe)}`,role:"assistant",content:"",contentParts:Re,createdAt:new Date().toISOString(),streaming:!1,sequence:Qe,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:ue}};f(Ue);let he=h;he&&(he.streaming=!1,f(he)),h=null,E.current=null}}else if(U==="execution_complete"){let H=x.kind??ae;H==="agent"&&pe&&(pe.status=x.success?"complete":"error",pe.completedAt=_e(x.completedAt),pe.stopReason=x.stopReason);let R=h;R&&(H==="flow"&&R.streaming!==!1?wt(R):(R.streaming=!1,f(R)),h=null),M=null,S="",Wt=null,n({type:"status",status:"idle",terminal:!0})}else if(U==="execution_error"){let H=typeof x.error=="string"?x.error:x.error?.message??"Execution error";n({type:"error",error:new Error(H)})}else if(U!=="ping"){if(U==="approval_start"){let H=x.approvalId??`approval-${d()}`,R={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:H,status:"pending",agentId:pe?.agentId??"virtual",executionId:x.executionId??pe?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(R)}else if(U==="step_await"&&x.awaitReason==="approval_required"){let H=x.approvalId??`approval-${d()}`,R={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:H,status:"pending",agentId:pe?.agentId??"virtual",executionId:x.executionId??pe?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(R)}else if(U==="approval_complete"){let H=x.approvalId;if(H){let B={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:H,status:x.decision??"approved",agentId:pe?.agentId??"virtual",executionId:x.executionId??pe?.executionId??"",toolName:x.toolName??"",description:x.description??"",resolvedAt:Date.now()}};f(B)}}else if(U==="artifact_start"||U==="artifact_delta"||U==="artifact_update"||U==="artifact_complete"){if(U==="artifact_start"){let H=x.artifactType,R=String(x.id),B=typeof x.title=="string"?x.title:void 0,K=x.file,_;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(_={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:R,artifactType:H,title:B,component:typeof x.component=="string"?x.component:void 0,..._?{file:_}:{}});let $=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?{...x.props}:void 0;if(we.set(R,{markdown:"",title:B,file:_,...$?{props:$}:{}}),!Ae.has(R)){Ae.add(R);let Y=Bn(this.config.features?.artifacts,{artifactType:H,..._?{file:_}:{}}),je=typeof x.component=="string"?x.component:void 0,Re={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:Ra(Y,{artifactId:R,title:B,artifactType:H,status:"streaming",..._?{file:_}:{},...je?{component:je}:{}})};me.set(R,Re),f(Re)}}else if(U==="artifact_delta"){let H=String(x.id),R=typeof x.delta=="string"?x.delta:String(x.delta??"");n({type:"artifact_delta",id:H,artDelta:R});let B=we.get(H);B&&(B.markdown+=R)}else if(U==="artifact_update"){let H=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};n({type:"artifact_update",id:String(x.id),props:H,component:typeof x.component=="string"?x.component:void 0});let R=we.get(String(x.id));R&&(R.props={...R.props??{},...H})}else if(U==="artifact_complete"){let H=String(x.id);n({type:"artifact_complete",id:H});let R=me.get(H);if(R){R.streaming=!1;try{let B=JSON.parse(R.rawContent??"{}");if(B.props){B.props.status="complete";let K=we.get(H);K?.markdown&&(B.props.markdown=K.markdown),K?.file&&(B.props.file=K.file),B.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(B.props.componentProps=K.props)}R.rawContent=JSON.stringify(B)}catch{}we.delete(H),f(R),me.delete(H)}}}else if(U==="transcript_insert"){let H=x.message;if(!H||typeof H!="object")continue;let R=String(H.id??`msg-${d()}`),B=H.role,_={id:R,role:B==="user"?"user":B==="system"?"system":"assistant",content:typeof H.content=="string"?H.content:"",rawContent:typeof H.rawContent=="string"?H.rawContent:void 0,createdAt:typeof H.createdAt=="string"?H.createdAt:new Date().toISOString(),streaming:H.streaming===!0,...typeof H.variant=="string"?{variant:H.variant}:{},sequence:d()};if(f(_),_.rawContent)try{let Y=JSON.parse(_.rawContent)?.props?.artifactId;typeof Y=="string"&&Ae.add(Y)}catch{}h=null,E.current=null,$e.delete(R),Me.delete(R)}else if(U==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let H=typeof x.error=="string"?x.error:x.error?.message!=null?String(x.error.message):"Execution error";n({type:"error",error:new Error(H)});let R=h;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}else if(U==="step_error"||U==="dispatch_error"||U==="flow_error"){let H=null;if(x.error instanceof Error)H=x.error;else if(U==="dispatch_error"){let R=x.message??x.error;R!=null&&R!==""&&(H=new Error(String(R)))}else{let R=x.error;typeof R=="string"&&R!==""?H=new Error(R):R!=null&&typeof R=="object"&&Reflect.has(R,"message")&&(H=new Error(String(R.message??R)))}if(H){n({type:"error",error:H});let R=h;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}}}}ce.length=0};;){let{done:P,value:U}=await a.read();if(P)break;l+=s.decode(U,{stream:!0});let x=l.split(`
|
|
13
13
|
|
|
14
|
-
`);l=
|
|
15
|
-
`),N="message",G="",_=null;for(let Te of I)Te.startsWith("event:")?N=Te.replace("event:","").trim():Te.startsWith("data:")?G+=Te.replace("data:","").trim():Te.startsWith("id:")&&(_=Te.slice(3).trim());let j=()=>{_!==null&&_!==""&&n({type:"cursor",id:_})};if(!G){j();continue}let re;try{re=JSON.parse(G)}catch(Te){n({type:"error",error:Te instanceof Error?Te:new Error("Failed to parse chat stream payload")});continue}let je=N!=="message"?N:re.type??"message";if(this.onSSEEvent?.(je,re),this.parseSSEEvent){L.current=h;let Te=await this.handleCustomSSEEvent(re,n,L,f,c,E);if(L.current&&L.current!==h&&(h=L.current),Te){j();continue}}Ke.push({payloadType:je,payload:re}),Ee(),j()}}Ee()}};function pm(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Lr(){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 oi="[Image]";function um(e){return typeof e=="string"?[{type:"text",text:e}]:e}function fm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function ri(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function mm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function bo(e){return{type:"text",text:e}}function gm(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function hm(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 ym(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 xm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],jx=["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=[...xm,...jx];function Gx(e){return xm.includes(e)||e.startsWith("image/")}function ai(e){return Gx(e.type)}async function bm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ai(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 vm(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 Kx(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Cm(e,t){let n=Kx(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 si=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 wm=16e3,Xx=24e3,Jx=4096,Qx=1380533830;function Yx(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Qx?new Uint8Array(e,44):new Uint8Array(e)}function Zx(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 Pa=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:wm,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:wm});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new si(Xx);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=`${Zx(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(Jx,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=Yx(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 Qo=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 Pa(e.runtype);case"browser":if(!Qo.isSupported())throw new Error("Browser speech recognition not supported");return new Qo(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 ii(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(Qo.isSupported())return vo({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ra(e){try{return ii(e),!0}catch{return!1}}function Pr(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):Pr(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 Yo=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 id(e){if(!e)return"";let t=eb(e);return Am(t!==null?t:e)}function eb(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 Am(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=x.pop()??"";for(let H of x){let R=H.split(`
|
|
15
|
+
`),B="message",K="",_=null;for(let Re of R)Re.startsWith("event:")?B=Re.replace("event:","").trim():Re.startsWith("data:")?K+=Re.replace("data:","").trim():Re.startsWith("id:")&&(_=Re.slice(3).trim());let $=()=>{_!==null&&_!==""&&n({type:"cursor",id:_})};if(!K){$();continue}let Y;try{Y=JSON.parse(K)}catch(Re){n({type:"error",error:Re instanceof Error?Re:new Error("Failed to parse chat stream payload")});continue}let je=B!=="message"?B:Y.type??"message";if(this.onSSEEvent?.(je,Y),this.parseSSEEvent){E.current=h;let Re=await this.handleCustomSSEEvent(Y,n,E,f,d,k);if(E.current&&E.current!==h&&(h=E.current),Re){$();continue}}ce.push({payloadType:je,payload:Y}),et(),$()}}et()}};function km(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Br(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function So(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var fi="[Image]";function Lm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Pm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function mi(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Rm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Mo(e){return{type:"text",text:e}}function Im(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Wm(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 Hm(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 Bm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],gx=["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"],Yn=[...Bm,...gx];function hx(e){return Bm.includes(e)||e.startsWith("image/")}function gi(e){return hx(e.type)}async function Dm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;gi(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 Fm(e,t=Yn,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 yx(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Om(e,t){let n=yx(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 hi=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 Nm=16e3,bx=24e3,xx=4096,vx=1380533830;function Cx(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===vx?new Uint8Array(e,44):new Uint8Array(e)}function wx(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 Na=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:Nm,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:Nm});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new hi(bx);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=`${wx(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(xx,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=Cx(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 tr=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 To(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Na(e.runtype);case"browser":if(!tr.isSupported())throw new Error("Browser speech recognition not supported");return new tr(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 yi(e){if(e?.type==="custom"&&e.custom)return To({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return To({type:"runtype",runtype:e.runtype});if(tr.isSupported())return To({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function _a(e){try{return yi(e),!0}catch{return!1}}function Dr(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 Eo=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):Dr(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 nr=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 vd(e){if(!e)return"";let t=Ax(e);return _m(t!==null?t:e)}function Ax(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 _m(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 Cd=null,Um=e=>{Cd=e},wd=()=>Cd?Cd():import("./runtype-tts-entry");var Tx=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Ex(e,t){return Tx.some(n=>e[n]!==t[n])}function Ad(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 Ia=e=>({isError:!0,content:[{type:"text",text:e}]}),Em=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,km=e=>uo(e)||e===Tn,Rr=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 Yo(()=>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 Jo(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||dd().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 Ra(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 dd().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(!rb(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 Jo(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"?Lr():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"?Lr():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(`
|
|
19
|
+
_Details: ${n.message}_`:o}var Ua=e=>({isError:!0,content:[{type:"text",text:e}]}),zm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,$m=e=>yo(e)||e===kn,Fr=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 nr(()=>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&&(yo(n.name)||n.name===kn&&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 er(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||wd().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 _a(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=Eo.isSupported()?new Eo({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 wd().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=To(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.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!Ex(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let a=this.client.getSSEEventCallback();this.config=o,this.client=new er(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),a&&this.client.setSSEEventCallback(a)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role: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"?Br():n==="assistant"?So():`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,A={id:p??(r==="user"?Br():r==="assistant"?So():`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(A)}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(`
|
|
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 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=Lr(),a=xo();this.activeAssistantMessageId=null;let s=n?.contentParts&&ri(n.contentParts)?oi:"",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=cd(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=cd(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:td(),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,Ia(M?"Aborted by cancel()":Em(E)),g),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,Ia("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,Ia("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=td():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,Ia("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,Ia(S||p.aborted?"Aborted by cancel()":Em(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=Go(this.config.features?.artifacts,t.artifactType),r=Ns(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(()=>(Tm(),Mm)).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=>cd(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=id(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Pr(t)}toggleReadAloud(t){let n=this.messages.find(a=>a.id===t);if(!n||n.role!=="assistant")return;let o=id(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&&km(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&&km(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 pd=[["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 ud=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var fd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var md=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var gd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var hd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var yd=[["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 xd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var bd=[["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 vd=[["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 wd=[["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 Ad=[["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 Sd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Md=[["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 Td=[["path",{d:"M20 6 9 17l-5-5"}]];var Ed=[["path",{d:"m6 9 6 6 6-6"}]];var kd=[["path",{d:"m15 18-6-6 6-6"}]];var Ld=[["path",{d:"m9 18 6-6-6-6"}]];var Pd=[["path",{d:"m18 15-6-6-6 6"}]];var li=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var di=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var Rd=[["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 Id=[["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 Wd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var ci=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Hd=[["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 Bd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Dd=[["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 Fd=[["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 pi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var ui=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Od=[["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 _d=[["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 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:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];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:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];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"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var zd=[["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 $d=[["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 jd=[["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 Gd=[["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 Kd=[["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 Xd=[["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 fi=[["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 Jd=[["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 Qd=[["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 Yd=[["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 Zd=[["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 ec=[["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 tc=[["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 mi=[["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 nc=[["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 oc=[["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 rc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var ac=[["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 sc=[["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 gi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var ic=[["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 lc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var dc=[["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 cc=[["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 pc=[["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 uc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var fc=[["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 mc=[["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 gc=[["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 hc=[["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 yc=[["path",{d:"M5 12h14"}]];var xc=[["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 bc=[["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 vc=[["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 wc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var Ac=[["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 Sc=[["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 Mc=[["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 Tc=[["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 Ec=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var kc=[["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 Lc=[["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 Pc=[["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 Rc=[["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 Ic=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Wc=[["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 Hc=[["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 Bc=[["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 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:"M12 8v4"}],["path",{d:"M12 16h.01"}]];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"}],["path",{d:"m9 12 2 2 4-4"}]];var hi=[["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 Oc=[["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 _c=[["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 Uc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var yi=[["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 qc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Vc=[["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 zc=[["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 $c=[["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 jc=[["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 Gc=[["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 Kc=[["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 Xc=[["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 Jc=[["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 Qc=[["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 xi=[["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 Yc=[["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 Zc=[["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 ep=[["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 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"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var np=[["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 op=[["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 rp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var ap=[["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 ab={activity:pd,"arrow-down":ud,"arrow-up":hd,"arrow-up-right":gd,bot:Cd,"chevron-down":Ed,"chevron-up":Pd,"chevron-right":Ld,"chevron-left":kd,check:Td,clipboard:Id,"clipboard-copy":Rd,"code-xml":ci,copy:Hd,file:zd,"file-code":Ud,"file-spreadsheet":qd,"file-text":Vd,"image-plus":nc,loader:ic,"loader-circle":gi,mic:gc,paperclip:Cc,"refresh-cw":Lc,search:Ic,send:Wc,"shield-alert":Dc,"shield-check":Fc,"shield-x":hi,square:qc,"thumbs-down":Gc,"thumbs-up":Kc,upload:Zc,"volume-2":tp,x:rp,user:ep,mail:dc,phone:Mc,calendar:Sd,clock:Wd,building:wd,"map-pin":cc,lock:lc,key:ac,"credit-card":Bd,"at-sign":yd,hash:Yd,globe:Qd,link:sc,"circle-check":li,"circle-x":di,"triangle-alert":xi,info:rc,ban:xd,shield:Oc,"arrow-left":fd,"arrow-right":md,"external-link":Nd,ellipsis:ui,"ellipsis-vertical":pi,menu:uc,house:mi,plus:Ec,minus:yc,pencil:Ac,trash:Qc,"trash-2":Jc,save:Rc,download:Fd,share:Bc,funnel:fi,settings:Hc,"rotate-cw":Pc,maximize:pc,minimize:hc,"shopping-cart":_c,"shopping-bag":Nc,package:vc,truck:Yc,tag:jc,gift:Jd,receipt:kc,wallet:op,store:zc,"dollar-sign":Dd,percent:Sc,play:Tc,pause:wc,"volume-x":np,camera:Md,image:oc,film:jd,headphones:Zd,"message-circle":fc,"message-square":mc,bell:bd,heart:ec,star:Vc,eye:_d,"eye-off":Od,bookmark:vd,"calendar-days":Ad,history:tc,timer:Xc,folder:Xd,"folder-open":Kd,files:$d,sparkles:yi,zap:ap,sun:$c,moon:bc,flag:Gd,monitor:xc,smartphone:Uc},te=(e,t=24,n="currentColor",o=2)=>{let r=ab[e];return r?sb(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 sb(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 bi={allowedTypes:Kn,maxFileSize:10*1024*1024,maxFiles:4};function ib(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function lb(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 Zo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??bi.allowedTypes,maxFileSize:t.maxFileSize??bi.maxFileSize,maxFiles:t.maxFiles??bi.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:bi.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=vm(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 bm(n),a=ai(n)?URL.createObjectURL(n):null,s={id:ib(),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=ai(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=lb(t.file.type),p=te(l,20,"var(--persona-muted, #6b7280)",1.5);p&&s.appendChild(p);let d=x("span");d.textContent=Cm(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 Lm=/\s/;function db(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=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=dp().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=()=>{Fm().then(A=>{let w=A.mountInlineComposer({textarea:e.textarea,renderToken:H=>Wa(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=Hm({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(!Rm(A))return;let w=d,T=w.selectionStart??0;Pm(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:()=>{dp().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 Nm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ha(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];Nm(a)&&Nm(r)?n[o]=Ha(a,r):n[o]=r}return n}var ln="min(440px, calc(100vw - 24px))",Ci="440px",xb={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)"},it={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:xb,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 _m(e,t){if(!(!e&&!t))return e?t?Ha(e,t):e:t}function Ir(e){return e?{...it,...e,theme:_m(it.theme,e.theme),darkTheme:_m(it.darkTheme,e.darkTheme),launcher:{...it.launcher,...e.launcher,dock:{...it.launcher?.dock,...e.launcher?.dock},clearChat:{...it.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...it.copy,...e.copy},sendButton:{...it.sendButton,...e.sendButton},statusIndicator:{...it.statusIndicator,...e.statusIndicator},voiceRecognition:{...it.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=it.features?.artifacts,n=e.features?.artifacts,o=it.features?.scrollToBottom,r=e.features?.scrollToBottom,a=it.features?.scrollBehavior,s=e.features?.scrollBehavior,l=it.features?.streamAnimation,p=e.features?.streamAnimation,d=it.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{...it.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??it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...it.layout,...e.layout,header:{...it.layout?.header,...e.layout?.header},messages:{...it.layout?.messages,...e.layout?.messages,avatar:{...it.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...it.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...it.layout?.slots,...e.layout?.slots}},markdown:{...it.markdown,...e.markdown,options:{...it.markdown?.options,...e.markdown?.options}},messageActions:{...it.messageActions,...e.messageActions}}:it}var wi="16px",Ai="transparent",cp={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"}},pp={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"}},up={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:Ci,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:wi,canvasBackground:Ai},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 Si(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 fp(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 Um(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]=Um(a,r):n[o]=r}return n}function bb(e,t){return t?Um(e,t):e}function Ba(e,t={}){let n={palette:cp,semantic:pp,components:up},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:bb(n.components,e?.components)};if(t.validate!==!1){let r=fp(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 Mi(e){let t=Si(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"]??wi,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ai,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"]=Xt(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=Xt(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"]=Xt(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"]=Xt(e,C.chromeBackground)??C.chromeBackground),C.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Xt(e,C.chromeBorder)??C.chromeBorder),C.titleColor&&(n["--persona-artifact-inline-title-color"]=Xt(e,C.titleColor)??C.titleColor),C.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Xt(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"]=Xt(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 qm={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 vb={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"}}},Vm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Da=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Cb=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Da()},Ti=e=>Cb(e),wb=e=>Ba(e),Ab=e=>Ba({...e,palette:{...e?.palette,colors:{...vb.colors,...e?.palette?.colors}}},{validate:!1}),wo=e=>{let t=Ti(e),n=Vm(e?.theme),o=Vm(e?.darkTheme);return t==="dark"?Ab(Ha(n??{},o??{})):wb(n)},Sb=e=>Mi(e),er=(e,t)=>{let n=wo(t),o=Sb(n);for(let[r,a]of Object.entries(o))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",Ti(t))},Wr=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Da())});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(Da());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 zm(e){let t=Wn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Ei(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 c=[];a&&c.push(Mo(a)),c.push(...r.contentParts),c.push(...t.contentParts),t.contentParts=c}else if(p){let c=[];s&&c.push(Mo(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=Br(),a=So();this.activeAssistantMessageId=null;let s=n?.contentParts&&mi(n.contentParts)?fi:"",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=Ad(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=So();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=Ad(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],A=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:A||"*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!==kn?!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===kn)return{dedupeKey:u,resumeKey:f,output:md(),toolMessage:p,startedAt:g,completedAt:Date.now()};let h=new AbortController;this.webMcpResolveControllers.add(h),r.push(h);let A=this.client.executeWebMcpToolCall(c,p.toolCall?.args,h.signal),E;if(!A)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await A}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,Ua(M?"Aborted by cancel()":zm(k)),g),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,Ua("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===kn?{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,Ua("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(A){this.callbacks.onError?.(A instanceof Error?A:new Error(String(A)))}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===kn,d=t.toolCall?.args,u=c?null:this.client.executeWebMcpToolCall(o,d,p),g="execute",f=s;try{let h;if(c?h=md():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,Ua("Aborted by cancel()"),s);return}let A=t.agentMetadata?.webMcpToolCallId??o;g="resume",await this.resumeWithToolOutput(n,A,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,h,s,f,c?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(h){let A=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));(g==="execute"||A||p.aborted)&&this.markWebMcpToolComplete(t,Ua(A||p.aborted?"Aborted by cancel()":zm(h)),s),A||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}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};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=Bn(this.config.features?.artifacts,t),r=Ra(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),a=this.messages.find(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})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(s=>s.id===`artifact-ref-${n.id}`);if(!o)continue;let r=Bn(this.config.features?.artifacts,n),a=Ra(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==a&&(o.rawContent=a,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let 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(()=>(Vm(),qm)).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=>Ad(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=So(),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=vd(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Dr(t)}toggleReadAloud(t){let n=this.messages.find(a=>a.id===t);if(!n||n.role!=="assistant")return;let o=vd(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&&$m(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&&$m(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 Sd=[["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 Md=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Td=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Ed=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var kd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Ld=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Pd=[["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 Rd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var Id=[["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 Wd=[["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 Hd=[["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 Dd=[["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 Fd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Od=[["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 Nd=[["path",{d:"M20 6 9 17l-5-5"}]];var _d=[["path",{d:"m6 9 6 6 6-6"}]];var Ud=[["path",{d:"m15 18-6-6 6-6"}]];var qd=[["path",{d:"m9 18 6-6-6-6"}]];var Vd=[["path",{d:"m18 15-6-6-6 6"}]];var bi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var xi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var zd=[["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 $d=[["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 jd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var vi=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Gd=[["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 Kd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Xd=[["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 Jd=[["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 Ci=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var wi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Qd=[["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 Yd=[["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 Zd=[["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 ec=[["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 tc=[["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 nc=[["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 oc=[["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 rc=[["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 ac=[["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 sc=[["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 ic=[["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 lc=[["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 Ai=[["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 dc=[["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 cc=[["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 pc=[["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 uc=[["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 fc=[["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 mc=[["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 Si=[["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 gc=[["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 hc=[["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 yc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var bc=[["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 xc=[["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 Mi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var vc=[["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 Cc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var wc=[["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 Ac=[["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 Sc=[["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 Mc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Tc=[["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 Ec=[["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 kc=[["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 Lc=[["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 Pc=[["path",{d:"M5 12h14"}]];var Rc=[["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 Ic=[["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 Wc=[["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 Hc=[["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 Dc=[["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 Fc=[["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 Oc=[["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 Nc=[["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 _c=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Uc=[["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 qc=[["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 Vc=[["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 zc=[["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 $c=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var jc=[["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 Gc=[["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 Kc=[["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 Xc=[["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 Jc=[["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 Ti=[["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 Qc=[["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 Yc=[["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 Zc=[["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 ep=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Ei=[["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 tp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var np=[["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 op=[["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 rp=[["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 ap=[["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 sp=[["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 ip=[["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 lp=[["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 dp=[["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 cp=[["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 ki=[["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 pp=[["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 up=[["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 fp=[["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 mp=[["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 gp=[["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 hp=[["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 yp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var bp=[["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:Sd,"arrow-down":Md,"arrow-up":Ld,"arrow-up-right":kd,bot:Hd,"chevron-down":_d,"chevron-up":Vd,"chevron-right":qd,"chevron-left":Ud,check:Nd,clipboard:$d,"clipboard-copy":zd,"code-xml":vi,copy:Gd,file:oc,"file-code":ec,"file-spreadsheet":tc,"file-text":nc,"image-plus":gc,loader:vc,"loader-circle":Mi,mic:kc,paperclip:Hc,"refresh-cw":qc,search:$c,send:jc,"shield-alert":Xc,"shield-check":Jc,"shield-x":Ti,square:tp,"thumbs-down":sp,"thumbs-up":ip,upload:up,"volume-2":mp,x:yp,user:fp,mail:wc,phone:Oc,calendar:Fd,clock:jd,building:Bd,"map-pin":Ac,lock:Cc,key:bc,"credit-card":Kd,"at-sign":Pd,hash:pc,globe:cc,link:xc,"circle-check":bi,"circle-x":xi,"triangle-alert":ki,info:yc,ban:Rd,shield:Qc,"arrow-left":Td,"arrow-right":Ed,"external-link":Yd,ellipsis:wi,"ellipsis-vertical":Ci,menu:Mc,house:Si,plus:_c,minus:Pc,pencil:Dc,trash:cp,"trash-2":dp,save:zc,download:Jd,share:Kc,funnel:Ai,settings:Gc,"rotate-cw":Vc,maximize:Sc,minimize:Lc,"shopping-cart":Zc,"shopping-bag":Yc,package:Wc,truck:pp,tag:ap,gift:dc,receipt:Uc,wallet:hp,store:op,"dollar-sign":Xd,percent:Fc,play:Nc,pause:Bc,"volume-x":gp,camera:Od,image:hc,film:ac,headphones:uc,"message-circle":Tc,"message-square":Ec,bell:Id,heart:fc,star:np,eye:Zd,"eye-off":Qd,bookmark:Wd,"calendar-days":Dd,history:mc,timer:lp,folder:lc,"folder-open":ic,files:rc,sparkles:Ei,zap:bp,sun:rp,moon:Ic,flag:sc,monitor:Rc,smartphone:ep},oe=(e,t=24,n="currentColor",o=2)=>{let r=kx[e];return r?Lx(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 Lx(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 Li={allowedTypes:Yn,maxFileSize:10*1024*1024,maxFiles:4};function Px(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Rx(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 or=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Li.allowedTypes,maxFileSize:t.maxFileSize??Li.maxFileSize,maxFiles:t.maxFiles??Li.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:Li.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=Fm(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 Dm(n),a=gi(n)?URL.createObjectURL(n):null,s={id:Px(),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=gi(t.file),o=b("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=b("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=b("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=Rx(t.file.type),p=oe(l,20,"var(--persona-muted, #6b7280)",1.5);p&&s.appendChild(p);let c=b("span");c.textContent=Om(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=b("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=oe("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 jm=/\s/;function Ix(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===""||jm.test(o)}function Wx(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 Ix(e,a,o)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(s===`
|
|
25
|
+
`||s==="\uFFFC"||!r&&jm.test(s))return null;a--}return null}function Gm(e,t,n){for(let o of n){let r=Wx(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Km(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Xm(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 It={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Gt=1e5,Pi=Gt+1;var Hx=8,Bx=8,xp=10,vp=new WeakMap,Jm=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Dx=e=>{let t=e.getRootNode?.();return Jm(t)?t:e.ownerDocument.body},Cp=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Ut(e){vp.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:a=Hx,viewportPadding:s=Bx}=e,l=()=>t.ownerDocument,p=()=>l().defaultView??window,c=null,d=null,u=null,g=!1,f=!1,h=!1,A=()=>(typeof o=="function"?o():o).trim(),E=()=>{u?.(),u=null,c?.remove(),c=null,d=null},k=()=>{if(!c)return;let j=l(),O=p(),q=t.getBoundingClientRect(),Q=c.getBoundingClientRect(),de=j.documentElement.clientWidth||O.innerWidth,be=j.documentElement.clientHeight||O.innerHeight,De=de-s-Q.width,ie=q.left+q.width/2-Q.width/2,ge=Cp(ie,s,De),ne=q.top-s,le=be-s-q.bottom,Z=Q.height+a,me=ne>=Z||ne>=le?"top":"bottom",Ae=me==="top"?q.top-a-Q.height:q.bottom+a,we=be-s-Q.height,Se=Cp(Ae,s,we),mt=q.left+q.width/2,We=Math.max(xp,Q.width-xp),_e=Cp(mt-ge,xp,We);c.dataset.placement=me,c.style.left=`${ge}px`,c.style.top=`${Se}px`,c.style.setProperty("--persona-tooltip-arrow-x",`${_e}px`)},M=()=>{if(h||!r||c||!t.isConnected)return;let j=A(),O=Dx(t);if(!j||!O)return;let q=l(),Q=p();c=q.createElement("div"),c.className="persona-control-tooltip",c.setAttribute("role","tooltip"),c.dataset.state="measuring",c.style.zIndex=String(Pi),d=q.createElement("span"),d.className="persona-control-tooltip__label",d.textContent=j,c.appendChild(d);let de=q.createElement("span");de.className="persona-control-tooltip__arrow",c.appendChild(de),O.appendChild(c),k(),c.dataset.state="open";let be=()=>{if(!t.isConnected){E();return}d&&(d.textContent=A()),k()};Q.addEventListener("scroll",be,!0),Q.addEventListener("resize",be);let De=t.getRootNode(),ie=Jm(De)?De:q.documentElement,ge=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||E()});ge?.observe(ie,{childList:!0,subtree:!0}),u=()=>{Q.removeEventListener("scroll",be,!0),Q.removeEventListener("resize",be),ge?.disconnect()}},S=()=>{g||f?M():E()},C=()=>{let j=p();(!j.matchMedia||!j.matchMedia("(hover: none)").matches)&&(g=!0,S())},T=()=>{g=!1,S()},W=()=>{f=!0,S()},w=()=>{f=!1,S()},D=j=>{j.key==="Escape"&&(g=!1,f=!1,E())};n.addEventListener("mouseenter",C),n.addEventListener("mouseleave",T),t.addEventListener("focus",W),t.addEventListener("blur",w),t.addEventListener("keydown",D);let F={get isOpen(){return c!==null},show:M,hide:E,reposition:k,destroy:()=>{h||(h=!0,E(),n.removeEventListener("mouseenter",C),n.removeEventListener("mouseleave",T),t.removeEventListener("focus",W),t.removeEventListener("blur",w),t.removeEventListener("keydown",D),vp.delete(t))}};return vp.set(t,F),F}function Qm(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=b("div","persona-send-button-wrapper"),c=Be("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"}}),d=oe(s,a,"currentColor",1.5);return d?c.appendChild(d):c.textContent="+",c.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(c),Ut({anchor:c,trigger:p,text:()=>c.getAttribute("aria-label")??l}),{button:c,wrapper:p}}var{setLoader:Fx,load:Ox}=Er({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),Ym=Fx,wp=Ox;var{setLoader:Nx,load:_x}=Er({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),Zm=Nx,eg=_x;function qa(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Be("span",{className:Kn("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=oe(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=b("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Be("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function tg(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Xm(t).filter(S=>S.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(S=>S.sources.some(C=>typeof C.matchCommand=="function")),r=S=>o.some(C=>C.trigger?C.position==="line-start"?S.split(`
|
|
26
|
+
`).some(W=>W.startsWith(C.trigger)):(C.position==="anywhere"?S:S.split(`
|
|
27
|
+
`)[0]).startsWith(C.trigger):!1),a=(S,C)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${S}`,{detail:C}))}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 S=wp().then(C=>(l=C.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(C=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",C),p===S&&(p=null),null));return p=S,S},A=()=>{eg().then(S=>{let C=S.mountInlineComposer({textarea:e.textarea,renderToken:W=>qa(W,{render:t.renderMentionToken}),onMentionRemoved:W=>l?.untrackMention(W)});d=C.input,u=C.destroy;let T=c;T.replaceWith(C.element),c=C.element,f={next:C.element,prev:T},g?.(C.element,T),l?l.rebindComposer(C.input):p&&p.then(W=>W?.rebindComposer(C.input))}).catch(S=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",S)})};t.display==="inline"&&A();let E=[],k=new Map;for(let S of n){if(!S.showButton)continue;let C=Qm({config:{...t,buttonIconName:S.buttonIconName,buttonTooltipText:S.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{h().then(T=>T?.openMenu(S.trigger))}});E.push(C),k.set(S.trigger,C.button)}let M=(S,C,T)=>{let W=k.get(C);W&&(W.setAttribute("aria-expanded",S?"true":"false"),S?W.setAttribute("aria-controls",T):W.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(S=>S.wrapper),contextRow:s,handleInput:S=>{if(l){l.handleInput();return}if(!Km(S))return;let C=c,T=C.selectionStart??0;Gm(C.value,T,n)&&h().then(W=>W?.handleInput())},handleKeydown:S=>{if(l?.isMenuOpen())return l.handleKeydown(S);if(S.key==="Backspace"&&l?.hasMentions()&&!f){let C=c,T=C.selectionStart===0&&C.selectionEnd===0;if((C.value.length===0||T)&&l.removeLastChip())return S.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async S=>r(S)?(l??await h())?.dispatchInlineCommand(S)??null:null,clear:()=>l?.clear(),prefetch:()=>{wp().catch(()=>{})},onComposerSwap:S=>{g=S,f&&S(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let S of E)S.wrapper.remove();s.remove()}}}var ng=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Va(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];ng(a)&&ng(r)?n[o]=Va(a,r):n[o]=r}return n}var pn="min(440px, calc(100vw - 24px))",Ri="440px",Ux={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:pn,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)"},st={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Ux,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 og(e,t){if(!(!e&&!t))return e?t?Va(e,t):e:t}function Or(e){return e?{...st,...e,theme:og(st.theme,e.theme),darkTheme:og(st.darkTheme,e.darkTheme),launcher:{...st.launcher,...e.launcher,dock:{...st.launcher?.dock,...e.launcher?.dock},clearChat:{...st.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...st.copy,...e.copy},sendButton:{...st.sendButton,...e.sendButton},statusIndicator:{...st.statusIndicator,...e.statusIndicator},voiceRecognition:{...st.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=st.features?.artifacts,n=e.features?.artifacts,o=st.features?.scrollToBottom,r=e.features?.scrollToBottom,a=st.features?.scrollBehavior,s=e.features?.scrollBehavior,l=st.features?.streamAnimation,p=e.features?.streamAnimation,c=st.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},A=c===void 0&&d===void 0?void 0:{...c,...d,styles:{...c?.styles,...d?.styles}};return{...st.features,...e.features,...g!==void 0?{scrollToBottom:g}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...h!==void 0?{streamAnimation:h}:{},...A!==void 0?{askUserQuestion:A}:{}}})(),suggestionChips:e.suggestionChips??st.suggestionChips,suggestionChipsConfig:{...st.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...st.layout,...e.layout,header:{...st.layout?.header,...e.layout?.header},messages:{...st.layout?.messages,...e.layout?.messages,avatar:{...st.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...st.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...st.layout?.slots,...e.layout?.slots}},markdown:{...st.markdown,...e.markdown,options:{...st.markdown?.options,...e.markdown?.options}},messageActions:{...st.messageActions,...e.messageActions}}:st}var Ii="16px",Wi="transparent",Ap={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"}},Sp={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"}},Mp={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"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:pn,maxWidth:Ri,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ii,canvasBackground:Wi},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:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},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 Qt(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."))?Qt(e,o):o}function Hi(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=Qt(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 Tp(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 rg(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]=rg(a,r):n[o]=r}return n}function qx(e,t){return t?rg(e,t):e}function za(e,t={}){let n={palette:Ap,semantic:Sp,components:Mp},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:qx(n.components,e?.components)};if(t.validate!==!1){let r=Tp(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=Hi(e),n={};for(let[w,D]of Object.entries(t)){let F=w.replace(/\./g,"-");n[`--persona-${F}`]=D.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"]??Ii,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Wi,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 w=f.toolbar;w.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Qt(e,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(f?.tab){let w=f.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(f?.pane){let w=f.pane;if(w.toolbarBackground){let D=Qt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=D}}if(f?.card){let w=f.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(f?.inline){let w=f.inline;w.background&&(n["--persona-artifact-inline-bg"]=Qt(e,w.background)??w.background),w.border&&(n["--persona-artifact-inline-border"]=w.border),w.borderRadius&&(n["--persona-artifact-inline-radius"]=w.borderRadius),w.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Qt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Qt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Qt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Qt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.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"]=Qt(e,h.background)??h.background));let A=n["--persona-surface"],E=n["--persona-container"],k=n["--persona-palette-colors-gray-100"]??"#f3f4f6",M=n["--persona-palette-colors-gray-200"]??"#e5e7eb",S=n["--persona-palette-colors-gray-300"]??"#d1d5db",C=!E||E===A,T=C?k:E,W=C?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"]??W,C&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??S),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 ag={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 Vx={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"}}},sg=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",zx=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":$a()},Di=e=>zx(e),$x=e=>za(e),jx=e=>za({...e,palette:{...e?.palette,colors:{...Vx.colors,...e?.palette?.colors}}},{validate:!1}),ko=e=>{let t=Di(e),n=sg(e?.theme),o=sg(e?.darkTheme);return t==="dark"?jx(Va(n??{},o??{})):$x(n)},Gx=e=>Bi(e),rr=(e,t)=>{let n=ko(t),o=Gx(n);for(let[r,a]of Object.entries(o))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",Di(t))},Nr=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 Dn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function ig(e){let t=Dn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Fi(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 ja(e){let t=ig(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 Lo(e){switch(ja(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=ig(e.path);return t?t.toUpperCase():"File"}}}function lg(e){let t=e.markdown??"";return e.file?{filename:Dn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Fi(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var Ep="http://www.w3.org/2000/svg";function dg(e){let t=document.createElementNS(Ep,"svg");t.setAttribute("class",Kn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(Ep,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Ep,"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 Po=(e,t,n)=>{let o=n;for(let r of t){let a=b("span","persona-tool-char");a.style.setProperty("--char-index",String(o)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),o++}return o};function cg(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)),Po(e,t,0)}var kp="persona-artifact-status-label",pg="persona-artifact-status-detail",ug="data-artifact-status-label",Lp=new Map,fg=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function _r(e){e&&Lp.delete(e)}function Kx(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Lo(t):e.artifactType==="component"?"Component":"Document"}function Ur(e,t,n){let o=Kx(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=Lp.get(s);e.status!=="complete"&&l===void 0&&(l=fg(),Lp.set(s,l));let p=l===void 0?0:Math.max(0,fg()-l),c=e.artifactType==="component",d=!c&&typeof e.markdown=="string"?e.markdown:"",u=c?0:d.length,g=c||d===""?0:d.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:()=>c?"":d,surface:n};try{let A=a(h);return typeof A=="string"?{label:A}:A&&typeof A=="object"&&typeof A.label=="string"?{label:A.label,detail:typeof A.detail=="string"?A.detail:void 0}:{label:r}}catch{return{label:r}}}function Xx(e){e.className=kp,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 ar(e,t,n){let o=e.querySelector(`:scope > .${kp}`);o||(o=b("span",kp),e.appendChild(o)),o.getAttribute(ug)!==t.label&&(Xx(o),cg(o,t.label,n),o.setAttribute(ug,t.label));let r=e.querySelector(`:scope > .${pg}`),a=t.detail;a?(r||(r=b("span",pg),e.appendChild(r)),r.textContent!==a&&(r.textContent=a)):r&&r.remove()}var Jx={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"},Qx=15e4,Oi={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 Yx(e,t){let n=(e||"").trim().toLowerCase();if(n&&Oi[n])return Oi[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(Oi[r])return Oi[r]}}return null}function Ni(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 c=l.map?l.map(p[0]):l.type;n.push({type:c,value:p[0]}),o+=p[0].length,r=o,s=!0;break}}s||(o+=1)}return a(e.length),n}var Zx=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"]),ev=[{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=>Zx.has(e)?"keyword":"plain"}];function mg(e){return Ni(e,ev)}var tv=[{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 nv(e){let t=Ni(e,tv);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 ov=[{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 gg(e){let t=Ni(e,ov),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 rv=[{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 av(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 d of Ni(p,rv))t.push(d);r=l;let c=/^<\s*(script|style)\b/i.exec(p);if(c&&!/\/>\s*$/.test(p)){let d=c[1].toLowerCase(),g=new RegExp("</\\s*"+d+"\\s*>","i").exec(e.slice(r)),f=g?r+g.index:o,h=e.slice(r,f),A=d==="script"?mg(h):gg(h);for(let E of A)t.push(E);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 sv(e,t){switch(t){case"html":return av(e);case"css":return gg(e);case"js":return mg(e);case"json":return nv(e)}}function iv(e){let t=lm(),n=b("span","persona-code-line"),o=(r,a)=>{if(!a)return;let s=Jx[r];if(s){let l=b("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=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 Zm(e,t,n){let o=e.length<=kb?Lb(t,n):null,r=o?Fb(e,o):[{type:"plain",value:e}];return Ob(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(vi)):(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 Mt(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 Dr(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=Mt({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 Pi(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 Ri="persona-artifact-custom-action-btn";function Fr(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 "+Ri+(n?" persona-artifact-doc-copy-btn":"");o=x("button",r)}else{let r="persona-icon-btn "+Ri+(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:Ri+(n?" persona-artifact-doc-copy-btn":"")}):o=Mt({icon:e.icon,label:e.label,className:Ri+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Oa(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 eg(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=Br(S,h,"card");tr(f,L,h)}else a&&Hr(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=Fr(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 Ii=(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:()=>eg(e,t)});if(l)return l}return eg(e,t)};var To=new WeakMap;function yp(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 ag(e){return To.has(e)}function Nb(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 tg(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 _b(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 ng=180,Ub=240,qb=.8,Vb=300,zb=500,$b="cubic-bezier(0.2, 0, 0, 1)",og=240,jb=.35;function Gb(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:ng,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(zb,Math.max(Vb,Ub+d*qb))),u=Math.round(c*jb),g=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=g?g.animate([{opacity:0},{opacity:1}],{duration:og,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+og)+120)},ng)}function Kb(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 Na="--persona-artifact-inline-body-height";function Xb(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 rg(e,t){let n=Nb(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:a,showExpand:s,showViewToggle:l}=Kb(o),p=o?.inlineActions??[],d=Xb(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=>Ii(_b(Z),t),S=Z=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Na),f.replaceChildren(h(Z)),To.set(f,de=>{f.replaceChildren(h(de))})};if(c&&n.status==="complete")return S(n),f;let L=Wi(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(Na,`${Y}px`):f.style.removeProperty(Na);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(Na,`${d.completeHeight}px`):f.style.removeProperty(Na),ig(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 ${tg(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"),ie=x("span","persona-flex persona-items-center persona-gap-1"),le=()=>u??d.viewMode,Ce=l?Dr({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,Ie=a?Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Ie&&n.id&&Ie.setAttribute("data-copy-artifact",n.id);let ae=s?Mt({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(ie),Ce&&U.appendChild(Ce.element),Ie&&U.appendChild(Ie),ae&&U.appendChild(ae),H.append(C,U),f.append(H,E);let me=Z=>{let{title:de,typeLabel:Y}=tg(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=Br(Z,o,"inline-chrome");tr(D,Ae,o)}else Hr(Z.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=Y;if(Ie&&Ie.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=Fa(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(ie.replaceChildren(),!ve&&p.length>0){let Ae=Oa(Z);if(Ae)for(let xe of p)try{if(xe.visible===void 0||xe.visible(Ae)){let Be=Fr(xe,{documentChrome:!0});Be.setAttribute("data-artifact-custom-action",xe.id),Be.classList.add("persona-flex-shrink-0"),ie.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),Gb(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 sg=(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:()=>rg(e,t)});if(l)return l}return rg(e,t)};var xp=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 xp;En.register("PersonaArtifactCard",Ii,{bubbleChrome:!1});En.register("PersonaArtifactInline",sg,{bubbleChrome:!1});function _a(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Ei(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var bp=!1;function Jb(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function ig(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"||bp||a){o();return}bp=!0;let s=Jb(n);e.style.setProperty("view-transition-name",s);let l=()=>{bp=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Qb="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Yb="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Zb(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 ev(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 tv=220;function nv(){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 ov(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 rv(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(jm());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 av(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=rv(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,tv))},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 Wi(e,t){let{config:n}=t,o=t.registry??En,r=t.bodyLayout,a=n.markdown?jo(n.markdown):null,s=Ar(n.sanitize),l=e,p=!1,d=ae=>{let me=Vn()!==null;a&&!me&&!p&&(p=!0,wr(()=>Ie(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)}))},ie=(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",Qb+" persona-code-pre"),Oe=x("code","persona-code");if(Be.appendChild(Oe),Y){let ze=x("div","persona-artifact-source-window");if(ze.appendChild(Be),c.appendChild(ze),!(r?.overflow==="clip")&&typeof ze.addEventListener=="function"){let rt=()=>ze.scrollHeight-ze.clientHeight>1;ze.addEventListener("scroll",()=>{q(ze)&&(M=!1),D(ze)},{passive:!0}),ze.addEventListener("wheel",Je=>{rt()&&Je.deltaY<0&&(M=!0)},{passive:!0}),ze.addEventListener("touchmove",()=>{rt()&&(M=!0)},{passive:!0})}S=ze}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(Zm(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",Yb);me.innerHTML=d(ae),c.appendChild(me)},Ce=ae=>{let me=ae.id,Z=n.features?.artifacts,de=Br(ae,Z,"status-body");if(w&&T===me&&w.parentElement===c){let Ae=w.querySelector(".persona-artifact-status-view-text");Ae&&tr(Ae,de,Z);return}h(),A(),c.replaceChildren();let Y=x("div","persona-artifact-status-view"),ve=x("div","persona-artifact-status-view-text");tr(ve,de,Z),Y.appendChild(ve),c.appendChild(Y),w=Y,T=me},Ie=ae=>{l=ae;let me=t.resolveViewMode?.(ae)??r?.viewMode??"rendered",Z=ae.artifactType==="markdown"?ae.file:void 0,de=ae.status!=="complete";de||Hr(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=Ei(ae.markdown??""),Be=Fa(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,Je=rt?.iframeSandbox??"allow-scripts";!rt?.dangerouslyAllowSameOrigin&&Je.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."),Je=Je.split(/\s+/).filter(Tt=>Tt&&Tt!=="allow-same-origin").join(" "));let We=ev(rt?.loading),Me=x("div","persona-artifact-frame"),Qe=x("iframe","persona-artifact-iframe");Qe.setAttribute("sandbox",Je),Qe.setAttribute("data-artifact-id",ae.id);let cn=null;We.enabled&&We.injectReadySignal?(cn=nv(),Qe.srcdoc=xe+ov(cn)):Qe.srcdoc=xe,Me.appendChild(Qe),c.appendChild(Me),We.enabled&&(f=av(Me,Qe,cn,We,ae.id,n)),u=Me,g=Ne;return}if(h(),!de&&Be==="markdown"&&me==="rendered"){le(xe);return}ie(xe,{language:Z.language,path:Z.path},ae,ve);return}if(ae.artifactType==="markdown"){if(me==="source"){h(),ie(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(Zb(ae))};return Ie(e),{el:c,update(ae){Ie(ae)}}}var lg=(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,ie=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)&&(ie++,U=U.nextSibling,ie>=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 Hi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;lg.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 dg=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var vp={index:-1,draft:""};function cg(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 pg(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 ug(){return new Map}function fg(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function mg(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function gg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function hg(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function Bi(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 Di(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 Fi(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 yg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function xg(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 bg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Ua={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},sv=["pre","code","a","script","style"],Oi=e=>({type:e?.type??Ua.type,placeholder:e?.placeholder??Ua.placeholder,speed:e?.speed??Ua.speed,duration:e?.duration??Ua.duration,buffer:e?.buffer??Ua.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"}],qa=new Map;for(let e of Cg)qa.set(e.name,e);var nr=e=>{qa.set(e.name,e)},Ap=e=>{Cg.some(t=>t.name===e)||qa.delete(e)},Sp=()=>Array.from(qa.keys()),Or=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:qa.get(e)??null,Ni=(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},iv=(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},lv=(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},Cp=/\s/,dv=(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},cv=(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(Cp.test(a[l])){let p=l;for(;p<a.length&&Cp.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&&!Cp.test(a[d]);)p.appendChild(iv(o,a[d],t,n.value)),n.value+=1,d+=1;s.appendChild(p),l=d}r.replaceChild(s,e)},pv=(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(lv(o,p,t,n.value)),n.value+=1));r.replaceChild(s,e)},Va=(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??sv).map(u=>u.toLowerCase())),s=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=s.nextNode();for(;p;)dv(p,a)||l.push(p),p=s.nextNode();let d={value:o?.startIndex??0},c=t==="char"?cv:pv;for(let u of l)c(u,n,d);return r.innerHTML},_i=(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},za=(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},vg=new WeakMap,uv=(e,t)=>{if(!e.styles)return;let n=vg.get(t);if(n||(n=new Set,vg.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)},wp=new WeakMap,fv=(e,t)=>{if(!e.onAttach)return;let n=wp.get(t);if(n||(n=new Map,wp.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},wg=e=>{let t=wp.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ui=(e,t)=>{uv(e,t),fv(e,t)};function Mp(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 $a=0,ko=null;function Tp(e=document){if($a++,$a===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,$a=Math.max(0,$a-1),$a===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 ja={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},kt=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??ja.side,width:t?.width??ja.width,animate:t?.animate??ja.animate,reveal:t?.reveal??ja.reveal,maxHeight:t?.maxHeight??ja.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 mv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",qi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=mv,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||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);return S?(S.style.display="block",h.appendChild(S)):h.textContent=g,p.appendChild(h),Ot({anchor:h,trigger:p,text:()=>h.getAttribute("aria-label")??d,enabled:c}),{button:h,wrapper:p}},gv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Vi=(e,t={})=>{let{wrapperClassName:n=gv,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||Jt.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),Ot({anchor:w,trigger:M,text:()=>w.getAttribute("aria-label")??L,enabled:E}),{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))"},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:Jt.titleColor}}),g=Fe("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Jt.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=Vi(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}=qi(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}},or=(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 Ep=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 hv(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 kp=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=Pi({label:s.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Jt.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=Jt.titleColor,c.textContent=s.title??"Chat Assistant",d.appendChild(c),hv(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||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 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}},zi={default:Ep,minimal:kp},Lp=e=>zi[e]??zi.default,Nr=(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=Lp(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 $i=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}},ji=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),Ot({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}}},Gi=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 Ot({anchor:f,trigger:g,text:()=>f.getAttribute("aria-label")??L,enabled:E}),{button:f,wrapper:g}},Ki=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 Ot({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??g}),{button:c,wrapper:d,input:r,previewsContainer:o}},Xi=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},Ji=()=>Fe("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var _r=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=Ji(),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}=$i(t);s();let l=ji(t),p=Gi(t),d=Ki(t),c=Xi(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 Ag=()=>{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}},Sg=e=>{let{config:t}=e,n=Fe("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Ji(),r=Xi(t);r.style.display="none";let{textarea:a,attachAutoResize:s}=$i(t);a.style.maxHeight="100px",s();let l=ji(t),p=Gi(t),d=Ki(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 Mg=e=>{let t=e?.launcher?.enabled??!0,n=kt(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??zt);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??zt),{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??zt);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}},yv=(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}=qi(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=Vi(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=Sg({config:e}),{root:M,textNode:A}=Ag();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}},Tg=(e,t=!0)=>{if(Lo(e))return yv(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?Nr(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:kt(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=_r({config:e}),h=e?.layout?.showFooter!==!1;r?or(n,a,e):(a.header.style.display="none",or(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 Pp=(e,t)=>{let n=x("button");n.type="button",n.innerHTML=`
|
|
32
|
+
`)),n=b("span","persona-code-line")),o(r.type,a[s])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function hg(e,t,n){let o=e.length<=Qx?Yx(t,n):null,r=o?sv(e,o):[{type:"plain",value:e}];return iv(r)}function Ro(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:a}=e,s=b("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(Pi)):(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=oe(f.icon,16,"currentColor",1.5);E&&h.appendChild(E)}let A=document.createElement("span");A.textContent=f.label,h.appendChild(A),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 Mt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:a,onClick:s,aria:l}=e,p=b("button","persona-icon-btn"+(a?" "+a:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let c=oe(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 Zn(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=b("button",c);if(d.type="button",d.setAttribute("aria-label",n),t){let g=oe(t,a??14,"currentColor",2);g&&d.appendChild(g)}let u=b("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 qr(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,a=b("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=Mt({icon:d.icon,label:d.label,className:d.className,onClick:()=>{s=d.id,p(),o(d.id)}}):(u=b("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 _i(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:a="bottom-left",portal:s,className:l,hover:p}=e,c=b("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=b("span","persona-combo-btn-label");d.textContent=t,c.appendChild(d);let u=oe(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=Ro({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 Ui="persona-artifact-custom-action-btn";function Vr(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 "+Ui+(n?" persona-artifact-doc-copy-btn":"");o=b("button",r)}else{let r="persona-icon-btn "+Ui+(n?" persona-artifact-doc-icon-btn":"");o=b("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=b("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Zn({icon:e.icon,label:e.label,className:Ui+(n?" persona-artifact-doc-copy-btn":"")}):o=Mt({icon:e.icon,label:e.label,className:Ui+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Ga(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 yg(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?Dn(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=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,c=n?Lo(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 u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let g=document.createElement("div");g.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let f=document.createElement("div");f.className="persona-truncate persona-text-sm persona-font-medium",f.style.color="var(--persona-text, #1f2937)",f.textContent=r;let h=document.createElement("div");if(h.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",h.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let A=t?.config?.features?.artifacts,E={id:a,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},k=Ur(E,A,"card");ar(h,k,A)}else a&&_r(a),h.textContent=c;if(g.append(f,h),d.append(u,g),s==="complete"){let A=t?.config?.features?.artifacts?.cardActions;if(A&&A.length>0){let k={artifactId:a||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let M of A)try{if(M.visible===void 0||M.visible(k)){let S=Vr(M);S.setAttribute("data-artifact-custom-action",M.id),S.className=`${S.className} persona-flex-shrink-0`,d.append(S)}}catch{}}let E=Zn({label:"Download",className:"persona-flex-shrink-0"});E.title=`Download ${r}`,E.setAttribute("data-download-artifact",a),d.append(E)}return d}var qi=(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:()=>yg(e,t)});if(l)return l}return yg(e,t)};var Io=new WeakMap;function Pp(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=Io.get(r);if(!a)return;let s=o.get(r.getAttribute("data-artifact-inline")??"");s&&a(s,n)})}function wg(e){return Io.has(e)}function lv(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",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let s=e.componentProps,l=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let a=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:"",...a?{file:a}:{},...r?{presentation:r}:{}}}function bg(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Dn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Lo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function dv(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 xg=180,cv=240,pv=.8,uv=300,fv=500,mv="cubic-bezier(0.2, 0, 0, 1)",vg=240,gv=.35;function hv(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:xg,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(fv,Math.max(uv,cv+c*pv))),u=Math.round(d*gv),g=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=g?g.animate([{opacity:0},{opacity:1}],{duration:vg,delay:u,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:d,easing:mv});e.style.height=`${p}px`;let A=!1,E=()=>{A||(A=!0,l(),r())};Promise.allSettled([h.finished,f?.finished].filter(Boolean)).then(E),window.setTimeout(E,Math.max(d,u+vg)+120)},xg)}function yv(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 Ka="--persona-artifact-inline-body-height";function bv(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 Cg(e,t){let n=lv(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:a,showExpand:s,showViewToggle:l}=yv(o),p=o?.inlineActions??[],c=bv(o),d=c.completeDisplay==="card",u=null,g=n,f=b("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=ne=>qi(dv(ne),t),A=ne=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Ka),f.replaceChildren(h(ne)),Io.set(f,le=>{f.replaceChildren(h(le))})};if(d&&n.status==="complete")return A(n),f;let E=Vi(n,{config:t.config,bodyLayout:c,resolveViewMode:()=>u??c.viewMode}),k=b("div","persona-artifact-inline-body");k.appendChild(E.el);let M=ne=>{let le=ne.status!=="complete",Z=le?c.streamingHeight:c.completeHeight,me=typeof Z=="number";me?f.style.setProperty(Ka,`${Z}px`):f.style.removeProperty(Ka);let Ae=!!E.el.querySelector(".persona-code-pre"),we=!!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",me&&we),k.classList.toggle("persona-artifact-inline-body--cap",!le&&!we&&typeof c.completeHeight=="number")},S=n.status,C=(ne,le)=>{S!=="complete"&&ne.status==="complete"?(typeof c.completeHeight=="number"?f.style.setProperty(Ka,`${c.completeHeight}px`):f.style.removeProperty(Ka),Sg(k,le?.suppressTransition?"none":c.transition,ne.id,()=>{E.update(ne),M(ne)})):E.update(ne),M(ne),S=ne.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 ${bg(n).title} in panel`)),!r)return f.appendChild(k),Io.set(f,C),f;let W=b("div","persona-artifact-inline-chrome");W.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=b("div","persona-artifact-inline-chrome-lead"),D=b("span","persona-flex persona-items-center persona-flex-shrink-0"),F=oe("file-text",16,"currentColor",2);F&&D.appendChild(F);let j=b("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),O=b("span","persona-artifact-inline-type");w.append(D,j,O);let q=b("div","persona-artifact-inline-chrome-actions"),Q=b("span","persona-flex persona-items-center persona-gap-1"),de=()=>u??c.viewMode,be=l?qr({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:de(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ne=>{let le=ne==="source"?"source":"rendered";le!==de()&&(u=le,E.update(g),M(g))}}):null,De=a?Mt({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 ie=s?Mt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ie&&n.id&&ie.setAttribute("data-expand-artifact-inline",n.id),q.appendChild(Q),be&&q.appendChild(be.element),De&&q.appendChild(De),ie&&q.appendChild(ie),W.append(w,q),f.append(W,k);let ge=ne=>{let{title:le,typeLabel:Z}=bg(ne);j.textContent=le,j.title=le,T&&k.setAttribute("aria-label",`Open ${le} in panel`);let me=ne.status!=="complete";if(me){O.classList.contains("persona-artifact-inline-status")||(O.className="persona-artifact-inline-status",O.removeAttribute("data-preserve-animation"),O.replaceChildren());let Ae=Ur(ne,o,"inline-chrome");ar(O,Ae,o)}else _r(ne.id),O.className="persona-artifact-inline-type",O.removeAttribute("data-preserve-animation"),O.replaceChildren(),O.textContent=Z;if(De&&De.classList.toggle("persona-hidden",me),be){let Ae=ne.artifactType==="markdown"?ne.file:void 0,we=!1;if(!me&&Ae&&c.viewMode!=="source"){let Se=ja(Ae);Se==="markdown"?we=!0:(Se==="html"||Se==="svg")&&(we=o?.filePreview?.enabled!==!1)}be.element.classList.toggle("persona-hidden",!we),be.setSelected(de())}if(Q.replaceChildren(),!me&&p.length>0){let Ae=Ga(ne);if(Ae)for(let we of p)try{if(we.visible===void 0||we.visible(Ae)){let Se=Vr(we,{documentChrome:!0});Se.setAttribute("data-artifact-custom-action",we.id),Se.classList.add("persona-flex-shrink-0"),Q.appendChild(Se)}}catch{}}};return ge(n),Io.set(f,(ne,le)=>{if(d&&S!=="complete"&&ne.status==="complete"){let Z=f.isConnected?f.getBoundingClientRect().height:0;S="complete";let me=ne,Ae=!1,we=Se=>{me=Se,Ae=!0};Io.set(f,we),hv(f,Z,{swap:()=>{A(me),Ae=!1,Io.set(f,we)},onSettled:()=>{Ae?A(me):Io.set(f,Se=>{f.replaceChildren(h(Se))})}});return}(ne.status!=="complete"||ne.id!==g.id)&&(u=null),g=ne,C(ne,le),ge(ne)}),f}var Ag=(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:()=>Cg(e,t)});if(l)return l}return Cg(e,t)};var Rp=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)})}},Ln=new Rp;Ln.register("PersonaArtifactCard",qi,{bubbleChrome:!1});Ln.register("PersonaArtifactInline",Ag,{bubbleChrome:!1});function Xa(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Fi(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Ip=!1;function xv(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Sg(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"||Ip||a){o();return}Ip=!0;let s=xv(n);e.style.setProperty("view-transition-name",s);let l=()=>{Ip=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var vv="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Cv="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function wv(e){let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("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 Av(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 Sv=220;function Mv(){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 Tv(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 Ev(e,t,n){let o=b("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=b("div","persona-artifact-frame-loading-indicator");r.appendChild(dg());let a=null;return n.label!==!1&&(a=b("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 kv(e,t,n,o,r,a){let s=null,l=0,p=!1,c=new Set,d=()=>{c.forEach(S=>clearTimeout(S)),c.clear()},u=(S,C)=>{let T=setTimeout(()=>{c.delete(T),S()},C);c.add(T)},g=()=>{s&&s.parentElement&&s.remove(),s=null},f=()=>{if(s||p)return;let S=Ev(r,a,o);s=S.el,e.appendChild(s),l=Date.now(),o.label!==!1&&u(S.revealLabel,o.labelDelayMs)},h=()=>{s&&(s.classList.add("persona-artifact-frame-loading--out"),u(g,Sv))},A=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",k):t.removeEventListener("load",M)},E=()=>{if(p||(p=!0,A(),d(),!s))return;let S=Math.max(0,o.minVisibleMs-(Date.now()-l));S>0?u(h,S):h()};function k(S){if(n===null)return;let C=S.data;!C||C.persona!=="artifact-preview-ready"||C.token!==n||S.source===t.contentWindow&&E()}function M(){let S=C=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>C()):setTimeout(C,0)};S(()=>S(()=>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(),A(),g()}}function Vi(e,t){let{config:n}=t,o=t.registry??Ln,r=t.bodyLayout,a=n.markdown?Qo(n.markdown):null,s=Lr(n.sanitize),l=e,p=!1,c=ie=>{let ge=Gn()!==null;a&&!ge&&!p&&(p=!0,kr(()=>De(l)));let ne=a?a(ie):Hn(ie);return a&&ge&&s?s(ne):ne},d=b("div","persona-artifact-preview-body"),u=null,g=null,f=null,h=()=>{f&&(f(),f=null),u=null,g=null},A=null,E=null,k=null,M=!1,S=()=>{A=null,E=null,k=null,M=!1},C=null,T=null,W=()=>{C=null,T=null},w=40,D=0,F=ie=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ie()):setTimeout(ie,0),j=ie=>ie.scrollHeight-ie.clientHeight-ie.scrollTop<=w,O=ie=>{if(!r)return;let ge=ie.scrollHeight-ie.clientHeight>1,ne=ie.scrollHeight-ie.clientHeight-ie.scrollTop;ie.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ge&&ie.scrollTop>1),ie.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ge&&ne>1)},q=ie=>{D||(D=F(()=>{D=0,ie.scrollTop=ie.scrollHeight,O(ie)}))},Q=(ie,ge,ne,le)=>{let Z=!!r,me=ne.id+"|"+(Z?"w":"p");if(!A||k!==me||A.parentElement!==d){h(),W(),d.replaceChildren();let Se=b("pre",vv+" persona-code-pre"),mt=b("code","persona-code");if(Se.appendChild(mt),Z){let We=b("div","persona-artifact-source-window");if(We.appendChild(Se),d.appendChild(We),!(r?.overflow==="clip")&&typeof We.addEventListener=="function"){let Xe=()=>We.scrollHeight-We.clientHeight>1;We.addEventListener("scroll",()=>{j(We)&&(M=!1),O(We)},{passive:!0}),We.addEventListener("wheel",$e=>{Xe()&&$e.deltaY<0&&(M=!0)},{passive:!0}),We.addEventListener("touchmove",()=>{Xe()&&(M=!0)},{passive:!0})}A=We}else d.appendChild(Se),A=Se;E=mt,k=me}let Ae=Z?A:null;Ae&&(Ae.classList.toggle("persona-artifact-source-window--fixed",le),Ae.classList.toggle("persona-artifact-source-window--clip",le&&r?.overflow==="clip"));let we=Ae?j(Ae):!0;if(E.replaceChildren(hg(ie,ge?.language,ge?.path)),Ae){let Se=ne.status!=="complete";le&&Se&&r?.followOutput&&!M&&we?q(Ae):Se||(M=!1),O(Ae)}},de=ie=>{h(),S(),W(),d.replaceChildren();let ge=b("div",Cv);ge.innerHTML=c(ie),d.appendChild(ge)},be=ie=>{let ge=ie.id,ne=n.features?.artifacts,le=Ur(ie,ne,"status-body");if(C&&T===ge&&C.parentElement===d){let Ae=C.querySelector(".persona-artifact-status-view-text");Ae&&ar(Ae,le,ne);return}h(),S(),d.replaceChildren();let Z=b("div","persona-artifact-status-view"),me=b("div","persona-artifact-status-view-text");ar(me,le,ne),Z.appendChild(me),d.appendChild(Z),C=Z,T=ge},De=ie=>{l=ie;let ge=t.resolveViewMode?.(ie)??r?.viewMode??"rendered",ne=ie.artifactType==="markdown"?ie.file:void 0,le=ie.status!=="complete";le||_r(ie.id);let Z=le?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&le){be(ie);return}if(ne){let we=Fi(ie.markdown??""),Se=ja(ne),mt=n.features?.artifacts?.filePreview?.enabled!==!1;if(!le&&ge==="rendered"&&mt&&(Se==="html"||Se==="svg")){let _e=ie.id+"\0"+we;if(u&&g===_e&&u.parentElement===d)return;S(),W(),h(),d.replaceChildren();let Xe=n.features?.artifacts?.filePreview,$e=Xe?.iframeSandbox??"allow-scripts";!Xe?.dangerouslyAllowSameOrigin&&$e.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."),$e=$e.split(/\s+/).filter(Wt=>Wt&&Wt!=="allow-same-origin").join(" "));let Me=Av(Xe?.loading),ke=b("div","persona-artifact-frame"),Je=b("iframe","persona-artifact-iframe");Je.setAttribute("sandbox",$e),Je.setAttribute("data-artifact-id",ie.id);let Dt=null;Me.enabled&&Me.injectReadySignal?(Dt=Mv(),Je.srcdoc=we+Tv(Dt)):Je.srcdoc=we,ke.appendChild(Je),d.appendChild(ke),Me.enabled&&(f=kv(ke,Je,Dt,Me,ie.id,n)),u=ke,g=_e;return}if(h(),!le&&Se==="markdown"&&ge==="rendered"){de(we);return}Q(we,{language:ne.language,path:ne.path},ie,me);return}if(ie.artifactType==="markdown"){if(ge==="source"){h(),Q(ie.markdown??"",void 0,ie,me);return}de(ie.markdown??"");return}h(),S(),W(),d.replaceChildren();let Ae=ie.component?o.get(ie.component):void 0;if(Ae){let Se={message:{id:ie.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let mt=Ae(ie.props??{},Se);if(mt){d.appendChild(mt);return}}catch{}}d.appendChild(wv(ie))};return De(e),{el:d,update(ie){De(ie)}}}var Mg=(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 A=u(f),E=c(g,A,h),k=r(E,()=>l(E,g,A,M=>M.morphStyle==="innerHTML"?(a(M,g,A),Array.from(g.childNodes)):o(M,g,A)));return E.pantry.remove(),k}function o(g,f,h){let A=u(f);return a(g,A,h,f,f.nextSibling),Array.from(A.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:A,selectionStart:E,selectionEnd:k}=h,M=f();return A&&A!==document.activeElement?.getAttribute("id")&&(h=g.target.querySelector(`[id="${A}"]`),h?.focus()),h&&!h.selectionEnd&&k&&h.setSelectionRange(E,k),M}let a=(function(){function g(C,T,W,w=null,D=null){T instanceof HTMLTemplateElement&&W instanceof HTMLTemplateElement&&(T=T.content,W=W.content),w||(w=T.firstChild);for(let F of W.childNodes){if(w&&w!=D){let O=h(C,F,w,D);if(O){O!==w&&E(C,w,O),s(O,F,C),w=O.nextSibling;continue}}if(F instanceof Element){let O=F.getAttribute("id");if(C.persistentIds.has(O)){let q=k(T,O,w,C);s(q,F,C),w=q.nextSibling;continue}}let j=f(T,F,w,C);j&&(w=j.nextSibling)}for(;w&&w!=D;){let F=w;w=w.nextSibling,A(C,F)}}function f(C,T,W,w){if(w.callbacks.beforeNodeAdded(T)===!1)return null;if(w.idMap.has(T)){let D=document.createElement(T.tagName);return C.insertBefore(D,W),s(D,T,w),w.callbacks.afterNodeAdded(D),D}else{let D=document.importNode(T,!0);return C.insertBefore(D,W),w.callbacks.afterNodeAdded(D),D}}let h=(function(){function C(w,D,F,j){let O=null,q=D.nextSibling,Q=0,de=F;for(;de&&de!=j;){if(W(de,D)){if(T(w,de,D))return de;O===null&&(w.idMap.has(de)||(O=de))}if(O===null&&q&&W(de,q)&&(Q++,q=q.nextSibling,Q>=2&&(O=void 0)),w.activeElementAndParents.includes(de))break;de=de.nextSibling}return O||null}function T(w,D,F){let j=w.idMap.get(D),O=w.idMap.get(F);if(!O||!j)return!1;for(let q of j)if(O.has(q))return!0;return!1}function W(w,D){let F=w,j=D;return F.nodeType===j.nodeType&&F.tagName===j.tagName&&(!F.getAttribute?.("id")||F.getAttribute?.("id")===j.getAttribute?.("id"))}return C})();function A(C,T){if(C.idMap.has(T))S(C.pantry,T,null);else{if(C.callbacks.beforeNodeRemoved(T)===!1)return;T.parentNode?.removeChild(T),C.callbacks.afterNodeRemoved(T)}}function E(C,T,W){let w=T;for(;w&&w!==W;){let D=w;w=w.nextSibling,A(C,D)}return w}function k(C,T,W,w){let D=w.target.getAttribute?.("id")===T&&w.target||w.target.querySelector(`[id="${T}"]`)||w.pantry.querySelector(`[id="${T}"]`);return M(D,w),S(C,D,W),D}function M(C,T){let W=C.getAttribute("id");for(;C=C.parentNode;){let w=T.idMap.get(C);w&&(w.delete(W),w.size||T.idMap.delete(C))}}function S(C,T,W){if(C.moveBefore)try{C.moveBefore(T,W)}catch{C.insertBefore(T,W)}else C.insertBefore(T,W)}return g})(),s=(function(){function g(M,S,C){return C.ignoreActive&&M===document.activeElement?null:(C.callbacks.beforeNodeMorphed(M,S)===!1||(M instanceof HTMLHeadElement&&C.head.ignore||(M instanceof HTMLHeadElement&&C.head.style!=="morph"?p(M,S,C):(f(M,S,C),k(M,C)||a(C,M,S))),C.callbacks.afterNodeMorphed(M,S)),M)}function f(M,S,C){let T=S.nodeType;if(T===1){let W=M,w=S,D=W.attributes,F=w.attributes;for(let j of F)E(j.name,W,"update",C)||W.getAttribute(j.name)!==j.value&&W.setAttribute(j.name,j.value);for(let j=D.length-1;0<=j;j--){let O=D[j];if(O&&!w.hasAttribute(O.name)){if(E(O.name,W,"remove",C))continue;W.removeAttribute(O.name)}}k(W,C)||h(W,w,C)}(T===8||T===3)&&M.nodeValue!==S.nodeValue&&(M.nodeValue=S.nodeValue)}function h(M,S,C){if(M instanceof HTMLInputElement&&S instanceof HTMLInputElement&&S.type!=="file"){let T=S.value,W=M.value;A(M,S,"checked",C),A(M,S,"disabled",C),S.hasAttribute("value")?W!==T&&(E("value",M,"update",C)||(M.setAttribute("value",T),M.value=T)):E("value",M,"remove",C)||(M.value="",M.removeAttribute("value"))}else if(M instanceof HTMLOptionElement&&S instanceof HTMLOptionElement)A(M,S,"selected",C);else if(M instanceof HTMLTextAreaElement&&S instanceof HTMLTextAreaElement){let T=S.value,W=M.value;if(E("value",M,"update",C))return;T!==W&&(M.value=T),M.firstChild&&M.firstChild.nodeValue!==T&&(M.firstChild.nodeValue=T)}}function A(M,S,C,T){let W=S[C],w=M[C];if(W!==w){let D=E(C,M,"update",T);D||(M[C]=S[C]),W?D||M.setAttribute(C,""):E(C,M,"remove",T)||M.removeAttribute(C)}}function E(M,S,C,T){return M==="value"&&T.ignoreActiveValue&&S===document.activeElement?!0:T.callbacks.beforeAttributeUpdated(M,S,C)===!1}function k(M,S){return!!S.ignoreActiveValue&&M===document.activeElement&&M!==document.body}return g})();function l(g,f,h,A){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 S=Object.assign(g,{head:{block:!1,ignore:!0}});return A(S)})}}return A(g)}function p(g,f,h){let A=[],E=[],k=[],M=[],S=new Map;for(let T of f.children)S.set(T.outerHTML,T);for(let T of g.children){let W=S.has(T.outerHTML),w=h.head.shouldReAppend(T),D=h.head.shouldPreserve(T);W||D?w?E.push(T):(S.delete(T.outerHTML),k.push(T)):h.head.style==="append"?w&&(E.push(T),M.push(T)):h.head.shouldRemove(T)!==!1&&E.push(T)}M.push(...S.values());let C=[];for(let T of M){let W=document.createRange().createContextualFragment(T.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(W)!==!1){if("href"in W&&W.href||"src"in W&&W.src){let w,D=new Promise(function(F){w=F});W.addEventListener("load",function(){w()}),C.push(D)}g.appendChild(W),h.callbacks.afterNodeAdded(W),A.push(W)}}for(let T of E)h.callbacks.beforeNodeRemoved(T)!==!1&&(g.removeChild(T),h.callbacks.afterNodeRemoved(T));return h.head.afterHeadMorphed(g,{added:A,kept:k,removed:E}),C}let c=(function(){function g(C,T,W){let{persistentIds:w,idMap:D}=M(C,T),F=f(W),j=F.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(j))throw`Do not understand how to morph style ${j}`;return{target:C,newContent:T,config:F,morphStyle:j,ignoreActive:F.ignoreActive,ignoreActiveValue:F.ignoreActiveValue,restoreFocus:F.restoreFocus,idMap:D,persistentIds:w,pantry:h(),activeElementAndParents:A(C),callbacks:F.callbacks,head:F.head}}function f(C){let T=Object.assign({},t);return Object.assign(T,C),T.callbacks=Object.assign({},t.callbacks,C.callbacks),T.head=Object.assign({},t.head,C.head),T}function h(){let C=document.createElement("div");return C.hidden=!0,document.body.insertAdjacentElement("afterend",C),C}function A(C){let T=[],W=document.activeElement;if(W?.tagName!=="BODY"&&C.contains(W))for(;W&&(T.push(W),W!==C);)W=W.parentElement;return T}function E(C){let T=Array.from(C.querySelectorAll("[id]"));return C.getAttribute?.("id")&&T.push(C),T}function k(C,T,W,w){for(let D of w){let F=D.getAttribute("id");if(T.has(F)){let j=D;for(;j;){let O=C.get(j);if(O==null&&(O=new Set,C.set(j,O)),O.add(F),j===W)break;j=j.parentElement}}}}function M(C,T){let W=E(C),w=E(T),D=S(W,w),F=new Map;k(F,D,C,W);let j=T.__idiomorphRoot||T;return k(F,D,j,w),{persistentIds:D,idMap:F}}function S(C,T){let W=new Set,w=new Map;for(let{id:F,tagName:j}of C)w.has(F)?W.add(F):w.set(F,j);let D=new Set;for(let{id:F,tagName:j}of T)D.has(F)?W.add(F):w.get(F)===j&&D.add(F);for(let F of W)D.delete(F);return D}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 A(k);{let M=document.createElement("div");return M.append(k),M}}else{let M=document.createElement("div");for(let S of[...k])M.append(S);return M}}class A{constructor(M){this.originalNode=M,this.realParentNode=M.parentNode,this.previousSibling=M.previousSibling,this.nextSibling=M.nextSibling}get childNodes(){let M=[],S=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;S&&S!=this.nextSibling;)M.push(S),S=S.nextSibling;return M}querySelectorAll(M){return this.childNodes.reduce((S,C)=>{if(C instanceof Element){C.matches(M)&&S.push(C);let T=C.querySelectorAll(M);for(let W=0;W<T.length;W++)S.push(T[W])}return S},[])}insertBefore(M,S){return this.realParentNode.insertBefore(M,S)}moveBefore(M,S){return this.realParentNode.moveBefore(M,S)}get __idiomorphRoot(){return this.originalNode}}function E(k){let M=new DOMParser,S=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(S.match(/<\/html>/)||S.match(/<\/head>/)||S.match(/<\/body>/)){let C=M.parseFromString(k,"text/html");if(S.match(/<\/html>/))return g.add(C),C;{let T=C.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 zi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Mg.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 Tg=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Wp={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 kg(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 Pg(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 Ig(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Wg(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function $i(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Fn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Wo(e,t){return Fn(e)-e.scrollTop<=t}function ji(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 Gi(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 Hg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Bg(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 Dg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Ja={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Lv=["pre","code","a","script","style"],Ki=e=>({type:e?.type??Ja.type,placeholder:e?.placeholder??Ja.placeholder,speed:e?.speed??Ja.speed,duration:e?.duration??Ja.duration,buffer:e?.buffer??Ja.buffer}),Og=[{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"}],Qa=new Map;for(let e of Og)Qa.set(e.name,e);var sr=e=>{Qa.set(e.name,e)},Dp=e=>{Og.some(t=>t.name===e)||Qa.delete(e)},Fp=()=>Array.from(Qa.keys()),zr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Qa.get(e)??null,Xi=(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},Pv=(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},Rv=(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},Hp=/\s/,Iv=(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},Wv=(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(Hp.test(a[l])){let p=l;for(;p<a.length&&Hp.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&&!Hp.test(a[c]);)p.appendChild(Pv(o,a[c],t,n.value)),n.value+=1,c+=1;s.appendChild(p),l=c}r.replaceChild(s,e)},Hv=(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(Rv(o,p,t,n.value)),n.value+=1));r.replaceChild(s,e)},Ya=(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??Lv).map(u=>u.toLowerCase())),s=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=s.nextNode();for(;p;)Iv(p,a)||l.push(p),p=s.nextNode();let c={value:o?.startIndex??0},d=t==="char"?Wv:Hv;for(let u of l)d(u,n,c);return r.innerHTML},Ji=(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},Za=(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},Fg=new WeakMap,Bv=(e,t)=>{if(!e.styles)return;let n=Fg.get(t);if(n||(n=new Set,Fg.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,Dv=(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)},Ng=e=>{let t=Bp.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Qi=(e,t)=>{Bv(e,t),Dv(e,t)};function Op(e,t=Gt){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 es=0,Ho=null;function Np(e=document){if(es++,es===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Ho={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,es=Math.max(0,es-1),es===0&&Ho)){let n=e.body,o=e.defaultView??window;n.style.overflow=Ho.originalOverflow,n.style.position=Ho.originalPosition,n.style.top=Ho.originalTop,n.style.width=Ho.originalWidth,o.scrollTo(0,Ho.scrollY),Ho=null}}}var ts={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Et=e=>(e?.launcher?.mountMode??"floating")==="docked",Bo=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",rn=e=>{let t=e?.launcher?.dock;return{side:t?.side??ts.side,width:t?.width??ts.width,animate:t?.animate??ts.animate,reveal:t?.reveal??ts.reveal,maxHeight:t?.maxHeight??ts.maxHeight}};var Pn={"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 Fv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Yi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Fv,buttonSize:r,iconSize:a="28px"}=t,s=e?.launcher??{},l=r??s.closeButtonSize??"32px",p=b("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:Kn("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||Yt.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}}),A=oe(u,a,"currentColor",1);return A?(A.style.display="block",h.appendChild(A)):h.textContent=g,p.appendChild(h),Ut({anchor:h,trigger:p,text:()=>h.getAttribute("aria-label")??c,enabled:d}),{button:h,wrapper:p}},Ov="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Zi=(e,t={})=>{let{wrapperClassName:n=Ov,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??"",A=s.paddingY??"",E=s.tooltipText??"Clear chat",k=s.showTooltip??!0,M=b("div",n),S=!!(u||g),C=Be("button",{className:Kn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"hover:persona-bg-gray-100",!S&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:l,width:l,color:c||Yt.actionIconColor,backgroundColor:d||void 0,border:S?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:A||void 0,paddingBottom:A||void 0}}),T=oe(p,r,"currentColor",1);return T&&(T.style.display="block",C.appendChild(T)),M.appendChild(C),Ut({anchor:C,trigger:M,text:()=>C.getAttribute("aria-label")??E,enabled:k}),{button:C,wrapper:M}};var Yt={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))"},eo=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,W=oe(p,T*.6,"currentColor",1);W?c.replaceChildren(W):c.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let T=b("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=b("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:Yt.titleColor}}),g=Be("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Yt.subtitleColor}});d.append(u,g),l?o.append(d):o.append(c,d);let f=r.clearChat??{},h=f.enabled??!0,A=f.placement??"inline",E=null,k=null;if(h){let W=Zi(t,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=W.button,k=W.wrapper,A==="top-right"&&(k.style.right="48px"),A==="inline"&&o.appendChild(k)}let M=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&A==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:S,wrapper:C}=Yi(t,{showClose:n,wrapperClassName:M});return s!=="top-right"&&o.appendChild(C),{header:o,iconHolder:c,headerTitle:u,headerSubtitle:g,closeButton:S,closeButtonWrapper:C,clearChatButton:E,clearChatButtonWrapper:k}},ir=(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 _p=e=>{let t=eo({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 Nv(e,t,n){if(t?.length)for(let o of t){let r=b("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=oe(o.icon,14,"currentColor",2);a&&r.appendChild(a)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let a=b("div","persona-relative");a.appendChild(r);let s=Ro({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 Up=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:a}=e,s=t?.launcher??{},l=b("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=_i({label:s.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=Yt.titleColor,d=c.querySelector(".persona-combo-btn-label")??c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=b("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Yt.titleColor,d.textContent=s.title??"Chat Assistant",c.appendChild(d),Nv(c,r?.trailingActions,r?.onAction??a),r?.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let S=r.onTitleClick;c.addEventListener("click",C=>{C.target.closest("button")||S()}),c.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),S())})}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=b("div",""),f=b("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||Yt.actionIconColor;let h=s.closeButtonIconName??"x",A=oe(h,"28px","currentColor",1);A?f.appendChild(A):f.textContent="\xD7",o&&f.addEventListener("click",o),g.appendChild(f),l.appendChild(g);let E=b("div");E.style.display="none";let k=b("span");return k.style.display="none",{header:l,iconHolder:E,headerTitle:d,headerSubtitle:k,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},el={default:_p,minimal:Up},qp=e=>el[e]??el.default,$r=(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=b("div");l.style.display="none";let p=b("span"),c=b("span"),d=b("button");d.style.display="none";let u=b("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=qp(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 tl=e=>{let t=b("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-text 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}},nl=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=b("div","persona-send-button-wrapper"),A=Be("button",{className:Kn("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 C=parseFloat(u)||24,T=f?.trim()||"currentColor";r?(E=oe(r,C,T,2),E?A.appendChild(E):A.textContent=o):A.textContent=o,k=oe(a,C,T,2)}else A.textContent=p;A.setAttribute("aria-label",s),h.appendChild(A),Ut({anchor:A,trigger:h,text:()=>A.getAttribute("aria-label")??"",enabled:d});let M="send";return{button:A,wrapper:h,setMode:C=>{if(C===M)return;M=C;let T=C==="stop"?l:s;if(A.setAttribute("aria-label",T),n){if(E&&k){let W=C==="stop"?k:E;A.replaceChildren(W)}}else A.textContent=C==="stop"?c:p}}},ol=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=b("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":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: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}}),A=oe(l,c,u||"currentColor",1.5);A?f.appendChild(A):f.textContent="\u{1F3A4}",g.appendChild(f);let E=t.tooltipText??"Start voice recognition",k=t.showTooltip??!1;return Ut({anchor:f,trigger:g,text:()=>f.getAttribute("aria-label")??E,enabled:k}),{button:f,wrapper:g}},rl=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=b("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=b("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Yn).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=b("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=oe(a,p,"currentColor",1.5);u?d.appendChild(u):d.textContent="\u{1F4CE}",d.addEventListener("click",f=>{f.preventDefault(),r.click()}),c.appendChild(d);let g=t.buttonTooltipText??"Attach file";return Ut({anchor:d,trigger:c,text:()=>d.getAttribute("aria-label")??g}),{button:d,wrapper:c,input:r,previewsContainer:o}},al=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("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=b("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},sl=()=>Be("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var jr=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=sl(),r=Be("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=tl(t);s();let l=nl(t),p=ol(t),c=rl(t),d=al(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=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=b("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 _g=()=>{let e=Be("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=b("span","persona-pill-peek__icon"),n=oe("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),a=oe("chevron-up",16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,o,r),{root:e,textNode:o}},Ug=e=>{let{config:t}=e,n=Be("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=sl(),r=al(t);r.style.display="none";let{textarea:a,attachAutoResize:s}=tl(t);a.style.maxHeight="100px",s();let l=nl(t),p=ol(t),c=rl(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=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let g=b("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 qg=e=>{let t=e?.launcher?.enabled??!0,n=Et(e);if(Bo(e)){let d=e?.launcher?.composerBar??{},u=b("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??Gt);let g=b("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=b("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??Gt),{wrapper:u,panel:g,pillRoot:f}}if(n){let d=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=b("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=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=b("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&&Pn[r.position]?Pn[r.position]:Pn["bottom-right"],s=b("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String(e?.launcher?.zIndex??Gt);let l=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=e?.launcher?.width??e?.launcherWidth??pn;return l.style.width=c,l.style.maxWidth=c,s.appendChild(l),{wrapper:s,panel:l}},_v=(e,t)=>{let n=b("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}=Yi(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 C=Zi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=C.button,l=C.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=b("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=Ug({config:e}),{root:M,textNode:S}=_g();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:b("span"),headerTitle:b("span"),headerSubtitle:b("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:S}},Vg=(e,t=!0)=>{if(Bo(e))return _v(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?$r(e,o,{showClose:t}):eo({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:Et(e)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),d=b("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=jr({config:e}),h=e?.layout?.showFooter!==!1;r?ir(n,a,e):(a.header.style.display="none",ir(n,a,e)),n.append(s);let A=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(A),{container:n,body:s,messagesWrapper:d,composerOverlay:A,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 Vp=(e,t)=>{let n=b("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 Ia=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=kt(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??zt));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 Eg=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Mg(e),a=Tg(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}}},Rp=({config:e,plugins:t,onToggle:n})=>{let o=t.find(a=>a.renderLauncher);if(o?.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>Pp(e,n).element,onToggle:n});if(a)return{instance:null,element:a}}let r=Pp(e,n);return{instance:r,element:r.element}};var xv=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}},bv=(e,t)=>{if(!e)return null;let n=xv(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},vv=(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},Cv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Ip=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(":"))},Wp=320,Rg=320,wv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Av=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Sv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Mv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Tv=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},Ev=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Wa(o.ref,{readonly:!0,render:t}))}return n},kg="\uE000",Lg="\uE001",kv=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),a=g=>`${kg}${r}:${g}${Lg}`,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(Ev(t,o));return}e.innerHTML=l;let d=new RegExp(`${kg}${r}:(\\d+)${Lg}`),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(Wa(S.ref,{readonly:!0,render:o}),L),f=L}}},Lv=(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=`${Wp}px`,d.style.maxHeight=`${Rg}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}),Cv(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}},Pv=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(!Ip(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=`${Wp}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Rv=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(!Ip(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=`${Wp}px`,r.style.maxHeight=`${Rg}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}},Iv=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(!Ip(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}},rr=()=>{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},Hp=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:rr};if(t){let r=t(o);if(r!==null)return r}return rr()},Wv=(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},Pg=(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},Hv=(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},Bp=(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=Mt({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},Ur=(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=Hv(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=wv(e),E=e.content?.trim()??"",A=L.length>0&&E===oi,w=Oi(a?.widgetConfig?.features?.streamAnimation),T=a?.widgetConfig?.features?.streamAnimation?.plugins,H=e.role==="assistant"&&w.type!=="none"?Or(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?Ni(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"?Va(Y,"char",e.id,{skipTags:H.skipTags}):B&&H?.wrap==="word"?Va(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?kv(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=_i(),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=Pg(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=Lv(L,!A&&!!E,()=>{A&&U&&(U.style.display="")});Y?S.appendChild(Y):A&&U&&(U.style.display="")}let ie=Av(e);if(ie.length>0){let Y=Pv(ie);Y&&S.appendChild(Y)}let le=Sv(e);if(le.length>0){let Y=Rv(le);Y&&S.appendChild(Y)}let Ce=Mv(e);if(Ce.length>0){let Y=Iv(Ce);Y&&S.appendChild(Y)}let Ie=e.contentSegments?.length?null:Tv(e.contextMentions);if(Ie&&S.appendChild(Ie),S.appendChild(F),u&&f==="below"&&e.createdAt){let Y=Pg(e,d);Y.classList.add("persona-mt-1"),S.appendChild(Y)}let ae=e.role==="assistant"?bv(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(za());else if(ve)S.appendChild(za());else{let xe=Hp("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);xe&&S.appendChild(xe)}}if(ae&&e.stopReason&&!e.streaming&&(E||(F.style.display="none"),S.appendChild(vv(e.stopReason,ae))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Y=Bp(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=Wv(p,e.role);return g==="right"||g==="left"&&e.role==="user"?Z.append(S,de):Z.append(de,S),Z},Ig=(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}):Ur(e,t,n,o,r,a)};var qr=new Set,Bv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Dv=(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
|
-
`):""},
|
|
44
|
-
`);let r=
|
|
45
|
-
`):""},Fp=(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)"},Nv=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",a=Ov(e,o?.previewMaxLines??3),s=n?im(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=ad(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=ad(n,p.completeTextTemplate,d)),{summary:d,previewText:a,isActive:l}},Hg=(e,t,n)=>{let o=Vr.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")},Op=(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&&Vr.has(e.id),{summary:p,previewText:d,isActive:c}=Nv(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=ka(n),D},L=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:a.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:ka(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 ie=n.name?.trim()||"tool",le=Qs(D,ie),Ce=0;for(let Ie of le){let ae=Ie.styles.length>0?(()=>{let me=x("span",Ie.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return f.appendChild(me),me})():f;if(Ie.isDuration&&c)ae.appendChild(S());else{let me=Ie.isDuration?ka(n):Ie.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 ie=x("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ie.append(C),u.append(g,ie)}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??{}});Fv(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 ie=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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Fp(ie,o),ie.textContent=yo(n.args),D.append(U,ie),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 ie=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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Fp(ie,o),ie.textContent=n.chunks.join(""),D.append(U,ie),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 ie=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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Fp(ie,o),ie.textContent=yo(n.result),D.append(U,ie),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 ar=new Map,Qi=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)},Bg=e=>e?.approval!==!1?e?.approval:void 0,Dg=(e,t)=>{let n=Bg(t)?.detailsDisplay??"collapsed";return ar.get(e)??n==="expanded"},Fg=(e,t,n)=>{let o=Bg(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)}},Og=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let a=Dg(e,n);Fg(o,a,n),r.style.display=a?"":"none"};var Yi=(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)?wa(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??Qi(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=Dg(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),Fg(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 ie=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(ie),C.append(B,D),u.appendChild(C)}return s.append(l,u),a.appendChild(s),a};function _v(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Ng(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??_v(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 _g(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Uv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Ug=(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))},sr=(e,t)=>{Ug(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)},qv=e=>e?.approval!==!1?e?.approval:void 0,Vv=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return ar.get(e)??n==="expanded"},Np=e=>{let t=x("span","persona-approval-kbd");return t.textContent=e,t},zv=(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)?wa(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??Qi(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?Qi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},jv=(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&&Vv(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=zv(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",Np("\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(Np("Esc"));let U=x("div","persona-approval-menu"),ie=x("button","persona-approval-menu-item");ie.type="button",ie.append("Allow once",Np("\u2318\u23CE")),U.appendChild(ie),T=Ng({anchor:B,content:U,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,T),ie.addEventListener("click",()=>{sr(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),ar.set(t.id,U)}return}if(q==="toggle-menu"){T?.toggle();return}if(q==="always"){sr(e,t.id),r({remember:!0});return}if(q==="allow"){sr(e,t.id),r();return}if(q==="deny"){sr(e,t.id),a();return}}),l},qg=()=>{let e=Uv();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=qv(s);if(l.status!=="pending"){if(sr(e,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return $v(l)}Ug(e,o.id);let d=p?.enableAlwaysAllow===!0,c=jv(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=>{_g(g)||o.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),sr(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()])sr(e,o);e.latestPendingApprovalId=null}}};var Vg=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 Ga=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 Ka=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 Gv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Kv=new Set(["step_start","execution_start"]),Xv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Jv=new Set(["step_complete","agent_turn_complete"]),Qv=new Set(["flow_complete","agent_complete"]),zg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),jg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),dn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ir=(e,t)=>{let n=e[t];return jg(n)?n:void 0};function _p(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Zi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Yv(e,t){return typeof t.type=="string"?t.type:e}function Zv(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 eC(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=ir(e,"result"),n=[ir(e,"tokens"),ir(e,"totalTokens"),t?ir(t,"tokens"):void 0,ir(e,"usage"),t?ir(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 tC(e){let t=ir(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 nC(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Xa=class{constructor(t=nC){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:Zi(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(!jg(n)){zg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Yv(t,n),r=this.now();if(Gv.has(o)){this.startRun(r);return}if(Kv.has(o)){this.run||this.startRun(r);return}if(Xv.has(o)){if(!eC(o,n))return;let a=Zv(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+_p(s.visibleCharCount),p=r-s.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Zi(l,p),outputTokens:l,durationMs:p,source:s.exactOutputTokens>0?"usage":"estimate"};return}if(Jv.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+_p(a.visibleCharCount),d=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Zi(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(Qv.has(o)){if(!this.run)return;let a=this.run,s=$g(n),l=s??a.exactOutputTokens+_p(a.visibleCharCount),p=s!==void 0||a.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Zi(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(zg.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:tC(n)??o-t.startedAt}};function zr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var oC={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)"}},rC={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},aC=["flowName","stepName","reasoningText","text","name","tool","toolName"],sC=100;function iC(e,t){let n={...oC,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return rC}function lC(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function dC(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 cC(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 pC(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 uC(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 fC(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function mC(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 gC(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 Up(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");zr(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"?lC(e.timestamp,n):dC(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=iC(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??aC,H=cC(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 pC(uC(e)),F.innerHTML="";let U=te("check","12px","currentColor",1.5);U&&F.appendChild(U),setTimeout(()=>{F.innerHTML="";let ie=te("clipboard","12px","currentColor",1.5);ie&&F.appendChild(ie)},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(gC(e,s,l)),g}}function Gg(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");zr(S,h?.panel);let L=[],E="",M="",A=null,w=[],T={},H=0,C=Bi(),B=0,F=0,q=!1,D=null,U=!1,ie=0,le=new Set,Ce=new Map,Ie="",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(zr(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 Ye=xe,Po=Be,Ro=()=>{if(!Po.textContent)return;let rs=Ye.getBoundingClientRect(),$t=_.getBoundingClientRect();Po.style.left=`${rs.left-$t.left}px`,Po.style.top=`${rs.bottom-$t.top+4}px`,Po.style.display="block"},ul=()=>{Po.style.display="none"};xe.addEventListener("mouseenter",Ro),xe.addEventListener("mouseleave",ul),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 je=x("option","");je.value="",je.textContent="All events (0)",Z.appendChild(je),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 qe=x("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");zr(qe,h?.searchBar);let we=te("search","14px","var(--persona-muted, #9ca3af)",1.5),Re=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&&Re.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"),zr(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 ke=te("x","12px","currentColor",2);return ke&&ve.appendChild(ke),qe.appendChild(Re),qe.appendChild(Y),qe.appendChild(ve),_.appendChild(j),_.appendChild(qe),Be&&_.appendChild(Be),_}let ze,Ne=a.find(_=>_.renderEventStreamToolbar);Ne?.renderEventStreamToolbar&&r?ze=Ne.renderEventStreamToolbar({config:r,defaultRenderer:()=>Oe(),eventCount:t.getSize(),filteredCount:0,onFilterChange:j=>{E=j,Ee(),ge()},onSearchChange:j=>{M=j,Ee(),ge()}})??Oe():ze=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 Je(){if(!s||!Ae||!xe)return;let _=s(),j=fC(_);Ae.textContent=j;let re=mC(_);Be&&(Be.textContent=re,re||(Be.style.display="none")),xe.setAttribute("aria-label",re?`Throughput: ${j}, ${re}`:`Throughput: ${j}`)}let We=x("div","persona-flex-1 persona-min-h-0 persona-relative"),Me=x("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Me.style.height="100%";let Qe=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");zr(Qe,h?.scrollIndicator),Qe.style.display="none",Qe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let cn=te(d,"14px","currentColor",2);cn&&Qe.appendChild(cn);let Tt=x("span","");Tt.textContent=c,Qe.appendChild(Tt);let yt=x("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");yt.style.display="none",We.appendChild(Me),We.appendChild(yt),We.appendChild(Qe),S.setAttribute("tabindex","0"),S.appendChild(ze),S.appendChild(rt),S.appendChild(We);function He(){let _=t.getAll(),j={};for(let qe of _)j[qe.type]=(j[qe.type]||0)+1;let re=Object.keys(j).sort(),je=re.length!==w.length||!re.every((qe,we)=>qe===w[we]),Te=!je&&re.some(qe=>j[qe]!==T[qe]),at=_.length!==Object.values(T).reduce((qe,we)=>qe+we,0);if(!je&&!Te&&!at||(w=re,T=j,!Z))return;let K=Z.value;if(Z.options[0].textContent=`All events (${_.length})`,je){for(;Z.options.length>1;)Z.remove(1);for(let qe of re){let we=x("option","");we.value=qe,we.textContent=`${qe} (${j[qe]||0})`,Z.appendChild(we)}K&&re.includes(K)?Z.value=K:K&&(Z.value="",E="")}else for(let qe=1;qe<Z.options.length;qe++){let we=Z.options[qe];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 Ke(){return E!==""||M!==""}function Ee(){H=0,B=0,C.resume(),Qe.style.display="none"}function pe(_){le.has(_)?le.delete(_):le.add(_),me=_;let j=Me.scrollTop,re=C.isFollowing();U=!0,C.pause(),ge(),Me.scrollTop=j,re&&C.resume(),U=!1}function se(){return Eo(Me,50)}function ge(){F=Date.now(),q=!1,Je(),He();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&&Ke()?(yt.textContent=M?`No events matching '${M}'`:"No events matching filter",yt.style.display="",Me.style.display="none"):(yt.style.display="none",Me.style.display=""),de&&(de.title=Ke()?`Copy Filtered (${j})`:"Copy All"),p&&!C.isFollowing()&&j>H&&(B+=j-H,Tt.textContent=c?`${c}${B>0?` (${B})`:""}`:"",Qe.style.display=""),H=j;let je=t.getAll(),Te=je.length>0?je[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!==Ie||M!==ae,qe=Ce.size===0&&L.length>0;if(K||qe||L.length===0){Me.innerHTML="",Ce.clear();let we=document.createDocumentFragment();for(let Re=0;Re<L.length;Re++){let ke=Up(L[Re],Re,Te,u,le,pe,a,r);Ce.set(L[Re].id,ke),we.appendChild(ke)}Me.appendChild(we),Ie=E,ae=M,me=null}else{if(me!==null){let Re=Ce.get(me);if(Re&&Re.parentNode===Me){let ke=L.findIndex(Ye=>Ye.id===me);if(ke>=0){let Ye=Up(L[ke],ke,Te,u,le,pe,a,r);Me.insertBefore(Ye,Re),Re.remove(),Ce.set(me,Ye)}}me=null}let we=new Set(L.map(Re=>Re.id));for(let[Re,ke]of Ce)we.has(Re)||(ke.remove(),Ce.delete(Re));for(let Re=0;Re<L.length;Re++){let ke=L[Re];if(!Ce.has(ke.id)){let Ye=Up(ke,Re,Te,u,le,pe,a,r);Ce.set(ke.id,Ye),Me.appendChild(Ye)}}}C.isFollowing()&&(Me.scrollTop=Me.scrollHeight)}function xt(){if(Date.now()-F>=sC){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 je=x("span","persona-text-xs");je.textContent="Copy All",de.appendChild(je),setTimeout(()=>{de.innerHTML="";let Te=te("clipboard-copy","12px","currentColor",1.5);Te&&de.appendChild(Te);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 _;Ke()?_=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,Ee(),ge())},Q=()=>{!Y||!ve||(ve.style.display=Y.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{M=Y.value,Ee(),ge()},150))},R=()=>{!Y||!ve||(Y.value="",M="",ve.style.display="none",A&&clearTimeout(A),Ee(),ge())},z=()=>{if(U)return;let _=Me.scrollTop,{action:j,nextLastScrollTop:re}=Di({following:C.isFollowing(),currentScrollTop:_,lastScrollTop:ie,nearBottom:se(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ie=re,j==="resume"?(C.resume(),B=0,Qe.style.display="none"):j==="pause"&&(C.pause(),p&&(Tt.textContent=c,Qe.style.display=""))},b=_=>{let j=Fi({following:C.isFollowing(),deltaY:_.deltaY,nearBottom:se(),resumeWhenNearBottom:!0});j==="pause"?(C.pause(),p&&(Tt.textContent=c,Qe.style.display="")):j==="resume"&&(C.resume(),B=0,Qe.style.display="none")},P=()=>{p&&(Me.scrollTop=Me.scrollHeight,C.resume(),B=0,Qe.style.display="none")},I=_=>{let j=_.target;if(!j||j.closest("button"))return;let re=j.closest("[data-event-id]");if(!re)return;let je=re.getAttribute("data-event-id");je&&pe(je)},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),Me.addEventListener("scroll",z),Me.addEventListener("wheel",b,{passive:!0}),Me.addEventListener("click",I),Qe.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),Me.removeEventListener("scroll",z),Me.removeEventListener("wheel",b),Me.removeEventListener("click",I),Qe.removeEventListener("click",P),S.removeEventListener("keydown",N)}return{element:S,update:xt,destroy:G}}}function Kg(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 Xg(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=Mt({icon:"x",label:s});E.addEventListener("click",()=>{f(),t.onDismiss?.()});let M="rendered",A=Dr({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"}):Mt({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"}):Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=Mt({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=Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(q=Mt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&q.classList.add("persona-hidden"));let ie=r?Mt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Mt({icon:"refresh-cw",label:"Refresh"}),le=r?Mt({icon:"x",label:s,className:"persona-artifact-doc-icon-btn"}):Mt({icon:"x",label:s}),Ce=Mt({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 Ie=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=We.find(P=>P.id===Me)??We[We.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=We.find(R=>R.id===Me)??We[We.length-1];try{await navigator.clipboard.writeText(_a(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()})}ie.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,ie,le):w.append(q,ie,le),w.insertBefore(Ie,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,Ie,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=Kg(Y,{onSelect:Q=>t.onSelect(We[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,ze=()=>{if(Oe)return;let Q=()=>{Oe=0,Be(Y)};Oe=typeof requestAnimationFrame=="function"?requestAnimationFrame(Q):setTimeout(Q,0)};Y.addEventListener("scroll",()=>ze(),{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},Je=()=>{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 We=[],Me=null,Qe=!1,cn=!1,Tt=!0,yt=!1,He=null,fe="",Ke=null,Ee=!1,pe=Q=>Q.artifactType==="markdown"&&!!Q.file||r?M:"rendered",se=Q=>{r||(Q&&!Ee?(S.insertBefore(A.element,L),Ee=!0):!Q&&Ee&&(A.element.remove(),Ee=!1))},ge=()=>Me&&We.find(Q=>Q.id===Me)||We[We.length-1],xt=()=>{let Q=Oa(ge());if(!Q){Ie.replaceChildren();return}let R=ae.filter(z=>z.visible===void 0||z.visible(Q)).map(z=>Fr(z,{documentChrome:r,onClick:()=>{let b=Oa(ge());if(b)try{Promise.resolve(z.onClick(b)).catch(()=>{})}catch{}}}));Ie.replaceChildren(...R)},he=()=>{xt();let Q=r&&We.length<=1,R=!!ve;if(Y.classList.toggle("persona-hidden",Q||R),Ae.classList.toggle("persona-hidden",Q||!R),R&&ve){let P=We.map(I=>I.id).join("|")+" "+(Me??"");if(P!==fe){fe=P;let I=ve({records:We,selectedId:Me,onSelect:t.onSelect});Ae.firstElementChild!==I&&Ae.replaceChildren(I)}}else{xe.beforeRender(),Y.replaceChildren();let P=[],I=-1;for(let[N,G]of We.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),je=j?.path||G.title||re;_.textContent=re,_.title=je,_.setAttribute("aria-label",je),G.id===Me&&(_.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&&Me!==He){He=Me;let N=P[I];typeof N.scrollIntoView=="function"&&N.scrollIntoView({block:"nearest",inline:"nearest"})}Be(Y)}let z=Me&&We.find(P=>P.id===Me)||We[We.length-1];if(!z){Ne.replaceChildren(),Ke=null,se(!1);return}let b=z.artifactType==="markdown"?z.file:void 0;if(se(!!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;Ke?(Ke.el.parentElement!==Ne&&Ne.replaceChildren(Ke.el),Ke.update(z)):(Ke=Wi(z,{config:e,resolveViewMode:pe}),Ne.replaceChildren(Ke.el)),Ne.classList.toggle("persona-artifact-content-flush",!!Ne.querySelector(".persona-code-pre"))},ce=()=>{let Q=We.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&&Qe?(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=()=>{yt=!1,he(),ce()};return{element:h,backdrop:g,update(Q){let R=Q.selectedId??Q.artifacts[Q.artifacts.length-1]?.id??null,z=R!==Me;We=Q.artifacts,Me=R,We.length>0&&(Qe=!0),yt=!0,Tt&&yn(),z&&rt()},setMobileOpen(Q){Qe=Q,!Q&&g?(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):ce()},setExpanded(Q){Q!==cn&&(cn=Q,Je());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,xt()},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!==Tt&&(Tt=Q,Q&&yt&&yn())}}}function Qt(e){return e?.features?.artifacts?.enabled===!0}function Jg(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 hC(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 Qg=["panel","seamless","detached"];function qp(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Qg.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Vp(e){return!e||!Qt(e)?!1:qp(e)==="detached"}function Ja(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"),hC(e),Jg(e,t);return}let n=t.features?.artifacts?.layout,o=qp(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"),Jg(e,t)}function Qa(e,t){for(let l of Qg)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=qp(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 Yg(e,t){return!t||!Qt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function yC(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 xC(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 bC(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function vC(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function zp(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 Zg(e,t,n,o,r,a){let s=yC(r,200),l=vC(t,n,o,200);l=Math.max(s,l);let p=xC(a);return p!==null&&(l=Math.min(l,p)),bC(e,s,l)}var eh={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"}},$p=(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=eh[s]??eh.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 jp=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()}},Ya=new jp;var th=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),CC=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),nh=(e,t,n)=>{if(!th(e)||!th(t)||CC.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]=nh(e[r],t[r],a)}return o};function el(e,t){let n=nh(e,t,"");return Ir(n)}var oh=()=>{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 wC=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},AC=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},Za=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=wC(e),n=AC(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}},Gp=e=>typeof e=="string"?e:e==null?"":String(e),lr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Gp(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Gp(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:Gp(n.text)}}},rh=e=>Array.isArray(e)?e.map(t=>String(t)):[],es=e=>{let t=new Set(rh(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(rh(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 SC=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}},MC=e=>e.map(t=>({...t,streaming:!1})),TC=e=>e.map(t=>({...t,status:"complete"})),tl=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?SC(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?MC(n.messages):void 0,artifacts:n.artifacts?TC(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 $r=po(qs(),1);function EC(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function kC(e,t){if(!EC(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 nl(){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,$r.parse)(n,$r.STR|$r.OBJ),a=kC(r,n);a&&(e=a)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function ah(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ol(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 sh(){let e=nl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ih(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 ts(e){let t=ih(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 rl(e){let t=ih(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 LC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function al(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=LC}=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=`
|
|
42
|
+
`,n.addEventListener("click",t);let o=a=>{let s=a.launcher??{},l=Et(a),p=n.querySelector("[data-role='launcher-title']");if(p){let S=s.title??"Chat Assistant";p.textContent=S,p.setAttribute("title",S)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let S=s.subtitle??"Here to help you get answers fast";c.textContent=S,c.setAttribute("title",S)}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 S=s.agentIconSize??"40px";if(u.style.height=S,u.style.width=S,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 C=parseFloat(S)||24,T=oe(s.agentIconName,C*.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 S=s.agentIconSize??"40px";g.style.height=S,g.style.width=S,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 S=s.callToActionIconSize??"32px";f.style.height=S,f.style.width=S,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 C=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,C=(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(S)||24,W=Math.max(T-C,8),w=oe(s.callToActionIconName,W,"currentColor",2);w?f.appendChild(w):f.textContent=s.callToActionIconText??"\u2197"}else f.textContent=s.callToActionIconText??"\u2197"}let h=s.position&&Pn[s.position]?Pn[s.position]:Pn["bottom-right"],A="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:`${A} ${h}`,l||(n.style.zIndex=String(s.zIndex??Gt));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 zg=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=qg(e),a=Vg(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}}},zp=({config:e,plugins:t,onToggle:n})=>{let o=t.find(a=>a.renderLauncher);if(o?.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>Vp(e,n).element,onToggle:n});if(a)return{instance:null,element:a}}let r=Vp(e,n);return{instance:r,element:r.element}};var Uv=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}},qv=(e,t)=>{if(!e)return null;let n=Uv(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Vv=(e,t)=>{let n=b("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},zv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},$p=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(":"))},jp=320,Kg=320,$v=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),jv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Gv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Kv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Xv=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=b("span","persona-mention-chip-icon"),a=oe(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},Jv=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(qa(o.ref,{readonly:!0,render:t}))}return n},$g="\uE000",jg="\uE001",Qv=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),a=g=>`${$g}${r}:${g}${jg}`,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(Jv(t,o));return}e.innerHTML=l;let c=new RegExp(`${$g}${r}:(\\d+)${jg}`),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 A=t[Number(h[1])],E=f.splitText(h.index);E.data=E.data.slice(h[0].length),A?.kind==="mention"&&E.parentNode?.insertBefore(qa(A.ref,{readonly:!0,render:o}),E),f=E}}},Yv=(e,t,n)=>{if(e.length===0)return null;try{let o=b("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=b("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=`${jp}px`,c.style.maxHeight=`${Kg}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}),zv(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}},Zv=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!$p(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${jp}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},eC=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!$p(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${jp}px`,r.style.maxHeight=`${Kg}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}},tC=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!$p(o.data))return;let r=b("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}},lr=()=>{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},Gp=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:lr};if(t){let r=t(o);if(r!==null)return r}return lr()},nC=(e,t)=>{let n=b("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=b("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},Gg=(e,t,n="div")=>{let o=b(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},Kp=(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-text","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-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),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-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},Xp=(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=b("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=b("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,A,E)=>{let k=Mt({icon:h,label:A,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},Gr=(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=Kp(e.role,l),A=b("div",h.join(" "));A.id=`bubble-${e.id}`,A.setAttribute("data-message-id",e.id),A.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(A.style.backgroundColor="transparent",A.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=$v(e),k=e.content?.trim()??"",S=E.length>0&&k===fi,C=Ki(a?.widgetConfig?.features?.streamAnimation),T=a?.widgetConfig?.features?.streamAnimation?.plugins,W=e.role==="assistant"&&C.type!=="none"?zr(C.type,T):null,w=e.role==="assistant"&&W?.isAnimating?.(e)===!0,D=e.role==="assistant"&&W!==null&&(!!e.streaming||w);D&&W?.bubbleClass&&A.classList.add(W.bubbleClass);let F=document.createElement("div");F.classList.add("persona-message-content"),e.streaming&&F.classList.add("persona-content-streaming"),D&&W&&(W.containerClass&&F.classList.add(W.containerClass),F.style.setProperty("--persona-stream-step",`${C.speed}ms`),F.style.setProperty("--persona-stream-duration",`${C.duration}ms`));let j=D?Xi(e.content??"",C.buffer,W,e,!!e.streaming):e.content??"",O=()=>{let Z=t({text:j,message:e,streaming:!!e.streaming,raw:e.rawContent});return D&&W?.wrap==="char"?Ya(Z,"char",e.id,{skipTags:W.skipTags}):D&&W?.wrap==="word"?Ya(Z,"word",e.id,{skipTags:W.skipTags}):Z},q=null;if(S?(q=document.createElement("div"),q.innerHTML=O(),q.style.display="none",F.appendChild(q)):e.contentSegments?.length?Qv(F,e.contentSegments,Z=>t({text:Z,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):F.innerHTML=O(),D&&W?.useCaret&&!S&&k){let Z=Ji(),me=F.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ae=me[me.length-1];if(Ae?.parentNode)Ae.parentNode.insertBefore(Z,Ae.nextSibling);else{let we=F.lastElementChild;we?we.appendChild(Z):F.appendChild(Z)}}if(u&&f==="inline"&&e.createdAt){let Z=Gg(e,c,"span");Z.classList.add("persona-timestamp-inline");let me=F.lastElementChild;me?me.appendChild(Z):F.appendChild(Z)}if(E.length>0){let Z=Yv(E,!S&&!!k,()=>{S&&q&&(q.style.display="")});Z?A.appendChild(Z):S&&q&&(q.style.display="")}let Q=jv(e);if(Q.length>0){let Z=Zv(Q);Z&&A.appendChild(Z)}let de=Gv(e);if(de.length>0){let Z=eC(de);Z&&A.appendChild(Z)}let be=Kv(e);if(be.length>0){let Z=tC(be);Z&&A.appendChild(Z)}let De=e.contentSegments?.length?null:Xv(e.contextMentions);if(De&&A.appendChild(De),A.appendChild(F),u&&f==="below"&&e.createdAt){let Z=Gg(e,c);Z.classList.add("persona-mt-1"),A.appendChild(Z)}let ie=e.role==="assistant"?qv(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Z=!!(j&&j.trim()),me=C.placeholder==="skeleton",Ae=me&&C.buffer==="line"&&Z;if(Z)Ae&&A.appendChild(Za());else if(me)A.appendChild(Za());else{let we=Gp("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);we&&A.appendChild(we)}}if(ie&&e.stopReason&&!e.streaming&&(k||(F.style.display="none"),A.appendChild(Vv(e.stopReason,ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Z=Xp(e,o,r);A.appendChild(Z)}if(!d||e.role==="system")return A;let ne=b("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),le=nC(p,e.role);return g==="right"||g==="left"&&e.role==="user"?ne.append(A,le):ne.append(le,A),ne},Xg=(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}):Gr(e,t,n,o,r,a)};var Kr=new Set,oC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),rC=(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
|
+
`):""},Jg=(e,t)=>{let n=Kr.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 c=oe(n?"chevron-up":"chevron-down",16,"currentColor",2);c?l.appendChild(c):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",a&&(a.style.display=n?"none":a.textContent||a.childNodes.length?"":"none")},Jp=(e,t)=>{let n=e.reasoning,o=b("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&&Kr.has(e.id),l=n.status!=="complete",p=rC(e,r.previewMaxLines??3),c=b("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");c.type="button",a&&(c.setAttribute("aria-expanded",s?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let d=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=t?.reasoning??{},h=String(n.startedAt??Date.now()),A=()=>{let de=b("span","");return de.setAttribute("data-tool-elapsed",h),de.textContent=si(n),de},E=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:g,previewText:p,isActive:l,config:t??{},elapsed:si(n),createElapsedElement:A});typeof E=="string"&&E.trim()?(u.textContent=E,d.appendChild(u)):E instanceof HTMLElement?d.appendChild(E):(u.textContent=g,d.appendChild(u));let k=b("span","persona-text-xs persona-text-persona-primary");k.textContent=Am(n),d.appendChild(k);let M=r.loadingAnimation??"none",S=f.activeTextTemplate,C=f.completeTextTemplate,T=l?S:C,W=E instanceof HTMLElement,w=(de,be)=>{u.textContent="";let De=ii(de,""),ie=0;for(let ge of De){let ne=ge.styles.length>0?(()=>{let le=b("span",ge.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return u.appendChild(le),le})():u;if(ge.isDuration&&l)ne.appendChild(A());else{let le=ge.isDuration?si(n):ge.text;be?ie=Po(ne,le,ie):ne.appendChild(document.createTextNode(le))}}};if(!W&&T)if(k.style.display="none",u.style.display="",l&&M!=="none"){let de=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",`${de}ms`),w(T,!1)):(u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${de}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)),w(T,!0))}else w(T,!1);else if(!W&&l&&M!=="none"){u.style.display="";let de=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",`${de}ms`);else{u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${de}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 be=u.textContent||g;u.textContent="",Po(u,be,0)}n.status==="complete"&&(u.style.display="none")}else W||(n.status==="complete"?u.style.display="none":u.style.display="");let D=null;if(a){D=b("div","persona-flex persona-items-center");let be=oe(s?"chevron-up":"chevron-down",16,"currentColor",2);be?D.appendChild(be):D.textContent=s?"Hide":"Show";let De=b("div","persona-flex persona-items-center persona-ml-auto");De.append(D),c.append(d,De)}else c.append(d);let F=b("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 de=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:l,config:t??{}});oC(F,de)||(F.textContent=p),F.style.display=""}if(!s&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!a)return o.append(c,F),o;let j=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=s?"":"none";let O=n.chunks.join(""),q=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return q.textContent=O||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(q),(()=>{if(c.setAttribute("aria-expanded",s?"true":"false"),D){D.innerHTML="";let be=oe(s?"chevron-up":"chevron-down",16,"currentColor",2);be?D.appendChild(be):D.textContent=s?"Hide":"Show"}j.style.display=s?"":"none",F.style.display=s?"none":F.textContent||F.childNodes.length?"":"none"})(),o.append(c,F,j),o};var Xr=new Set,aC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),sC=(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
|
+
`);let r=Ao(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
45
|
+
`):""},Qp=(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)"},iC=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",a=sC(e,o?.previewMaxLines??3),s=n?Sm(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=bd(n,p.activeTextTemplate,c):!l&&p.completeTextTemplate&&(c=bd(n,p.completeTextTemplate,c)),{summary:c,previewText:a,isActive:l}},Qg=(e,t,n)=>{let o=Xr.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=oe(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")},Yp=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=b("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&&Xr.has(e.id),{summary:p,previewText:c,isActive:d}=iC(e,t),u=b("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=b("div","persona-flex persona-flex-col persona-text-left"),f=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let h=String(n.startedAt??Date.now()),A=()=>{let O=b("span","");return O.setAttribute("data-tool-elapsed",h),O.textContent=Fa(n),O},E=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:c,collapsedMode:a.collapsedMode??"tool-call",isActive:d,config:t??{},elapsed:Fa(n),createElapsedElement:A});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,S=o.completeTextTemplate,C=d?M:S,T=E instanceof HTMLElement,W=(O,q)=>{f.textContent="";let Q=n.name?.trim()||"tool",de=ii(O,Q),be=0;for(let De of de){let ie=De.styles.length>0?(()=>{let ge=b("span",De.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return f.appendChild(ge),ge})():f;if(De.isDuration&&d)ie.appendChild(A());else{let ge=De.isDuration?Fa(n):De.text;q?be=Po(ie,ge,be):ie.appendChild(document.createTextNode(ge))}}};if(!T)if(d&&k!=="none"){let O=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",`${O}ms`),C&&W(C,!1);else if(f.classList.add(`persona-tool-loading-${k}`),f.style.setProperty("--persona-tool-anim-duration",`${O}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)),C)W(C,!0);else{let q=f.textContent||p;f.textContent="",Po(f,q,0)}}else C&&W(C,!1);let w=null;if(s){w=b("div","persona-flex persona-items-center");let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",q=oe(l?"chevron-up":"chevron-down",16,O,2);q?w.appendChild(q):w.textContent=l?"Hide":"Show";let Q=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(w),u.append(g,Q)}else u.append(g);let D=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","tool"),D.style.display="none",D.style.whiteSpace="pre-wrap",!l&&d&&a.activePreview&&c){let O=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:c,isActive:d,config:t??{}});aC(D,O)||(D.textContent=c),D.style.display=""}if(!l&&d&&a.activeMinHeight&&(r.style.minHeight=a.activeMinHeight),!s)return r.append(u,D),r;let F=b("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 O=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?O.style.color=o.contentTextColor:o.headerTextColor&&(O.style.color=o.headerTextColor),O.textContent=n.name,F.appendChild(O)}if(n.args!==void 0){let O=b("div","persona-space-y-1"),q=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(q.style.color=o.labelTextColor),q.textContent="Arguments";let Q=b("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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Qp(Q,o),Q.textContent=Ao(n.args),O.append(q,Q),F.appendChild(O)}if(n.chunks&&n.chunks.length){let O=b("div","persona-space-y-1"),q=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(q.style.color=o.labelTextColor),q.textContent="Activity";let Q=b("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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Qp(Q,o),Q.textContent=n.chunks.join(""),O.append(q,Q),F.appendChild(O)}if(n.status==="complete"&&n.result!==void 0){let O=b("div","persona-space-y-1"),q=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(q.style.color=o.labelTextColor),q.textContent="Result";let Q=b("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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Qp(Q,o),Q.textContent=Ao(n.result),O.append(q,Q),F.appendChild(O)}if(n.status==="complete"&&typeof n.duration=="number"){let O=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(O.style.color=o.contentTextColor),O.textContent=`Duration: ${n.duration}ms`,F.appendChild(O)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),w){w.innerHTML="";let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",q=oe(l?"chevron-up":"chevron-down",16,O,2);q?w.appendChild(q):w.textContent=l?"Hide":"Show"}F.style.display=l?"":"none",D.style.display=l?"none":D.textContent||D.childNodes.length?"":"none"})(),r.append(u,D,F),r};var dr=new Map,il=e=>{let n=(e.startsWith(En)?e.slice(En.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)},Yg=e=>e?.approval!==!1?e?.approval:void 0,Zg=(e,t)=>{let n=Yg(t)?.detailsDisplay??"collapsed";return dr.get(e)??n==="expanded"},eh=(e,t,n)=>{let o=Yg(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=oe(t?"chevron-up":"chevron-down",14,"currentColor",2);s&&a.appendChild(s)}},th=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let a=Zg(e,n);eh(o,a,n),r.style.display=a?"":"none"};var ll=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",a=b("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=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=b("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=oe(p,20,c,2);d&&l.appendChild(d);let u=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),f=b("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 w=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");w.setAttribute("data-approval-status",n.status),n.status==="approved"?(w.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",w.style.color="var(--persona-palette-colors-success-700, #15803d)",w.textContent="Approved"):n.status==="denied"?(w.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",w.style.color="var(--persona-palette-colors-error-700, #b91c1c)",w.textContent="Denied"):n.status==="timeout"&&(w.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",w.style.color="var(--persona-palette-colors-warning-700, #b45309)",w.textContent="Timeout"),g.appendChild(w)}u.appendChild(g);let A=n.toolType==="webmcp"||n.toolName.startsWith(En)?Pa(n.toolName):void 0,E=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...A?{displayTitle:A}:{},...n.reason?{reason:n.reason}:{}}),k=!n.toolName,M=E||(k?n.description:`The assistant wants to use \u201C${A??il(n.toolName)}\u201D.`),S=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(S.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(S.style.color=o.descriptionColor),S.textContent=M,u.appendChild(S),n.reason){let w=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");w.setAttribute("data-approval-reason","true"),o?.reasonColor?w.style.color=o.reasonColor:o?.descriptionColor&&(w.style.color=o.descriptionColor);let D=b("span","persona-font-medium");D.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(D),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let C=o?.detailsDisplay??"collapsed",T=!!n.description&&!k,W=T||!!n.parameters;if(C!=="hidden"&&W){let w=Zg(e.id,t),D=b("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");D.type="button",D.setAttribute("data-expand-header","true"),D.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(D.style.color=o.descriptionColor);let F=b("span");F.setAttribute("data-approval-details-label","true");let j=b("span","persona-inline-flex persona-items-center");j.setAttribute("data-approval-details-chevron","true"),D.append(F,j),eh(D,w,t),u.appendChild(D);let O=b("div");if(O.setAttribute("data-approval-details","true"),O.style.display=w?"":"none",T){let q=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(q.style.color=o.descriptionColor),q.textContent=n.description,O.appendChild(q)}if(n.parameters){let q=b("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&&(q.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(q.style.color=o.parameterTextColor),q.style.fontSize="0.75rem",q.style.lineHeight="1rem",q.textContent=Ao(n.parameters),O.appendChild(q)}u.appendChild(O)}if(r){let w=b("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let D=b("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");D.type="button",D.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",D.style.color=o?.approveButtonTextColor??"#ffffff",D.setAttribute("data-approval-action","approve");let F=oe("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);F&&(F.style.marginRight="4px",D.appendChild(F));let j=document.createTextNode(o?.approveLabel??"Approve");D.appendChild(j);let O=b("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");O.type="button",O.style.backgroundColor=o?.denyButtonColor??"transparent",O.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",O.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,O.setAttribute("data-approval-action","deny");let q=oe("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);q&&(q.style.marginRight="4px",O.appendChild(q));let Q=document.createTextNode(o?.denyLabel??"Deny");O.appendChild(Q),w.append(D,O),u.appendChild(w)}return s.append(l,u),a.appendChild(s),a};function lC(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function nh(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??lC(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(),S=l?.()??null,C=S!=null?k.top+S:k.top,T=o==="top-start"||o==="top-end"?C-r-M.height:k.bottom+r,w=o==="bottom-end"||o==="top-end"?k.right-M.width:k.left,D=s?.()??null;if(D!=null){let F=Math.max(k.left,k.right-M.width);w=Math.min(Math.max(k.left+D,k.left),F)}n.style.top=`${T}px`,n.style.left=`${w}px`},A=()=>{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,S=()=>{if(!t.isConnected){A(),d?.("anchor-removed");return}h()},C=W=>{let w=typeof W.composedPath=="function"?W.composedPath():[];w.includes(n)||w.includes(t)||(A(),d?.("outside"))},T=k.setTimeout(()=>{M.addEventListener("pointerdown",C,!0)},0);k.addEventListener("scroll",S,!0),k.addEventListener("resize",S),f=()=>{k.clearTimeout(T),M.removeEventListener("pointerdown",C,!0),k.removeEventListener("scroll",S,!0),k.removeEventListener("resize",S)},c?.()};return{get isOpen(){return g},open:E,close:A,toggle:()=>g?A():E(),reposition:h,destroy:A}}function oh(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var dC=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),rh=(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))},cr=(e,t)=>{rh(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)},cC=e=>e?.approval!==!1?e?.approval:void 0,pC=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return dr.get(e)??n==="expanded"},Zp=e=>{let t=b("span","persona-approval-kbd");return t.textContent=e,t},uC=(e,t)=>{let n=b("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(En)?Pa(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??il(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},fC=e=>{let t=b("div","persona-approval-resolved"),n=oe("ban",15,"currentColor",2);n&&t.appendChild(n);let o=b("span","persona-approval-resolved-name");return o.textContent=e.toolName?il(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},mC=(e,t,n,o,r,a,s)=>{let l=b("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&&pC(t.id,o),f=o?.showDetailsLabel??"Show details",h=o?.hideDetailsLabel??"Hide details",A=b("button","persona-approval-head");A.type="button",u?(A.setAttribute("data-action","toggle-params"),A.setAttribute("aria-expanded",g?"true":"false"),A.setAttribute("aria-label",g?h:f)):A.setAttribute("data-static","true");let E=b("span","persona-approval-logo"),k=oe("shield-check",16,"currentColor",2);k&&E.appendChild(k),A.appendChild(E);let M=uC(n,o);if(u){let D=b("span","persona-approval-toggle");D.setAttribute("aria-hidden","true");let F=oe("chevron-down",14,"currentColor",2);F&&D.appendChild(F),M.append(" "),M.appendChild(D)}A.appendChild(M),l.appendChild(A);let S=b("div","persona-approval-body");if(u){let D=b("div","persona-approval-details");if(D.setAttribute("data-role","params"),D.hidden=!g,c){let F=b("p","persona-approval-desc");o?.descriptionColor&&(F.style.color=o.descriptionColor),F.textContent=n.description,D.appendChild(F)}if(d){let F=b("pre","persona-approval-params");o?.parameterBackgroundColor&&(F.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(F.style.color=o.parameterTextColor),F.textContent=Ao(n.parameters),D.appendChild(F)}S.appendChild(D)}if(n.reason){let D=b("p","persona-approval-reason");o?.reasonColor?D.style.color=o.reasonColor:o?.descriptionColor&&(D.style.color=o.descriptionColor);let F=b("span","persona-approval-reason-label");F.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,D.append(F,document.createTextNode(n.reason)),S.appendChild(D)}let C=b("div","persona-approval-actions"),T=null,W=D=>{o?.approveButtonColor&&(D.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(D.style.color=o.approveButtonTextColor)},w=b("button","persona-approval-deny");if(w.type="button",w.setAttribute("data-action","deny"),o?.denyButtonColor&&(w.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(w.style.color=o.denyButtonTextColor),w.append(o?.denyLabel??"Deny"),s){let D=b("div","persona-approval-split"),F=b("button","persona-approval-primary");F.type="button",F.setAttribute("data-action","always"),W(F),F.append(o?.approveLabel??"Always allow",Zp("\u23CE"));let j=b("button","persona-approval-caret");j.type="button",j.setAttribute("data-action","toggle-menu"),j.setAttribute("aria-label","More options"),W(j);let O=oe("chevron-down",15,"currentColor",2);O&&j.appendChild(O),D.append(F,j),C.append(D,w),w.append(Zp("Esc"));let q=b("div","persona-approval-menu"),Q=b("button","persona-approval-menu-item");Q.type="button",Q.append("Allow once",Zp("\u2318\u23CE")),q.appendChild(Q),T=nh({anchor:D,content:q,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,T),Q.addEventListener("click",()=>{cr(e,t.id),r()})}else{let D=b("button","persona-approval-primary persona-approval-primary--solo");D.type="button",D.setAttribute("data-action","allow"),W(D),D.append(o?.approveLabel??"Allow"),C.append(D,w)}return S.appendChild(C),l.appendChild(S),l.addEventListener("click",D=>{let F=D.target instanceof Element?D.target.closest("[data-action]"):null;if(!F)return;let j=F.getAttribute("data-action");if(j==="toggle-params"){let O=l.querySelector('[data-role="params"]');if(O){let q=O.hidden;O.hidden=!q,A.setAttribute("aria-expanded",q?"true":"false"),A.setAttribute("aria-label",q?h:f),dr.set(t.id,q)}return}if(j==="toggle-menu"){T?.toggle();return}if(j==="always"){cr(e,t.id),r({remember:!0});return}if(j==="allow"){cr(e,t.id),r();return}if(j==="deny"){cr(e,t.id),a();return}}),l},ah=()=>{let e=dC();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=cC(s);if(l.status!=="pending"){if(cr(e,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return fC(l)}rh(e,o.id);let c=p?.enableAlwaysAllow===!0,d=mC(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=>{oh(g)||o.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),cr(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()])cr(e,o);e.latestPendingApprovalId=null}}};var sh=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 A=b("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");A.type="button",A.textContent=h,A.disabled=g,p?.fontFamily&&(A.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(A.style.fontWeight=p.fontWeight),p?.paddingX&&(A.style.paddingLeft=p.paddingX,A.style.paddingRight=p.paddingX),p?.paddingY&&(A.style.paddingTop=p.paddingY,A.style.paddingBottom=p.paddingY),A.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(A),t.push(A)}),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 ns=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 os=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 gC=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),hC=new Set(["step_start","execution_start"]),yC=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),bC=new Set(["step_complete","agent_turn_complete"]),xC=new Set(["flow_complete","agent_complete"]),ih=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),dh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),un=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,pr=(e,t)=>{let n=e[t];return dh(n)?n:void 0};function eu(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function dl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function vC(e,t){return typeof t.type=="string"?t.type:e}function CC(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 wC(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 lh(e){let t=pr(e,"result"),n=[pr(e,"tokens"),pr(e,"totalTokens"),t?pr(t,"tokens"):void 0,pr(e,"usage"),t?pr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=un(o.output)??un(o.outputTokens)??un(o.completionTokens);if(r!==void 0)return r}return un(e.outputTokens)??un(e.completionTokens)??(t?un(t.outputTokens)??un(t.completionTokens):void 0)}function AC(e){let t=pr(e,"result");return un(e.executionTime)??un(e.executionTimeMs)??un(e.execution_time)??un(e.duration)??(t?un(t.executionTime)??un(t.executionTimeMs):void 0)}function SC(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var rs=class{constructor(t=SC){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:dl(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(!dh(n)){ih.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=vC(t,n),r=this.now();if(gC.has(o)){this.startRun(r);return}if(hC.has(o)){this.run||this.startRun(r);return}if(yC.has(o)){if(!wC(o,n))return;let a=CC(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+eu(s.visibleCharCount),p=r-s.firstDeltaAt;this.metric={status:"running",tokensPerSecond:dl(l,p),outputTokens:l,durationMs:p,source:s.exactOutputTokens>0?"usage":"estimate"};return}if(bC.has(o)){if(!this.run)return;let a=this.run,s=lh(n);s!==void 0&&(a.exactOutputTokens+=s,a.visibleCharCount=0);let l=a.exactOutputTokens>0,p=a.exactOutputTokens+eu(a.visibleCharCount),c=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:dl(p,c),outputTokens:p,durationMs:c,source:l?"usage":"estimate"};return}if(xC.has(o)){if(!this.run)return;let a=this.run,s=lh(n),l=s??a.exactOutputTokens+eu(a.visibleCharCount),p=s!==void 0||a.exactOutputTokens>0?"usage":"estimate",c=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:dl(l,c),outputTokens:l,durationMs:c,source:p},this.run=null;return}if(ih.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:AC(n)??o-t.startedAt}};function Jr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var MC={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)"}},TC={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},EC=["flowName","stepName","reasoningText","text","name","tool","toolName"],kC=100;function LC(e,t){let n={...MC,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return TC}function PC(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 IC(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 WC(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 HC(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 BC(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 FC(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=b("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=b("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 tu(e,t,n,o,r,a,s,l){let p=r.has(e.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");Jr(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=b("div",""),f=b("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=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),A=oe(p?"chevron-down":"chevron-right","14px","currentColor",2);A&&h.appendChild(A);let E=b("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"?PC(e.timestamp,n):RC(e.timestamp);let M=null;o.showSequenceNumbers!==!1&&(M=b("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 S=LC(e.type,o.badgeColors),C=b("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");C.style.backgroundColor=S.bg,C.style.color=S.text,C.style.borderColor=S.text+"50",C.textContent=e.type;let T=o.descriptionFields??EC,W=IC(e.payload,T),w=null;W&&(w=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=W);let D=b("div","persona-flex-1 persona-min-w-0"),F=b("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"),j=oe("clipboard","12px","currentColor",1.5);return j&&F.appendChild(j),F.addEventListener("click",async O=>{O.stopPropagation(),await WC(HC(e)),F.innerHTML="";let q=oe("check","12px","currentColor",1.5);q&&F.appendChild(q),setTimeout(()=>{F.innerHTML="";let Q=oe("clipboard","12px","currentColor",1.5);Q&&F.appendChild(Q)},1500)}),f.appendChild(h),f.appendChild(E),M&&f.appendChild(M),f.appendChild(C),w&&f.appendChild(w),f.appendChild(D),f.appendChild(F),g.appendChild(f),p&&g.appendChild(FC(e,s,l)),g}}function ch(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,A=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Jr(A,h?.panel);let E=[],k="",M="",S=null,C=[],T={},W=0,w=$i(),D=0,F=0,j=!1,O=null,q=!1,Q=0,de=new Set,be=new Map,De="",ie="",ge=null,ne,le,Z,me,Ae=null,we=null,Se=null;function mt(){let _=b("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),$=b("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(Jr($,h?.headerBar),s){we=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),we.style.cursor="help",Ae=b("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",Se=b("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"),Se.style.display="none",Se.style.pointerEvents="none";let Fe=we,Ht=Se,Sl=()=>{if(!Ht.textContent)return;let ms=Fe.getBoundingClientRect(),gs=_.getBoundingClientRect();Ht.style.left=`${ms.left-gs.left}px`,Ht.style.top=`${ms.bottom-gs.top+4}px`,Ht.style.display="block"},Do=()=>{Ht.style.display="none"};we.addEventListener("mouseenter",Sl),we.addEventListener("mouseleave",Do),we.appendChild(Ae)}let Y=b("div","persona-flex-1");ne=b("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 je=b("option","");je.value="",je.textContent="All events (0)",ne.appendChild(je),le=b("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 Qe=oe("clipboard-copy","12px","currentColor",1.5);Qe&&le.appendChild(Qe);let rt=b("span","persona-event-copy-all persona-text-xs");rt.textContent="Copy All",le.appendChild(rt),we&&$.appendChild(we),$.appendChild(Y),$.appendChild(ne),$.appendChild(le);let G=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Jr(G,h?.searchBar);let Ue=oe("search","14px","var(--persona-muted, #9ca3af)",1.5),he=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ue&&he.appendChild(Ue),Z=b("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"),Jr(Z,h?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",me=b("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"),me.type="button",me.style.display="none";let qe=oe("x","12px","currentColor",2);return qe&&me.appendChild(qe),G.appendChild(he),G.appendChild(Z),G.appendChild(me),_.appendChild($),_.appendChild(G),Se&&_.appendChild(Se),_}let We,_e=a.find(_=>_.renderEventStreamToolbar);_e?.renderEventStreamToolbar&&r?We=_e.renderEventStreamToolbar({config:r,defaultRenderer:()=>mt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:$=>{k=$,et(),ae()},onSearchChange:$=>{M=$,et(),ae()}})??mt():We=mt();let Xe=b("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");Xe.style.display="none";function $e(){if(!s||!Ae||!we)return;let _=s(),$=BC(_);Ae.textContent=$;let Y=DC(_);Se&&(Se.textContent=Y,Y||(Se.style.display="none")),we.setAttribute("aria-label",Y?`Throughput: ${$}, ${Y}`:`Throughput: ${$}`)}let Me=b("div","persona-flex-1 persona-min-h-0 persona-relative"),ke=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ke.style.height="100%";let Je=b("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");Jr(Je,h?.scrollIndicator),Je.style.display="none",Je.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false");let Dt=oe(c,"14px","currentColor",2);Dt&&Je.appendChild(Dt);let Wt=b("span","");Wt.textContent=d,Je.appendChild(Wt);let Kt=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Kt.style.display="none",Me.appendChild(ke),Me.appendChild(Kt),Me.appendChild(Je),A.setAttribute("tabindex","0"),A.appendChild(We),A.appendChild(Xe),A.appendChild(Me);function wt(){let _=t.getAll(),$={};for(let G of _)$[G.type]=($[G.type]||0)+1;let Y=Object.keys($).sort(),je=Y.length!==C.length||!Y.every((G,Ue)=>G===C[Ue]),Re=!je&&Y.some(G=>$[G]!==T[G]),Qe=_.length!==Object.values(T).reduce((G,Ue)=>G+Ue,0);if(!je&&!Re&&!Qe||(C=Y,T=$,!ne))return;let rt=ne.value;if(ne.options[0].textContent=`All events (${_.length})`,je){for(;ne.options.length>1;)ne.remove(1);for(let G of Y){let Ue=b("option","");Ue.value=G,Ue.textContent=`${G} (${$[G]||0})`,ne.appendChild(Ue)}rt&&Y.includes(rt)?ne.value=rt:rt&&(ne.value="",k="")}else for(let G=1;G<ne.options.length;G++){let Ue=ne.options[G];Ue.textContent=`${Ue.value} (${$[Ue.value]||0})`}}function He(){let _=t.getAll();if(k&&(_=_.filter($=>$.type===k)),M){let $=M.toLowerCase();_=_.filter(Y=>Y.type.toLowerCase().includes($)||Y.payload.toLowerCase().includes($))}return _}function ce(){return k!==""||M!==""}function et(){W=0,D=0,w.resume(),Je.style.display="none"}function Pe(_){de.has(_)?de.delete(_):de.add(_),ge=_;let $=ke.scrollTop,Y=w.isFollowing();q=!0,w.pause(),ae(),ke.scrollTop=$,Y&&w.resume(),q=!1}function ue(){return Wo(ke,50)}function ae(){F=Date.now(),j=!1,$e(),wt();let _=t.getEvictedCount();_>0?(Xe.textContent=`${_.toLocaleString()} older events truncated`,Xe.style.display=""):Xe.style.display="none",E=He();let $=E.length,Y=t.getSize()>0;$===0&&Y&&ce()?(Kt.textContent=M?`No events matching '${M}'`:"No events matching filter",Kt.style.display="",ke.style.display="none"):(Kt.style.display="none",ke.style.display=""),le&&(le.title=ce()?`Copy Filtered (${$})`:"Copy All"),p&&!w.isFollowing()&&$>W&&(D+=$-W,Wt.textContent=d?`${d}${D>0?` (${D})`:""}`:"",Je.style.display=""),W=$;let je=t.getAll(),Re=je.length>0?je[0].timestamp:0,Qe=new Set(E.map(Ue=>Ue.id));for(let Ue of de)Qe.has(Ue)||de.delete(Ue);let rt=k!==De||M!==ie,G=be.size===0&&E.length>0;if(rt||G||E.length===0){ke.innerHTML="",be.clear();let Ue=document.createDocumentFragment();for(let he=0;he<E.length;he++){let qe=tu(E[he],he,Re,u,de,Pe,a,r);be.set(E[he].id,qe),Ue.appendChild(qe)}ke.appendChild(Ue),De=k,ie=M,ge=null}else{if(ge!==null){let he=be.get(ge);if(he&&he.parentNode===ke){let qe=E.findIndex(Fe=>Fe.id===ge);if(qe>=0){let Fe=tu(E[qe],qe,Re,u,de,Pe,a,r);ke.insertBefore(Fe,he),he.remove(),be.set(ge,Fe)}}ge=null}let Ue=new Set(E.map(he=>he.id));for(let[he,qe]of be)Ue.has(he)||(qe.remove(),be.delete(he));for(let he=0;he<E.length;he++){let qe=E[he];if(!be.has(qe.id)){let Fe=tu(qe,he,Re,u,de,Pe,a,r);be.set(qe.id,Fe),ke.appendChild(Fe)}}}w.isFollowing()&&(ke.scrollTop=ke.scrollHeight)}function Le(){if(Date.now()-F>=kC){O!==null&&(cancelAnimationFrame(O),O=null),ae();return}j||(j=!0,O=requestAnimationFrame(()=>{O=null,ae()}))}let it=(_,$)=>{if(!le)return;le.innerHTML="";let Y=oe(_,"12px","currentColor",1.5);Y&&le.appendChild(Y);let je=b("span","persona-text-xs");je.textContent="Copy All",le.appendChild(je),setTimeout(()=>{le.innerHTML="";let Re=oe("clipboard-copy","12px","currentColor",1.5);Re&&le.appendChild(Re);let Qe=b("span","persona-text-xs");Qe.textContent="Copy All",le.appendChild(Qe),le.disabled=!1},$)},pe=async()=>{if(le){le.disabled=!0;try{let _;ce()?_=E:n?(_=await n(),_.length===0&&(_=t.getAll())):_=t.getAll();let $=_.map(Y=>{try{return JSON.parse(Y.payload)}catch{return Y.payload}});await navigator.clipboard.writeText(JSON.stringify($,null,2)),it("check",1500)}catch{it("x",1500)}}},ve=()=>{ne&&(k=ne.value,et(),ae())},ee=()=>{!Z||!me||(me.style.display=Z.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{M=Z.value,et(),ae()},150))},P=()=>{!Z||!me||(Z.value="",M="",me.style.display="none",S&&clearTimeout(S),et(),ae())},U=()=>{if(q)return;let _=ke.scrollTop,{action:$,nextLastScrollTop:Y}=ji({following:w.isFollowing(),currentScrollTop:_,lastScrollTop:Q,nearBottom:ue(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Q=Y,$==="resume"?(w.resume(),D=0,Je.style.display="none"):$==="pause"&&(w.pause(),p&&(Wt.textContent=d,Je.style.display=""))},x=_=>{let $=Gi({following:w.isFollowing(),deltaY:_.deltaY,nearBottom:ue(),resumeWhenNearBottom:!0});$==="pause"?(w.pause(),p&&(Wt.textContent=d,Je.style.display="")):$==="resume"&&(w.resume(),D=0,Je.style.display="none")},H=()=>{p&&(ke.scrollTop=ke.scrollHeight,w.resume(),D=0,Je.style.display="none")},R=_=>{let $=_.target;if(!$||$.closest("button"))return;let Y=$.closest("[data-event-id]");if(!Y)return;let je=Y.getAttribute("data-event-id");je&&Pe(je)},B=_=>{if((_.metaKey||_.ctrlKey)&&_.key==="f"){_.preventDefault(),Z?.focus(),Z?.select();return}_.key==="Escape"&&(Z&&document.activeElement===Z?(P(),Z.blur(),A.focus()):o&&o())};le&&le.addEventListener("click",pe),ne&&ne.addEventListener("change",ve),Z&&Z.addEventListener("input",ee),me&&me.addEventListener("click",P),ke.addEventListener("scroll",U),ke.addEventListener("wheel",x,{passive:!0}),ke.addEventListener("click",R),Je.addEventListener("click",H),A.addEventListener("keydown",B);function K(){S&&clearTimeout(S),O!==null&&(cancelAnimationFrame(O),O=null),j=!1,be.clear(),le&&le.removeEventListener("click",pe),ne&&ne.removeEventListener("change",ve),Z&&Z.removeEventListener("input",ee),me&&me.removeEventListener("click",P),ke.removeEventListener("scroll",U),ke.removeEventListener("wheel",x),ke.removeEventListener("click",R),Je.removeEventListener("click",H),A.removeEventListener("keydown",B)}return{element:A,update:Le,destroy:K}}}function ph(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 A=h===g;f.setAttribute("aria-selected",A?"true":"false"),f.tabIndex=A||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 uh(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=ee=>({start:ee===!1?!1:typeof ee=="object"&&ee?ee.start!==!1:!0,end:ee===!1?!1:typeof ee=="object"&&ee?ee.end!==!1:!0}),{start:d,end:u}=c(n?.tabFade),g=typeof document<"u"?b("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"),q?.hide()};g&&g.addEventListener("click",()=>{f(),t.onDismiss?.()});let h=b("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 A=b("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");A.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&A.classList.add("persona-artifact-toolbar-document");let E=b("span","persona-text-xs persona-font-medium persona-truncate");E.textContent=a;let k=Mt({icon:"x",label:s});k.addEventListener("click",()=>{f(),t.onDismiss?.()});let M="rendered",S=qr({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:ee=>{M=ee==="source"?"source":"rendered",it()}}),C=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),T=n?.documentToolbarShowCopyLabel===!0,W=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,D=!!(W&&w&&w.length>0),F=null,j,O=null,q=null;if(r&&(T||W)&&!D){if(j=T?Zn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let ee=oe("chevron-down",14,"currentColor",2);ee&&j.appendChild(ee)}}else r&&D?(F=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),j=T?Zn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),O=Mt({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(j,O)):r?j=Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(j=Mt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&j.classList.add("persona-hidden"));let Q=r?Mt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Mt({icon:"refresh-cw",label:"Refresh"}),de=r?Mt({icon:"x",label:s,className:"persona-artifact-doc-icon-btn"}):Mt({icon:"x",label:s}),be=Mt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&be.classList.add("persona-hidden");let De=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ie=e.features?.artifacts?.toolbarActions??[],ge=()=>{let ee=Me.find(H=>H.id===ke)??Me[Me.length-1],P=ee?.id??null,U=ee?.artifactType==="markdown"?ee.markdown??"":"",x=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"";return{markdown:U,jsonPayload:x,id:P}},ne=async()=>{let ee=Me.find(P=>P.id===ke)??Me[Me.length-1];try{await navigator.clipboard.writeText(Xa(ee))}catch{}};if(j.addEventListener("click",async()=>{let ee=n?.onDocumentToolbarCopyMenuSelect;if(ee&&D){let{markdown:P,jsonPayload:U,id:x}=ge();try{await ee({actionId:"primary",artifactId:x,markdown:P,jsonPayload:U})}catch{}return}await ne()}),O&&w?.length){let ee=()=>h.closest("[data-persona-root]")??document.body,P=()=>{q=Ro({items:w.map(U=>({id:U.id,label:U.label})),onSelect:async U=>{let{markdown:x,jsonPayload:H,id:R}=ge(),B=n?.onDocumentToolbarCopyMenuSelect;try{B?await B({actionId:U,artifactId:R,markdown:x,jsonPayload:H}):U==="markdown"||U==="md"?await navigator.clipboard.writeText(x):U==="json"||U==="source"?await navigator.clipboard.writeText(H):await navigator.clipboard.writeText(x||H)}catch{}},anchor:F??O,position:"bottom-right",portal:ee()})};h.isConnected?P():requestAnimationFrame(P),O.addEventListener("click",U=>{U.stopPropagation(),q?.toggle()})}Q.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}it()}),de.addEventListener("click",()=>{f(),t.onDismiss?.()});let le=b("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)A.replaceChildren(),F?C.append(F,Q,de):C.append(j,Q,de),C.insertBefore(De,de),C.insertBefore(be,de),A.append(S.element,le,C);else{let ee=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ee.append(j,De,be,k),A.appendChild(E),A.appendChild(ee)}l&&(A.style.paddingLeft=l,A.style.paddingRight=l);let Z=b("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&&Z.style.setProperty("--persona-artifact-tab-fade-size",p);let me=e.features?.artifacts?.renderTabBar,Ae=b("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),we=ph(Z,{onSelect:ee=>t.onSelect(Me[ee].id)}),Se=ee=>{let P=ee.scrollWidth-ee.clientWidth,U=P>1,x=Math.abs(ee.scrollLeft);ee.classList.toggle("persona-artifact-tab-fade-start",d&&U&&x>1),ee.classList.toggle("persona-artifact-tab-fade-end",u&&U&&x<P-1)},mt=0,We=()=>{if(mt)return;let ee=()=>{mt=0,Se(Z)};mt=typeof requestAnimationFrame=="function"?requestAnimationFrame(ee):setTimeout(ee,0)};Z.addEventListener("scroll",()=>We(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Se(Z)).observe(Z);let _e=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Xe=()=>{_e.scrollLeft=0},$e=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Xe):setTimeout(Xe,0)};if(l){for(let ee of[Z,Ae])ee.style.paddingLeft=l,ee.style.paddingRight=l;_e.style.padding=l}h.appendChild(A),h.appendChild(Z),h.appendChild(Ae),h.appendChild(_e);let Me=[],ke=null,Je=!1,Dt=!1,Wt=!0,Kt=!1,wt=null,He="",ce=null,et=!1,Pe=ee=>ee.artifactType==="markdown"&&!!ee.file||r?M:"rendered",ue=ee=>{r||(ee&&!et?(A.insertBefore(S.element,E),et=!0):!ee&&et&&(S.element.remove(),et=!1))},ae=()=>ke&&Me.find(ee=>ee.id===ke)||Me[Me.length-1],Le=()=>{let ee=Ga(ae());if(!ee){De.replaceChildren();return}let P=ie.filter(U=>U.visible===void 0||U.visible(ee)).map(U=>Vr(U,{documentChrome:r,onClick:()=>{let x=Ga(ae());if(x)try{Promise.resolve(U.onClick(x)).catch(()=>{})}catch{}}}));De.replaceChildren(...P)},it=()=>{Le();let ee=r&&Me.length<=1,P=!!me;if(Z.classList.toggle("persona-hidden",ee||P),Ae.classList.toggle("persona-hidden",ee||!P),P&&me){let H=Me.map(R=>R.id).join("|")+" "+(ke??"");if(H!==He){He=H;let R=me({records:Me,selectedId:ke,onSelect:t.onSelect});Ae.firstElementChild!==R&&Ae.replaceChildren(R)}}else{we.beforeRender(),Z.replaceChildren();let H=[],R=-1;for(let[B,K]of Me.entries()){let _=b("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 $=K.artifactType==="markdown"?K.file:void 0,Y=$?Dn($.path):K.title||K.id.slice(0,8),je=$?.path||K.title||Y;_.textContent=Y,_.title=je,_.setAttribute("aria-label",je),K.id===ke&&(_.classList.add("persona-bg-persona-container","persona-border-persona-border"),R=B),_.addEventListener("click",()=>t.onSelect(K.id)),Z.appendChild(_),H.push(_)}if(we.render(H,R),R>=0&&ke!==wt){wt=ke;let B=H[R];typeof B.scrollIntoView=="function"&&B.scrollIntoView({block:"nearest",inline:"nearest"})}Se(Z)}let U=ke&&Me.find(H=>H.id===ke)||Me[Me.length-1];if(!U){_e.replaceChildren(),ce=null,ue(!1);return}let x=U.artifactType==="markdown"?U.file:void 0;if(ue(!!x),r){let H=x?Lo(x):U.artifactType==="markdown"?"MD":U.component??"Component",R=(U.title||"Document").trim(),B=x?Dn(x.path):R.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${B} \xB7 ${H}`}else E.textContent=x?Dn(x.path):a;ce?(ce.el.parentElement!==_e&&_e.replaceChildren(ce.el),ce.update(U)):(ce=Vi(U,{config:e,resolveViewMode:Pe}),_e.replaceChildren(ce.el)),_e.classList.toggle("persona-artifact-content-flush",!!_e.querySelector(".persona-code-pre"))},pe=()=>{let ee=Me.length>0;if(h.classList.toggle("persona-hidden",!ee),g){let x=((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;ee&&x&&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"))}},ve=()=>{Kt=!1,it(),pe()};return{element:h,backdrop:g,update(ee){let P=ee.selectedId??ee.artifacts[ee.artifacts.length-1]?.id??null,U=P!==ke;Me=ee.artifacts,ke=P,Me.length>0&&(Je=!0),Kt=!0,Wt&&ve(),U&&Xe()},setMobileOpen(ee){Je=ee,!ee&&g?(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):pe()},setExpanded(ee){ee!==Dt&&(Dt=ee,$e());let P=oe(ee?"minimize":"maximize",16,"currentColor",2);P&&be.replaceChildren(P);let U=ee?"Collapse artifacts panel":"Expand artifacts panel";be.setAttribute("aria-label",U),be.title=U},setExpandToggleVisible(ee){be.classList.toggle("persona-hidden",!ee)},setCopyButtonVisible(ee){r||j.classList.toggle("persona-hidden",!ee)},setCustomActions(ee){ie=ee,Le()},setTabFade(ee){let P=c(ee);P.start===d&&P.end===u||(d=P.start,u=P.end,Se(Z))},setRenderTabBar(ee){ee!==me&&(me=ee,He="",it())},setVisible(ee){ee!==Wt&&(Wt=ee,ee&&Kt&&ve())}}}function Zt(e){return e?.features?.artifacts?.enabled===!0}function fh(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"),!Zt(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 OC(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 mh=["panel","seamless","detached"];function nu(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&mh.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function ou(e){return!e||!Zt(e)?!1:nu(e)==="detached"}function as(e,t){if(!Zt(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"),OC(e),fh(e,t);return}let n=t.features?.artifacts?.layout,o=nu(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"),fh(e,t)}function ss(e,t){for(let l of mh)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"),!Zt(t))return;let n=t.features?.artifacts?.layout,o=nu(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 gh(e,t){return!t||!Zt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var NC=new Set(["__proto__","prototype","constructor"]),_C=new Set(["collapsed","card","panel","inline"]),hh=new Set(["markdown","component"]),UC=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,ur=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pl=e=>!NC.has(e),ru=e=>typeof e=="string"&&_C.has(e),fr=e=>Object.keys(e).length>0;function On(e,t,n,o){e.push({path:t,code:n,message:o})}var qC="Ignored because this key is not part of the persisted preference schema.",cl="Ignored an unsupported value.",VC="Expected collapsed, panel, or inline.",zC='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',yh={kind:"mode",message:cl},Qr={kind:"string",message:"Expected a CSS length string."},to={kind:"boolean"},$C={paneWidth:Qr,paneMaxWidth:Qr,paneMinWidth:Qr,expandedPanelWidth:Qr,resizableMinWidth:Qr,resizableMaxWidth:Qr,expandLauncherPanelWhenOpen:to,resizable:to},jC={kind:"object",message:"Expected a preference object.",children:{showToolCalls:to,showReasoning:to,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:cl},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:cl},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:cl},expandable:to,grouped:to}},reasoningDisplay:{kind:"object",children:{expandable:to,activePreview:to}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:yh,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:yh,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:hh,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:hh}}},filePreview:{kind:"object",children:{enabled:to}},layout:{kind:"object",children:$C}}}}};function bh(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:On(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:On(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:On(o,n,"invalid_value",t.message);case"mode":return ru(e)?on(e):On(o,n,"invalid_value",t.message);case"modeMap":{if(!ur(e))return On(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,a={};for(let[s,l]of Object.entries(e)){let p=r?s:bo(s);pl(s)&&(r?r.has(s):UC.test(p))?ru(l)?a[p]=on(l):On(o,`${n}.${s}`,"invalid_value",VC):On(o,`${n}.${s}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":zC)}return fr(a)?a:void 0}case"object":{if(t.bareMode&&ru(e))return on(e);if(!ur(e))return On(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),a=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!pl(l)||!r.includes(l))&&On(o,a(l),"unknown_key",qC);let s={};for(let l of r){let p=t.children[l],c=bh(e[l],p,a(l),o);if(p.deprecated&&e[l]!==void 0&&On(o,a(l),"deprecated_key",p.deprecated),c===void 0)continue;let d=p.alias??l,u=s[d];s[d]=ur(u)&&ur(c)?{...u,...c}:c}return fr(s)?s:void 0}}}function au(e){let t=[];return{preferences:(e===null?void 0:bh(e,jC,"",t))??{},issues:t}}function Yr(e){if(Array.isArray(e))return e.map(Yr);if(!ur(e))return e;let t={};for(let[n,o]of Object.entries(e))pl(n)&&o!==void 0&&(t[n]=Yr(o));return t}function xh(e,t){let n=Yr(e);for(let[o,r]of Object.entries(t)){if(!pl(o)||r===void 0)continue;let a=n[o];n[o]=ur(a)&&ur(r)?xh(a,r):Yr(r)}return n}function GC(e){let t={},n;for(let r of e){let a=au(r).preferences;n=vh(n,a.artifacts?.display),t=xh(t,a)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function KC(e,t){if(t===void 0)return e===void 0?void 0:Yr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},a={...o?{default:o}:{},...fr(r)?{byMediaType:r}:{}};return fr(a)?a:void 0}function vh(e,t){if(t===void 0)return e===void 0?void 0:Yr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},a=KC(n.files,t.files),s={...o?{default:o}:{},...fr(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return fr(s)?s:void 0}function su(e={},t){let n=GC(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},a={...r};if(n.artifacts.display!==void 0){let s=vh(r.display,n.artifacts.display);s!==void 0&&(a.display=s)}n.artifacts.filePreview&&(a.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(a.layout={...r.layout,...n.artifacts.layout}),o.artifacts=a}return o}function is(e){let t=e.preferences;return!t||!fr(t)?e:{...e,features:su(e.features??{},[t])}}function XC(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 JC(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 QC(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function YC(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function iu(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 Ch(e,t,n,o,r,a){let s=XC(r,200),l=YC(t,n,o,200);l=Math.max(s,l);let p=JC(a);return p!==null&&(l=Math.min(l,p)),QC(e,s,l)}var wh={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"}},lu=(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=wh[s]??wh.init;a.classList.add("persona-form-card","persona-space-y-4");let p=b("div","persona-space-y-1"),c=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=l.title,p.appendChild(c),l.description){let h=b("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 A=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${t.id}-${s}-${h.name}`;let E=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=h.label,A.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),A.appendChild(M),d.appendChild(A)});let u=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=b("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 A=n.formEndpoint??"/form",E=new FormData(d),k={};E.forEach((M,S)=>{k[S]=M}),k.type=s,f.disabled=!0,g.textContent="Submitting\u2026";try{let M=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let S=await M.json();g.textContent=S.message??"Thanks! We'll be in touch soon.",S.success&&S.nextPrompt&&await o.sendMessage(String(S.nextPrompt))}catch(M){g.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var du=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()}},ls=new du;var Ah=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ZC=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),Sh=(e,t,n)=>{if(!Ah(e)||!Ah(t)||ZC.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]=Sh(e[r],t[r],a)}return o};function ul(e,t){let n=Sh(e,t,"");return Or(n)}var Mh=()=>{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 ew=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},tw=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},ds=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=ew(e),n=tw(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}},cu=e=>typeof e=="string"?e:e==null?"":String(e),mr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:cu(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=cu(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:cu(n.text)}}},Th=e=>Array.isArray(e)?e.map(t=>String(t)):[],cs=e=>{let t=new Set(Th(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Th(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 nw=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}},ow=e=>e.map(t=>({...t,streaming:!1})),rw=e=>e.map(t=>({...t,status:"complete"})),fl=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?nw(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?ow(n.messages):void 0,artifacts:n.artifacts?rw(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=ho(Ys(),1);function aw(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function sw(e,t){if(!aw(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 ml(){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=sw(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 gl(e,t){let{config:n,message:o,onPropsUpdate:r}=t,a=Ln.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 kh(){let e=ml();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Lh(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 ps(e){let t=Lh(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 hl(e){let t=Lh(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 iw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function yl(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=iw}=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 A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=r,f.appendChild(A),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 W=1;W<=5;W++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${c[W-1]}`),w.title=c[W-1],w.dataset.rating=String(W),w.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
|
-
`,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 sl(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((ie,le)=>{ie.classList.toggle("selected",le===D),ie.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 jr="persona-chat-history",PC=30*1e3,RC=641,IC={"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 WC(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=IC[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 il(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 HC(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 BC(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Kp=e=>!e||typeof e!="object"?{}:{...e},lh=e=>e.map(t=>({...t,streaming:!1})),dh=(e,t,n)=>{let o=e?.markdown?jo(e.markdown):null,r=Ar(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?Wf(s):s,u=o(c);d=r&&p?r(u):u}else d=In(s);return d}};function ch(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 DC=(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},FC=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:DC(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),ll=(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=Ir(t),r=Ya.getForInstance(o.plugins),{plugin:a,teardown:s}=qg();o.components&&En.registerAll(o.components);let l=oh(),d=o.persistState===!1?null:o.storageAdapter??tl(),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=Kp(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})??{},Tl()},L=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Za],E=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[lr.message,lr.messageAndClick],M=es({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,ie=!1,le=null,Ce=()=>{ie=!0,le&&clearTimeout(le),le=setTimeout(()=>{ie&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ie=!1)},1e4)},Ie=dh(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 Ka(Ae):null,Be=o.features?.eventStream?.maxEvents??2e3,Oe=Z?new Ga(Be,xe):null,ze=Z?new Xa:null,Ne=null,rt=!1,Je=null,We=0;xe?.open().then(()=>Oe?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Me={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)}},Qe=o.statusIndicator??{},cn=i=>i==="idle"?Qe.idleText??Wt.idle:i==="connecting"?Qe.connectingText??Wt.connecting:i==="connected"?Qe.connectedText??Wt.connected:i==="error"?Qe.errorText??Wt.error:i==="paused"?Qe.pausedText??Wt.paused:i==="resuming"?Qe.resumingText??Wt.resuming:Wt[i];function Tt(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 yt=Eg({config:o,showClose:D()}),{wrapper:He,panel:fe,pillRoot:Ke}=yt.shell,Ee=yt.panelElements,{container:pe,body:se,messagesWrapper:ge,suggestions:xt,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:je}=Ee,Te=Ee.leftActions,at=Ee.setSendButtonMode,K=Ee.micButton,qe=Ee.micButtonWrapper,we=Ee.attachmentButton,Re=Ee.attachmentButtonWrapper,ke=Ee.attachmentInput,Ye=Ee.attachmentPreviewsContainer;pe.classList.add("persona-relative"),se.classList.add("persona-relative");let Po=12,Ro=()=>de.label??"",ul=()=>de.iconName??"arrow-down",rs=()=>de.enabled!==!1,$t=()=>Y.mode??"anchor-top",Qn=()=>$t()==="follow"||$t()==="anchor-top"&&oa,cu=()=>Y.anchorTopOffset??16,Xh=()=>Y.restorePosition??"bottom",pu=()=>Y.pauseOnInteraction===!0,uu=()=>Y.showActivityWhilePinned!==!1,fu=()=>Y.announce===!0,Lt=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");Lt.type="button",Lt.style.display="none",Lt.setAttribute("data-persona-scroll-to-bottom","true");let Kr=x("span","persona-flex persona-items-center"),fl=x("span",""),Io=x("span","");Io.setAttribute("data-persona-scroll-to-bottom-count",""),Io.style.display="none",Lt.append(Kr,fl,Io),pe.appendChild(Lt);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",se.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 Xr=null,as=null,mu=i=>{!fu()||!i||(as=i,Xr===null&&(Xr=setTimeout(()=>{Xr=null,as&&fu()&&(Wo.textContent=as),as=null},400)))},dr=()=>{let m=j.style.display==="none"?0:j.offsetHeight;Lt.style.bottom=`${m+Po}px`};dr();let gu=()=>{let i=!!Ro();Lt.setAttribute("aria-label",Ro()||"Jump to latest"),Lt.title=Ro(),Lt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Kr.innerHTML="";let m=te(ul(),"14px","currentColor",2);m?(Kr.appendChild(m),Kr.style.display=""):Kr.style.display="none",fl.textContent=Ro(),fl.style.display=i?"":"none"};gu();let wt=null,nn=null,hu=null,yu=r.find(i=>i.renderHeader);if(yu?.renderHeader){let i=yu.renderHeader({config:o,defaultRenderer:()=>{let m=Jn({config:o,showClose:D()});return or(pe,m,o),m.header},onClose:()=>ct(!1,"user")});if(i){let m=pe.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(i),_=i,yt.header.element=i)}}let ml=()=>{if(!Oe)return;if(rt=!0,!Ne&&Oe&&(Ne=Gg({buffer:Oe,getFullHistory:()=>Oe.getAllFromStore(),onClose:()=>Jr(),config:o,plugins:r,getThroughput:()=>ze?.getMetric()??{status:"idle"}})),Ne&&(se.style.display="none",j.parentNode?.insertBefore(Ne.element,j),Ne.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Jt.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-We>=200&&(Ne?.update(),We=m),Je=requestAnimationFrame(i)};We=0,Je=requestAnimationFrame(i),rn(),l.emit("eventStream:opened",{timestamp:Date.now()})},Jr=()=>{if(rt){if(rt=!1,Ne&&Ne.element.remove(),se.style.display="",tt){tt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(m=>m&&tt.classList.remove(m))}Je!==null&&(cancelAnimationFrame(Je),Je=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=Jt.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=Ee.clearChatButtonWrapper,k=Ee.closeButtonWrapper,W=v||k;W&&W.parentNode===_?_.insertBefore(tt,W):_.appendChild(tt),tt.addEventListener("click",()=>{rt?Jr():ml()})}let Jh=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)}},xu=r.find(i=>i.renderComposer);if(xu?.renderComposer){let i=o.composer,m=xu.renderComposer({config:o,defaultRenderer:()=>_r({config:o}).footer,onSubmit:y=>{if(!$||$.isStreaming())return;let v=y.trim(),k=wt?.hasAttachments()??!1;if(!v&&!k)return;Ku();let W;k&&(W=[],W.push(...wt.getContentParts()),v&&W.push(bo(v))),$.sendMessage(v,{contentParts:W}),k&&wt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ke?.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?()=>{hu?.()}:void 0});m&&(yt.replaceComposer(m),j=yt.composer.footer)}let Qh=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,qe=W.parentElement),J&&(R=J);let V=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(xt=V);let X=m("[data-persona-composer-attachment-button]",".persona-attachment-button");X&&(we=X,Re=X.parentElement),ke=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Ye=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),Te=m(".persona-widget-composer__left-actions")};Jh(j),Qh(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&&xt&&!q()&&(xt.style.maxWidth=Zn,xt.style.marginLeft="auto",xt.style.marginRight="auto"),Zn&&Ye&&!q()&&(Ye.style.maxWidth=Zn,Ye.style.marginLeft="auto",Ye.style.marginRight="auto"),o.attachments?.enabled&&ke&&Ye){wt=Zo.fromConfig(o.attachments),wt.setPreviewsContainer(Ye),ke.addEventListener("change",y=>{let v=y.target;wt?.handleFileSelect(v.files),v.value=""});let i=o.attachments.dropOverlay,m=ch(i);pe.appendChild(m)}let Yh=()=>nn?.prefetch();if(o.contextMentions?.enabled&&he&&(nn=Om({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];Te?Te.insertBefore(v,Te.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 xt;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=se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");W?W.replaceWith(k):se.insertBefore(k,se.firstChild);break}case"body-bottom":se.appendChild(k);break;case"footer-top":xt.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 bu=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")qr.has(k)?qr.delete(k):qr.add(k),Wg(k,v);else if(W==="tool")Vr.has(k)?Vr.delete(k):Vr.add(k),Hg(k,v,o);else if(W==="approval"){let V=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",X=ar.get(k)??V;ar.set(k,!X),Og(k,v,o)}Fo.delete(k)};ge.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),bu(i))}),ge.addEventListener("keydown",i=>{let m=i.target;(i.key==="Enter"||i.key===" ")&&m.closest('button[data-expand-header="true"]')&&(i.preventDefault(),bu(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=dg(k);!W||W===k||(m.setData("text/plain",W),i.preventDefault())});let gl=new Map,vu=null,Cu="idle",Zh={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},ey=(i,m)=>{let{icon:y,label:v}=Zh[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))},wu=()=>{ge.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{let v=m.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;ey(m,v&&v===vu?Cu:"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&&Me.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)}),Me.onCopy(V)}}else if(W==="read-aloud")$.toggleReadAloud(k);else if(W==="upvote"||W==="downvote"){let V=(gl.get(k)??null)===W,X=W==="upvote"?"thumbs-up":"thumbs-down";if(V){gl.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))}gl.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 $e=$.getMessages().find(pt=>pt.id===k);$e&&Me.onFeedback&&Me.onFeedback({type:W,messageId:$e.id,message:$e})}}}),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 Ze=null,Qr=null,Yr=()=>{},Zr="none",ss=null,xn={artifacts:[],selectedId:null},Dn=!1,bn=!1,ea=!1,cr=!1,Au=()=>cr||xn.artifacts.some(i=>Go(o.features?.artifacts,i.artifactType)==="panel"),is=()=>xn.artifacts.length>0&&!Dn&&Au(),lt={current:null},hl=(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}=hl(y,v);if(!W)return;let{filename:X,mime:oe,content:ue}=$m({title:J,markdown:W,file:V}),ne=new Blob([ue],{type:oe}),be=URL.createObjectURL(ne),$e=document.createElement("a");$e.href=be,$e.download=X,$e.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(pt=>pt.id===v);if(!X)return;let{markdown:oe,title:ue,file:ne,artifactType:be}=hl(y,J??""),$e={artifactId:J,title:ue,artifactType:be,markdown:oe,file:ne};try{Promise.resolve(X.onClick($e)).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=_a(k);else{let{markdown:J,file:V,artifactType:X}=hl(y,v);X==="markdown"&&(W=_a({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,cr=!0,bn=!0,ea=!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,cr=!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 pr=Ee.composerOverlay,ur=(i,m,y)=>{let v=m.trim();if(!v||!lt.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(pr,k);let J=lt.current.getMessages().find(V=>V.toolCall?.id===k);J?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(J,y.structured??v):lt.current.sendMessage(v)},Ho=i=>{let m=lt.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:zs(i,v),currentIndex:hn(i)})},Su=i=>Object.entries(i).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),yl=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let m=hn(i),y=Tr(i);if(m>=y-1)return;let v=lt.current?.getMessages().find(k=>k.toolCall?.id===i.getAttribute("data-tool-call-id"));v&&($s(i,v,o,m+1),Ho(i))};pr.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(pr,W);let J=lt.current?.getMessages().find(V=>V.toolCall?.id===W);J?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(J),lt.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=Ko(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),yl(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=Zl(v).length===0);return}ur(v,W,{source:"pick",values:[W]});return}if(k==="submit-multi"){let W=Zl(v);if(W.length===0)return;ur(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),yl(v);return}ur(v,J,{source:"free-text"});return}if(k==="next"||k==="back"){if(!lt.current)return;let W=v.getAttribute("data-tool-call-id")??"",J=lt.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=Ko(v)[hn(v)];(typeof ne!="string"||ne!==X)&&ho(v,X)}let oe=k==="next"?1:-1,ue=hn(v)+oe;$s(v,J,o,ue),Ho(v);return}if(k==="submit-all"){if(!lt.current)return;let W=v.getAttribute("data-tool-call-id")??"",J=lt.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=zs(v,J);lt.current.persistAskUserQuestionProgress(J,{answers:oe,currentIndex:hn(v)});let ue=Su(oe);ur(v,ue||"(submitted)",{source:"submit-all",structured:oe});return}if(k==="skip"){if(!lt.current)return;let W=v.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(be=>be.toolCall?.id===W);if(!J)return;let V=mo(v),X=hn(v),oe=Tr(v),ue=X>=oe-1;if(!V){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:W},bubbles:!0,composed:!0})),go(pr,W),J.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(J),lt.current.resolveAskUserQuestion(J,"(dismissed)"));return}ho(v,"");let ne=v.querySelector('[data-ask-free-text-input="true"]');if(ne&&(ne.value=""),ue){let be=zs(v,J),$e=Su(be);ur(v,$e||"(skipped)",{source:"submit-all",structured:be});return}$s(v,J,o,X+1),Ho(v);return}}),pr.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),yl(v);return}ur(v,k,{source:"free-text"})}});let Mu=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=pr.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",Mu);let eo=null,bt=null,ta=null,ls=null,xl=()=>{},Tu=!1,ds="",cs="";function bl(){ls?.(),ls=null}let Eu=()=>{if(!eo||!bt)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){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let v=eo.firstElementChild;if(!v||v===bt)return;let k=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${k}px`,bt.style.zIndex="5";let W=zp(eo,m),J=v.offsetWidth+W/2-k/2;bt.style.left=`${Math.max(0,J)}px`},ps=()=>{},ty=()=>{let i=e.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640;return!m||i.innerWidth>y?!1:A||kt(o)},us=()=>!Qt(o)||!is()||e.classList.contains("persona-artifact-narrow-host")||ty()||(e.ownerDocument.defaultView??window).innerWidth<RC?"none":Vp(o)?"detached":"welded",Fn=()=>{if(!Ze||!Qt(o))return;Ja(e,o),Qa(e,o),ps();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=is();Ze.setVisible(y),Ze.update(xn),Dn?(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),bn=!1,ea=!1):xn.artifacts.length>0&&Au()?(Ze.element.classList.remove("persona-hidden"),Ze.setMobileOpen(!0)):(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),bn=!1,ea=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ze.setExpandToggleVisible(v),Ze.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ze.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ze.setTabFade(o.features?.artifacts?.layout?.tabFade),Ze.setRenderTabBar(o.features?.artifacts?.renderTabBar),!v&&!ea&&(bn=!1),bn!==Tu){let W=Ze.element;bn?(ds=W.style.width,cs=W.style.maxWidth,W.style.removeProperty("width"),W.style.removeProperty("max-width")):(ds&&(W.style.width=ds),cs&&(W.style.maxWidth=cs),ds="",cs=""),Tu=bn}e.classList.toggle("persona-artifact-expanded",bn),Ze.setExpanded(bn);let k=us();k!==Zr&&(Zr=k,Yr()),xl()};if(Qt(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),Ze=Xg(o,{onSelect:y=>lt.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||(ea=!1),Fn())}}),Ze.element.classList.add("persona-hidden"),eo=m,m.appendChild(i),m.appendChild(Ze.element),Ze.backdrop&&fe.appendChild(Ze.backdrop),fe.appendChild(m),xl=()=>{if(!eo||!Ze)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){ta?.(),ta=null,bl(),bt&&(bt.remove(),bt=null),Ze.element.style.removeProperty("width"),Ze.element.style.removeProperty("maxWidth");return}if(!bt){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(!Ze||V.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||W.innerWidth<=640)return;V.preventDefault(),bl();let X=V.clientX,oe=Ze.element.getBoundingClientRect().width,ue=o.features?.artifacts?.layout,ne=$e=>{let pt=eo.getBoundingClientRect().width,nt=e.classList.contains("persona-artifact-welded-split"),an=zp(eo,W),At=nt?0:v.getBoundingClientRect().width||6,Rt=oe-($e.clientX-X),O=Zg(Rt,pt,an,At,ue?.resizableMinWidth,ue?.resizableMaxWidth);Ze.element.style.width=`${O}px`,Ze.element.style.maxWidth="none",Eu()},be=()=>{k.removeEventListener("pointermove",ne),k.removeEventListener("pointerup",be),k.removeEventListener("pointercancel",be),ls=null;try{v.releasePointerCapture(V.pointerId)}catch{}};ls=be,k.addEventListener("pointermove",ne),k.addEventListener("pointerup",be),k.addEventListener("pointercancel",be);try{v.setPointerCapture(V.pointerId)}catch{}};v.addEventListener("pointerdown",J),bt=v,eo.insertBefore(v,Ze.element),ta=()=>{v.removeEventListener("pointerdown",J)}}if(bt){let v=is();bt.classList.toggle("persona-hidden",!v),Eu()}},ps=()=>{if(!A||!Ze||(o.launcher?.sidebarMode??!1)||kt(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||!Yg(o,A))return;let J=o.launcher?.width??o.launcherWidth??ln,V=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";is()?(fe.style.width=V,fe.style.maxWidth=V):(fe.style.width=J,fe.style.maxWidth=J)},typeof ResizeObserver<"u"&&(Qr=new ResizeObserver(()=>{Fn()}),Qr.observe(fe))}else fe.appendChild(pe);q()&&Ke&&(Ee.peekBanner&&Ke.appendChild(Ee.peekBanner),Ke.appendChild(j)),e.appendChild(He),Ke&&e.appendChild(Ke);let fs=()=>{if(q()){fe.style.width="100%",fe.style.maxWidth="100%";let Et=o.launcher?.composerBar??{},en=He.dataset.state==="expanded",Rs=Et.expandedSize??"anchored";if(!(en&&Rs!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let ya=o.theme?.components?.panel,Is=wo(o),vr=(Un,$o)=>Un==null||Un===""?$o:Xt(Is,Un)??Un,Ws="1px solid var(--persona-border)",Ul="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",zo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=vr(ya?.border,Ws),pe.style.borderRadius=vr(ya?.borderRadius,zo),pe.style.boxShadow=vr(ya?.shadow,Ul),pe.style.overflow="hidden";return}let i=kt(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=(Et,en)=>Et==null||Et===""?en:Xt(J,Et)??Et,X=e.ownerDocument.defaultView??window,oe=o.launcher?.mobileFullscreen??!0,ue=o.launcher?.mobileBreakpoint??640,ne=X.innerWidth<=ue,be=oe&&ne&&A,$e=i&&oe&&ne,pt=o.launcher?.position??"bottom-left",nt=pt==="bottom-left"||pt==="top-left",an=o.launcher?.zIndex??zt,At="var(--persona-panel-border, 1px solid var(--persona-border))",Rt="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))",Le=k&&!be&&!$e;Le?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let _e=Le?At:m||be?"none":At,Se=Le?Rt: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":Rt;i&&!be&&!Le&&(Se="none",_e="none");let St=Le?O:m||be?"0":O,ut=V(W?.border,_e),Gt=V(W?.shadow,Se),ft=V(W?.borderRadius,St),Zt=us(),It=Zt==="detached",Pe=Zt==="welded";e.classList.toggle("persona-artifact-detached-split",It),e.classList.toggle("persona-artifact-welded-split",Pe);let Ue="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)))))",Ct=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Qt(o)&&Vp(o)&&v&&!i;e.classList.toggle("persona-artifact-chat-flush",Ct);let dt=It||Ct?"none":Gt,mt=It?At:Pe?"none":ut,et=It?O:ft;Ct&&(mt="none",et="0");let De=W?.borderRadius!=null&&W.borderRadius!=="",ht=Ct&&!De?"0":ft,Ut=se.scrollTop;e.style.cssText="",He.style.cssText="",fe.style.cssText="",pe.style.cssText="",se.style.cssText="",j.style.cssText="",rt&&(se.style.display="none"),(y||v)&&(e.style.minWidth="0");let gn=()=>{if(Ut<=0)return;(se.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(se.scrollTop===Ut)return;let en=se.scrollHeight-se.clientHeight;en<=0||(se.scrollTop=Math.min(Ut,en))})};if(be){He.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"),He.style.cssText=`
|
|
49
|
+
`,w.addEventListener("click",()=>{u=W,k.forEach((D,F)=>{let j=F<W;D.classList.toggle("selected",j),D.setAttribute("aria-checked",F===W-1?"true":"false")})}),k.push(w),E.appendChild(w)}g.appendChild(E);let M=null;if(p){let W=document.createElement("div");W.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"),W.appendChild(M),g.appendChild(W)}let S=document.createElement("div");S.className="persona-feedback-actions";let C=document.createElement("button");C.type="button",C.className="persona-feedback-btn persona-feedback-btn-skip",C.textContent=l,C.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 W=M?.value.trim()||void 0;await t(u,W),d.remove()}catch(W){T.disabled=!1,T.textContent=s,console.error("[CSAT Feedback] Failed to submit:",W)}}),S.appendChild(C),S.appendChild(T),g.appendChild(S),d.appendChild(g),d}function bl(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 A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=o,h.appendChild(A);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 S=document.createElement("span");S.className="persona-feedback-label-low",S.textContent=c;let C=document.createElement("span");C.className="persona-feedback-label-high",C.textContent=d,M.appendChild(S),M.appendChild(C);let T=document.createElement("div");T.className="persona-feedback-numbers";let W=[];for(let O=0;O<=10;O++){let q=document.createElement("button");q.type="button",q.className="persona-feedback-rating-btn persona-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${O} out of 10`),q.textContent=String(O),q.dataset.rating=String(O),O<=6?q.classList.add("persona-feedback-detractor"):O<=8?q.classList.add("persona-feedback-passive"):q.classList.add("persona-feedback-promoter"),q.addEventListener("click",()=>{g=O,W.forEach((Q,de)=>{Q.classList.toggle("selected",de===O),Q.setAttribute("aria-checked",de===O?"true":"false")})}),W.push(q),T.appendChild(q)}k.appendChild(M),k.appendChild(T),f.appendChild(k);let w=null;if(p){let O=document.createElement("div");O.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=a,w.rows=3,w.setAttribute("aria-label","Additional comments"),O.appendChild(w),f.appendChild(O)}let D=document.createElement("div");D.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 j=document.createElement("button");return j.type="button",j.className="persona-feedback-btn persona-feedback-btn-submit",j.textContent=s,j.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}j.disabled=!0,j.textContent="Submitting...";try{let O=w?.value.trim()||void 0;await t(g,O),u.remove()}catch(O){j.disabled=!1,j.textContent=s,console.error("[NPS Feedback] Failed to submit:",O)}}),D.appendChild(F),D.appendChild(j),f.appendChild(D),u.appendChild(f),u}var ea="persona-chat-history",lw=30*1e3,dw=641,cw={"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 pw(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=cw[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 xl(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 uw(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 fw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var pu=e=>!e||typeof e!="object"?{}:{...e},Ph=e=>e.map(t=>({...t,streaming:!1})),Rh=(e,t,n)=>{let o=e?.markdown?Qo(e.markdown):null,r=Lr(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=Gn()!==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?Jf(s):s,u=o(d);c=r&&p?r(u):u}else c=Hn(s);return c}};function Ih(e){let t=b("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=oe(n,o,r,a);if(s&&t.appendChild(s),e?.label){let l=b("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var mw=(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},gw=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:mw(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),vl=(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=Or(t),r=o.features;o=is(o);let a=ls.getForInstance(o.plugins),{plugin:s,teardown:l}=ah();o.components&&Ln.registerAll(o.components);let p=Mh(),d=o.persistState===!1?null:o.storageAdapter??fl(),u={},g=null,f=!1,h=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&&(f=!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")g=i.then(m=>h(m??{messages:[],metadata:{}}));else{let y=h(i??{messages:[],metadata:{}});y.metadata&&(u=pu(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=h({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let A=()=>u,E=i=>{u=i({...u})??{},Ol()},k=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ds],M=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[mr.message,mr.messageAndClick],S=cs({parsers:k,handlers:M,getSessionMetadata:A,updateSessionMetadata:E,emit:p.emit,documentRef:typeof document<"u"?document:null});S.syncFromMetadata();let C=o.launcher?.enabled??!0,T=o.launcher?.autoExpand??!1,W=o.autoFocusInput??!1,w=T,D=C,F=o.layout?.header?.layout,j=!1,O=()=>Bo(o),q=()=>C||O(),Q=O()?!1:C?T:!0,de=!1,be=null,De=()=>{de=!0,be&&clearTimeout(be),be=setTimeout(()=>{de&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),de=!1)},1e4)},ie=Rh(o,S,De),ge=o.features?.showReasoning??!0,ne=o.features?.showToolCalls??!0,le=o.features?.showEventStreamToggle??!1,Z=o.features?.scrollToBottom??{},me=o.features?.scrollBehavior??{},we=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Se=le?new os(we):null,mt=o.features?.eventStream?.maxEvents??2e3,We=le?new ns(mt,Se):null,_e=le?new rs:null,Xe=null,$e=!1,Me=null,ke=0;Se?.open().then(()=>We?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Je={onCopy:i=>{p.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=>{p.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)}},Dt=o.statusIndicator??{},Wt=i=>i==="idle"?Dt.idleText??It.idle:i==="connecting"?Dt.connectingText??It.connecting:i==="connected"?Dt.connectedText??It.connected:i==="error"?Dt.errorText??It.error:i==="paused"?Dt.pausedText??It.paused:i==="resuming"?Dt.resumingText??It.resuming:It[i];function Kt(i,m,y,v){if(v==="idle"&&y.idleLink){i.textContent="";let L=document.createElement("a");L.href=y.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=m,L.style.color="inherit",L.style.textDecoration="none",i.appendChild(L)}else i.textContent=m}let wt=zg({config:o,showClose:q()}),{wrapper:He,panel:ce,pillRoot:et}=wt.shell,Pe=wt.panelElements,{container:ue,body:ae,messagesWrapper:Le,suggestions:it,textarea:pe,sendButton:ve,sendButtonWrapper:ee,composerForm:P,statusText:U,introTitle:x,introSubtitle:H,closeButton:R,iconHolder:B,headerTitle:K,headerSubtitle:_,header:$,footer:Y,actionsRow:je,rightActions:Re}=Pe,Qe=Pe.leftActions,rt=Pe.setSendButtonMode,G=Pe.micButton,Ue=Pe.micButtonWrapper,he=Pe.attachmentButton,qe=Pe.attachmentButtonWrapper,Fe=Pe.attachmentInput,Ht=Pe.attachmentPreviewsContainer;ue.classList.add("persona-relative"),ae.classList.add("persona-relative");let Sl=12,Do=()=>Z.label??"",ms=()=>Z.iconName??"arrow-down",gs=()=>Z.enabled!==!1,fn=()=>me.mode??"anchor-top",no=()=>fn()==="follow"||fn()==="anchor-top"&&pa,Eu=()=>me.anchorTopOffset??16,yy=()=>me.restorePosition??"bottom",ku=()=>me.pauseOnInteraction===!0,Lu=()=>me.showActivityWhilePinned!==!1,Pu=()=>me.announce===!0,kt=b("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");kt.type="button",kt.style.display="none",kt.setAttribute("data-persona-scroll-to-bottom","true");let na=b("span","persona-flex persona-items-center"),Ml=b("span",""),Fo=b("span","");Fo.setAttribute("data-persona-scroll-to-bottom-count",""),Fo.style.display="none",kt.append(na,Ml,Fo),ue.appendChild(kt);let oo=b("div","persona-stream-anchor-spacer");oo.setAttribute("aria-hidden","true"),oo.setAttribute("data-persona-anchor-spacer",""),oo.style.flexShrink="0",oo.style.pointerEvents="none",oo.style.height="0px",ae.appendChild(oo);let Oo=b("div","persona-sr-only");Oo.setAttribute("aria-live","polite"),Oo.setAttribute("aria-atomic","true"),Oo.setAttribute("role","status"),Oo.setAttribute("data-persona-live-region",""),Object.assign(Oo.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(Oo);let oa=null,hs=null,Ru=i=>{!Pu()||!i||(hs=i,oa===null&&(oa=setTimeout(()=>{oa=null,hs&&Pu()&&(Oo.textContent=hs),hs=null},400)))},gr=()=>{let m=Y.style.display==="none"?0:Y.offsetHeight;kt.style.bottom=`${m+Sl}px`};gr();let Iu=()=>{let i=!!Do();kt.setAttribute("aria-label",Do()||"Jump to latest"),kt.title=Do(),kt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),na.innerHTML="";let m=oe(ms(),"14px","currentColor",2);m?(na.appendChild(m),na.style.display=""):na.style.display="none",Ml.textContent=Do(),Ml.style.display=i?"":"none"};Iu();let At=null,an=null,Wu=null,Hu=a.find(i=>i.renderHeader);if(Hu?.renderHeader){let i=Hu.renderHeader({config:o,defaultRenderer:()=>{let m=eo({config:o,showClose:q()});return ir(ue,m,o),m.header},onClose:()=>ct(!1,"user")});if(i){let m=ue.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(i),$=i,wt.header.element=i)}}let Tl=()=>{if(!We)return;if($e=!0,!Xe&&We&&(Xe=ch({buffer:We,getFullHistory:()=>We.getAllFromStore(),onClose:()=>ra(),config:o,plugins:a,getThroughput:()=>_e?.getMetric()??{status:"idle"}})),Xe&&(ae.style.display="none",Y.parentNode?.insertBefore(Xe.element,Y),Xe.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Yt.actionIconColor}`;let m=o.features?.eventStream?.classNames?.toggleButtonActive;m&&m.split(/\s+/).forEach(y=>y&&tt.classList.add(y))}let i=()=>{if(!$e)return;let m=Date.now();m-ke>=200&&(Xe?.update(),ke=m),Me=requestAnimationFrame(i)};ke=0,Me=requestAnimationFrame(i),ln(),p.emit("eventStream:opened",{timestamp:Date.now()})},ra=()=>{if($e){if($e=!1,Xe&&Xe.element.remove(),ae.style.display="",tt){tt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(m=>m&&tt.classList.remove(m))}Me!==null&&(cancelAnimationFrame(Me),Me=null),ln(),p.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(le){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=b("button",m),tt.style.width="28px",tt.style.height="28px",tt.style.color=Yt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let y=oe("activity","18px","currentColor",1.5);y&&tt.appendChild(y);let v=Pe.clearChatButtonWrapper,L=Pe.closeButtonWrapper,I=v||L;I&&I.parentNode===$?$.insertBefore(tt,I):$.appendChild(tt),tt.addEventListener("click",()=>{$e?ra():Tl()})}let by=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=b("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 L=i.querySelector("[data-persona-composer-form]");L?.parentNode?L.parentNode.insertBefore(y,L):i.insertBefore(y,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let L=b("input");L.type="file",L.setAttribute("data-persona-composer-attachment-input",""),L.accept=(m.allowedTypes??Yn).join(","),L.multiple=(m.maxFiles??4)>1,L.style.display="none",L.setAttribute("aria-label",m.buttonTooltipText??"Attach files"),i.appendChild(L)}},Bu=a.find(i=>i.renderComposer);if(Bu?.renderComposer){let i=o.composer,m=Bu.renderComposer({config:o,defaultRenderer:()=>jr({config:o}).footer,onSubmit:y=>{if(!z||z.isStreaming())return;let v=y.trim(),L=At?.hasAttachments()??!1;if(!v&&!L)return;uf();let I;L&&(I=[],I.push(...At.getContentParts()),v&&I.push(Mo(v))),z.sendMessage(v,{contentParts:I}),L&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Fe?.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?()=>{Wu?.()}:void 0});m&&(wt.replaceComposer(m),Y=wt.composer.footer)}let xy=i=>{let m=(...fe)=>{for(let re of fe){let xe=i.querySelector(re);if(xe)return xe}return null},y=i.querySelector("[data-persona-composer-form]"),v=i.querySelector("[data-persona-composer-input]"),L=i.querySelector("[data-persona-composer-submit]"),I=i.querySelector("[data-persona-composer-mic]"),J=i.querySelector("[data-persona-composer-status]");y&&(P=y),v&&(pe=v),L&&(ve=L),I&&(G=I,Ue=I.parentElement),J&&(U=J);let V=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(it=V);let X=m("[data-persona-composer-attachment-button]",".persona-attachment-button");X&&(he=X,qe=X.parentElement),Fe=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Ht=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(je=se),Qe=m(".persona-widget-composer__left-actions")};by(Y),xy(Y);let ro=o.layout?.contentMaxWidth??(O()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(ro&&(Le.style.maxWidth=ro,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%"),ro&&P&&!O()&&(P.style.maxWidth=ro,P.style.marginLeft="auto",P.style.marginRight="auto"),ro&&it&&!O()&&(it.style.maxWidth=ro,it.style.marginLeft="auto",it.style.marginRight="auto"),ro&&Ht&&!O()&&(Ht.style.maxWidth=ro,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),o.attachments?.enabled&&Fe&&Ht){At=or.fromConfig(o.attachments),At.setPreviewsContainer(Ht),Fe.addEventListener("change",y=>{let v=y.target;At?.handleFileSelect(v.files),v.value=""});let i=o.attachments.dropOverlay,m=Ih(i);ue.appendChild(m)}let vy=()=>an?.prefetch();if(o.contextMentions?.enabled&&pe&&(an=tg({config:o,textarea:pe,anchor:P??pe,getMessages:()=>z.getMessages(),liveRegionHost:ue}),an)){let i=pe;i.parentElement?.insertBefore(an.contextRow,i);let m=an.affordanceButtons;for(let y=m.length-1;y>=0;y--){let v=m[y];Qe?Qe.insertBefore(v,Qe.firstChild):P?.appendChild(v)}}(()=>{let i=o.layout?.slots??{},m=v=>{switch(v){case"body-top":return ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Le;case"footer-top":return it;case"composer":return P;case"footer-bottom":return U;default:return null}},y=(v,L)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")$.insertBefore(L,$.firstChild);else if(v==="header-right")$.appendChild(L);else{let I=$.querySelector(".persona-flex-col");I?I.parentNode?.insertBefore(L,I.nextSibling):$.appendChild(L)}break;case"body-top":{let I=ae.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");I?I.replaceWith(L):ae.insertBefore(L,ae.firstChild);break}case"body-bottom":ae.appendChild(L);break;case"footer-top":it.replaceWith(L);break;case"footer-bottom":U.replaceWith(L);break;default:break}};for(let[v,L]of Object.entries(i))if(L)try{let I=L({config:o,defaultContent:()=>m(v)});I&&y(v,I)}catch(I){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,I)}})();let Du=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 L=v.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-bubble-type");if(I==="reasoning")Kr.has(L)?Kr.delete(L):Kr.add(L),Jg(L,v);else if(I==="tool")Xr.has(L)?Xr.delete(L):Xr.add(L),Qg(L,v,o);else if(I==="approval"){let V=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",X=dr.get(L)??V;dr.set(L,!X),th(L,v,o)}qo.delete(L)};Le.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Du(i))}),Le.addEventListener("keydown",i=>{let m=i.target;(i.key==="Enter"||i.key===" ")&&m.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Du(i))}),Le.addEventListener("copy",i=>{let{clipboardData:m}=i;if(!m)return;let y=Le.getRootNode(),v=typeof y.getSelection=="function"?y.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let L=v.toString(),I=Tg(L);!I||I===L||(m.setData("text/plain",I),i.preventDefault())});let El=new Map,Fu=null,Ou="idle",Cy={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},wy=(i,m)=>{let{icon:y,label:v}=Cy[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 L=oe(y,14,"currentColor",2);L&&(i.innerHTML="",i.appendChild(L))},Nu=()=>{Le.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{let v=m.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;wy(m,v&&v===Fu?Ou:"idle")})};Le.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 L=v.getAttribute("data-actions-for");if(!L)return;let I=y.getAttribute("data-action");if(I==="copy"){let V=z.getMessages().find(X=>X.id===L);if(V&&Je.onCopy){let X=V.content||"";navigator.clipboard.writeText(X).then(()=>{y.classList.add("persona-message-action-success");let se=oe("check",14,"currentColor",2);se&&(y.innerHTML="",y.appendChild(se)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let fe=oe("copy",14,"currentColor",2);fe&&(y.innerHTML="",y.appendChild(fe))},2e3)}).catch(se=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",se)}),Je.onCopy(V)}}else if(I==="read-aloud")z.toggleReadAloud(L);else if(I==="upvote"||I==="downvote"){let V=(El.get(L)??null)===I,X=I==="upvote"?"thumbs-up":"thumbs-down";if(V){El.delete(L),y.classList.remove("persona-message-action-active");let se=oe(X,14,"currentColor",2);se&&(y.innerHTML="",y.appendChild(se))}else{let se=I==="upvote"?"downvote":"upvote",fe=v.querySelector(`[data-action="${se}"]`);if(fe){fe.classList.remove("persona-message-action-active");let nt=oe(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(fe.innerHTML="",fe.appendChild(nt))}El.set(L,I),y.classList.add("persona-message-action-active");let re=oe(X,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(re)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let ze=z.getMessages().find(pt=>pt.id===L);ze&&Je.onFeedback&&Je.onFeedback({type:I,messageId:ze.id,message:ze})}}}),Le.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 L=v.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-approval-action");if(!I)return;let J=I==="approve"?"approved":"denied",X=z.getMessages().find(fe=>fe.id===L);if(!X?.approval)return;let se=v.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),X.approval.toolType==="webmcp"?z.resolveWebMcpApproval(L,J):z.resolveApproval(X.approval,J)});let Ye=null,aa=null,sa=()=>{},ia="none",ys=null,vn={artifacts:[],selectedId:null},_n=!1,Cn=!1,la=!1,hr=!1,_u=()=>hr||vn.artifacts.some(i=>Bn(o.features?.artifacts,i)==="panel"),bs=()=>vn.artifacts.length>0&&!_n&&_u(),lt={current:null},kl=(i,m)=>{let y=z.getArtifactById(m),v=y?.markdown,L=y?.title||"artifact",I=y?.file,J=y?.artifactType??"markdown";if(!v){let se=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(se){let re=z.getMessages().find(xe=>xe.id===se);if(re?.rawContent)try{let xe=JSON.parse(re.rawContent);v=xe?.props?.markdown,L=xe?.props?.title||L,xe?.props?.file&&typeof xe.props.file=="object"&&(I=xe.props.file),!y&&typeof xe?.props?.artifactType=="string"&&(J=xe.props.artifactType)}catch{}}}return{markdown:v,title:L,file:I,artifactType:J}};Le.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:I,title:J,file:V}=kl(y,v);if(!I)return;let{filename:X,mime:se,content:fe}=lg({title:J,markdown:I,file:V}),re=new Blob([fe],{type:se}),xe=URL.createObjectURL(re),ze=document.createElement("a");ze.href=xe,ze.download=X,ze.click(),URL.revokeObjectURL(xe)}),Le.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 L=y.closest("[data-artifact-inline]"),I=L?null:y.closest("[data-open-artifact]"),J=L?L.getAttribute("data-artifact-inline"):I?.getAttribute("data-open-artifact")??null,X=(L?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(pt=>pt.id===v);if(!X)return;let{markdown:se,title:fe,file:re,artifactType:xe}=kl(y,J??""),ze={artifactId:J,title:fe,artifactType:xe,markdown:se,file:re};try{Promise.resolve(X.onClick(ze)).catch(()=>{})}catch{}}),Le.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 L=z.getArtifactById(v),I="";if(L)I=Xa(L);else{let{markdown:J,file:V,artifactType:X}=kl(y,v);X==="markdown"&&(I=Xa({id:v,artifactType:"markdown",status:"complete",markdown:J??"",...V?{file:V}:{}}))}I&&navigator.clipboard.writeText(I).then(()=>{let J=oe("check",16,"currentColor",2);J&&(y.replaceChildren(J),setTimeout(()=>{let V=oe("copy",16,"currentColor",2);V&&y.replaceChildren(V)},1500))}).catch(()=>{})}),Le.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||(_n=!1,hr=!0,Cn=!0,la=!0,z.selectArtifact(v),Un())}),Le.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(),_n=!1,hr=!0,z.selectArtifact(v),Un())}),Le.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 yr=Pe.composerOverlay,br=(i,m,y)=>{let v=m.trim();if(!v||!lt.current)return;let L=i.getAttribute("data-tool-call-id")??"",I=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:L,answer:v,answers:y.structured,values:y.values??(y.source==="multi"?v.split(", "):[v]),isFreeText:I,source:y.source},bubbles:!0,composed:!0})),Co(yr,L);let J=lt.current.getMessages().find(V=>V.toolCall?.id===L);J?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(J,y.structured??v):lt.current.sendMessage(v)},No=i=>{let m=lt.current;if(!m)return;let y=i.getAttribute("data-tool-call-id")??"",v=m.getMessages().find(L=>L.toolCall?.id===y);v&&m.persistAskUserQuestionProgress(v,{answers:ei(i,v),currentIndex:xn(i)})},Uu=i=>Object.entries(i).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Ll=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let m=xn(i),y=Ir(i);if(m>=y-1)return;let v=lt.current?.getMessages().find(L=>L.toolCall?.id===i.getAttribute("data-tool-call-id"));v&&(ti(i,v,o,m+1),No(i))};yr.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 L=y.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),L==="dismiss"){let I=v.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:I},bubbles:!0,composed:!0})),Co(yr,I);let J=lt.current?.getMessages().find(V=>V.toolCall?.id===I);J?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(J),lt.current?.resolveAskUserQuestion(J,"(dismissed)"));return}if(L==="pick"){let I=y.getAttribute("data-option-label");if(!I)return;let J=v.getAttribute("data-multi-select")==="true",V=vo(v);if(V&&J){let X=Yo(v)[xn(v)],se=new Set(Array.isArray(X)?X:[]);se.has(I)?se.delete(I):se.add(I),wo(v,Array.from(se)),No(v);return}if(V){wo(v,I),No(v),Ll(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 se=v.querySelector('[data-ask-user-action="submit-multi"]');se&&(se.disabled=ud(v).length===0);return}br(v,I,{source:"pick",values:[I]});return}if(L==="submit-multi"){let I=ud(v);if(I.length===0)return;br(v,I.join(", "),{source:"multi",values:I});return}if(L==="open-free-text"){let I=v.querySelector('[data-ask-free-text-row="true"]');I&&(I.classList.remove("persona-hidden"),I.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(L==="focus-free-text"){v.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(L==="submit-free-text"){let J=v.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!J.trim())return;if(vo(v)){wo(v,J.trim()),No(v),Ll(v);return}br(v,J,{source:"free-text"});return}if(L==="next"||L==="back"){if(!lt.current)return;let I=v.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(re=>re.toolCall?.id===I);if(!J)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(X){let re=Yo(v)[xn(v)];(typeof re!="string"||re!==X)&&wo(v,X)}let se=L==="next"?1:-1,fe=xn(v)+se;ti(v,J,o,fe),No(v);return}if(L==="submit-all"){if(!lt.current)return;let I=v.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(re=>re.toolCall?.id===I);if(!J)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";X&&wo(v,X);let se=ei(v,J);lt.current.persistAskUserQuestionProgress(J,{answers:se,currentIndex:xn(v)});let fe=Uu(se);br(v,fe||"(submitted)",{source:"submit-all",structured:se});return}if(L==="skip"){if(!lt.current)return;let I=v.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(xe=>xe.toolCall?.id===I);if(!J)return;let V=vo(v),X=xn(v),se=Ir(v),fe=X>=se-1;if(!V){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:I},bubbles:!0,composed:!0})),Co(yr,I),J.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(J),lt.current.resolveAskUserQuestion(J,"(dismissed)"));return}wo(v,"");let re=v.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),fe){let xe=ei(v,J),ze=Uu(xe);br(v,ze||"(skipped)",{source:"submit-all",structured:xe});return}ti(v,J,o,X+1),No(v);return}}),yr.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 L=y.value;if(L.trim()){if(vo(v)){wo(v,L.trim()),No(v),Ll(v);return}br(v,L,{source:"free-text"})}});let qu=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=yr.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),I=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];I&&(i.preventDefault(),I.click())};document.addEventListener("keydown",qu);let ao=null,bt=null,da=null,xs=null,Pl=()=>{},Vu=!1,vs="",Cs="";function Rl(){xs?.(),xs=null}let zu=()=>{if(!ao||!bt)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){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let v=ao.firstElementChild;if(!v||v===bt)return;let L=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${L}px`,bt.style.zIndex="5";let I=iu(ao,m),J=v.offsetWidth+I/2-L/2;bt.style.left=`${Math.max(0,J)}px`},ws=()=>{},Ay=()=>{let i=e.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640;return!m||i.innerWidth>y?!1:C||Et(o)},As=()=>!Zt(o)||!bs()||e.classList.contains("persona-artifact-narrow-host")||Ay()||(e.ownerDocument.defaultView??window).innerWidth<dw?"none":ou(o)?"detached":"welded",Un=()=>{if(!Ye||!Zt(o))return;as(e,o),ss(e,o),ws();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,m=ce.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=i);let y=bs();Ye.setVisible(y),Ye.update(vn),_n?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),Cn=!1,la=!1):vn.artifacts.length>0&&_u()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),Cn=!1,la=!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&&!la&&(Cn=!1),Cn!==Vu){let I=Ye.element;Cn?(vs=I.style.width,Cs=I.style.maxWidth,I.style.removeProperty("width"),I.style.removeProperty("max-width")):(vs&&(I.style.width=vs),Cs&&(I.style.maxWidth=Cs),vs="",Cs=""),Vu=Cn}e.classList.toggle("persona-artifact-expanded",Cn),Ye.setExpanded(Cn);let L=As();L!==ia&&(ia=L,sa()),Pl()};if(Zt(o)){ce.style.position="relative";let i=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(ue),Ye=uh(o,{onSelect:y=>lt.current?.selectArtifact(y),onDismiss:()=>{_n=!0,Un()},onToggleExpand:()=>{let y=!Cn,v=vn.selectedId??vn.artifacts[vn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:v,expanded:y})!==!0&&(Cn=y,y||(la=!1),Un())}}),Ye.element.classList.add("persona-hidden"),ao=m,m.appendChild(i),m.appendChild(Ye.element),Ye.backdrop&&ce.appendChild(Ye.backdrop),ce.appendChild(m),Pl=()=>{if(!ao||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){da?.(),da=null,Rl(),bt&&(bt.remove(),bt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!bt){let v=b("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 L=e.ownerDocument,I=L.defaultView??window,J=V=>{if(!Ye||V.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||I.innerWidth<=640)return;V.preventDefault(),Rl();let X=V.clientX,se=Ye.element.getBoundingClientRect().width,fe=o.features?.artifacts?.layout,re=ze=>{let pt=ao.getBoundingClientRect().width,nt=e.classList.contains("persona-artifact-welded-split"),dn=iu(ao,I),St=nt?0:v.getBoundingClientRect().width||6,Pt=se-(ze.clientX-X),N=Ch(Pt,pt,dn,St,fe?.resizableMinWidth,fe?.resizableMaxWidth);Ye.element.style.width=`${N}px`,Ye.element.style.maxWidth="none",zu()},xe=()=>{L.removeEventListener("pointermove",re),L.removeEventListener("pointerup",xe),L.removeEventListener("pointercancel",xe),xs=null;try{v.releasePointerCapture(V.pointerId)}catch{}};xs=xe,L.addEventListener("pointermove",re),L.addEventListener("pointerup",xe),L.addEventListener("pointercancel",xe);try{v.setPointerCapture(V.pointerId)}catch{}};v.addEventListener("pointerdown",J),bt=v,ao.insertBefore(v,Ye.element),da=()=>{v.removeEventListener("pointerdown",J)}}if(bt){let v=bs();bt.classList.toggle("persona-hidden",!v),zu()}},ws=()=>{if(!C||!Ye||(o.launcher?.sidebarMode??!1)||Et(o)&&rn(o).reveal==="emerge")return;let v=e.ownerDocument.defaultView??window,L=o.launcher?.mobileFullscreen??!0,I=o.launcher?.mobileBreakpoint??640;if(L&&v.innerWidth<=I||!gh(o,C))return;let J=o.launcher?.width??o.launcherWidth??pn,V=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";bs()?(ce.style.width=V,ce.style.maxWidth=V):(ce.style.width=J,ce.style.maxWidth=J)},typeof ResizeObserver<"u"&&(aa=new ResizeObserver(()=>{Un()}),aa.observe(ce))}else ce.appendChild(ue);O()&&et&&(Pe.peekBanner&&et.appendChild(Pe.peekBanner),et.appendChild(Y)),e.appendChild(He),et&&e.appendChild(et);let Ss=()=>{if(O()){ce.style.width="100%",ce.style.maxWidth="100%";let Tt=o.launcher?.composerBar??{},nn=He.dataset.state==="expanded",qs=Tt.expandedSize??"anchored";if(!(nn&&qs!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Ma=o.theme?.components?.panel,Vs=ko(o),Tr=($n,Jo)=>$n==null||$n===""?Jo:Qt(Vs,$n)??$n,zs="1px solid var(--persona-border)",Zl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Xo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Tr(Ma?.border,zs),ue.style.borderRadius=Tr(Ma?.borderRadius,Xo),ue.style.boxShadow=Tr(Ma?.shadow,Zl),ue.style.overflow="hidden";return}let i=Et(o),m=o.launcher?.sidebarMode??!1,y=i||m||(o.launcher?.fullHeight??!1),v=o.launcher?.enabled===!1,L=o.launcher?.detachedPanel===!0,I=o.theme?.components?.panel,J=ko(o),V=(Tt,nn)=>Tt==null||Tt===""?nn:Qt(J,Tt)??Tt,X=e.ownerDocument.defaultView??window,se=o.launcher?.mobileFullscreen??!0,fe=o.launcher?.mobileBreakpoint??640,re=X.innerWidth<=fe,xe=se&&re&&C,ze=i&&se&&re,pt=o.launcher?.position??"bottom-left",nt=pt==="bottom-left"||pt==="top-left",dn=o.launcher?.zIndex??Gt,St="var(--persona-panel-border, 1px solid var(--persona-border))",Pt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",N="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Te=L&&!xe&&!ze;Te?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Oe=Te?St:m||xe?"none":St,Ce=Te?Pt:xe?"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":Pt;i&&!xe&&!Te&&(Ce="none",Oe="none");let Ct=Te?N:m||xe?"0":N,ut=V(I?.border,Oe),Ft=V(I?.shadow,Ce),ft=V(I?.borderRadius,Ct),tn=As(),Rt=tn==="detached",Ee=tn==="welded";e.classList.toggle("persona-artifact-detached-split",Rt),e.classList.toggle("persona-artifact-welded-split",Ee);let Ne="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)))))",vt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Zt(o)&&ou(o)&&v&&!i;e.classList.toggle("persona-artifact-chat-flush",vt);let dt=Rt||vt?"none":Ft,gt=Rt?St:Ee?"none":ut,Ze=Rt?N:ft;vt&&(gt="none",Ze="0");let Ie=I?.borderRadius!=null&&I.borderRadius!=="",yt=vt&&!Ie?"0":ft,zt=ae.scrollTop;e.style.cssText="",He.style.cssText="",ce.style.cssText="",ue.style.cssText="",ae.style.cssText="",Y.style.cssText="",$e&&(ae.style.display="none"),(y||v)&&(e.style.minWidth="0");let bn=()=>{if(zt<=0)return;(ae.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ae.scrollTop===zt)return;let nn=ae.scrollHeight-ae.clientHeight;nn<=0||(ae.scrollTop=Math.min(zt,nn))})};if(xe){He.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"),He.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 Ia=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: ${dn} !important;
|
|
60
60
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
61
|
-
`,
|
|
61
|
+
`,ce.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 Ia=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
|
+
`,ue.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 Ia=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
|
+
`,ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",Y.style.flexShrink="0",j=!0,bn();return}let Us=o?.launcher?.width??o?.launcherWidth??pn;if(!m&&!i)v&&y?(ce.style.width="100%",ce.style.maxWidth="100%"):(ce.style.width=Us,ce.style.maxWidth=Us);else if(i)if(rn(o).reveal==="emerge"&&!L){let nn=rn(o).width;ce.style.width=nn,ce.style.maxWidth=nn}else ce.style.width="100%",ce.style.maxWidth="100%";if(ws(),ce.style.boxShadow=dt,ce.style.borderRadius=yt,Rt?ce.style.border="none":Ee&&(ce.style.border=ut),ue.style.border=gt,ue.style.borderRadius=Ze,ue.style.boxShadow=Rt&&!vt?Ne:"",vt&&(ue.style.background="transparent",ae.style.background="transparent",Y.style.background="transparent",Y.style.borderTop="none"),Ee){let Tt=o.features?.artifacts?.layout;ys=Tt?.unifiedSplitOuterRadius?.trim()||Tt?.paneBorderRadius?.trim()||ft}else ys=null;if(i&&!xe&&!Te&&!Rt&&!Ee&&I?.border===void 0&&(ue.style.border="none",rn(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),i&&!xe&&Ee&&I?.border===void 0&&(rn(o).side==="right"?ce.style.borderLeft="1px solid var(--persona-border)":ce.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%"),He.style.display="flex",He.style.flexDirection="column",He.style.flex="1 1 0%",He.style.minHeight="0",He.style.maxHeight="100%",He.style.height="100%",v&&(He.style.overflow="hidden"),ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.height="100%",Rt||(ce.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",Y.style.flexShrink="0"),v&&(Te||Rt||vt)&&!i&&(vt||(He.style.padding="var(--persona-panel-inset)"),He.style.background="var(--persona-panel-canvas-bg)"),He.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&&(Pn[pt]??Pn["bottom-right"]).split(" ").forEach(nn=>He.classList.add(nn)),m){let Tt=o.launcher?.sidebarWidth??"420px";L?He.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: ${Tt} !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: ${
|
|
96
|
+
z-index: ${dn} !important;
|
|
97
97
|
${nt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
98
98
|
`:He.style.cssText=`
|
|
99
99
|
position: fixed !important;
|
|
100
100
|
top: 0 !important;
|
|
101
101
|
bottom: 0 !important;
|
|
102
|
-
width: ${
|
|
102
|
+
width: ${Tt} !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: ${
|
|
109
|
+
z-index: ${dn} !important;
|
|
110
110
|
${nt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
111
|
-
`,
|
|
111
|
+
`,ce.style.cssText=`
|
|
112
112
|
position: relative !important;
|
|
113
113
|
display: flex !important;
|
|
114
114
|
flex-direction: column !important;
|
|
@@ -120,9 +120,9 @@ _Details: ${n.message}_`:o}var Ia=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
120
120
|
margin: 0 !important;
|
|
121
121
|
padding: 0 !important;
|
|
122
122
|
box-shadow: ${dt} !important;
|
|
123
|
-
border-radius: ${
|
|
124
|
-
${
|
|
125
|
-
`,
|
|
123
|
+
border-radius: ${yt} !important;
|
|
124
|
+
${Rt?"border: none !important;":Ee?`border: ${ut} !important;`:""}
|
|
125
|
+
`,ce.style.setProperty("width","100%","important"),ce.style.setProperty("max-width","100%","important"),ue.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 Ia=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
|
-
${
|
|
138
|
-
`,
|
|
134
|
+
border-radius: ${Ze} !important;
|
|
135
|
+
border: ${gt} !important;
|
|
136
|
+
${Rt&&!vt?`box-shadow: ${Ne} !important;`:""}
|
|
137
|
+
${vt?"background: transparent !important;":""}
|
|
138
|
+
`,Y.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(!v&&!i){let Et="max-height: -moz-available !important; max-height: stretch !important;",en=m?"":"padding-top: 1.25em !important;",Rs=m?"":`z-index: ${o.launcher?.zIndex??zt} !important;`;He.style.cssText+=Et+en+Rs}gn()};fs(),er(e,o),Ja(e,o),Qa(e,o),Yr=()=>{fs(),er(e,o),Ja(e,o),Qa(e,o),ss?e.style.setProperty("--persona-artifact-welded-outer-radius",ss):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ve=[];Ve.push(()=>{document.removeEventListener("keydown",Mu)}),Ve.push(()=>{Xr!==null&&clearTimeout(Xr)});let Ln=null,Pn=null;Ve.push(()=>{Ln?.(),Ln=null,Pn?.(),Pn=null}),Qr&&Ve.push(()=>{Qr?.disconnect(),Qr=null}),Ve.push(()=>{ta?.(),ta=null,bl(),bt&&(bt.remove(),bt=null),Ze?.element.style.removeProperty("width"),Ze?.element.style.removeProperty("maxWidth")}),Z&&Ve.push(()=>{Je!==null&&(cancelAnimationFrame(Je),Je=null),Ne?.destroy(),Ne=null,Oe?.destroy(),Oe=null,xe=null});let Bo=null,ku=()=>{Bo&&(Bo(),Bo=null),o.colorScheme==="auto"&&(Bo=Wr(()=>{er(e,o)}))};ku(),Ve.push(()=>{Bo&&(Bo(),Bo=null)}),Ve.push(s);let ms=o.features?.streamAnimation;if(ms?.type&&ms.type!=="none"){let i=Or(ms.type,ms.plugins);i&&(Ui(i,e),Ve.push(()=>wg(e)))}let gs=Vg(xt),Do=null,$,vl=i=>{if(!$)return;let m=i??$.getMessages(),y=o.features?.suggestReplies?.enabled!==!1?Gs(m):null;y?gs.render(y,$,he,m,o.suggestionChipsConfig,{agentPushed:!0}):m.some(v=>v.role==="user")?gs.render([],$,he,m):gs.render(o.suggestionChips,$,he,m,o.suggestionChipsConfig)},vn=!1,Fo=ug(),fr=new Map,Oo=new Map,to=new Map,Cl=0,ny=Vn()!==null,on=Bi(),pn=0,no=null,un=!1,hs=!1,oo=0,Cn=null,No=null,wl=!1,ys=!1,na=null,oa=!0,xs=!1,bs=null,vs=!1,_o=()=>{vs=!0},Al=null,oy=4,Cs=24,ry=80,Sl=new Map,Xe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Lu=o.voiceRecognition?.autoResume??!1,On=i=>{l.emit("voice:state",{active:Xe.active,source:i,timestamp:Date.now()})},wn=()=>{S(i=>({...i,voiceState:{active:Xe.active,timestamp:Date.now(),manuallyDeactivated:Xe.manuallyDeactivated}}))},ay=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Kp(c.voiceState),m=!!i.active,y=Number(i.timestamp??0);Xe.manuallyDeactivated=!!i.manuallyDeactivated,m&&Date.now()-y<PC&&setTimeout(()=>{Xe.active||(Xe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Xe.active=$.isVoiceActive(),On("restore"),$.isVoiceActive()&&xr()}):Ts("restore"))},1e3)},sy=()=>$?lh($.getMessages()).filter(i=>!i.__skipPersist):[],ws=null,Pu=(i,m)=>{typeof console<"u"&&console.error(i,m)},Ml=(i,m)=>{let y=()=>{try{let J=i();return!J||typeof J.then!="function"?null:Promise.resolve(J).catch(V=>{Pu(m,V)})}catch(J){return Pu(m,J),null}},v=ws,k=v?v.then(()=>y()??void 0):y();if(!k)return;let W=k.finally(()=>{ws===W&&(ws=null)});ws=W};function Tl(i){if(!d?.save)return;let y={messages:i?lh(i):$?sy():[],metadata:c,artifacts:xn.artifacts,selectedArtifactId:xn.selectedId};Ml(()=>d.save(y),"[AgentWidget] Failed to persist state:")}let mr=null,Ru=()=>He.querySelector("#persona-scroll-container")||se,ra=()=>{mr!==null&&(cancelAnimationFrame(mr),mr=null),un=!1},Iu=()=>{no!==null&&(cancelAnimationFrame(no),no=null),hs=!1,ra()},iy=()=>vn&&kl()&&($t()!=="anchor-top"||uu()),El=()=>{let i=Ro()||"Jump to latest",m=iy();Lt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),oo>0?(Io.textContent=String(oo),Io.style.display="",Lt.setAttribute("aria-label",`${i} (${oo} new)`)):(Io.textContent="",Io.style.display="none",Lt.setAttribute("aria-label",m?`${i} (response streaming below)`:i))},Wu=()=>{oo!==0&&(oo=0,El())},kl=()=>Qn()?!on.isFollowing():!Eo(se,Cs),rn=()=>{if(!rs()||rt){Lt.parentNode&&Lt.remove(),Lt.style.display="none";return}Lt.parentNode!==pe&&pe.appendChild(Lt),dr();let m=Hn(se)>0&&kl();m?El():Wu(),Lt.style.display=m?"":"none"},aa=()=>{on.pause()&&(Iu(),rn())},ro=()=>{on.resume(),Wu(),rn()},ao=(i=!1)=>{Qn()&&on.isFollowing()&&(!i&&!vn||(no!==null&&(cancelAnimationFrame(no),no=null),hs=!0,no=requestAnimationFrame(()=>{no=null,hs=!1,on.isFollowing()&&ly(Ru(),i?220:140)})))},Hu=(i,m,y,v=()=>!0)=>{let k=i.scrollTop,W=m(),J=W-k;if(ra(),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()){ra();return}let ne=m();ne!==W&&(W=ne,J=W-k);let be=ue-V,$e=Math.min(be/y,1),pt=X($e),nt=k+J*pt;i.scrollTop=nt,pn=i.scrollTop,$e<1?mr=requestAnimationFrame(oe):(i.scrollTop=W,pn=i.scrollTop,mr=null,un=!1)};mr=requestAnimationFrame(oe)},ly=(i,m=500)=>{let y=Hn(i)-i.scrollTop;if(Math.abs(y)<1){pn=i.scrollTop;return}if(Math.abs(y)>=ry){ra(),un=!0,i.scrollTop=Hn(i),pn=i.scrollTop,un=!1;return}Hu(i,()=>Hn(i),m,()=>on.isFollowing())},Bu=()=>{let i=Ru();un=!0,i.scrollTop=Hn(i),pn=i.scrollTop,un=!1,rn()},Du=i=>{let m=0,y=i;for(;y&&y!==se;)m+=y.offsetTop,y=y.offsetParent;return m},dy=()=>{let i=se.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??se.ownerDocument.getSelection()},As=()=>yg(dy(),se),Fu=()=>{if(Xh()!=="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=se.querySelector(`[data-message-id="${y}"]`);if(!v)return!1;let k=Math.min(Math.max(0,Du(v)-cu()),Hn(se));return un=!0,se.scrollTop=k,pn=se.scrollTop,un=!1,$t()==="follow"&&!Eo(se,Cs)&&on.pause(),rn(),!0},Ou=i=>{Yn.style.height=`${Math.max(0,Math.round(i))}px`,Cn&&(Cn.spacerHeight=Math.max(0,i))},sa=()=>{No!==null&&(cancelAnimationFrame(No),No=null),ra(),Cn=null,Yn.style.height="0px"},Nu=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=se.querySelector(`[data-message-id="${m}"]`);if(!y)return;let v=Du(y),k=Cn?.spacerHeight??0,W=se.scrollHeight-k,{targetScrollTop:J,spacerHeight:V}=xg({anchorOffsetTop:v,topOffset:cu(),viewportHeight:se.clientHeight,contentHeight:W});Cn={initialSpacerHeight:V,contentHeightAtAnchor:W,spacerHeight:V},Ou(V),Hu(se,()=>J,220)})},cy=()=>{if(Qn()){if(!on.isFollowing()||Eo(se,1))return;ao(!vn);return}if(Cn&&Cn.initialSpacerHeight>0){let i=se.scrollHeight-Cn.spacerHeight,m=bg({initialSpacerHeight:Cn.initialSpacerHeight,contentHeightAtAnchor:Cn.contentHeightAtAnchor,currentContentHeight:i});m!==Cn.spacerHeight&&Ou(m)}rn()},py=i=>{let m=$t();m==="follow"?(ro(),ao(!0)):m==="anchor-top"&&(oa=!1,xs=!0,vs=!1,bs=i,Nu(i))},uy=()=>{if($t()==="anchor-top"){if(xs){oa=!1;return}oa=!0,sa(),ro(),ao(!0)}},fy=i=>{if($t()!=="anchor-top"||!xs||vs||As())return;let m=na===null;for(let y of i){if(!m){y.id===na&&(m=!0);continue}if(hg(y)){if(y.id===bs)return;bs=y.id,Nu(y.id);return}}},my=i=>{let m=new Map;i.forEach(y=>{let v=Sl.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!v&&y.role==="assistant"&&(l.emit("assistant:message",y),!ys&&($t()!=="anchor-top"||uu())&&kl()&&(oo+=1,El(),rn(),mu(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}))}),Sl.clear(),m.forEach((y,v)=>{Sl.set(v,y)})},Ss=(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)},Uo=(i,m)=>{let y=document.createElement("div");return y.className="persona-flex",y.id=`wrapper-${i}`,y.setAttribute("data-wrapper-id",i),Ss(y,m),y},gy=(i,m,y)=>{let v=document.createElement("div"),W=(()=>{let O=r.find(Le=>Le.renderLoadingIndicator);if(O?.renderLoadingIndicator)return O.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),J=(O,Le)=>Le==null?!1:typeof Le=="string"?(O.textContent=Le,!0):(O.appendChild(Le),!0),V=new Set,X=new Map,oe=new Set,ue=r.some(O=>O.renderAskUserQuestion),ne=[],be=[],$e=o.enableComponentStreaming!==!1,pt=o.approval!==!1,nt=[];if(m.forEach(O=>{V.add(O.id),X.set(O.id,O.role);let Le=ue&&$n(O),_e=pt&&O.variant==="approval"&&!!O.approval,Se=!Le&&O.role==="assistant"&&!O.variant&&$e&&ts(O);!_e&&to.has(O.id)&&(i.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),to.delete(O.id)),!Se&&Oo.has(O.id)&&(i.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),Oo.delete(O.id));let St=$n(O)?`:${O.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${O.agentMetadata?.askUserQuestionAnswers?Object.keys(O.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=pg(O,Cl)+St,Gt=Le||_e||Se?null:fg(Fo,O.id,ut);if(Gt){v.appendChild(Gt.cloneNode(!0)),$n(O)&&O.toolCall?.id&&O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(oe.add(O.toolCall.id),Er(O,o,Ee.composerOverlay));return}let ft=null,Zt=r.find(Ue=>!!(O.variant==="reasoning"&&Ue.renderReasoning||O.variant==="tool"&&Ue.renderToolCall||!O.variant&&Ue.renderMessage)),It=o.layout?.messages;if($n(O)&&O.agentMetadata?.askUserQuestionAnswered===!0){fr.delete(O.id),i.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ta(O)&&o.features?.suggestReplies?.enabled!==!1)return;if($n(O)&&o.features?.askUserQuestion?.enabled!==!1){let Ue=r.find(Nt=>typeof Nt.renderAskUserQuestion=="function");if(Ue&<.current){let Nt=fr.get(O.id),_t=Nt!==ut,Ct=null;if(_t){let{payload:et,complete:De}=jn(O),ht=O.id,Ut=()=>lt.current?.getMessages().find(gn=>gn.id===ht);Ct=Ue.renderAskUserQuestion({message:O,payload:et,complete:De,resolve:gn=>{let ha=Ut();ha&<.current?.resolveAskUserQuestion(ha,gn)},dismiss:()=>{let gn=Ut();gn?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(gn),lt.current?.resolveAskUserQuestion(gn,"(dismissed)"))},config:o})}let dt=Nt!=null;if(_t&&Ct===null&&!dt){O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(oe.add(O.toolCall.id),Er(O,o,Ee.composerOverlay));return}let mt=Uo(O.id,O.role);mt.setAttribute("data-ask-plugin-stub","true"),mt.setAttribute("data-preserve-runtime","true"),v.appendChild(mt),ne.push({messageId:O.id,fingerprint:ut,bubble:Ct});return}else{O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(oe.add(O.toolCall.id),Er(O,o,Ee.composerOverlay));return}}else if(_e){let Ue=r.find(dt=>typeof dt.renderApproval=="function")??a,_t=to.get(O.id)!==ut,Ct=null;if(_t&&Ue?.renderApproval){let dt=O.id,mt=(et,De)=>{let ht=lt.current?.getMessages().find(Ut=>Ut.id===dt);ht?.approval&&(ht.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(ht.id,et):lt.current?.resolveApproval(ht.approval,et,De))};Ct=Ue.renderApproval({message:O,defaultRenderer:()=>Yi(O,o),config:o,approve:et=>mt("approved",et),deny:et=>mt("denied",et)})}if(_t&&Ct===null)i.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),to.delete(O.id),ft=Yi(O,o);else{let dt=Uo(O.id,O.role);dt.setAttribute("data-approval-plugin-stub","true"),dt.setAttribute("data-preserve-runtime","true"),v.appendChild(dt),nt.push({messageId:O.id,fingerprint:ut,bubble:Ct});return}}else if(Zt)if(O.variant==="reasoning"&&O.reasoning&&Zt.renderReasoning){if(!ae)return;ft=Zt.renderReasoning({message:O,defaultRenderer:()=>Dp(O,o),config:o})}else if(O.variant==="tool"&&O.toolCall&&Zt.renderToolCall){if(!me)return;ft=Zt.renderToolCall({message:O,defaultRenderer:()=>Op(O,o),config:o})}else Zt.renderMessage&&(ft=Zt.renderMessage({message:O,defaultRenderer:()=>{let Ue=Ur(O,y,It,o.messageActions,Me,{loadingIndicatorRenderer:W,widgetConfig:o});return O.role!=="user"&&$p(Ue,O,o,$),Ue},config:o}));if(!ft&&Se){let Ue=rl(O);if(Ue){let Nt=Oo.get(O.id),_t=Nt!==ut,Ct=o.wrapComponentDirectiveInBubble!==!1&&En.getOptions(Ue.component)?.bubbleChrome!==!1,dt=null;if(_t){let mt=ol(Ue,{config:o,message:O,transform:y});if(mt&&Ue.component==="PersonaArtifactInline"){let et=mt.hasAttribute("data-artifact-inline")?mt:mt.querySelector("[data-artifact-inline]"),De=et?.getAttribute("data-artifact-inline")??"",ht=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(De):De,Ut=De?i.querySelector(`#wrapper-${O.id}`)?.querySelector(`[data-artifact-inline="${ht}"]`)??null:null;et&&Ut&&Ut!==et&&ag(Ut)&&(et===mt?mt=Ut:et.replaceWith(Ut))}if(mt)if(Ct){let et=document.createElement("div");if(et.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),et.id=`bubble-${O.id}`,et.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}),et.appendChild(De)}et.appendChild(mt),dt=et}else{let et=document.createElement("div");if(et.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",et.id=`bubble-${O.id}`,et.setAttribute("data-message-id",O.id),et.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}),et.appendChild(De)}et.appendChild(mt),dt=et}}if(dt||Nt!=null){let mt=Uo(O.id,O.role);mt.setAttribute("data-component-directive-stub","true"),mt.setAttribute("data-preserve-runtime","true"),v.appendChild(mt),be.push({messageId:O.id,fingerprint:ut,bubble:dt});return}}}if(!ft)if(O.variant==="reasoning"&&O.reasoning){if(!ae)return;ft=Dp(O,o)}else if(O.variant==="tool"&&O.toolCall){if(!me)return;ft=Op(O,o)}else if(O.variant==="approval"&&O.approval){if(o.approval===!1)return;ft=Yi(O,o)}else{let Ue=o.layout?.messages;Ue?.renderUserMessage&&O.role==="user"?ft=Ue.renderUserMessage({message:O,config:o,streaming:!!O.streaming}):Ue?.renderAssistantMessage&&O.role==="assistant"?ft=Ue.renderAssistantMessage({message:O,config:o,streaming:!!O.streaming}):ft=Ur(O,y,Ue,o.messageActions,Me,{loadingIndicatorRenderer:W,widgetConfig:o}),O.role!=="user"&&ft&&$p(ft,O,o,$)}let Pe=Uo(O.id,O.role);Pe.appendChild(ft),mg(Fo,O.id,ut,Pe),v.appendChild(Pe)}),Ee.composerOverlay&&Ee.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Le=>{let _e=Le.getAttribute("data-persona-ask-sheet-for");_e&&!oe.has(_e)&&go(Ee.composerOverlay,_e)}),o.features?.toolCallDisplay?.grouped){let O=[],Le=[],_e=o.features.toolCallDisplay.groupedMode==="summary";m.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&me){Le.push(Se);return}Se.variant==="reasoning"&&!ae||((Le.length>1||_e&&Le.length>0)&&O.push(Le),Le=[])}),(Le.length>1||_e&&Le.length>0)&&O.push(Le),O.forEach(Se=>{let St=Se.map(Ue=>Array.from(v.children).find(Nt=>Nt instanceof HTMLElement&&Nt.getAttribute("data-wrapper-id")===Ue.id)).filter(Ue=>!!Ue);if(St.length<(_e?1:2))return;let ut=Uo(`tool-group-${Se[0].id}`,"assistant");ut.setAttribute("data-persona-tool-group-row","true");let Gt=document.createElement("div");Gt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Gt.setAttribute("data-persona-tool-group","true");let ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ft.id=`tool-group-summary-${Se[0].id}`;let Zt=`Called ${Se.length} ${Se.length===1?"tool":"tools"}`,It=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map(Ue=>Ue.toolCall).filter(Ue=>!!Ue),defaultSummary:Zt,config:o});J(ft,It)||(ft.textContent=Zt);let Pe=document.createElement("div");Pe.className="persona-tool-group-stack persona-flex persona-flex-col",Pe.id=`tool-group-stack-${Se[0].id}`,Pe.setAttribute("data-persona-tool-group-stack","true"),Gt.appendChild(ft),_e||Gt.appendChild(Pe),ut.appendChild(Gt),St[0].before(ut),St.forEach((Ue,Nt)=>{if(_e){Ue.remove();return}Ue.style.setProperty("--persona-message-row-max-width","100%");let _t=document.createElement("div");_t.className="persona-tool-group-item persona-relative",_t.setAttribute("data-persona-tool-group-item","true"),Nt<St.length-1&&_t.setAttribute("data-persona-tool-group-connector","true"),_t.appendChild(Ue),Pe.appendChild(_t)})})}gg(Fo,V);let an=m.some(O=>O.role==="assistant"&&O.streaming),At=m[m.length-1],Rt=At?.role==="assistant"&&!At.streaming&&At.variant!=="approval";if(vn&&m.some(O=>O.role==="user")&&!an&&!Rt){let O={config:o,streaming:!0,location:"standalone",defaultRenderer:rr},Le=r.find(Se=>Se.renderLoadingIndicator),_e=null;if(Le?.renderLoadingIndicator&&(_e=Le.renderLoadingIndicator(O)),_e===null&&o.loadingIndicator?.render&&(_e=o.loadingIndicator.render(O)),_e===null&&(_e=rr()),_e){let Se=document.createElement("div"),St=o.loadingIndicator?.showBubble!==!1;Se.className=St?["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(" "),Se.setAttribute("data-typing-indicator","true"),Se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Se.appendChild(_e);let ut=Uo("typing-indicator","assistant");ut.appendChild(Se),v.appendChild(ut)}}if(!vn&&m.length>0){let O=m[m.length-1],Le={config:o,lastMessage:O,messageCount:m.length},_e=r.find(St=>St.renderIdleIndicator),Se=null;if(_e?.renderIdleIndicator&&(Se=_e.renderIdleIndicator(Le)),Se===null&&o.loadingIndicator?.renderIdle&&(Se=o.loadingIndicator.renderIdle(Le)),Se){let St=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;St.className=ut?["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(" "),St.setAttribute("data-idle-indicator","true"),St.appendChild(Se);let Gt=Uo("idle-indicator","assistant");Gt.appendChild(St),v.appendChild(Gt)}}if(Ff(v),Hi(i,v),$l(i),ne.length>0)for(let{messageId:O,fingerprint:Le,bubble:_e}of ne){let Se=i.querySelector(`#wrapper-${O}`);Se&&(Ss(Se,X.get(O)??"assistant"),_e!==null&&(Se.replaceChildren(_e),Se.setAttribute("data-bubble-fp",Le),fr.set(O,Le)))}if(fr.size>0)for(let O of fr.keys())V.has(O)||fr.delete(O);if(be.length>0)for(let{messageId:O,fingerprint:Le,bubble:_e}of be){let Se=i.querySelector(`#wrapper-${O}`);Se&&(Ss(Se,X.get(O)??"assistant"),_e!==null&&(Se.replaceChildren(_e),Se.setAttribute("data-bubble-fp",Le),Oo.set(O,Le)))}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:Le,bubble:_e}of nt){let Se=i.querySelector(`#wrapper-${O}`);Se&&(Ss(Se,X.get(O)??"assistant"),_e!==null&&(Se.replaceChildren(_e),Se.setAttribute("data-bubble-fp",Le),to.set(O,Le)))}if(to.size>0)for(let O of to.keys())V.has(O)||to.delete(O)},ia=(i,m,y)=>{gy(i,m,y),wu()},la=null,hy=()=>{if(la)return;let i=y=>{let v=y.composedPath();v.includes(He)||Ke&&v.includes(Ke)||ct(!1,"user")};la=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},_u=()=>{if(!la)return;(e.ownerDocument??document).removeEventListener("pointerdown",la,!0),la=null};Ve.push(()=>_u());let da=null,yy=()=>{if(da)return;let i=y=>{y.key==="Escape"&&(y.isComposing||ct(!1,"user"))};da=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Uu=()=>{if(!da)return;(e.ownerDocument??document).removeEventListener("keydown",da,!0),da=null};Ve.push(()=>Uu());let ca=!1,qu=new Set,xy=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},gr=()=>{if(!q())return;let i=Ee.peekBanner,m=Ee.peekTextNode;if(!i||!m)return;if(U){i.classList.remove("persona-pill-peek--visible");return}let y=$?.getMessages()??[],v;for(let At=y.length-1;At>=0;At--){let Rt=y[At];if(Rt.role==="assistant"&&Rt.content){v=Rt;break}}if(!v){i.classList.remove("persona-pill-peek--visible");return}let k=v.content,W=!!v.streaming,J=xy(),V=Oi(J),X=V.type!=="none"?Or(V.type,J?.plugins):null,oe=X?.isAnimating?.(v)===!0,ue=X!==null&&(W||oe);ue&&X&&!qu.has(X.name)&&(Ui(X,e),qu.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 $e=ue?Ni(k,V.buffer,X,v,W):k;if(ue&&V.placeholder==="skeleton"&&W&&(!$e||!$e.trim())){let At=document.createElement("div"),Rt=za();Rt.classList.add("persona-pill-peek__skeleton"),At.appendChild(Rt),Hi(m,At)}else{let At=Math.max(0,$e.length-100),Rt=$e.length>100?$e.slice(-100):$e,O=In(Rt);if(!ue||!X){let Le=$e.length>100?`\u2026${Rt}`:Rt;m.textContent!==Le&&(m.textContent=Le)}else{let Le=O;(X.wrap==="char"||X.wrap==="word")&&(Le=Va(O,X.wrap,`peek-${v.id}`,{skipTags:X.skipTags,startIndex:At}));let _e=document.createElement("div");if(_e.innerHTML=Le,X.useCaret&&Rt.length>0){let Se=_i(),St=_e.querySelectorAll(".persona-stream-char, .persona-stream-word"),ut=St[St.length-1];ut?.parentNode?ut.parentNode.insertBefore(Se,ut.nextSibling):_e.appendChild(Se)}Hi(m,_e),X.onAfterRender?.({container:m,bubble:i,messageId:v.id,message:v,speed:V.speed,duration:V.duration})}}let an=vn||ca;i.classList.toggle("persona-pill-peek--visible",an)};if(q()){let i=Ee.peekBanner;if(i){let v=k=>{k.preventDefault(),k.stopPropagation(),ct(!0,"user")};i.addEventListener("pointerdown",v),Ve.push(()=>{i.removeEventListener("pointerdown",v)})}let m=()=>{ca||(ca=!0,gr())},y=()=>{ca&&(ca=!1,gr())};fe.addEventListener("pointerenter",m),fe.addEventListener("pointerleave",y),Ve.push(()=>{fe.removeEventListener("pointerenter",m),fe.removeEventListener("pointerleave",y)}),Ke&&(Ke.addEventListener("pointerenter",m),Ke.addEventListener("pointerleave",y),Ve.push(()=>{Ke.removeEventListener("pointerenter",m),Ke.removeEventListener("pointerleave",y)}))}let by=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=He.style;if(ne.left="",ne.right="",ne.top="",ne.bottom="",ne.transform="",ne.width="",ne.maxWidth="",ne.height="",ne.maxHeight="",Ke){let be=Ke.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}},pa=()=>{if(!D())return;if(q()){let oe=(o.launcher?.composerBar??{}).expandedSize??"anchored",ue=U?"expanded":"collapsed";He.dataset.state=ue,He.dataset.expandedSize=oe,Ke&&(Ke.dataset.state=ue,Ke.dataset.expandedSize=oe),He.style.removeProperty("display"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),by(U),pe.style.display=U?"flex":"none",fs(),U?(hy(),yy()):(_u(),Uu()),gr();return}let i=kt(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?(He.style.removeProperty("display"),He.style.display=i?"flex":"",He.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"),Bt?Bt.element.style.display="none":jt&&(jt.style.display="none")):(i?i&&(J==="overlay"||J==="push")&&!W?(He.style.removeProperty("display"),He.style.display="flex",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.setProperty("display","none","important"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.display="",He.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")),Bt?Bt.element.style.display=i?"none":"":jt&&(jt.style.display=i?"none":""))},ct=(i,m="user")=>{if(!D()||U===i)return;let y=U;U=i,pa();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=kt(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=Mp(J,o.launcher?.zIndex??zt))}Pn||(Pn=Tp(e.ownerDocument))}else U||(Ln?.(),Ln=null,Pn?.(),Pn=null);U&&(ma(),Fu()||($t()==="follow"?ao(!0):Bu()));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:Xe.active,streaming:$.isStreaming()})},Ll=i=>{at(i?"stop":"send"),K&&(K.disabled=i),gs.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)})},Pl=()=>{Xe.active||he&&he.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Pl(),200)});let Vu=()=>{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=se.querySelector("[data-persona-intro-card]");if(i){let y=o.copy?.showWelcomeCard!==!1;i.style.display=y?"":"none",y?(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)&&!$?.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 qo=null,vy=()=>{qo==null&&(qo=setInterval(()=>{let i=ge.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(qo),qo=null;return}let m=Date.now();i.forEach(y=>{let v=Number(y.getAttribute("data-tool-elapsed"));v&&(y.textContent=Xs(m-v))})},100))},Rl=(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)=>Rl(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)&&Rl(y[J],v[J]))},zu=i=>{let{content:m,rawContent:y,llmContent:v,...k}=i;return k},Il=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!ts(i),Cy=(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))&&Il(v)&&Il(k)&&Rl(zu(v),zu(k))},$u=null,hr=null,Vo=null,Nn=null,Ms=i=>{$u=i;let m,y;hr=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),!hr&&Il(W)&&(hr={index:k,id:W.id}),m&&y&&hr)break}ia(ge,i,Ie),yp(ge,xn.artifacts,{suppressTransition:vn}),vy(),vl(i),ao(!vn),my(i),i.length===0&&(sa(),oa=!0,xs=!1,bs=null,vs=!1),!wl||ys?(wl=!0,na=m?.id??null,Al=y?.id??null):m&&m.id!==na?(na=m.id,py(m.id)):y&&y.id!==Al&&uy(),y&&(Al=y.id),fy(i);let v=Xe.lastUserMessageId;m&&m.id!==v&&(Xe.lastUserMessageId=m.id,l.emit("user:message",m)),Xe.lastUserMessageWasVoice=!!m?.viaVoice,Tl(i),gr()},Wl=()=>{Nn!==null&&(cancelAnimationFrame(Nn),Nn=null);let i=Vo;Vo=null,i&&Ms(i)},ju=()=>{Nn!==null&&cancelAnimationFrame(Nn),Nn=null,Vo=null},wy=i=>{let m=Vo??$u;if(vn&&m&&hr&&Cy(m,i,hr)){Vo=i,Nn===null&&(Nn=requestAnimationFrame(()=>{Nn=null;let y=Vo;Vo=null,y&&Ms(y)}));return}if(i.length===0){ju(),Ms(i);return}Wl(),Ms(i)};$=new Rr(o,{onMessagesChanged(i){wy(i)},onStatusChanged(i){let m=o.statusIndicator??{};Tt(R,(v=>v==="idle"?m.idleText??Wt.idle:v==="connecting"?m.connectingText??Wt.connecting:v==="connected"?m.connectedText??Wt.connected:v==="error"?m.errorText??Wt.error:v==="paused"?m.pausedText??Wt.paused:v==="resuming"?m.resumingText??Wt.resuming:Wt[v])(i),m,i)},onStreamingChanged(i){i||($?.getMessages().length===0?ju():Wl()),vn=i,Ll(i),$&&ia(ge,$.getMessages(),Ie),i||ao(!0),rn(),mu(i?"Responding\u2026":"Response complete."),gr()},onVoiceStatusChanged(i){if(l.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":_n(),xr();break;case"processing":_n(),Wy();break;case"speaking":_n(),Hy();break;default:i==="idle"&&$.isBargeInActive()?(_n(),xr(),K?.setAttribute("aria-label","End voice session")):(Xe.active=!1,_n(),On("system"),wn());break}},onArtifactsState(i){xn=i,i.artifacts.length===0&&(cr=!1),yp(ge,i.artifacts,{suppressTransition:vn}),Fn(),Tl()},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})}}),lt.current=$,Ve.push(()=>$.cancel());let Hl=null;if($.onReadAloudChange((i,m)=>{vu=i,Cu=m,wu();let y=i??Hl;i&&(Hl=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"&&(Hl=null)}),wl=!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),ze?.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 Gu=()=>{o.resume&&typeof o.reconnectStream=="function"&&$.resumeFromHandle(o.resume)};u?u.then(i=>{if(i){if(i.metadata&&(c=Kp(i.metadata),M.syncFromMetadata()),i.messages?.length){ys=!0;try{$.hydrateMessages(i.messages)}finally{ys=!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(()=>Gu()):Gu();let Ku=()=>{!q()||U||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ct(!0,"auto")},Ay=(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),FC(k)}}:i:m,Sy=()=>{let m=he.getInlineMessageFields?.();return m&&m.contentSegments.some(v=>v.kind==="mention")?m.contentSegments:void 0},ua=!1,My=async i=>{let m=he.value.trim(),y=wt?.hasAttachments()??!1,v=m?await(nn?.takeInlineCommand(m)??Promise.resolve(null)):null;if(v?.kind==="action"){he.value="",he.style.height="auto",fa(),nn?.clear();return}let k=nn?.collectForSubmit()??null,W=v?.kind==="server"?v.mentions:null,J=Ay(k,W),V=v?.kind==="prompt"?v.sendText:m,X=!!k&&k.refs.length>0;if(!V&&!y&&!X&&!W)return;Ku();let oe;y&&(oe=[],oe.push(...wt.getContentParts()),V&&oe.push(bo(V)));let ue=v?.kind==="prompt"?void 0:Sy();he.value="",he.style.height="auto",fa(),$.sendMessage(V,{contentParts:oe,mentions:J??void 0,contentSegments:ue,viaVoice:i?.viaVoice}),y&&wt.clearAttachments(),k&&nn?.clear()},Bl=async i=>{if(!ua){ua=!0;try{await My(i)}finally{ua=!1}}},Xu=i=>{if(i.preventDefault(),$.isStreaming()){$.cancel(),ze?.reset(),Ne?.update();return}ua||Bl()},Ty=()=>o.features?.composerHistory!==!1,Dl={...vp},Fl=!1,fa=()=>{Dl={...vp}},Ey=()=>$.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),ky=i=>{if(!he)return;Fl=!0,he.value=i,he.dispatchEvent(new Event("input",{bubbles:!0})),Fl=!1;let m=he.value.length;he.setSelectionRange(m,m)},Ly=i=>{Fl||(i.isComposing||nn?.handleInput(i.inputType??void 0),fa())},Py=i=>{if(he&&!(!i.isComposing&&nn?.handleKeydown(i))){if(Ty()&&(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=cg({direction:i.key==="ArrowUp"?"up":"down",history:Ey(),currentValue:he.value,atStart:m,state:Dl});if(Dl=y.state,y.handled){i.preventDefault(),y.value!==void 0&&ky(y.value);return}}if(i.key==="Enter"&&!i.shiftKey){if($.isStreaming()){i.preventDefault();return}if(ua){i.preventDefault();return}fa(),i.preventDefault(),ce.click()}}},Ju=i=>{i.key!=="Escape"||i.isComposing||$.isStreaming()&&i.composedPath().includes(pe)&&($.cancel(),ze?.reset(),Ne?.update(),fa(),i.preventDefault(),i.stopImmediatePropagation())},Ry=async i=>{if(o.attachments?.enabled!==!0||!wt)return;let m=WC(i.clipboardData);m.length!==0&&(i.preventDefault(),await wt.handleFiles(m))},fn=null,Rn=!1,yr=null,vt=null,Qu=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ts=(i="user")=>{if(Rn||$.isStreaming())return;let m=Qu();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,yr&&clearTimeout(yr),(J||V)&&(yr=window.setTimeout(()=>{he.value.trim()&&fn&&Rn&&(so(),Bl({viaVoice:!0}))},v))},fn.onerror=W=>{W.error!=="no-speech"&&so()},fn.onend=()=>{if(Rn){let W=he.value.trim();W&&W!==k.trim()&&Bl({viaVoice:!0}),so()}};try{if(fn.start(),Rn=!0,Xe.active=!0,i!=="system"&&(Xe.manuallyDeactivated=!1),On(i),wn(),K){let W=o.voiceRecognition??{};vt={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,yr&&(clearTimeout(yr),yr=null),fn){try{fn.stop()}catch{}fn=null}if(Xe.active=!1,On(i),wn(),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")}}},Iy=(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,$e=i?.backgroundColor??m?.backgroundColor,pt=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",pt?V.style.color=pt:V.style.color="var(--persona-text, #111827)";let an=te(oe,be,pt||"currentColor",1.5);an?V.appendChild(an):V.textContent="\u{1F3A4}",$e?V.style.backgroundColor=$e: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 At=i?.showTooltip??!1;return Ot({anchor:V,trigger:J,text:()=>V.getAttribute("aria-label")??X,enabled:At}),{micButton:V,micButtonWrapper:J}},Ol=()=>{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 y=K.querySelector("svg");y&&y.remove();let v=vt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),k=te(i,v,m,1.5);k&&K.appendChild(k)},Es=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},xr=()=>{if(!K)return;Ol();let i=o.voiceRecognition??{},m=i.recordingBackgroundColor,y=i.recordingIconColor,v=i.recordingBorderColor;if(Es(),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")},Wy=()=>{if(!K)return;Ol();let i=o.voiceRecognition??{},m=$.getVoiceInterruptionMode(),y=i.processingIconName??"loader",v=i.processingIconColor??vt?.color??"",k=i.processingBackgroundColor??vt?.backgroundColor??"",W=i.processingBorderColor??vt?.borderColor??"";Es(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=k,K.style.borderColor=W;let J=v||"currentColor";K.style.color=J,Nl(y,J),K.setAttribute("aria-label","Processing voice input"),m==="none"&&(K.style.cursor="default")},Hy=()=>{if(!K)return;Ol();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??vt?.color??"":vt?.color??""),W=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??"");Es(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=W,K.style.borderColor=J;let V=k||"currentColor";K.style.color=V,Nl(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&&(Es(),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"))},ks=()=>{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(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,wn(),On("user"),_n()});return}$.toggleVoice().then(()=>{Xe.active=$.isVoiceActive(),Xe.manuallyDeactivated=!$.isVoiceActive(),wn(),On("user"),$.isVoiceActive()?xr():_n()});return}if(Rn){let i=he.value.trim();Xe.manuallyDeactivated=!0,wn(),so("user"),i&&(he.value="",he.style.height="auto",$.sendMessage(i))}else Xe.manuallyDeactivated=!1,wn(),Ts("user")};hu=ks,K&&(K.addEventListener("click",ks),Ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()&&$.toggleVoice(),_n()):so("system"),K&&K.removeEventListener("click",ks)}));let By=l.on("assistant:complete",()=>{Lu&&(Xe.active||Xe.manuallyDeactivated||Lu==="assistant"&&!Xe.lastUserMessageWasVoice||setTimeout(()=>{!Xe.active&&!Xe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Xe.active=$.isVoiceActive(),On("auto"),$.isVoiceActive()&&xr()}):Ts("auto"))},600))});Ve.push(By);let Dy=l.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});Ve.push(Dy);let Yu=()=>{ct(!U,"user")},Bt=null,jt=null;if(A&&!q()){let{instance:i,element:m}=Rp({config:o,plugins:r,onToggle:Yu});Bt=i,i||(jt=m)}Bt?e.appendChild(Bt.element):jt&&e.appendChild(jt),pa(),vl(),Vu(),Ll($.isStreaming()),Fu()||($t()==="follow"?ao(!0):Bu()),ay(),T&&(!A||q()?setTimeout(()=>Pl(),0):U&&setTimeout(()=>Pl(),200));let ma=()=>{if(q()){dr(),pa();return}let i=kt(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){Yr(),Zr=us();return}let X=!1;F&&(F=!1,Yr(),X=!0);let oe=us();if(!X&&oe!==Zr&&(Yr(),X=!0),Zr=oe,X&&xl(),!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(ps(),!y){let ue=v.innerHeight,ne=64,be=o.launcher?.heightOffset??0,$e=Math.max(200,ue-ne),pt=Math.min(640,$e),nt=Math.max(200,pt-be);fe.style.height=`${nt}px`}}finally{if(dr(),pa(),U&&A){let oe=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ue=o.launcher?.sidebarMode??!1,ne=o.launcher?.mobileFullscreen??!0,be=kt(o)&&ne&&oe,$e=ue||ne&&oe&&A||be;if($e&&!Pn){let pt=e.getRootNode(),nt=pt instanceof ShadowRoot?pt.host:e.closest(".persona-host");nt&&!Ln&&(Ln=Mp(nt,o.launcher?.zIndex??zt)),Pn=Tp(e.ownerDocument)}else $e||(Ln?.(),Ln=null,Pn?.(),Pn=null)}}};ma();let Zu=e.ownerDocument.defaultView??window;if(Zu.addEventListener("resize",ma),Ve.push(()=>Zu.removeEventListener("resize",ma)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{dr()});i.observe(j),Ve.push(()=>i.disconnect())}pn=se.scrollTop;let ef=Hn(se),tf=()=>{let i=se.scrollTop,m=Hn(se),y=m<ef;if(ef=m,!Qn()){pn=i,rn();return}let{action:v,nextLastScrollTop:k}=Di({following:on.isFollowing(),currentScrollTop:i,lastScrollTop:pn,nearBottom:Eo(se,Cs),userScrollThreshold:oy,isAutoScrolling:un||hs||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(pn=k,v==="resume"){As()||ro();return}v==="pause"&&aa()};if(se.addEventListener("scroll",tf,{passive:!0}),Ve.push(()=>se.removeEventListener("scroll",tf)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{cy(),$l(ge)});i.observe(ge),i.observe(se),Ve.push(()=>i.disconnect())}let nf=()=>{Qn()&&on.isFollowing()&&As()&&aa()},of=se.ownerDocument;of.addEventListener("selectionchange",nf),Ve.push(()=>{of.removeEventListener("selectionchange",nf)});let Fy=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),rf=i=>{Fy.has(i.key)&&(_o(),pu()&&Qn()&&on.isFollowing()&&aa())},af=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(_o(),pu()&&Qn()&&on.isFollowing()&&aa())};se.addEventListener("keydown",rf),se.addEventListener("focusin",af),Ve.push(()=>{se.removeEventListener("keydown",rf),se.removeEventListener("focusin",af)});let sf=i=>{if(i.deltaY!==0&&_o(),!Qn())return;let m=Fi({following:on.isFollowing(),deltaY:i.deltaY,nearBottom:Eo(se,Cs),resumeWhenNearBottom:!0});m==="pause"?aa():m==="resume"&&!As()&&ro()};se.addEventListener("wheel",sf,{passive:!0}),se.addEventListener("touchmove",_o,{passive:!0}),se.addEventListener("pointerdown",_o,{passive:!0}),Ve.push(()=>{se.removeEventListener("touchmove",_o),se.removeEventListener("pointerdown",_o)}),Ve.push(()=>se.removeEventListener("wheel",sf)),Lt.addEventListener("click",()=>{sa(),se.scrollTop=se.scrollHeight,pn=se.scrollTop,ro(),ao(!0),rn()}),Ve.push(()=>Lt.remove()),Ve.push(()=>{Iu(),sa()});let lf=()=>{P&&(Do&&(P.removeEventListener("click",Do),Do=null),D()?(P.style.display="",Do=()=>{ct(!1,"user")},P.addEventListener("click",Do)):P.style.display="none")};lf(),(()=>{let{clearChatButton:i}=Ee;i&&i.addEventListener("click",()=>{$.clearMessages(),Fo.clear(),ro(),go(Ee.composerOverlay);try{localStorage.removeItem(jr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${jr}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==jr)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&&Ml(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},M.syncFromMetadata(),Oe?.clear(),ze?.reset(),Ne?.update()})})(),Q&&Q.addEventListener("submit",Xu);let df=[["keydown",Py],["input",Ly],["paste",Ry],["focus",Yh]],cf=i=>{if(i)for(let[m,y]of df)i.addEventListener(m,y)},pf=i=>{if(i)for(let[m,y]of df)i.removeEventListener(m,y)};cf(he),nn?.onComposerSwap((i,m)=>{pf(m),he=i,cf(i)});let uf=e.ownerDocument??document;uf.addEventListener("keydown",Ju,!0);let ff="persona-attachment-drop-active",ga=0,_l=()=>{ga=0,pe.classList.remove(ff)},br=()=>o.attachments?.enabled===!0&&wt!==null,mf=i=>{!il(i.dataTransfer)||!br()||(ga++,ga===1&&pe.classList.add(ff))},gf=i=>{!il(i.dataTransfer)||!br()||(ga--,ga<=0&&_l())},hf=i=>{!il(i.dataTransfer)||!br()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},yf=i=>{if(!il(i.dataTransfer)||!br())return;i.preventDefault(),i.stopPropagation(),_l();let m=Array.from(i.dataTransfer.files??[]);m.length!==0&&wt.handleFiles(m)},io=!0;pe.addEventListener("dragenter",mf,io),pe.addEventListener("dragleave",gf,io),e.addEventListener("dragover",hf,io),e.addEventListener("drop",yf,io);let Ls=e.ownerDocument,xf=i=>{br()&&i.preventDefault()},bf=i=>{br()&&i.preventDefault()};Ls.addEventListener("dragover",xf),Ls.addEventListener("drop",bf),Ve.push(()=>{Q&&Q.removeEventListener("submit",Xu),pf(he),uf.removeEventListener("keydown",Ju,!0),nn?.destroy()}),Ve.push(()=>{pe.removeEventListener("dragenter",mf,io),pe.removeEventListener("dragleave",gf,io),e.removeEventListener("dragover",hf,io),e.removeEventListener("drop",yf,io),Ls.removeEventListener("dragover",xf),Ls.removeEventListener("drop",bf),_l()}),Ve.push(()=>{$.cancel()}),Bt?Ve.push(()=>{Bt?.destroy()}):jt&&Ve.push(()=>{jt?.remove()});let Pt={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=el(o,i),fs(),er(e,o),Ja(e,o),Qa(e,o),Fn(),o.colorScheme!==k&&ku();let be=Ya.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 $e=$t();Y=o.features?.scrollBehavior??{},$e!==$t()&&(sa(),ro()),gu(),rn();let pt=Z;if(Z=o.features?.showEventStreamToggle??!1,Z&&!pt){if(Oe||(xe=new Ka(Ae),Oe=new Ga(Be,xe),ze=ze??new Xa,xe.open().then(()=>Oe?.restore()).catch(()=>{}),$.setSSEEventCallback((ee,Ge)=>{o.onSSEEvent?.(ee,Ge),ze?.processEvent(ee,Ge),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Ge)})})),!tt&&_){let ee=o.features?.eventStream?.classNames,Ge="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",Ge),tt.style.width="28px",tt.style.height="28px",tt.style.color=Jt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let gt=te("activity","18px","currentColor",1.5);gt&&tt.appendChild(gt);let ot=Ee.clearChatButtonWrapper,st=Ee.closeButtonWrapper,qt=ot||st;qt&&qt.parentNode===_?_.insertBefore(tt,qt):_.appendChild(tt),tt.addEventListener("click",()=>{rt?Jr():ml()})}}else!Z&&pt&&(Jr(),tt&&(tt.remove(),tt=null),Oe?.clear(),xe?.destroy(),Oe=null,xe=null,ze?.reset(),ze=null);if(o.launcher?.enabled===!1&&Bt&&(Bt.destroy(),Bt=null),o.launcher?.enabled===!1&&jt&&(jt.remove(),jt=null),o.launcher?.enabled!==!1&&!Bt&&!jt){let{instance:ee,element:Ge}=Rp({config:o,plugins:r,onToggle:Yu});Bt=ee,ee||(jt=Ge),e.appendChild(Ge)}Bt&&Bt.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?Nr(o,nt,{showClose:D(),onClose:()=>ct(!1,"user")}):Jn({config:o,showClose:D(),onClose:()=>ct(!1,"user")});yt.replaceHeader(ee),_=yt.header.element,I=yt.header.iconHolder,N=yt.header.headerTitle,G=yt.header.headerSubtitle,P=yt.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(Ee.clearChatButtonWrapper){let ee=nt.showClearChat;if(ee!==void 0){Ee.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Ge}=Ee;Ge&&!Ge.classList.contains("persona-absolute")&&(ee?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}}let At=o.layout?.showHeader!==!1;_&&(_.style.display=At?"":"none");let Rt=o.layout?.showFooter!==!1;j&&(j.style.display=Rt?"":"none"),dr(),rn(),A!==C?A?ct(w,"auto"):(U=!0,pa()):w!==H&&ct(w,"auto"),H=w,C=A,ma(),lf();let _e=JSON.stringify(o.toolCall)!==JSON.stringify(m),Se=JSON.stringify(o.messageActions)!==JSON.stringify(y),St=JSON.stringify(o.layout?.messages)!==JSON.stringify(v),ut=o.loadingIndicator?.render!==W?.render||o.loadingIndicator?.renderIdle!==W?.renderIdle||o.loadingIndicator?.showBubble!==W?.showBubble,Gt=o.iterationDisplay!==J,ft=(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);(_e||Se||St||ut||Gt||ft)&&$&&(Cl++,ia(ge,$.getMessages(),Ie));let It=o.features?.streamAnimation?.type;if(It!==ne&&It&&It!=="none"){let ee=Or(It,o.features?.streamAnimation?.plugins);ee&&Ui(ee,e)}let Pe=o.launcher??{},Ue=Pe.headerIconHidden??!1,Nt=o.layout?.header?.showIcon,_t=Ue||Nt===!1,Ct=Pe.headerIconName,dt=Pe.headerIconSize??"48px";if(I){let ee=pe.querySelector(".persona-border-b-persona-divider"),Ge=ee?.querySelector(".persona-flex-col");if(_t)I.style.display="none",ee&&Ge&&!ee.contains(Ge)&&ee.insertBefore(Ge,ee.firstChild);else{if(I.style.display="",I.style.height=dt,I.style.width=dt,ee&&Ge&&(ee.contains(I)?I.nextSibling!==Ge&&(I.remove(),ee.insertBefore(I,Ge)):ee.insertBefore(I,Ge)),Ct){let ot=parseFloat(dt)||24,st=te(Ct,ot*.6,"currentColor",1);st?I.replaceChildren(st):I.textContent=Pe.agentIconText??"\u{1F4AC}"}else if(Pe.iconUrl){let ot=I.querySelector("img");if(ot)ot.src=Pe.iconUrl,ot.style.height=dt,ot.style.width=dt;else{let st=document.createElement("img");st.src=Pe.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=dt,st.style.width=dt,I.replaceChildren(st)}}else{let ot=I.querySelector("svg"),st=I.querySelector("img");(ot||st)&&I.replaceChildren(),I.textContent=Pe.agentIconText??"\u{1F4AC}"}let gt=I.querySelector("img");gt&&(gt.style.height=dt,gt.style.width=dt)}}let mt=o.layout?.header?.showTitle,et=o.layout?.header?.showSubtitle;if(N&&(N.style.display=mt===!1?"none":""),G&&(G.style.display=et===!1?"none":""),P){let ee=D()&&o.layout?.header?.showCloseButton!==!1;P.style.display=ee?"":"none";let Ge=Pe.closeButtonSize??"32px",gt=Pe.closeButtonPlacement??"inline";P.style.height=Ge,P.style.width=Ge;let{closeButtonWrapper:ot}=Ee,st=gt==="top-right",qt=ot?.classList.contains("persona-absolute");if(ot&&st!==qt)if(ot.remove(),st)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(ot);else{let co=Pe.clearChat?.placement??"inline",xa=Pe.clearChat?.enabled??!0;ot.className=xa&&co==="inline"?"":"persona-ml-auto";let vf=pe.querySelector(".persona-border-b-persona-divider");vf&&vf.appendChild(ot)}if(P.style.color=Pe.closeButtonColor||Jt.actionIconColor,Pe.closeButtonBackgroundColor?(P.style.backgroundColor=Pe.closeButtonBackgroundColor,P.classList.remove("hover:persona-bg-gray-100")):(P.style.backgroundColor="",P.classList.add("hover:persona-bg-gray-100")),Pe.closeButtonBorderWidth||Pe.closeButtonBorderColor){let co=Pe.closeButtonBorderWidth||"0px",xa=Pe.closeButtonBorderColor||"transparent";P.style.border=`${co} solid ${xa}`,P.classList.remove("persona-border-none")}else P.style.border="",P.classList.add("persona-border-none");Pe.closeButtonBorderRadius?(P.style.borderRadius=Pe.closeButtonBorderRadius,P.classList.remove("persona-rounded-full")):(P.style.borderRadius="",P.classList.add("persona-rounded-full")),Pe.closeButtonPaddingX?(P.style.paddingLeft=Pe.closeButtonPaddingX,P.style.paddingRight=Pe.closeButtonPaddingX):(P.style.paddingLeft="",P.style.paddingRight=""),Pe.closeButtonPaddingY?(P.style.paddingTop=Pe.closeButtonPaddingY,P.style.paddingBottom=Pe.closeButtonPaddingY):(P.style.paddingTop="",P.style.paddingBottom="");let sn=Pe.closeButtonIconName??"x",An=Pe.closeButtonIconText??"\xD7";P.innerHTML="";let Dt=te(sn,"28px","currentColor",1);Dt?(Dt.style.display="block",P.appendChild(Dt)):P.textContent=An;let Vt=Pe.closeButtonTooltipText??"Close chat",qn=Pe.closeButtonShowTooltip??!0;P.setAttribute("aria-label",Vt),ot&&Ot({anchor:P,trigger:ot,text:()=>P?.getAttribute("aria-label")??Vt,enabled:qn})}let{clearChatButton:De,clearChatButtonWrapper:ht}=Ee;if(De){let ee=Pe.clearChat??{},Ge=ee.enabled??!0,gt=o.layout?.header?.showClearChat,ot=gt!==void 0?gt:Ge,st=ee.placement??"inline";if(ht){ht.style.display=ot?"":"none";let{closeButtonWrapper:qt}=Ee;!q()&&qt&&!qt.classList.contains("persona-absolute")&&(ot?qt.classList.remove("persona-ml-auto"):qt.classList.add("persona-ml-auto"));let sn=st==="top-right",An=ht.classList.contains("persona-absolute");if(!q()&&sn!==An&&ot){if(ht.remove(),sn)ht.className="persona-absolute persona-top-4 persona-z-50",ht.style.right="48px",pe.style.position="relative",pe.appendChild(ht);else{ht.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ht.style.right="";let Vt=pe.querySelector(".persona-border-b-persona-divider"),qn=Ee.closeButtonWrapper;Vt&&qn&&qn.parentElement===Vt?Vt.insertBefore(ht,qn):Vt&&Vt.appendChild(ht)}let Dt=Ee.closeButtonWrapper;Dt&&!Dt.classList.contains("persona-absolute")&&(sn?Dt.classList.add("persona-ml-auto"):Dt.classList.remove("persona-ml-auto"))}}if(ot){if(!q()){let co=ee.size??"32px";De.style.height=co,De.style.width=co}let qt=ee.iconName??"refresh-cw",sn=ee.iconColor??"";De.style.color=sn||Jt.actionIconColor,De.innerHTML="";let An=q()?"14px":"20px",Dt=te(qt,An,"currentColor",1);if(Dt&&(Dt.style.display="block",De.appendChild(Dt)),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",xa=ee.borderColor||"transparent";De.style.border=`${co} solid ${xa}`,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 Vt=ee.tooltipText??"Clear chat",qn=ee.showTooltip??!0;De.setAttribute("aria-label",Vt),ht&&Ot({anchor:De,trigger:ht,text:()=>De?.getAttribute("aria-label")??Vt,enabled:qn})}}let Ut=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Za],gn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[lr.message,lr.messageAndClick];M=es({parsers:Ut,handlers:gn,getSessionMetadata:h,updateSessionMetadata:S,emit:l.emit,documentRef:typeof document<"u"?document:null}),Ie=dh(o,M,Ce),$.updateConfig(o),ia(ge,$.getMessages(),Ie),vl(),Vu(),Ll($.isStreaming());let ha=o.voiceRecognition?.enabled===!0,Ps=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Et=o.voiceRecognition?.provider?.type==="runtype";if(ha&&(Ps||Et))if(!K||!qe){let ee=Iy(o.voiceRecognition,o.sendButton);ee&&(K=ee.micButton,qe=ee.micButtonWrapper,je.insertBefore(qe,yn),K.addEventListener("click",ks),K.disabled=$.isStreaming())}else{let ee=o.voiceRecognition??{},Ge=o.sendButton??{},gt=ee.iconName??"mic",ot=Ge.size??"40px",st=ee.iconSize??ot,qt=parseFloat(st)||24;K.style.width=st,K.style.height=st,K.style.minWidth=st,K.style.minHeight=st;let sn=ee.iconColor??Ge.textColor;K.innerHTML="";let An=te(gt,qt,sn||"currentColor",1.5);An?K.appendChild(An):K.textContent="\u{1F3A4}";let Dt=ee.backgroundColor??Ge.backgroundColor;Dt?K.style.backgroundColor=Dt: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 Vt=ee.tooltipText??"Start voice recognition",qn=ee.showTooltip??!1;K.setAttribute("aria-label",Vt),qe&&Ot({anchor:K,trigger:qe,text:()=>K?.getAttribute("aria-label")??Vt,enabled:qn}),qe.style.display="",K.disabled=$.isStreaming()}else K&&qe&&(qe.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()&&$.toggleVoice():Rn&&so());if(o.attachments?.enabled===!0){if(!Re||!we){let ee=o.attachments??{},gt=(o.sendButton??{}).size??"40px";Ye||(Ye=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ye.style.display="none",Q.insertBefore(Ye,he)),ke||(ke=document.createElement("input"),ke.type="file",ke.accept=(ee.allowedTypes??Kn).join(","),ke.multiple=(ee.maxFiles??4)>1,ke.style.display="none",ke.setAttribute("aria-label","Attach files"),Q.insertBefore(ke,he)),Re=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",st=gt,qt=parseFloat(st)||40,sn=Math.round(qt*.6);we.style.width=st,we.style.height=st,we.style.minWidth=st,we.style.minHeight=st,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",Vt=>{Vt.preventDefault(),ke?.click()}),Re.appendChild(we);let Dt=ee.buttonTooltipText??"Attach file";Ot({anchor:we,trigger:Re,text:()=>we?.getAttribute("aria-label")??Dt}),Te?Te.append(Re):Q.appendChild(Re),!wt&&ke&&Ye&&(wt=Zo.fromConfig(ee),wt.setPreviewsContainer(Ye),ke.addEventListener("change",async()=>{wt&&ke?.files&&(await wt.handleFileSelect(ke.files),ke.value="")}))}else{Re.style.display="";let ee=o.attachments??{};ke&&(ke.accept=(ee.allowedTypes??Kn).join(","),ke.multiple=(ee.maxFiles??4)>1),wt&&wt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}if(pe.querySelector(".persona-attachment-drop-overlay")?.remove(),pe.appendChild(ch(o.attachments?.dropOverlay)),we){let ee=o.attachments??{},Ge=ee.buttonTooltipText??"Attach file";we.setAttribute("aria-label",Ge),we.textContent="";let gt=parseFloat(o.sendButton?.size??"40px")||40,ot=te(ee.buttonIconName??"paperclip",Math.round(gt*.6),"currentColor",1.5);ot?we.appendChild(ot):we.textContent="\u{1F4CE}",Re&&Ot({anchor:we,trigger:Re,text:()=>we?.getAttribute("aria-label")??Ge})}}else Re&&(Re.style.display="none"),wt&&wt.clearAttachments(),pe.querySelector(".persona-attachment-drop-overlay")?.remove();let Ht=o.sendButton??{},ya=Ht.useIcon??!1,Is=Ht.iconText??"\u2191",vr=Ht.iconName,Ws=Ht.tooltipText??"Send message",Ul=Ht.showTooltip??!1,zo=Ht.size??"40px",Un=Ht.backgroundColor,$o=Ht.textColor;if(ya){if(ce.style.width=zo,ce.style.height=zo,ce.style.minWidth=zo,ce.style.minHeight=zo,ce.style.fontSize="18px",ce.style.lineHeight="1",$o?ce.style.color=$o:ce.style.color="var(--persona-button-primary-fg, #ffffff)",!$.isStreaming())if(ce.innerHTML="",vr){let ee=parseFloat(zo)||24,Ge=$o?.trim()||"currentColor",gt=te(vr,ee,Ge,2);gt?ce.appendChild(gt):ce.textContent=Is}else ce.textContent=Is;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"),$o?ce.style.color=$o:ce.classList.add("persona-text-white");Ht.borderWidth?(ce.style.borderWidth=Ht.borderWidth,ce.style.borderStyle="solid"):(ce.style.borderWidth="",ce.style.borderStyle=""),Ht.borderColor?ce.style.borderColor=Ht.borderColor:ce.style.borderColor="",Ht.paddingX?(ce.style.paddingLeft=Ht.paddingX,ce.style.paddingRight=Ht.paddingX):(ce.style.paddingLeft="",ce.style.paddingRight=""),Ht.paddingY?(ce.style.paddingTop=Ht.paddingY,ce.style.paddingBottom=Ht.paddingY):(ce.style.paddingTop="",ce.style.paddingBottom=""),$.isStreaming()||ce.setAttribute("aria-label",Ws),yn&&Ot({anchor:ce,trigger:yn,text:()=>ce.getAttribute("aria-label")??Ws,enabled:Ul});let Hs=o.layout?.contentMaxWidth??(q()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);Hs?(ge.style.maxWidth=Hs,ge.style.marginLeft="auto",ge.style.marginRight="auto",ge.style.width="100%",Q&&(Q.style.maxWidth=Hs,Q.style.marginLeft="auto",Q.style.marginRight="auto"),xt&&(xt.style.maxWidth=Hs,xt.style.marginLeft="auto",xt.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=""),xt&&(xt.style.maxWidth="",xt.style.marginLeft="",xt.style.marginRight=""));let lo=o.statusIndicator??{},Oy=lo.visible??!0;if(R.style.display=Oy?"":"none",$){let ee=$.getStatus();Tt(R,(gt=>gt==="idle"?lo.idleText??Wt.idle:gt==="connecting"?lo.connectingText??Wt.connecting:gt==="connected"?lo.connectedText??Wt.connected:gt==="error"?lo.errorText??Wt.error:Wt[gt])(ee),lo,ee)}R.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Ny=lo.align==="left"?"persona-text-left":lo.align==="center"?"persona-text-center":"persona-text-right";R.classList.add(Ny)},open(){D()&&ct(!0,"api")},close(){D()&&ct(!1,"api")},toggle(){D()&&ct(!U,"api")},reconnect(){$.reconnectNow()},clearChat(){Dn=!1,$.clearMessages(),Fo.clear(),ro();try{localStorage.removeItem(jr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${jr}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==jr)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&&Ml(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},M.syncFromMetadata(),Oe?.clear(),ze?.reset(),Ne?.update()},setMessage(i){return!he||$.isStreaming()?!1:(!U&&D()&&ct(!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()&&ct(!0,"system"),he.value="",he.style.height="auto",$.sendMessage(m),!0):!1},startVoiceRecognition(){return $.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()||(!U&&D()&&ct(!0,"system"),Xe.manuallyDeactivated=!1,wn(),$.toggleVoice().then(()=>{Xe.active=$.isVoiceActive(),On("user"),$.isVoiceActive()&&xr()})),!0):Rn?!0:Qu()?(!U&&D()&&ct(!0,"system"),Xe.manuallyDeactivated=!1,wn(),Ts("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,wn(),On("user"),_n()}),!0):!1:Rn?(Xe.manuallyDeactivated=!0,wn(),so("user"),!0):!1},injectMessage(i){return!U&&D()&&ct(!0,"system"),$.injectMessage(i)},injectAssistantMessage(i){!U&&D()&&ct(!0,"system");let m=$.injectAssistantMessage(i);return ie&&(ie=!1,le&&(clearTimeout(le),le=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),m},injectUserMessage(i){return!U&&D()&&ct(!0,"system"),$.injectUserMessage(i)},injectSystemMessage(i){return!U&&D()&&ct(!0,"system"),$.injectSystemMessage(i)},injectMessageBatch(i){return!U&&D()&&ct(!0,"system"),$.injectMessageBatch(i)},injectComponentDirective(i){return!U&&D()&&ct(!0,"system"),$.injectComponentDirective(i)},injectTestMessage(i){!U&&D()&&ct(!0,"system"),$.injectTestEvent(i)},async connectStream(i,m){return $.connectStream(i,m)},__pushEventStreamEvent(i){Oe&&(ze?.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||ml()},hideEventStream(){rt&&Jr()},isEventStreamVisible(){return rt},showArtifacts(){Qt(o)&&(Dn=!1,cr=!0,Fn(),Ze?.setMobileOpen(!0))},hideArtifacts(){Qt(o)&&(Dn=!0,Fn())},upsertArtifact(i){return Qt(o)?(Go(o.features?.artifacts,i.artifactType)==="panel"&&(Dn=!1,cr=!0),$.upsertArtifact(i)):null},selectArtifact(i){Qt(o)&&$.selectArtifact(i)},clearArtifacts(){Qt(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 Xe.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:Xe.active,streaming:$.isStreaming()}},showCSATFeedback(i){!U&&D()&&ct(!0,"system");let m=ge.querySelector(".persona-feedback-container");m&&m.remove();let y=al({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()&&ct(!0,"system");let m=ge.querySelector(".persona-feedback-container");m&&m.remove();let y=sl({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(){Wl(),qo!=null&&(clearInterval(qo),qo=null),Ve.forEach(i=>i()),He.remove(),Ke?.remove(),Bt?.destroy(),jt?.remove(),Do&&P.removeEventListener("click",Do)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,m={controller:Pt,getMessages:Pt.getMessages,getStatus:Pt.getStatus,getMetadata:Pt.getPersistentMetadata,updateMetadata:Pt.updatePersistentMetadata,clearHistory:()=>Pt.clearChat(),setVoiceActive:y=>y?Pt.startVoiceRecognition():Pt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,Ve.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)&&Pt.focusInput()};if(window.addEventListener("persona:focusInput",m),Ve.push(()=>{window.removeEventListener("persona:focusInput",m)}),Z){let V=oe=>{let ue=oe.detail;(!ue?.instanceId||ue.instanceId===i)&&Pt.showEventStream()},X=oe=>{let ue=oe.detail;(!ue?.instanceId||ue.instanceId===i)&&Pt.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",X),Ve.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",X)})}let y=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Pt.showArtifacts()},v=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Pt.hideArtifacts()},k=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||X?.artifact&&Pt.upsertArtifact(X.artifact)},W=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||typeof X?.id=="string"&&Pt.selectArtifact(X.id)},J=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Pt.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),Ve.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=HC(o.persistState);if(mn&&D()){let i=BC(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(()=>{Pt.open(),setTimeout(()=>{if(W||J)Pt.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),Ve.push(()=>{window.removeEventListener("persona:clear-chat",X)})}}}if(g&&D()&&setTimeout(()=>{Pt.open()},0),gr(),!ny){let i=wr(()=>{$&&(Cl++,Fo.clear(),ia(ge,$.getMessages(),Ie))});Ve.push(i)}return Pt};var ph=(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},OC=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},NC=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},_C=(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.")},uh=(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"},Yp=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=""},fh=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Yp(e)},Xp=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=""},Qp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},dl=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},UC=(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))},qC=(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)},VC=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,wi),canvasBackground:o(n?.canvasBackground,Ai)}},mh=(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},zC=(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??"";UC(e,t,n,o,d),qC(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"),Jp(t),Xp(o),fh(o),Qp(n),dl(r,o),mh(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",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"),fh(o),OC(o,p.maxHeight),mh(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",Jp(t),Xp(o),Qp(n),dl(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",Xp(o),Yp(o),dl(r,o);let M=ph(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),Yp(o),Qp(n),dl(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",NC(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(${ph(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 uh(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){uh(n,o)},destroy(){n.remove()}}},jC=(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?VC(t):null};S();let L=()=>{zC(s,l,p,d,c,t,u,h)},E=null,M=()=>{E?.(),E=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(E=Wr(()=>{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,_C(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()}}},ns=(e,t)=>kt(t)?jC(e,t):$C(e,t);var GC=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},gh=(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)},hh=e=>{let t=GC(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,a=ns(t,r),s,l=[],p=(L,E)=>{let A=!(E?.launcher?.enabled??!0)||kt(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),gh(T,o)}else L.appendChild(w),gh(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=ll(L,r,{debugTools:e.debugTools}),c()},g=()=>{l.forEach(L=>L()),l=[],s.destroy()};u(),e.onChatReady?.();let f=L=>{g(),a.destroy(),a=ns(t,L),r=L,u()},h={update(L){let E=el(r??{},L),M=kt(r),A=kt(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 KC(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 XC(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:KC(o,n)?2:3}function yh(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function cl(e,t){let n=t.trim();if(!n)return[...e].sort(yh);let o=[];for(let r of e){let a=XC(r.label,n);a!==3&&o.push({item:r,tier:a})}return o.sort((r,a)=>r.tier!==a.tier?r.tier-a.tier:yh(r.item,a.item)),o.map(r=>r.item)}function JC(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 xh(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>cl(e.items,t),resolve:e.resolve}}function bh(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=>cl(t,JC(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 Sh=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),QC=new Set(["button","a","input","select","textarea","details","summary"]),YC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Zp=/\b(product|card|item|listing|result)\b/i,tu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,ZC=3e3,ew=100;function Mh(e){let t=typeof e.className=="string"?e.className:"";if(Zp.test(t)||e.id&&Zp.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Zp.test(o.value))return!0}return!1}function Th(e){return tu.test((e.textContent??"").trim())}function Eh(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 tw(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function vh(e){let t=e.match(tu);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 nw(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 ow="commerce-card",rw="result-card";function wh(e){return!Mh(e)||!Th(e)||!Eh(e)&&!tw(e)?0:5200}function Ah(e){return!Mh(e)||Th(e)||!Eh(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var nu=[{id:ow,scoreElement(e){return wh(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||tu.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(wh(e)===0)return null;let{title:n,href:o}=Ch(e),r=vh((e.textContent??"").trim())??vh(t.text)??"",a=nw(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
|
+
${vt?"background: transparent !important;":""}
|
|
143
|
+
`}if(!v&&!i){let Tt="max-height: -moz-available !important; max-height: stretch !important;",nn=m?"":"padding-top: 1.25em !important;",qs=m?"":`z-index: ${o.launcher?.zIndex??Gt} !important;`;He.style.cssText+=Tt+nn+qs}bn()};Ss(),rr(e,o),as(e,o),ss(e,o),sa=()=>{Ss(),rr(e,o),as(e,o),ss(e,o),ys?e.style.setProperty("--persona-artifact-welded-outer-radius",ys):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ve=[];Ve.push(()=>{document.removeEventListener("keydown",qu)}),Ve.push(()=>{oa!==null&&clearTimeout(oa)});let Rn=null,In=null;Ve.push(()=>{Rn?.(),Rn=null,In?.(),In=null}),aa&&Ve.push(()=>{aa?.disconnect(),aa=null}),Ve.push(()=>{da?.(),da=null,Rl(),bt&&(bt.remove(),bt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),le&&Ve.push(()=>{Me!==null&&(cancelAnimationFrame(Me),Me=null),Xe?.destroy(),Xe=null,We?.destroy(),We=null,Se=null});let _o=null,$u=()=>{_o&&(_o(),_o=null),o.colorScheme==="auto"&&(_o=Nr(()=>{rr(e,o)}))};$u(),Ve.push(()=>{_o&&(_o(),_o=null)}),Ve.push(l);let Ms=o.features?.streamAnimation;if(Ms?.type&&Ms.type!=="none"){let i=zr(Ms.type,Ms.plugins);i&&(Qi(i,e),Ve.push(()=>Ng(e)))}let Ts=sh(it),Uo=null,z,Il=i=>{if(!z)return;let m=i??z.getMessages(),y=o.features?.suggestReplies?.enabled!==!1?oi(m):null;y?Ts.render(y,z,pe,m,o.suggestionChipsConfig,{agentPushed:!0}):m.some(v=>v.role==="user")?Ts.render([],z,pe,m):Ts.render(o.suggestionChips,z,pe,m,o.suggestionChipsConfig)},wn=!1,qo=Lg(),xr=new Map,Vo=new Map,so=new Map,Wl=0,Sy=Gn()!==null,sn=$i(),mn=0,io=null,gn=!1,Es=!1,lo=0,An=null,zo=null,Hl=!1,ks=!1,ca=null,pa=!0,Ls=!1,Ps=null,Rs=!1,$o=()=>{Rs=!0},Bl=null,My=4,Is=24,Ty=80,Dl=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ju=o.voiceRecognition?.autoResume??!1,qn=i=>{p.emit("voice:state",{active:Ke.active,source:i,timestamp:Date.now()})},Sn=()=>{E(i=>({...i,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Ey=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=pu(u.voiceState),m=!!i.active,y=Number(i.timestamp??0);Ke.manuallyDeactivated=!!i.manuallyDeactivated,m&&Date.now()-y<lw&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?z.toggleVoice().then(()=>{Ke.active=z.isVoiceActive(),qn("restore"),z.isVoiceActive()&&Sr()}):Fs("restore"))},1e3)},ky=()=>z?Ph(z.getMessages()).filter(i=>!i.__skipPersist):[],Ws=null,Gu=(i,m)=>{typeof console<"u"&&console.error(i,m)},Fl=(i,m)=>{let y=()=>{try{let J=i();return!J||typeof J.then!="function"?null:Promise.resolve(J).catch(V=>{Gu(m,V)})}catch(J){return Gu(m,J),null}},v=Ws,L=v?v.then(()=>y()??void 0):y();if(!L)return;let I=L.finally(()=>{Ws===I&&(Ws=null)});Ws=I};function Ol(i){if(!d?.save)return;let y={messages:i?Ph(i):z?ky():[],metadata:u,artifacts:vn.artifacts,selectedArtifactId:vn.selectedId};Fl(()=>d.save(y),"[AgentWidget] Failed to persist state:")}let vr=null,Ku=()=>He.querySelector("#persona-scroll-container")||ae,ua=()=>{vr!==null&&(cancelAnimationFrame(vr),vr=null),gn=!1},Xu=()=>{io!==null&&(cancelAnimationFrame(io),io=null),Es=!1,ua()},Ly=()=>wn&&_l()&&(fn()!=="anchor-top"||Lu()),Nl=()=>{let i=Do()||"Jump to latest",m=Ly();kt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),lo>0?(Fo.textContent=String(lo),Fo.style.display="",kt.setAttribute("aria-label",`${i} (${lo} new)`)):(Fo.textContent="",Fo.style.display="none",kt.setAttribute("aria-label",m?`${i} (response streaming below)`:i))},Ju=()=>{lo!==0&&(lo=0,Nl())},_l=()=>no()?!sn.isFollowing():!Wo(ae,Is),ln=()=>{if(!gs()||$e){kt.parentNode&&kt.remove(),kt.style.display="none";return}kt.parentNode!==ue&&ue.appendChild(kt),gr();let m=Fn(ae)>0&&_l();m?Nl():Ju(),kt.style.display=m?"":"none"},fa=()=>{sn.pause()&&(Xu(),ln())},co=()=>{sn.resume(),Ju(),ln()},po=(i=!1)=>{no()&&sn.isFollowing()&&(!i&&!wn||(io!==null&&(cancelAnimationFrame(io),io=null),Es=!0,io=requestAnimationFrame(()=>{io=null,Es=!1,sn.isFollowing()&&Py(Ku(),i?220:140)})))},Qu=(i,m,y,v=()=>!0)=>{let L=i.scrollTop,I=m(),J=I-L;if(ua(),Math.abs(J)<1){gn=!0,i.scrollTop=I,mn=i.scrollTop,gn=!1;return}let V=performance.now();gn=!0;let X=fe=>1-Math.pow(1-fe,3),se=fe=>{if(!v()){ua();return}let re=m();re!==I&&(I=re,J=I-L);let xe=fe-V,ze=Math.min(xe/y,1),pt=X(ze),nt=L+J*pt;i.scrollTop=nt,mn=i.scrollTop,ze<1?vr=requestAnimationFrame(se):(i.scrollTop=I,mn=i.scrollTop,vr=null,gn=!1)};vr=requestAnimationFrame(se)},Py=(i,m=500)=>{let y=Fn(i)-i.scrollTop;if(Math.abs(y)<1){mn=i.scrollTop;return}if(Math.abs(y)>=Ty){ua(),gn=!0,i.scrollTop=Fn(i),mn=i.scrollTop,gn=!1;return}Qu(i,()=>Fn(i),m,()=>sn.isFollowing())},Yu=()=>{let i=Ku();gn=!0,i.scrollTop=Fn(i),mn=i.scrollTop,gn=!1,ln()},Zu=i=>{let m=0,y=i;for(;y&&y!==ae;)m+=y.offsetTop,y=y.offsetParent;return m},Ry=()=>{let i=ae.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ae.ownerDocument.getSelection()},Hs=()=>Hg(Ry(),ae),ef=()=>{if(yy()!=="last-user-turn")return!1;let i=z?.getMessages()??[];if(i.length<2)return!1;let m=[...i].reverse().find(I=>I.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=ae.querySelector(`[data-message-id="${y}"]`);if(!v)return!1;let L=Math.min(Math.max(0,Zu(v)-Eu()),Fn(ae));return gn=!0,ae.scrollTop=L,mn=ae.scrollTop,gn=!1,fn()==="follow"&&!Wo(ae,Is)&&sn.pause(),ln(),!0},tf=i=>{oo.style.height=`${Math.max(0,Math.round(i))}px`,An&&(An.spacerHeight=Math.max(0,i))},ma=()=>{zo!==null&&(cancelAnimationFrame(zo),zo=null),ua(),An=null,oo.style.height="0px"},nf=i=>{zo!==null&&cancelAnimationFrame(zo),zo=requestAnimationFrame(()=>{zo=null;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=ae.querySelector(`[data-message-id="${m}"]`);if(!y)return;let v=Zu(y),L=An?.spacerHeight??0,I=ae.scrollHeight-L,{targetScrollTop:J,spacerHeight:V}=Bg({anchorOffsetTop:v,topOffset:Eu(),viewportHeight:ae.clientHeight,contentHeight:I});An={initialSpacerHeight:V,contentHeightAtAnchor:I,spacerHeight:V},tf(V),Qu(ae,()=>J,220)})},Iy=()=>{if(no()){if(!sn.isFollowing()||Wo(ae,1))return;po(!wn);return}if(An&&An.initialSpacerHeight>0){let i=ae.scrollHeight-An.spacerHeight,m=Dg({initialSpacerHeight:An.initialSpacerHeight,contentHeightAtAnchor:An.contentHeightAtAnchor,currentContentHeight:i});m!==An.spacerHeight&&tf(m)}ln()},Wy=i=>{let m=fn();m==="follow"?(co(),po(!0)):m==="anchor-top"&&(pa=!1,Ls=!0,Rs=!1,Ps=i,nf(i))},Hy=()=>{if(fn()==="anchor-top"){if(Ls){pa=!1;return}pa=!0,ma(),co(),po(!0)}},By=i=>{if(fn()!=="anchor-top"||!Ls||Rs||Hs())return;let m=ca===null;for(let y of i){if(!m){y.id===ca&&(m=!0);continue}if(Wg(y)){if(y.id===Ps)return;Ps=y.id,nf(y.id);return}}},Dy=i=>{let m=new Map;i.forEach(y=>{let v=Dl.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!v&&y.role==="assistant"&&(p.emit("assistant:message",y),!ks&&(fn()!=="anchor-top"||Lu())&&_l()&&(lo+=1,Nl(),ln(),Ru(lo===1?"1 new message below.":`${lo} new messages below.`))),y.role==="assistant"&&v?.streaming&&y.streaming===!1&&p.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(v?y.approval.status!=="pending"&&p.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):p.emit("approval:requested",{approval:y.approval,message:y}))}),Dl.clear(),m.forEach((y,v)=>{Dl.set(v,y)})},Bs=(i,m)=>{let y=m==="user"?"user":"assistant",v=o.layout?.messages?.[y],L=v?.width??"content",I=v?.maxWidth??(L==="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-${L}`),i.classList.toggle("persona-justify-end",m==="user"),i.setAttribute("data-message-role",m),i.setAttribute("data-message-width",L),i.style.setProperty("--persona-message-row-max-width",I)},jo=(i,m)=>{let y=document.createElement("div");return y.className="persona-flex",y.id=`wrapper-${i}`,y.setAttribute("data-wrapper-id",i),Bs(y,m),y},Fy=(i,m,y)=>{let v=document.createElement("div"),I=(()=>{let N=a.find(Te=>Te.renderLoadingIndicator);if(N?.renderLoadingIndicator)return N.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),J=(N,Te)=>Te==null?!1:typeof Te=="string"?(N.textContent=Te,!0):(N.appendChild(Te),!0),V=new Set,X=new Map,se=new Set,fe=a.some(N=>N.renderAskUserQuestion),re=[],xe=[],ze=o.enableComponentStreaming!==!1,pt=o.approval!==!1,nt=[];if(m.forEach(N=>{V.add(N.id),X.set(N.id,N.role);let Te=fe&&Xn(N),Oe=pt&&N.variant==="approval"&&!!N.approval,Ce=!Te&&N.role==="assistant"&&!N.variant&&ze&&ps(N);!Oe&&so.has(N.id)&&(i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),so.delete(N.id)),!Ce&&Vo.has(N.id)&&(i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),Vo.delete(N.id));let Ct=Xn(N)?`:${N.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${N.agentMetadata?.askUserQuestionAnswers?Object.keys(N.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=kg(N,Wl)+Ct,Ft=Te||Oe||Ce?null:Pg(qo,N.id,ut);if(Ft){v.appendChild(Ft.cloneNode(!0)),Xn(N)&&N.toolCall?.id&&N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(se.add(N.toolCall.id),Wr(N,o,Pe.composerOverlay));return}let ft=null,tn=a.find(Ne=>!!(N.variant==="reasoning"&&Ne.renderReasoning||N.variant==="tool"&&Ne.renderToolCall||!N.variant&&Ne.renderMessage)),Rt=o.layout?.messages;if(Xn(N)&&N.agentMetadata?.askUserQuestionAnswered===!0){xr.delete(N.id),i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ba(N)&&o.features?.suggestReplies?.enabled!==!1)return;if(Xn(N)&&o.features?.askUserQuestion?.enabled!==!1){let Ne=a.find(qt=>typeof qt.renderAskUserQuestion=="function");if(Ne&<.current){let qt=xr.get(N.id),Vt=qt!==ut,vt=null;if(Vt){let{payload:Ze,complete:Ie}=Jn(N),yt=N.id,zt=()=>lt.current?.getMessages().find(bn=>bn.id===yt);vt=Ne.renderAskUserQuestion({message:N,payload:Ze,complete:Ie,resolve:bn=>{let Sa=zt();Sa&<.current?.resolveAskUserQuestion(Sa,bn)},dismiss:()=>{let bn=zt();bn?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(bn),lt.current?.resolveAskUserQuestion(bn,"(dismissed)"))},config:o})}let dt=qt!=null;if(Vt&&vt===null&&!dt){N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(se.add(N.toolCall.id),Wr(N,o,Pe.composerOverlay));return}let gt=jo(N.id,N.role);gt.setAttribute("data-ask-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),v.appendChild(gt),re.push({messageId:N.id,fingerprint:ut,bubble:vt});return}else{N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(se.add(N.toolCall.id),Wr(N,o,Pe.composerOverlay));return}}else if(Oe){let Ne=a.find(dt=>typeof dt.renderApproval=="function")??s,Vt=so.get(N.id)!==ut,vt=null;if(Vt&&Ne?.renderApproval){let dt=N.id,gt=(Ze,Ie)=>{let yt=lt.current?.getMessages().find(zt=>zt.id===dt);yt?.approval&&(yt.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(yt.id,Ze):lt.current?.resolveApproval(yt.approval,Ze,Ie))};vt=Ne.renderApproval({message:N,defaultRenderer:()=>ll(N,o),config:o,approve:Ze=>gt("approved",Ze),deny:Ze=>gt("denied",Ze)})}if(Vt&&vt===null)i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),so.delete(N.id),ft=ll(N,o);else{let dt=jo(N.id,N.role);dt.setAttribute("data-approval-plugin-stub","true"),dt.setAttribute("data-preserve-runtime","true"),v.appendChild(dt),nt.push({messageId:N.id,fingerprint:ut,bubble:vt});return}}else if(tn)if(N.variant==="reasoning"&&N.reasoning&&tn.renderReasoning){if(!ge)return;ft=tn.renderReasoning({message:N,defaultRenderer:()=>Jp(N,o),config:o})}else if(N.variant==="tool"&&N.toolCall&&tn.renderToolCall){if(!ne)return;ft=tn.renderToolCall({message:N,defaultRenderer:()=>Yp(N,o),config:o})}else tn.renderMessage&&(ft=tn.renderMessage({message:N,defaultRenderer:()=>{let Ne=Gr(N,y,Rt,o.messageActions,Je,{loadingIndicatorRenderer:I,widgetConfig:o});return N.role!=="user"&&lu(Ne,N,o,z),Ne},config:o}));if(!ft&&Ce){let Ne=hl(N);if(Ne){let qt=Vo.get(N.id),Vt=qt!==ut,vt=o.wrapComponentDirectiveInBubble!==!1&&Ln.getOptions(Ne.component)?.bubbleChrome!==!1,dt=null;if(Vt){let gt=gl(Ne,{config:o,message:N,transform:y});if(gt&&Ne.component==="PersonaArtifactInline"){let Ze=gt.hasAttribute("data-artifact-inline")?gt:gt.querySelector("[data-artifact-inline]"),Ie=Ze?.getAttribute("data-artifact-inline")??"",yt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Ie):Ie,zt=Ie?i.querySelector(`#wrapper-${N.id}`)?.querySelector(`[data-artifact-inline="${yt}"]`)??null:null;Ze&&zt&&zt!==Ze&&wg(zt)&&(Ze===gt?gt=zt:Ze.replaceWith(zt))}if(gt)if(vt){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-${N.id}`,Ze.setAttribute("data-message-id",N.id),N.content&&N.content.trim()){let Ie=document.createElement("div");Ie.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ie.innerHTML=y({text:N.content,message:N,streaming:!!N.streaming,raw:N.rawContent}),Ze.appendChild(Ie)}Ze.appendChild(gt),dt=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-${N.id}`,Ze.setAttribute("data-message-id",N.id),Ze.setAttribute("data-persona-component-directive","true"),N.content&&N.content.trim()){let Ie=document.createElement("div");Ie.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ie.innerHTML=y({text:N.content,message:N,streaming:!!N.streaming,raw:N.rawContent}),Ze.appendChild(Ie)}Ze.appendChild(gt),dt=Ze}}if(dt||qt!=null){let gt=jo(N.id,N.role);gt.setAttribute("data-component-directive-stub","true"),gt.setAttribute("data-preserve-runtime","true"),v.appendChild(gt),xe.push({messageId:N.id,fingerprint:ut,bubble:dt});return}}}if(!ft)if(N.variant==="reasoning"&&N.reasoning){if(!ge)return;ft=Jp(N,o)}else if(N.variant==="tool"&&N.toolCall){if(!ne)return;ft=Yp(N,o)}else if(N.variant==="approval"&&N.approval){if(o.approval===!1)return;ft=ll(N,o)}else{let Ne=o.layout?.messages;Ne?.renderUserMessage&&N.role==="user"?ft=Ne.renderUserMessage({message:N,config:o,streaming:!!N.streaming}):Ne?.renderAssistantMessage&&N.role==="assistant"?ft=Ne.renderAssistantMessage({message:N,config:o,streaming:!!N.streaming}):ft=Gr(N,y,Ne,o.messageActions,Je,{loadingIndicatorRenderer:I,widgetConfig:o}),N.role!=="user"&&ft&&lu(ft,N,o,z)}let Ee=jo(N.id,N.role);Ee.appendChild(ft),Rg(qo,N.id,ut,Ee),v.appendChild(Ee)}),Pe.composerOverlay&&Pe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Te=>{let Oe=Te.getAttribute("data-persona-ask-sheet-for");Oe&&!se.has(Oe)&&Co(Pe.composerOverlay,Oe)}),o.features?.toolCallDisplay?.grouped){let N=[],Te=[],Oe=o.features.toolCallDisplay.groupedMode==="summary";m.forEach(Ce=>{if(Ce.variant==="tool"&&Ce.toolCall&&ne){Te.push(Ce);return}Ce.variant==="reasoning"&&!ge||((Te.length>1||Oe&&Te.length>0)&&N.push(Te),Te=[])}),(Te.length>1||Oe&&Te.length>0)&&N.push(Te),N.forEach(Ce=>{let Ct=Ce.map(Ne=>Array.from(v.children).find(qt=>qt instanceof HTMLElement&&qt.getAttribute("data-wrapper-id")===Ne.id)).filter(Ne=>!!Ne);if(Ct.length<(Oe?1:2))return;let ut=jo(`tool-group-${Ce[0].id}`,"assistant");ut.setAttribute("data-persona-tool-group-row","true");let Ft=document.createElement("div");Ft.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ft.setAttribute("data-persona-tool-group","true");let ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ft.id=`tool-group-summary-${Ce[0].id}`;let tn=`Called ${Ce.length} ${Ce.length===1?"tool":"tools"}`,Rt=o.toolCall?.renderGroupedSummary?.({messages:Ce,toolCalls:Ce.map(Ne=>Ne.toolCall).filter(Ne=>!!Ne),defaultSummary:tn,config:o});J(ft,Rt)||(ft.textContent=tn);let Ee=document.createElement("div");Ee.className="persona-tool-group-stack persona-flex persona-flex-col",Ee.id=`tool-group-stack-${Ce[0].id}`,Ee.setAttribute("data-persona-tool-group-stack","true"),Ft.appendChild(ft),Oe||Ft.appendChild(Ee),ut.appendChild(Ft),Ct[0].before(ut),Ct.forEach((Ne,qt)=>{if(Oe){Ne.remove();return}Ne.style.setProperty("--persona-message-row-max-width","100%");let Vt=document.createElement("div");Vt.className="persona-tool-group-item persona-relative",Vt.setAttribute("data-persona-tool-group-item","true"),qt<Ct.length-1&&Vt.setAttribute("data-persona-tool-group-connector","true"),Vt.appendChild(Ne),Ee.appendChild(Vt)})})}Ig(qo,V);let dn=m.some(N=>N.role==="assistant"&&N.streaming),St=m[m.length-1],Pt=St?.role==="assistant"&&!St.streaming&&St.variant!=="approval";if(wn&&m.some(N=>N.role==="user")&&!dn&&!Pt){let N={config:o,streaming:!0,location:"standalone",defaultRenderer:lr},Te=a.find(Ce=>Ce.renderLoadingIndicator),Oe=null;if(Te?.renderLoadingIndicator&&(Oe=Te.renderLoadingIndicator(N)),Oe===null&&o.loadingIndicator?.render&&(Oe=o.loadingIndicator.render(N)),Oe===null&&(Oe=lr()),Oe){let Ce=document.createElement("div"),Ct=o.loadingIndicator?.showBubble!==!1,ut=o.layout?.messages?.layout??"bubble";Ce.className=Ct?Kp("assistant",ut).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Ce.setAttribute("data-typing-indicator","true"),Ct&&(Ce.style.color="var(--persona-message-assistant-text, var(--persona-text))",ut!=="flat"&&(Ce.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Ce.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Ce.appendChild(Oe);let Ft=jo("typing-indicator","assistant");Ft.appendChild(Ce),v.appendChild(Ft)}}if(!wn&&m.length>0){let N=m[m.length-1],Te={config:o,lastMessage:N,messageCount:m.length},Oe=a.find(Ct=>Ct.renderIdleIndicator),Ce=null;if(Oe?.renderIdleIndicator&&(Ce=Oe.renderIdleIndicator(Te)),Ce===null&&o.loadingIndicator?.renderIdle&&(Ce=o.loadingIndicator.renderIdle(Te)),Ce){let Ct=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;Ct.className=ut?["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(" "),Ct.setAttribute("data-idle-indicator","true"),Ct.appendChild(Ce);let Ft=jo("idle-indicator","assistant");Ft.appendChild(Ct),v.appendChild(Ft)}}if(em(v),zi(i,v),od(i),re.length>0)for(let{messageId:N,fingerprint:Te,bubble:Oe}of re){let Ce=i.querySelector(`#wrapper-${N}`);Ce&&(Bs(Ce,X.get(N)??"assistant"),Oe!==null&&(Ce.replaceChildren(Oe),Ce.setAttribute("data-bubble-fp",Te),xr.set(N,Te)))}if(xr.size>0)for(let N of xr.keys())V.has(N)||xr.delete(N);if(xe.length>0)for(let{messageId:N,fingerprint:Te,bubble:Oe}of xe){let Ce=i.querySelector(`#wrapper-${N}`);Ce&&(Bs(Ce,X.get(N)??"assistant"),Oe!==null&&(Ce.replaceChildren(Oe),Ce.setAttribute("data-bubble-fp",Te),Vo.set(N,Te)))}if(Vo.size>0)for(let N of Vo.keys())V.has(N)||Vo.delete(N);if(nt.length>0)for(let{messageId:N,fingerprint:Te,bubble:Oe}of nt){let Ce=i.querySelector(`#wrapper-${N}`);Ce&&(Bs(Ce,X.get(N)??"assistant"),Oe!==null&&(Ce.replaceChildren(Oe),Ce.setAttribute("data-bubble-fp",Te),so.set(N,Te)))}if(so.size>0)for(let N of so.keys())V.has(N)||so.delete(N)},ga=(i,m,y)=>{Fy(i,m,y),Nu()},ha=null,Oy=()=>{if(ha)return;let i=y=>{let v=y.composedPath();v.includes(He)||et&&v.includes(et)||ct(!1,"user")};ha=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},of=()=>{if(!ha)return;(e.ownerDocument??document).removeEventListener("pointerdown",ha,!0),ha=null};Ve.push(()=>of());let ya=null,Ny=()=>{if(ya)return;let i=y=>{y.key==="Escape"&&(y.isComposing||ct(!1,"user"))};ya=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},rf=()=>{if(!ya)return;(e.ownerDocument??document).removeEventListener("keydown",ya,!0),ya=null};Ve.push(()=>rf());let ba=!1,af=new Set,_y=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Cr=()=>{if(!O())return;let i=Pe.peekBanner,m=Pe.peekTextNode;if(!i||!m)return;if(Q){i.classList.remove("persona-pill-peek--visible");return}let y=z?.getMessages()??[],v;for(let St=y.length-1;St>=0;St--){let Pt=y[St];if(Pt.role==="assistant"&&Pt.content){v=Pt;break}}if(!v){i.classList.remove("persona-pill-peek--visible");return}let L=v.content,I=!!v.streaming,J=_y(),V=Ki(J),X=V.type!=="none"?zr(V.type,J?.plugins):null,se=X?.isAnimating?.(v)===!0,fe=X!==null&&(I||se);fe&&X&&!af.has(X.name)&&(Qi(X,e),af.add(X.name));let re=fe&&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),fe?(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=fe?Xi(L,V.buffer,X,v,I):L;if(fe&&V.placeholder==="skeleton"&&I&&(!ze||!ze.trim())){let St=document.createElement("div"),Pt=Za();Pt.classList.add("persona-pill-peek__skeleton"),St.appendChild(Pt),zi(m,St)}else{let St=Math.max(0,ze.length-100),Pt=ze.length>100?ze.slice(-100):ze,N=Hn(Pt);if(!fe||!X){let Te=ze.length>100?`\u2026${Pt}`:Pt;m.textContent!==Te&&(m.textContent=Te)}else{let Te=N;(X.wrap==="char"||X.wrap==="word")&&(Te=Ya(N,X.wrap,`peek-${v.id}`,{skipTags:X.skipTags,startIndex:St}));let Oe=document.createElement("div");if(Oe.innerHTML=Te,X.useCaret&&Pt.length>0){let Ce=Ji(),Ct=Oe.querySelectorAll(".persona-stream-char, .persona-stream-word"),ut=Ct[Ct.length-1];ut?.parentNode?ut.parentNode.insertBefore(Ce,ut.nextSibling):Oe.appendChild(Ce)}zi(m,Oe),X.onAfterRender?.({container:m,bubble:i,messageId:v.id,message:v,speed:V.speed,duration:V.duration})}}let dn=wn||ba;i.classList.toggle("persona-pill-peek--visible",dn)};if(O()){let i=Pe.peekBanner;if(i){let v=L=>{L.preventDefault(),L.stopPropagation(),ct(!0,"user")};i.addEventListener("pointerdown",v),Ve.push(()=>{i.removeEventListener("pointerdown",v)})}let m=()=>{ba||(ba=!0,Cr())},y=()=>{ba&&(ba=!1,Cr())};ce.addEventListener("pointerenter",m),ce.addEventListener("pointerleave",y),Ve.push(()=>{ce.removeEventListener("pointerenter",m),ce.removeEventListener("pointerleave",y)}),et&&(et.addEventListener("pointerenter",m),et.addEventListener("pointerleave",y),Ve.push(()=>{et.removeEventListener("pointerenter",m),et.removeEventListener("pointerleave",y)}))}let Uy=i=>{let m=o.launcher?.composerBar??{},y=m.expandedSize??"anchored",v=m.bottomOffset??"16px",L=m.collapsedMaxWidth,I=m.expandedMaxWidth??"880px",J=m.expandedTopOffset??"5vh",V=m.modalMaxWidth??"880px",X=m.modalMaxHeight??"min(90vh, 800px)",se="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",re=He.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",et){let xe=et.style;xe.bottom=v,xe.width=L??""}if(i&&y!=="fullscreen"){if(y==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=V,re.maxWidth=se,re.maxHeight=X,re.height=X;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${v} + ${fe})`,re.top=J,re.width=I,re.maxWidth=se}},xa=()=>{if(!q())return;if(O()){let se=(o.launcher?.composerBar??{}).expandedSize??"anchored",fe=Q?"expanded":"collapsed";He.dataset.state=fe,He.dataset.expandedSize=se,et&&(et.dataset.state=fe,et.dataset.expandedSize=se),He.style.removeProperty("display"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Uy(Q),ue.style.display=Q?"flex":"none",Ss(),Q?(Oy(),Ny()):(of(),rf()),Cr();return}let i=Et(o),m=e.ownerDocument.defaultView??window,y=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,L=m.innerWidth<=y,I=v&&L&&C,J=rn(o).reveal;Q?(He.style.removeProperty("display"),He.style.display=i?"flex":"",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0"),ce.classList.add("persona-scale-100","persona-opacity-100"),Ot?Ot.element.style.display="none":Xt&&(Xt.style.display="none")):(i?i&&(J==="overlay"||J==="push")&&!I?(He.style.removeProperty("display"),He.style.display="flex",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.setProperty("display","none","important"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.display="",He.classList.add("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100"),ce.classList.add("persona-scale-95","persona-opacity-0")),Ot?Ot.element.style.display=i?"none":"":Xt&&(Xt.style.display=i?"none":""))},ct=(i,m="user")=>{if(!q()||Q===i)return;let y=Q;Q=i,xa();let v=(()=>{let I=o.launcher?.sidebarMode??!1,J=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,se=J.innerWidth<=X,fe=Et(o)&&V&&se,re=O()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return I||V&&se&&C||fe||re})();if(Q&&v){if(!Rn){let I=e.getRootNode(),J=I instanceof ShadowRoot?I.host:e.closest(".persona-host");J&&(Rn=Op(J,o.launcher?.zIndex??Gt))}In||(In=Np(e.ownerDocument))}else Q||(Rn?.(),Rn=null,In?.(),In=null);Q&&(wa(),ef()||(fn()==="follow"?po(!0):Yu()));let L={open:Q,source:m,timestamp:Date.now()};Q&&!y?p.emit("widget:opened",L):!Q&&y&&p.emit("widget:closed",L),p.emit("widget:state",{open:Q,launcherEnabled:C,voiceActive:Ke.active,streaming:z.isStreaming()})},Ul=i=>{rt(i?"stop":"send"),G&&(G.disabled=i),Ts.buttons.forEach(m=>{m.disabled=i}),Y.dataset.personaComposerStreaming=i?"true":"false",Y.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=i)})},ql=()=>{Ke.active||pe&&pe.focus()};p.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ql(),200)});let sf=()=>{x.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",H.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",pe.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=ae.querySelector("[data-persona-intro-card]");if(i){let y=o.copy?.showWelcomeCard!==!1;i.style.display=y?"":"none",y?(ae.classList.remove("persona-gap-3"),ae.classList.add("persona-gap-6")):(ae.classList.remove("persona-gap-6"),ae.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!z?.isStreaming()&&(ve.textContent=o.copy?.sendButtonLabel??"Send"),pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=u.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{E(m=>({...m,sessionId:i}))}});let Go=null,qy=()=>{Go==null&&(Go=setInterval(()=>{let i=Le.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Go),Go=null;return}let m=Date.now();i.forEach(y=>{let v=Number(y.getAttribute("data-tool-elapsed"));v&&(y.textContent=ai(m-v))})},100))},Vl=(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)=>Vl(J,m[V]));let y=i,v=m,L=Object.keys(y),I=Object.keys(v);return L.length===I.length&&L.every(J=>Object.prototype.hasOwnProperty.call(v,J)&&Vl(y[J],v[J]))},lf=i=>{let{content:m,rawContent:y,llmContent:v,...L}=i;return L},zl=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!ps(i),Vy=(i,m,y)=>{if(i.length!==m.length)return!1;let v=i[y.index],L=m[y.index];return!v||!L||v.id!==y.id||L.id!==y.id?!1:(!Object.is(v.content,L.content)||!Object.is(v.rawContent,L.rawContent)||!Object.is(v.llmContent,L.llmContent))&&zl(v)&&zl(L)&&Vl(lf(v),lf(L))},df=null,wr=null,Ko=null,Vn=null,Ds=i=>{df=i;let m,y;wr=null;for(let L=i.length-1;L>=0;L-=1){let I=i[L];if(!m&&I.role==="user"&&(m=I),!y&&I.role==="assistant"&&(y=I),!wr&&zl(I)&&(wr={index:L,id:I.id}),m&&y&&wr)break}ga(Le,i,ie),Pp(Le,vn.artifacts,{suppressTransition:wn}),qy(),Il(i),po(!wn),Dy(i),i.length===0&&(ma(),pa=!0,Ls=!1,Ps=null,Rs=!1),!Hl||ks?(Hl=!0,ca=m?.id??null,Bl=y?.id??null):m&&m.id!==ca?(ca=m.id,Wy(m.id)):y&&y.id!==Bl&&Hy(),y&&(Bl=y.id),By(i);let v=Ke.lastUserMessageId;m&&m.id!==v&&(Ke.lastUserMessageId=m.id,p.emit("user:message",m)),Ke.lastUserMessageWasVoice=!!m?.viaVoice,Ol(i),Cr()},$l=()=>{Vn!==null&&(cancelAnimationFrame(Vn),Vn=null);let i=Ko;Ko=null,i&&Ds(i)},cf=()=>{Vn!==null&&cancelAnimationFrame(Vn),Vn=null,Ko=null},zy=i=>{let m=Ko??df;if(wn&&m&&wr&&Vy(m,i,wr)){Ko=i,Vn===null&&(Vn=requestAnimationFrame(()=>{Vn=null;let y=Ko;Ko=null,y&&Ds(y)}));return}if(i.length===0){cf(),Ds(i);return}$l(),Ds(i)};z=new Fr(o,{onMessagesChanged(i){zy(i)},onStatusChanged(i){let m=o.statusIndicator??{};Kt(U,(v=>v==="idle"?m.idleText??It.idle:v==="connecting"?m.connectingText??It.connecting:v==="connected"?m.connectedText??It.connected:v==="error"?m.errorText??It.error:v==="paused"?m.pausedText??It.paused:v==="resuming"?m.resumingText??It.resuming:It[v])(i),m,i)},onStreamingChanged(i){i||(z?.getMessages().length===0?cf():$l()),wn=i,Ul(i),z&&ga(Le,z.getMessages(),ie),i||po(!0),ln(),Ru(i?"Responding\u2026":"Response complete."),Cr()},onVoiceStatusChanged(i){if(p.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":zn(),Sr();break;case"processing":zn(),tb();break;case"speaking":zn(),nb();break;default:i==="idle"&&z.isBargeInActive()?(zn(),Sr(),G?.setAttribute("aria-label","End voice session")):(Ke.active=!1,zn(),qn("system"),Sn());break}},onArtifactsState(i){vn=i,i.artifacts.length===0&&(hr=!1),Pp(Le,i.artifacts,{suppressTransition:wn}),Un(),Ol()},onReconnect(i){let{executionId:m,lastEventId:y}=i.handle;i.phase==="paused"?p.emit("stream:paused",{executionId:m,after:y}):i.phase==="resuming"?p.emit("stream:resuming",{executionId:m,after:y,attempt:i.attempt??1}):p.emit("stream:resumed",{executionId:m,after:y})}}),lt.current=z,Ve.push(()=>z.cancel());let jl=null;if(z.onReadAloudChange((i,m)=>{Fu=i,Ou=m,Nu();let y=i??jl;i&&(jl=i);let v=y?z.getMessages().find(L=>L.id===y)??null:null;p.emit("message:read-aloud",{messageId:y,message:v,state:m,timestamp:Date.now()}),m==="idle"&&(jl=null)}),Hl=!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)}),(We||o.onSSEEvent)&&z.setSSEEventCallback((i,m)=>{o.onSSEEvent?.(i,m),_e?.processEvent(i,m),We?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(m)})});let pf=()=>{o.resume&&typeof o.reconnectStream=="function"&&z.resumeFromHandle(o.resume)};g?g.then(i=>{if(i){if(i.metadata&&(u=pu(i.metadata),S.syncFromMetadata()),i.messages?.length){ks=!0;try{z.hydrateMessages(i.messages)}finally{ks=!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(()=>pf()):pf();let uf=()=>{!O()||Q||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ct(!0,"auto")},$y=(i,m)=>i?m?{refs:[...i.refs,...m.refs],finalize:async()=>{let[y,v]=await Promise.allSettled([i.finalize(),m.finalize()]),L=[];return y.status==="fulfilled"?L.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),v.status==="fulfilled"?L.push(v.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",v.reason),gw(L)}}:i:m,jy=()=>{let m=pe.getInlineMessageFields?.();return m&&m.contentSegments.some(v=>v.kind==="mention")?m.contentSegments:void 0},va=!1,Gy=async i=>{let m=pe.value.trim(),y=At?.hasAttachments()??!1,v=m?await(an?.takeInlineCommand(m)??Promise.resolve(null)):null;if(v?.kind==="action"){pe.value="",pe.style.height="auto",Ca(),an?.clear();return}let L=an?.collectForSubmit()??null,I=v?.kind==="server"?v.mentions:null,J=$y(L,I),V=v?.kind==="prompt"?v.sendText:m,X=!!L&&L.refs.length>0;if(!V&&!y&&!X&&!I)return;uf();let se;y&&(se=[],se.push(...At.getContentParts()),V&&se.push(Mo(V)));let fe=v?.kind==="prompt"?void 0:jy();pe.value="",pe.style.height="auto",Ca(),z.sendMessage(V,{contentParts:se,mentions:J??void 0,contentSegments:fe,viaVoice:i?.viaVoice}),y&&At.clearAttachments(),L&&an?.clear()},Gl=async i=>{if(!va){va=!0;try{await Gy(i)}finally{va=!1}}},ff=i=>{if(i.preventDefault(),z.isStreaming()){z.cancel(),_e?.reset(),Xe?.update();return}va||Gl()},Ky=()=>o.features?.composerHistory!==!1,Kl={...Wp},Xl=!1,Ca=()=>{Kl={...Wp}},Xy=()=>z.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Jy=i=>{if(!pe)return;Xl=!0,pe.value=i,pe.dispatchEvent(new Event("input",{bubbles:!0})),Xl=!1;let m=pe.value.length;pe.setSelectionRange(m,m)},Qy=i=>{Xl||(i.isComposing||an?.handleInput(i.inputType??void 0),Ca())},Yy=i=>{if(pe&&!(!i.isComposing&&an?.handleKeydown(i))){if(Ky()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let m=pe.selectionStart===0&&pe.selectionEnd===0,y=Eg({direction:i.key==="ArrowUp"?"up":"down",history:Xy(),currentValue:pe.value,atStart:m,state:Kl});if(Kl=y.state,y.handled){i.preventDefault(),y.value!==void 0&&Jy(y.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(z.isStreaming()){i.preventDefault();return}if(va){i.preventDefault();return}Ca(),i.preventDefault(),ve.click()}}},mf=i=>{i.key!=="Escape"||i.isComposing||z.isStreaming()&&i.composedPath().includes(ue)&&(z.cancel(),_e?.reset(),Xe?.update(),Ca(),i.preventDefault(),i.stopImmediatePropagation())},Zy=async i=>{if(o.attachments?.enabled!==!0||!At)return;let m=pw(i.clipboardData);m.length!==0&&(i.preventDefault(),await At.handleFiles(m))},hn=null,Wn=!1,Ar=null,xt=null,gf=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Fs=(i="user")=>{if(Wn||z.isStreaming())return;let m=gf();if(!m)return;hn=new m;let v=(o.voiceRecognition??{}).pauseDuration??2e3;hn.continuous=!0,hn.interimResults=!0,hn.lang="en-US";let L=pe.value;hn.onresult=I=>{let J="",V="";for(let se=0;se<I.results.length;se++){let fe=I.results[se],re=fe[0].transcript;fe.isFinal?J+=re+" ":V=re}let X=L+J+V;pe.value=X,Ar&&clearTimeout(Ar),(J||V)&&(Ar=window.setTimeout(()=>{pe.value.trim()&&hn&&Wn&&(uo(),Gl({viaVoice:!0}))},v))},hn.onerror=I=>{I.error!=="no-speech"&&uo()},hn.onend=()=>{if(Wn){let I=pe.value.trim();I&&I!==L.trim()&&Gl({viaVoice:!0}),uo()}};try{if(hn.start(),Wn=!0,Ke.active=!0,i!=="system"&&(Ke.manuallyDeactivated=!1),qn(i),Sn(),G){let I=o.voiceRecognition??{};xt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:I.iconName??"mic",iconSize:parseFloat(I.iconSize??o.sendButton?.size??"40")||24};let J=I.recordingBackgroundColor,V=I.recordingIconColor,X=I.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=J??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=V??"var(--persona-voice-recording-indicator, #ffffff)",V){let se=G.querySelector("svg");se&&se.setAttribute("stroke",V)}X&&(G.style.borderColor=X),G.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(i="user")=>{if(Wn){if(Wn=!1,Ar&&(clearTimeout(Ar),Ar=null),hn){try{hn.stop()}catch{}hn=null}if(Ke.active=!1,qn(i),Sn(),G){if(G.classList.remove("persona-voice-recording"),xt){G.style.backgroundColor=xt.backgroundColor,G.style.color=xt.color,G.style.borderColor=xt.borderColor;let m=G.querySelector("svg");m&&m.setAttribute("stroke",xt.color||"currentColor"),xt=null}G.setAttribute("aria-label","Start voice recognition")}}},eb=(i,m)=>{let y=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),v=i?.provider?.type==="runtype",L=i?.provider?.type==="custom";if(!(y||v||L))return null;let J=b("div","persona-send-button-wrapper"),V=b("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 se=i?.iconName??"mic",fe=m?.size??"40px",re=i?.iconSize??fe,xe=parseFloat(re)||24,ze=i?.backgroundColor??m?.backgroundColor,pt=i?.iconColor??m?.textColor;V.style.width=re,V.style.height=re,V.style.minWidth=re,V.style.minHeight=re,V.style.fontSize="18px",V.style.lineHeight="1",pt?V.style.color=pt:V.style.color="var(--persona-text, #111827)";let dn=oe(se,xe,pt||"currentColor",1.5);dn?V.appendChild(dn):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 Ut({anchor:V,trigger:J,text:()=>V.getAttribute("aria-label")??X,enabled:St}),{micButton:V,micButtonWrapper:J}},Jl=()=>{if(!G||xt)return;let i=o.voiceRecognition??{};xt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Ql=(i,m)=>{if(!G)return;let y=G.querySelector("svg");y&&y.remove();let v=xt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),L=oe(i,v,m,1.5);L&&G.appendChild(L)},Os=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Sr=()=>{if(!G)return;Jl();let i=o.voiceRecognition??{},m=i.recordingBackgroundColor,y=i.recordingIconColor,v=i.recordingBorderColor;if(Os(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=m??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=y??"var(--persona-voice-recording-indicator, #ffffff)",y){let L=G.querySelector("svg");L&&L.setAttribute("stroke",y)}v&&(G.style.borderColor=v),G.setAttribute("aria-label","Stop voice recognition")},tb=()=>{if(!G)return;Jl();let i=o.voiceRecognition??{},m=z.getVoiceInterruptionMode(),y=i.processingIconName??"loader",v=i.processingIconColor??xt?.color??"",L=i.processingBackgroundColor??xt?.backgroundColor??"",I=i.processingBorderColor??xt?.borderColor??"";Os(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=L,G.style.borderColor=I;let J=v||"currentColor";G.style.color=J,Ql(y,J),G.setAttribute("aria-label","Processing voice input"),m==="none"&&(G.style.cursor="default")},nb=()=>{if(!G)return;Jl();let i=o.voiceRecognition??{},m=z.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",v=i.speakingIconName??y,L=i.speakingIconColor??(m==="barge-in"?i.recordingIconColor??xt?.color??"":xt?.color??""),I=i.speakingBackgroundColor??(m==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":xt?.backgroundColor??""),J=i.speakingBorderColor??(m==="barge-in"?i.recordingBorderColor??"":xt?.borderColor??"");Os(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=I,G.style.borderColor=J;let V=L||"currentColor";G.style.color=V,Ql(v,V);let X=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",X),m==="none"&&(G.style.cursor="default"),m==="barge-in"&&G.classList.add("persona-voice-recording")},zn=()=>{G&&(Os(),xt&&(G.style.backgroundColor=xt.backgroundColor??"",G.style.color=xt.color??"",G.style.borderColor=xt.borderColor??"",Ql(xt.iconName,xt.color||"currentColor"),xt=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},Ns=()=>{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(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,Sn(),qn("user"),zn()});return}z.toggleVoice().then(()=>{Ke.active=z.isVoiceActive(),Ke.manuallyDeactivated=!z.isVoiceActive(),Sn(),qn("user"),z.isVoiceActive()?Sr():zn()});return}if(Wn){let i=pe.value.trim();Ke.manuallyDeactivated=!0,Sn(),uo("user"),i&&(pe.value="",pe.style.height="auto",z.sendMessage(i))}else Ke.manuallyDeactivated=!1,Sn(),Fs("user")};Wu=Ns,G&&(G.addEventListener("click",Ns),Ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(z.isVoiceActive()&&z.toggleVoice(),zn()):uo("system"),G&&G.removeEventListener("click",Ns)}));let ob=p.on("assistant:complete",()=>{ju&&(Ke.active||Ke.manuallyDeactivated||ju==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?z.toggleVoice().then(()=>{Ke.active=z.isVoiceActive(),qn("auto"),z.isVoiceActive()&&Sr()}):Fs("auto"))},600))});Ve.push(ob);let rb=p.on("action:resubmit",()=>{setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)});Ve.push(rb);let hf=()=>{ct(!Q,"user")},Ot=null,Xt=null;if(C&&!O()){let{instance:i,element:m}=zp({config:o,plugins:a,onToggle:hf});Ot=i,i||(Xt=m)}Ot?e.appendChild(Ot.element):Xt&&e.appendChild(Xt),xa(),Il(),sf(),Ul(z.isStreaming()),ef()||(fn()==="follow"?po(!0):Yu()),Ey(),W&&(!C||O()?setTimeout(()=>ql(),0):Q&&setTimeout(()=>ql(),200));let wa=()=>{if(O()){gr(),xa();return}let i=Et(o),m=o.launcher?.sidebarMode??!1,y=i||m||(o.launcher?.fullHeight??!1),v=e.ownerDocument.defaultView??window,L=o.launcher?.mobileFullscreen??!0,I=o.launcher?.mobileBreakpoint??640,J=v.innerWidth<=I,V=L&&J&&C;try{if(V){sa(),ia=As();return}let X=!1;j&&(j=!1,sa(),X=!0);let se=As();if(!X&&se!==ia&&(sa(),X=!0),ia=se,X&&Pl(),!C&&!i){ce.style.height="",ce.style.width="";return}if(!m&&!i){let re=o?.launcher?.width??o?.launcherWidth??pn;ce.style.width=re,ce.style.maxWidth=re}if(ws(),!y){let fe=v.innerHeight,re=64,xe=o.launcher?.heightOffset??0,ze=Math.max(200,fe-re),pt=Math.min(640,ze),nt=Math.max(200,pt-xe);ce.style.height=`${nt}px`}}finally{if(gr(),xa(),Q&&C){let se=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),fe=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,xe=Et(o)&&re&&se,ze=fe||re&&se&&C||xe;if(ze&&!In){let pt=e.getRootNode(),nt=pt instanceof ShadowRoot?pt.host:e.closest(".persona-host");nt&&!Rn&&(Rn=Op(nt,o.launcher?.zIndex??Gt)),In=Np(e.ownerDocument)}else ze||(Rn?.(),Rn=null,In?.(),In=null)}}};wa();let yf=e.ownerDocument.defaultView??window;if(yf.addEventListener("resize",wa),Ve.push(()=>yf.removeEventListener("resize",wa)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{gr()});i.observe(Y),Ve.push(()=>i.disconnect())}mn=ae.scrollTop;let bf=Fn(ae),xf=()=>{let i=ae.scrollTop,m=Fn(ae),y=m<bf;if(bf=m,!no()){mn=i,ln();return}let{action:v,nextLastScrollTop:L}=ji({following:sn.isFollowing(),currentScrollTop:i,lastScrollTop:mn,nearBottom:Wo(ae,Is),userScrollThreshold:My,isAutoScrolling:gn||Es||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(mn=L,v==="resume"){Hs()||co();return}v==="pause"&&fa()};if(ae.addEventListener("scroll",xf,{passive:!0}),Ve.push(()=>ae.removeEventListener("scroll",xf)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Iy(),od(Le)});i.observe(Le),i.observe(ae),Ve.push(()=>i.disconnect())}let vf=()=>{no()&&sn.isFollowing()&&Hs()&&fa()},Cf=ae.ownerDocument;Cf.addEventListener("selectionchange",vf),Ve.push(()=>{Cf.removeEventListener("selectionchange",vf)});let ab=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),wf=i=>{ab.has(i.key)&&($o(),ku()&&no()&&sn.isFollowing()&&fa())},Af=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&($o(),ku()&&no()&&sn.isFollowing()&&fa())};ae.addEventListener("keydown",wf),ae.addEventListener("focusin",Af),Ve.push(()=>{ae.removeEventListener("keydown",wf),ae.removeEventListener("focusin",Af)});let Sf=i=>{if(i.deltaY!==0&&$o(),!no())return;let m=Gi({following:sn.isFollowing(),deltaY:i.deltaY,nearBottom:Wo(ae,Is),resumeWhenNearBottom:!0});m==="pause"?fa():m==="resume"&&!Hs()&&co()};ae.addEventListener("wheel",Sf,{passive:!0}),ae.addEventListener("touchmove",$o,{passive:!0}),ae.addEventListener("pointerdown",$o,{passive:!0}),Ve.push(()=>{ae.removeEventListener("touchmove",$o),ae.removeEventListener("pointerdown",$o)}),Ve.push(()=>ae.removeEventListener("wheel",Sf)),kt.addEventListener("click",()=>{ma(),ae.scrollTop=ae.scrollHeight,mn=ae.scrollTop,co(),po(!0),ln()}),Ve.push(()=>kt.remove()),Ve.push(()=>{Xu(),ma()});let Mf=()=>{R&&(Uo&&(R.removeEventListener("click",Uo),Uo=null),q()?(R.style.display="",Uo=()=>{ct(!1,"user")},R.addEventListener("click",Uo)):R.style.display="none")};Mf(),(()=>{let{clearChatButton:i}=Pe;i&&i.addEventListener("click",()=>{z.clearMessages(),qo.clear(),co(),Co(Pe.composerOverlay);try{localStorage.removeItem(ea),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ea}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ea)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&&Fl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},S.syncFromMetadata(),We?.clear(),_e?.reset(),Xe?.update()})})(),P&&P.addEventListener("submit",ff);let Tf=[["keydown",Yy],["input",Qy],["paste",Zy],["focus",vy]],Ef=i=>{if(i)for(let[m,y]of Tf)i.addEventListener(m,y)},kf=i=>{if(i)for(let[m,y]of Tf)i.removeEventListener(m,y)};Ef(pe),an?.onComposerSwap((i,m)=>{kf(m),pe=i,Ef(i)});let Lf=e.ownerDocument??document;Lf.addEventListener("keydown",mf,!0);let Pf="persona-attachment-drop-active",Aa=0,Yl=()=>{Aa=0,ue.classList.remove(Pf)},Mr=()=>o.attachments?.enabled===!0&&At!==null,Rf=i=>{!xl(i.dataTransfer)||!Mr()||(Aa++,Aa===1&&ue.classList.add(Pf))},If=i=>{!xl(i.dataTransfer)||!Mr()||(Aa--,Aa<=0&&Yl())},Wf=i=>{!xl(i.dataTransfer)||!Mr()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Hf=i=>{if(!xl(i.dataTransfer)||!Mr())return;i.preventDefault(),i.stopPropagation(),Yl();let m=Array.from(i.dataTransfer.files??[]);m.length!==0&&At.handleFiles(m)},fo=!0;ue.addEventListener("dragenter",Rf,fo),ue.addEventListener("dragleave",If,fo),e.addEventListener("dragover",Wf,fo),e.addEventListener("drop",Hf,fo);let _s=e.ownerDocument,Bf=i=>{Mr()&&i.preventDefault()},Df=i=>{Mr()&&i.preventDefault()};_s.addEventListener("dragover",Bf),_s.addEventListener("drop",Df),Ve.push(()=>{P&&P.removeEventListener("submit",ff),kf(pe),Lf.removeEventListener("keydown",mf,!0),an?.destroy()}),Ve.push(()=>{ue.removeEventListener("dragenter",Rf,fo),ue.removeEventListener("dragleave",If,fo),e.removeEventListener("dragover",Wf,fo),e.removeEventListener("drop",Hf,fo),_s.removeEventListener("dragover",Bf),_s.removeEventListener("drop",Df),Yl()}),Ve.push(()=>{z.cancel()}),Ot?Ve.push(()=>{Ot?.destroy()}):Xt&&Ve.push(()=>{Xt?.remove()});let Lt={update(i){let m=o.toolCall,y=o.messageActions,v=o.layout?.messages,L=o.colorScheme,I=o.loadingIndicator,J=o.iterationDisplay,V=o.features?.showReasoning,X=o.features?.showToolCalls,se=o.features?.toolCallDisplay,fe=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o=ul({...o,features:r},i),r=o.features,o=is(o),Ss(),rr(e,o),as(e,o),ss(e,o),Un(),o.colorScheme!==L&&$u();let xe=ls.getForInstance(o.plugins);a.length=0,a.push(...xe),C=o.launcher?.enabled??!0,T=o.launcher?.autoExpand??!1,ge=o.features?.showReasoning??!0,ne=o.features?.showToolCalls??!0,Z=o.features?.scrollToBottom??{};let ze=fn();me=o.features?.scrollBehavior??{},ze!==fn()&&(ma(),co()),Iu(),ln();let pt=le;if(le=o.features?.showEventStreamToggle??!1,le&&!pt){if(We||(Se=new os(we),We=new ns(mt,Se),_e=_e??new rs,Se.open().then(()=>We?.restore()).catch(()=>{}),z.setSSEEventCallback((te,Ge)=>{o.onSSEEvent?.(te,Ge),_e?.processEvent(te,Ge),We.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Ge)})})),!tt&&$){let te=o.features?.eventStream?.classNames,Ge="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"+(te?.toggleButton?" "+te.toggleButton:"");tt=b("button",Ge),tt.style.width="28px",tt.style.height="28px",tt.style.color=Yt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let ht=oe("activity","18px","currentColor",1.5);ht&&tt.appendChild(ht);let ot=Pe.clearChatButtonWrapper,at=Pe.closeButtonWrapper,$t=ot||at;$t&&$t.parentNode===$?$.insertBefore(tt,$t):$.appendChild(tt),tt.addEventListener("click",()=>{$e?ra():Tl()})}}else!le&&pt&&(ra(),tt&&(tt.remove(),tt=null),We?.clear(),Se?.destroy(),We=null,Se=null,_e?.reset(),_e=null);if(o.launcher?.enabled===!1&&Ot&&(Ot.destroy(),Ot=null),o.launcher?.enabled===!1&&Xt&&(Xt.remove(),Xt=null),o.launcher?.enabled!==!1&&!Ot&&!Xt){let{instance:te,element:Ge}=zp({config:o,plugins:a,onToggle:hf});Ot=te,te||(Xt=Ge),e.appendChild(Ge)}Ot&&Ot.update(o),K&&o.launcher?.title!==void 0&&(K.textContent=o.launcher.title),_&&o.launcher?.subtitle!==void 0&&(_.textContent=o.launcher.subtitle);let nt=o.layout?.header;if(nt?.layout!==F&&$){let te=nt?$r(o,nt,{showClose:q(),onClose:()=>ct(!1,"user")}):eo({config:o,showClose:q(),onClose:()=>ct(!1,"user")});wt.replaceHeader(te),$=wt.header.element,B=wt.header.iconHolder,K=wt.header.headerTitle,_=wt.header.headerSubtitle,R=wt.header.closeButton,F=nt?.layout}else if(nt){if(B&&(B.style.display=nt.showIcon===!1?"none":""),K&&(K.style.display=nt.showTitle===!1?"none":""),_&&(_.style.display=nt.showSubtitle===!1?"none":""),R){let te=q()&&nt.showCloseButton!==!1;R.style.display=te?"":"none"}if(Pe.clearChatButtonWrapper){let te=nt.showClearChat;if(te!==void 0){Pe.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Ge}=Pe;Ge&&!Ge.classList.contains("persona-absolute")&&(te?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}}let St=o.layout?.showHeader!==!1;$&&($.style.display=St?"":"none");let Pt=o.layout?.showFooter!==!1;Y&&(Y.style.display=Pt?"":"none"),gr(),ln(),C!==D?C?ct(T,"auto"):(Q=!0,xa()):T!==w&&ct(T,"auto"),w=T,D=C,wa(),Mf();let Oe=JSON.stringify(o.toolCall)!==JSON.stringify(m),Ce=JSON.stringify(o.messageActions)!==JSON.stringify(y),Ct=JSON.stringify(o.layout?.messages)!==JSON.stringify(v),ut=o.loadingIndicator?.render!==I?.render||o.loadingIndicator?.renderIdle!==I?.renderIdle||o.loadingIndicator?.showBubble!==I?.showBubble,Ft=o.iterationDisplay!==J,ft=(o.features?.showReasoning??!0)!==(V??!0)||(o.features?.showToolCalls??!0)!==(X??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(fe);(Oe||Ce||Ct||ut||Ft||ft)&&z&&(Wl++,ga(Le,z.getMessages(),ie));let Rt=o.features?.streamAnimation?.type;if(Rt!==re&&Rt&&Rt!=="none"){let te=zr(Rt,o.features?.streamAnimation?.plugins);te&&Qi(te,e)}let Ee=o.launcher??{},Ne=Ee.headerIconHidden??!1,qt=o.layout?.header?.showIcon,Vt=Ne||qt===!1,vt=Ee.headerIconName,dt=Ee.headerIconSize??"48px";if(B){let te=ue.querySelector(".persona-border-b-persona-divider"),Ge=te?.querySelector(".persona-flex-col");if(Vt)B.style.display="none",te&&Ge&&!te.contains(Ge)&&te.insertBefore(Ge,te.firstChild);else{if(B.style.display="",B.style.height=dt,B.style.width=dt,te&&Ge&&(te.contains(B)?B.nextSibling!==Ge&&(B.remove(),te.insertBefore(B,Ge)):te.insertBefore(B,Ge)),vt){let ot=parseFloat(dt)||24,at=oe(vt,ot*.6,"currentColor",1);at?B.replaceChildren(at):B.textContent=Ee.agentIconText??"\u{1F4AC}"}else if(Ee.iconUrl){let ot=B.querySelector("img");if(ot)ot.src=Ee.iconUrl,ot.style.height=dt,ot.style.width=dt;else{let at=document.createElement("img");at.src=Ee.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=dt,at.style.width=dt,B.replaceChildren(at)}}else{let ot=B.querySelector("svg"),at=B.querySelector("img");(ot||at)&&B.replaceChildren(),B.textContent=Ee.agentIconText??"\u{1F4AC}"}let ht=B.querySelector("img");ht&&(ht.style.height=dt,ht.style.width=dt)}}let gt=o.layout?.header?.showTitle,Ze=o.layout?.header?.showSubtitle;if(K&&(K.style.display=gt===!1?"none":""),_&&(_.style.display=Ze===!1?"none":""),R){let te=q()&&o.layout?.header?.showCloseButton!==!1;R.style.display=te?"":"none";let Ge=Ee.closeButtonSize??"32px",ht=Ee.closeButtonPlacement??"inline";R.style.height=Ge,R.style.width=Ge;let{closeButtonWrapper:ot}=Pe,at=ht==="top-right",$t=ot?.classList.contains("persona-absolute");if(ot&&at!==$t)if(ot.remove(),at)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(ot);else{let go=Ee.clearChat?.placement??"inline",Ta=Ee.clearChat?.enabled??!0;ot.className=Ta&&go==="inline"?"":"persona-ml-auto";let Ff=ue.querySelector(".persona-border-b-persona-divider");Ff&&Ff.appendChild(ot)}if(R.style.color=Ee.closeButtonColor||Yt.actionIconColor,Ee.closeButtonBackgroundColor?(R.style.backgroundColor=Ee.closeButtonBackgroundColor,R.classList.remove("hover:persona-bg-gray-100")):(R.style.backgroundColor="",R.classList.add("hover:persona-bg-gray-100")),Ee.closeButtonBorderWidth||Ee.closeButtonBorderColor){let go=Ee.closeButtonBorderWidth||"0px",Ta=Ee.closeButtonBorderColor||"transparent";R.style.border=`${go} solid ${Ta}`,R.classList.remove("persona-border-none")}else R.style.border="",R.classList.add("persona-border-none");Ee.closeButtonBorderRadius?(R.style.borderRadius=Ee.closeButtonBorderRadius,R.classList.remove("persona-rounded-full")):(R.style.borderRadius="",R.classList.add("persona-rounded-full")),Ee.closeButtonPaddingX?(R.style.paddingLeft=Ee.closeButtonPaddingX,R.style.paddingRight=Ee.closeButtonPaddingX):(R.style.paddingLeft="",R.style.paddingRight=""),Ee.closeButtonPaddingY?(R.style.paddingTop=Ee.closeButtonPaddingY,R.style.paddingBottom=Ee.closeButtonPaddingY):(R.style.paddingTop="",R.style.paddingBottom="");let cn=Ee.closeButtonIconName??"x",Mn=Ee.closeButtonIconText??"\xD7";R.innerHTML="";let Nt=oe(cn,"28px","currentColor",1);Nt?(Nt.style.display="block",R.appendChild(Nt)):R.textContent=Mn;let jt=Ee.closeButtonTooltipText??"Close chat",jn=Ee.closeButtonShowTooltip??!0;R.setAttribute("aria-label",jt),ot&&Ut({anchor:R,trigger:ot,text:()=>R?.getAttribute("aria-label")??jt,enabled:jn})}let{clearChatButton:Ie,clearChatButtonWrapper:yt}=Pe;if(Ie){let te=Ee.clearChat??{},Ge=te.enabled??!0,ht=o.layout?.header?.showClearChat,ot=ht!==void 0?ht:Ge,at=te.placement??"inline";if(yt){yt.style.display=ot?"":"none";let{closeButtonWrapper:$t}=Pe;!O()&&$t&&!$t.classList.contains("persona-absolute")&&(ot?$t.classList.remove("persona-ml-auto"):$t.classList.add("persona-ml-auto"));let cn=at==="top-right",Mn=yt.classList.contains("persona-absolute");if(!O()&&cn!==Mn&&ot){if(yt.remove(),cn)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",ue.style.position="relative",ue.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let jt=ue.querySelector(".persona-border-b-persona-divider"),jn=Pe.closeButtonWrapper;jt&&jn&&jn.parentElement===jt?jt.insertBefore(yt,jn):jt&&jt.appendChild(yt)}let Nt=Pe.closeButtonWrapper;Nt&&!Nt.classList.contains("persona-absolute")&&(cn?Nt.classList.add("persona-ml-auto"):Nt.classList.remove("persona-ml-auto"))}}if(ot){if(!O()){let go=te.size??"32px";Ie.style.height=go,Ie.style.width=go}let $t=te.iconName??"refresh-cw",cn=te.iconColor??"";Ie.style.color=cn||Yt.actionIconColor,Ie.innerHTML="";let Mn=O()?"14px":"20px",Nt=oe($t,Mn,"currentColor",1);if(Nt&&(Nt.style.display="block",Ie.appendChild(Nt)),te.backgroundColor?(Ie.style.backgroundColor=te.backgroundColor,Ie.classList.remove("hover:persona-bg-gray-100")):(Ie.style.backgroundColor="",Ie.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let go=te.borderWidth||"0px",Ta=te.borderColor||"transparent";Ie.style.border=`${go} solid ${Ta}`,Ie.classList.remove("persona-border-none")}else Ie.style.border="",Ie.classList.add("persona-border-none");te.borderRadius?(Ie.style.borderRadius=te.borderRadius,Ie.classList.remove("persona-rounded-full")):(Ie.style.borderRadius="",Ie.classList.add("persona-rounded-full")),te.paddingX?(Ie.style.paddingLeft=te.paddingX,Ie.style.paddingRight=te.paddingX):(Ie.style.paddingLeft="",Ie.style.paddingRight=""),te.paddingY?(Ie.style.paddingTop=te.paddingY,Ie.style.paddingBottom=te.paddingY):(Ie.style.paddingTop="",Ie.style.paddingBottom="");let jt=te.tooltipText??"Clear chat",jn=te.showTooltip??!0;Ie.setAttribute("aria-label",jt),yt&&Ut({anchor:Ie,trigger:yt,text:()=>Ie?.getAttribute("aria-label")??jt,enabled:jn})}}let zt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ds],bn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[mr.message,mr.messageAndClick];S=cs({parsers:zt,handlers:bn,getSessionMetadata:A,updateSessionMetadata:E,emit:p.emit,documentRef:typeof document<"u"?document:null}),ie=Rh(o,S,De),z.updateConfig(o),ga(Le,z.getMessages(),ie),Il(),sf(),Ul(z.isStreaming());let Sa=o.voiceRecognition?.enabled===!0,Us=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Tt=o.voiceRecognition?.provider?.type==="runtype";if(Sa&&(Us||Tt))if(!G||!Ue){let te=eb(o.voiceRecognition,o.sendButton);te&&(G=te.micButton,Ue=te.micButtonWrapper,Re.insertBefore(Ue,ee),G.addEventListener("click",Ns),G.disabled=z.isStreaming())}else{let te=o.voiceRecognition??{},Ge=o.sendButton??{},ht=te.iconName??"mic",ot=Ge.size??"40px",at=te.iconSize??ot,$t=parseFloat(at)||24;G.style.width=at,G.style.height=at,G.style.minWidth=at,G.style.minHeight=at;let cn=te.iconColor??Ge.textColor;G.innerHTML="";let Mn=oe(ht,$t,cn||"currentColor",1.5);Mn?G.appendChild(Mn):G.textContent="\u{1F3A4}";let Nt=te.backgroundColor??Ge.backgroundColor;Nt?G.style.backgroundColor=Nt:G.style.backgroundColor="",cn?G.style.color=cn:G.style.color="var(--persona-text, #111827)",te.borderWidth?(G.style.borderWidth=te.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),te.borderColor?G.style.borderColor=te.borderColor:G.style.borderColor="",te.paddingX?(G.style.paddingLeft=te.paddingX,G.style.paddingRight=te.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),te.paddingY?(G.style.paddingTop=te.paddingY,G.style.paddingBottom=te.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let jt=te.tooltipText??"Start voice recognition",jn=te.showTooltip??!1;G.setAttribute("aria-label",jt),Ue&&Ut({anchor:G,trigger:Ue,text:()=>G?.getAttribute("aria-label")??jt,enabled:jn}),Ue.style.display="",G.disabled=z.isStreaming()}else G&&Ue&&(Ue.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?z.isVoiceActive()&&z.toggleVoice():Wn&&uo());if(o.attachments?.enabled===!0){if(!qe||!he){let te=o.attachments??{},ht=(o.sendButton??{}).size??"40px";Ht||(Ht=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ht.style.display="none",P.insertBefore(Ht,pe)),Fe||(Fe=document.createElement("input"),Fe.type="file",Fe.accept=(te.allowedTypes??Yn).join(","),Fe.multiple=(te.maxFiles??4)>1,Fe.style.display="none",Fe.setAttribute("aria-label","Attach files"),P.insertBefore(Fe,pe)),qe=b("div","persona-send-button-wrapper"),he=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),he.type="button",he.setAttribute("aria-label",te.buttonTooltipText??"Attach file");let ot=te.buttonIconName??"paperclip",at=ht,$t=parseFloat(at)||40,cn=Math.round($t*.6);he.style.width=at,he.style.height=at,he.style.minWidth=at,he.style.minHeight=at,he.style.fontSize="18px",he.style.lineHeight="1";let Mn=oe(ot,cn,"currentColor",1.5);Mn?he.appendChild(Mn):he.textContent="\u{1F4CE}",he.addEventListener("click",jt=>{jt.preventDefault(),Fe?.click()}),qe.appendChild(he);let Nt=te.buttonTooltipText??"Attach file";Ut({anchor:he,trigger:qe,text:()=>he?.getAttribute("aria-label")??Nt}),Qe?Qe.append(qe):P.appendChild(qe),!At&&Fe&&Ht&&(At=or.fromConfig(te),At.setPreviewsContainer(Ht),Fe.addEventListener("change",async()=>{At&&Fe?.files&&(await At.handleFileSelect(Fe.files),Fe.value="")}))}else{qe.style.display="";let te=o.attachments??{};Fe&&(Fe.accept=(te.allowedTypes??Yn).join(","),Fe.multiple=(te.maxFiles??4)>1),At&&At.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(Ih(o.attachments?.dropOverlay)),he){let te=o.attachments??{},Ge=te.buttonTooltipText??"Attach file";he.setAttribute("aria-label",Ge),he.textContent="";let ht=parseFloat(o.sendButton?.size??"40px")||40,ot=oe(te.buttonIconName??"paperclip",Math.round(ht*.6),"currentColor",1.5);ot?he.appendChild(ot):he.textContent="\u{1F4CE}",qe&&Ut({anchor:he,trigger:qe,text:()=>he?.getAttribute("aria-label")??Ge})}}else qe&&(qe.style.display="none"),At&&At.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Bt=o.sendButton??{},Ma=Bt.useIcon??!1,Vs=Bt.iconText??"\u2191",Tr=Bt.iconName,zs=Bt.tooltipText??"Send message",Zl=Bt.showTooltip??!1,Xo=Bt.size??"40px",$n=Bt.backgroundColor,Jo=Bt.textColor;if(Ma){if(ve.style.width=Xo,ve.style.height=Xo,ve.style.minWidth=Xo,ve.style.minHeight=Xo,ve.style.fontSize="18px",ve.style.lineHeight="1",Jo?ve.style.color=Jo:ve.style.color="var(--persona-button-primary-fg, #ffffff)",!z.isStreaming())if(ve.innerHTML="",Tr){let te=parseFloat(Xo)||24,Ge=Jo?.trim()||"currentColor",ht=oe(Tr,te,Ge,2);ht?ve.appendChild(ht):ve.textContent=Vs}else ve.textContent=Vs;ve.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",$n?(ve.style.backgroundColor=$n,ve.classList.remove("persona-bg-persona-primary")):(ve.style.backgroundColor="",ve.classList.add("persona-bg-persona-primary"))}else ve.textContent=o.copy?.sendButtonLabel??"Send",ve.style.width="",ve.style.height="",ve.style.minWidth="",ve.style.minHeight="",ve.style.fontSize="",ve.style.lineHeight="",ve.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",$n?(ve.style.backgroundColor=$n,ve.classList.remove("persona-bg-persona-accent")):ve.classList.add("persona-bg-persona-accent"),Jo?ve.style.color=Jo:ve.classList.add("persona-text-white");Bt.borderWidth?(ve.style.borderWidth=Bt.borderWidth,ve.style.borderStyle="solid"):(ve.style.borderWidth="",ve.style.borderStyle=""),Bt.borderColor?ve.style.borderColor=Bt.borderColor:ve.style.borderColor="",Bt.paddingX?(ve.style.paddingLeft=Bt.paddingX,ve.style.paddingRight=Bt.paddingX):(ve.style.paddingLeft="",ve.style.paddingRight=""),Bt.paddingY?(ve.style.paddingTop=Bt.paddingY,ve.style.paddingBottom=Bt.paddingY):(ve.style.paddingTop="",ve.style.paddingBottom=""),z.isStreaming()||ve.setAttribute("aria-label",zs),ee&&Ut({anchor:ve,trigger:ee,text:()=>ve.getAttribute("aria-label")??zs,enabled:Zl});let $s=o.layout?.contentMaxWidth??(O()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);$s?(Le.style.maxWidth=$s,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%",P&&(P.style.maxWidth=$s,P.style.marginLeft="auto",P.style.marginRight="auto"),it&&(it.style.maxWidth=$s,it.style.marginLeft="auto",it.style.marginRight="auto")):(Le.style.maxWidth="",Le.style.marginLeft="",Le.style.marginRight="",Le.style.width="",P&&(P.style.maxWidth="",P.style.marginLeft="",P.style.marginRight=""),it&&(it.style.maxWidth="",it.style.marginLeft="",it.style.marginRight=""));let mo=o.statusIndicator??{},sb=mo.visible??!0;if(U.style.display=sb?"":"none",z){let te=z.getStatus();Kt(U,(ht=>ht==="idle"?mo.idleText??It.idle:ht==="connecting"?mo.connectingText??It.connecting:ht==="connected"?mo.connectedText??It.connected:ht==="error"?mo.errorText??It.error:It[ht])(te),mo,te)}U.classList.remove("persona-text-left","persona-text-center","persona-text-right");let ib=mo.align==="left"?"persona-text-left":mo.align==="center"?"persona-text-center":"persona-text-right";U.classList.add(ib)},open(){q()&&ct(!0,"api")},close(){q()&&ct(!1,"api")},toggle(){q()&&ct(!Q,"api")},reconnect(){z.reconnectNow()},clearChat(){_n=!1,z.clearMessages(),qo.clear(),co();try{localStorage.removeItem(ea),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ea}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ea)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&&Fl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},S.syncFromMetadata(),We?.clear(),_e?.reset(),Xe?.update()},setMessage(i){return!pe||z.isStreaming()?!1:(!Q&&q()&&ct(!0,"system"),pe.value=i,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(z.isStreaming())return!1;let m=i?.trim()||pe.value.trim();return m?(!Q&&q()&&ct(!0,"system"),pe.value="",pe.style.height="auto",z.sendMessage(m),!0):!1},startVoiceRecognition(){return z.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(z.isVoiceActive()||(!Q&&q()&&ct(!0,"system"),Ke.manuallyDeactivated=!1,Sn(),z.toggleVoice().then(()=>{Ke.active=z.isVoiceActive(),qn("user"),z.isVoiceActive()&&Sr()})),!0):Wn?!0:gf()?(!Q&&q()&&ct(!0,"system"),Ke.manuallyDeactivated=!1,Sn(),Fs("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?z.isVoiceActive()?(z.toggleVoice().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,Sn(),qn("user"),zn()}),!0):!1:Wn?(Ke.manuallyDeactivated=!0,Sn(),uo("user"),!0):!1},injectMessage(i){return!Q&&q()&&ct(!0,"system"),z.injectMessage(i)},injectAssistantMessage(i){!Q&&q()&&ct(!0,"system");let m=z.injectAssistantMessage(i);return de&&(de=!1,be&&(clearTimeout(be),be=null),setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)),m},injectUserMessage(i){return!Q&&q()&&ct(!0,"system"),z.injectUserMessage(i)},injectSystemMessage(i){return!Q&&q()&&ct(!0,"system"),z.injectSystemMessage(i)},injectMessageBatch(i){return!Q&&q()&&ct(!0,"system"),z.injectMessageBatch(i)},injectComponentDirective(i){return!Q&&q()&&ct(!0,"system"),z.injectComponentDirective(i)},injectTestMessage(i){!Q&&q()&&ct(!0,"system"),z.injectTestEvent(i)},async connectStream(i,m){return z.connectStream(i,m)},__pushEventStreamEvent(i){We&&(_e?.processEvent(i.type,i.payload),We.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!le||!We||Tl()},hideEventStream(){$e&&ra()},isEventStreamVisible(){return $e},showArtifacts(){Zt(o)&&(_n=!1,hr=!0,Un(),Ye?.setMobileOpen(!0))},hideArtifacts(){Zt(o)&&(_n=!0,Un())},upsertArtifact(i){return Zt(o)?(Bn(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(_n=!1,hr=!0),z.upsertArtifact(i)):null},selectArtifact(i){Zt(o)&&z.selectArtifact(i)},clearArtifacts(){Zt(o)&&z.clearArtifacts()},getArtifacts(){return z?.getArtifacts()??[]},getSelectedArtifactId(){return z?.getSelectedArtifactId()??null},focusInput(){return C&&!Q&&!O()||!pe?!1:(pe.focus(),!0)},async resolveApproval(i,m,y){let L=z.getMessages().find(I=>I.variant==="approval"&&I.approval?.id===i);if(!L?.approval)throw new Error(`Approval not found: ${i}`);if(L.approval.toolType==="webmcp"){z.resolveWebMcpApproval(L.id,m);return}return z.resolveApproval(L.approval,m,y)},getMessages(){return z.getMessages()},getStatus(){return z.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(i){E(i)},on(i,m){return p.on(i,m)},off(i,m){p.off(i,m)},isOpen(){return q()&&Q},isVoiceActive(){return Ke.active},toggleReadAloud(i){z.toggleReadAloud(i)},stopReadAloud(){z.stopSpeaking()},getReadAloudState(i){return z.getReadAloudState(i)},onReadAloudChange(i){return z.onReadAloudChange(i)},getState(){return{open:q()&&Q,launcherEnabled:C,voiceActive:Ke.active,streaming:z.isStreaming()}},showCSATFeedback(i){!Q&&q()&&ct(!0,"system");let m=Le.querySelector(".persona-feedback-container");m&&m.remove();let y=yl({onSubmit:async(v,L)=>{z.isClientTokenMode()&&await z.submitCSATFeedback(v,L),i?.onSubmit?.(v,L)},onDismiss:i?.onDismiss,...i});Le.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Q&&q()&&ct(!0,"system");let m=Le.querySelector(".persona-feedback-container");m&&m.remove();let y=bl({onSubmit:async(v,L)=>{z.isClientTokenMode()&&await z.submitNPSFeedback(v,L),i?.onSubmit?.(v,L)},onDismiss:i?.onDismiss,...i});Le.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,m){return z.submitCSATFeedback(i,m)},async submitNPSFeedback(i,m){return z.submitNPSFeedback(i,m)},destroy(){$l(),Go!=null&&(clearInterval(Go),Go=null),Ve.forEach(i=>i()),He.remove(),et?.remove(),Ot?.destroy(),Xt?.remove(),Uo&&R.removeEventListener("click",Uo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,m={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:y=>y?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,Ve.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)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",m),Ve.push(()=>{window.removeEventListener("persona:focusInput",m)}),le){let V=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===i)&&Lt.showEventStream()},X=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===i)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",X),Ve.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",X)})}let y=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.showArtifacts()},v=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.hideArtifacts()},L=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||X?.artifact&&Lt.upsertArtifact(X.artifact)},I=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||typeof X?.id=="string"&&Lt.selectArtifact(X.id)},J=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",I),window.addEventListener("persona:clearArtifacts",J),Ve.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",I),window.removeEventListener("persona:clearArtifacts",J)})}let yn=uw(o.persistState);if(yn&&q()){let i=fw(yn.storage),m=`${yn.keyPrefix}widget-open`,y=`${yn.keyPrefix}widget-voice`,v=`${yn.keyPrefix}widget-voice-mode`;if(i){let L=yn.persist?.openState&&i.getItem(m)==="true",I=yn.persist?.voiceState&&i.getItem(y)==="true",J=yn.persist?.voiceState&&i.getItem(v)==="true";if(L&&setTimeout(()=>{Lt.open(),setTimeout(()=>{if(I||J)Lt.startVoiceRecognition();else if(yn.persist?.focusInput){let V=e.querySelector("textarea");V&&V.focus()}},100)},0),yn.persist?.openState&&(p.on("widget:opened",()=>{i.setItem(m,"true")}),p.on("widget:closed",()=>{i.setItem(m,"false")})),yn.persist?.voiceState&&(p.on("voice:state",V=>{i.setItem(y,V.active?"true":"false")}),p.on("user:message",V=>{i.setItem(v,V.viaVoice?"true":"false")})),yn.clearOnChatClear){let V=()=>{i.removeItem(m),i.removeItem(y),i.removeItem(v)},X=()=>V();window.addEventListener("persona:clear-chat",X),Ve.push(()=>{window.removeEventListener("persona:clear-chat",X)})}}}if(f&&q()&&setTimeout(()=>{Lt.open()},0),Cr(),!Sy){let i=kr(()=>{z&&(Wl++,qo.clear(),ga(Le,z.getMessages(),ie))});Ve.push(i)}return Lt};var Wh=(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},hw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},yw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},bw=(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.")},Hh=(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"},gu=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=""},Bh=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",gu(e)},uu=e=>{e.style.transition=""},fu=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=""},mu=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Cl=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},xw=(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))},vw=(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)},Cw=e=>{let t=ko(e),n=t.components?.panel,o=(r,a)=>r==null||r===""?a:Qt(t,r)??r;return{inset:o(n?.inset,Ii),canvasBackground:o(n?.canvasBackground,Wi)}},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},ww=(e,t,n,o,r,a,s,l)=>{let p=rn(a),c=p.reveal==="push",d=l!=null,u=l?.inset??"",g=l?.canvasBackground??"";xw(e,t,n,o,c),vw(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,A=a?.launcher?.mobileBreakpoint??640,E=f!=null?f.innerWidth<=A:!1;if(h&&E&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),fu(t),uu(o),Bh(o),mu(n),Cl(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??Gt),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"),Bh(o),hw(o,p.maxHeight),Dh(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",fu(t),uu(o),mu(n),Cl(r,o);let M=p.animate?"transform 180ms ease":"none",S=p.side==="right"?"translateX(100%)":"translateX(-100%)",C=s?"translateX(0)":S;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=C,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",uu(o),gu(o),Cl(r,o);let M=Wh(p.width,e.clientWidth),S=Math.max(0,e.clientWidth),C=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=`${S+M}px`,t.style.transition=C,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=`${S}px`,n.style.maxWidth=`${S}px`,n.style.minWidth=`${S}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="",fu(t),gu(o),mu(n),Cl(r,o);let M=p.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let S=s?p.width:"0px",C=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 ${S}`,o.style.width=S,o.style.maxWidth=S,o.style.minWidth=S,o.style.minHeight="0",yw(o,p.maxHeight),o.style.overflow=M||T?"hidden":"visible",o.style.transition=C,M){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let W=d?`calc(${Wh(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=W,r.style.minWidth=W,r.style.maxWidth=W,r.style.boxSizing="border-box"}}},Aw=(e,t)=>{let n=e.ownerDocument.createElement("div");return Hh(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Hh(n,o)},destroy(){n.remove()}}},Sw=(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,A=()=>{h=t?.launcher?.detachedPanel===!0?Cw(t):null};A();let E=()=>{ww(s,l,p,c,d,t,u,h)},k=null,M=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=Nr(()=>{A(),E()}))},S=()=>{f(),rn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{E()}),g.observe(s)))},C=!1,T=()=>{E(),S(),u&&!C&&s.dataset.personaDockMobileFullscreen!=="true"&&(C=!0,bw(s,rn(t)))},W=s.ownerDocument.defaultView,w=()=>{T()};return W?.addEventListener("resize",w),rn(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(D){let F=D.launcherEnabled?D.open:!0;u!==F&&(u=F,T())},updateConfig(D){t=D,(t?.launcher?.enabled??!0)===!1&&(u=!0),A(),T(),M()},destroy(){W?.removeEventListener("resize",w),k?.(),k=null,f(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},us=(e,t)=>Et(t)?Sw(e,t):Aw(e,t);var Mw=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},Fh=(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)},Oh=e=>{let t=Mw(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,a=us(t,r),s,l=[],p=(E,k)=>{let S=!(k?.launcher?.enabled??!0)||Et(k),C=o.createElement("div");if(C.setAttribute("data-persona-root","true"),S&&(C.style.height="100%",C.style.display="flex",C.style.flexDirection="column",C.style.flex="1",C.style.minHeight="0",C.style.minWidth="0"),n){let T=E.attachShadow({mode:"open"});T.appendChild(C),Fh(T,o)}else E.appendChild(C),Fh(E,o);return t.id&&C.setAttribute("data-persona-instance",t.id),C},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=vl(E,r,{debugTools:e.debugTools}),d()},g=()=>{l.forEach(E=>E()),l=[],s.destroy()};u(),e.onChatReady?.();let f=E=>{g(),a.destroy(),a=us(t,E),r=E,u()},h={update(E){let k=ul(r??{},E),M=Et(r),S=Et(k),C=Bo(r),T=Bo(k);if(M!==S||C!==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]}},A=new Proxy(h,{get(E,k,M){if(k==="host")return a.host;if(k in E)return Reflect.get(E,k,M);let S=s[k];return typeof S=="function"?S.bind(s):S}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=A),A};function Tw(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 Ew(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:Tw(o,n)?2:3}function Nh(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function wl(e,t){let n=t.trim();if(!n)return[...e].sort(Nh);let o=[];for(let r of e){let a=Ew(r.label,n);a!==3&&o.push({item:r,tier:a})}return o.sort((r,a)=>r.tier!==a.tier?r.tier-a.tier:Nh(r.item,a.item)),o.map(r=>r.item)}function kw(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 _h(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>wl(e.items,t),resolve:e.resolve}}function Uh(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=>wl(t,kw(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 jh=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Lw=new Set(["button","a","input","select","textarea","details","summary"]),Pw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),hu=/\b(product|card|item|listing|result)\b/i,bu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Rw=3e3,Iw=100;function Gh(e){let t=typeof e.className=="string"?e.className:"";if(hu.test(t)||e.id&&hu.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&hu.test(o.value))return!0}return!1}function Kh(e){return bu.test((e.textContent??"").trim())}function Xh(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 Ww(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function qh(e){let t=e.match(bu);return t?t[0]:null}function Vh(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 Hw(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 Bw="commerce-card",Dw="result-card";function zh(e){return!Gh(e)||!Kh(e)||!Xh(e)&&!Ww(e)?0:5200}function $h(e){return!Gh(e)||Kh(e)||!Xh(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var xu=[{id:Bw,scoreElement(e){return zh(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||bu.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(zh(e)===0)return null;let{title:n,href:o}=Vh(e),r=qh((e.textContent??"").trim())??qh(t.text)??"",a=Hw(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:Dw,scoreElement(e){return $h(e)},formatSummary(e,t){if($h(e)===0)return null;let{title:n,href:o}=Vh(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
145
|
+
`)}}];function Fw(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Ow(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),c=e.rules??xu;return l==="simple"&&e.rules&&e.rules.length>0?(Fw(),c=[]):l==="simple"&&(c=[]),{mode:l,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:a,root:s,rules:c}}function yu(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 _w(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"||Lw.has(t)||n&&Pw.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Jh(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 Uw(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 c=0;c<e.attributes.length;c++){let d=e.attributes[c];d.name.startsWith("data-")&&(t[d.name]=d.value)}return t}function vu(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${yu(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}="${yu(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=>yu(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 qw(e){return e==="static"?Iw:Rw}function Qh(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:vu(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:_w(e),attributes:Uw(e)}}function Vw(e,t,n,o){let r=qw(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 zw(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 $w(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 c=l,d=c.tagName.toLowerCase();if(jh.has(d)){l=s.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){l=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Jh(c)){l=s.nextNode();continue}let u=Qh(c,e.maxTextLength),g=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(E=>E==="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:A}=Vw(c,u,e.rules,n);r.push({el:c,domIndex:a,enriched:u,score:h,formattingRule:A}),a+=1}l=s.nextNode()}r.sort((c,d)=>{let u=c.enriched.interactivity==="static"?1:0,g=d.enriched.interactivity==="static"?1:0;return u!==g?u-g:d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex});let p=[];for(let c of r){if(p.length>=e.maxElements)break;zw(p,c)||p.push(c)}return p.sort((c,d)=>{let u=c.enriched.interactivity==="static"?1:0,g=d.enriched.interactivity==="static"?1:0;return u!==g?u-g:u===1&&d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex}),p.map(c=>{let d;if(c.formattingRule?.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,n);g&&(d=g)}let u={...c.enriched};return d&&(u.formattedSummary=d),u})}function jw(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,c=p.tagName.toLowerCase();if(jh.has(c)){a=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Jh(p)){a=r.nextNode();continue}let d=Qh(p,e.maxTextLength),u=d.text.length>0,g=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(f=>f==="role");if(!u&&!g){a=r.nextNode();continue}o.has(d.selector)||(o.add(d.selector),n.push(d))}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 Yh(e={}){let t=Ow(e),n=t.root??document.body;return n?t.mode==="simple"?jw(t,n):$w(t,n):[]}var Al=100;function Zh(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 ey(){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 ty(){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 ny(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:Nn(e.colors.primary,.95),100:Nn(e.colors.primary,.9),200:Nn(e.colors.primary,.8),300:Nn(e.colors.primary,.7),400:Nn(e.colors.primary,.6),500:e.colors.primary,600:Nn(e.colors.primary,.8),700:Nn(e.colors.primary,.7),800:Nn(e.colors.primary,.6),900:Nn(e.colors.primary,.5),950:Nn(e.colors.primary,.45)}}),{...t,palette:n}}}}function oy(){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 ry(){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 Nn(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 ay(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Gw={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"}}},sy={components:{panel:{borderRadius:"0",shadow:"none"}}},Cu={id:"shop",label:"Shopping Assistant",config:{theme:Gw,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:pn},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?"]}},wu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:sy}},Au={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:sy}},Su={shop:Cu,minimal:wu,fullscreen:Au};function iy(e){return Su[e]}var Kw=`
|
|
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(),Xw={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:Kw};sr(Xw);var Jw=`
|
|
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(),fs="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",Qw=10,Yw=120,Mu=120,Zw=.4,eA=50,tA=e=>{if(!e)return Mu;let n=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):Mu},gy=e=>{let t=e.closest(".persona-stream-glyph-cycle"),n=tA(t);return Yw*n/Mu},Tu=e=>{let t=fs[Math.floor(Math.random()*fs.length)];return e&&t===e&&(t=fs[(fs.indexOf(t)+1)%fs.length]),t},nA=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()<Zw&&(r.textContent=Tu())}},ly=new WeakMap,dy=25,cy=.5,oA=6,py=.25,uy=new WeakMap,fy=new WeakMap,rA=(e,t)=>{if(!e)return dy*cy;let n=uy.get(e);uy.set(e,t);let o=fy.get(e)??dy;if(n!==void 0){let r=t-n;r>1&&(o=o*(1-py)+r*py,fy.set(e,o))}return Math.max(oA,o*cy)},ta=new Map,aA=e=>e.closest("[data-message-id]")?.dataset.messageId??null,sA=e=>{e&&ta.set(e,(ta.get(e)??0)+1)},iA=e=>{if(!e)return;let t=ta.get(e)??0;t<=1?ta.delete(e):ta.set(e,t-1)},hy=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=Tu();let n=aA(e);n&&(e.dataset.glyphCycleMessageId=n),sA(n);let o=e.closest(".persona-stream-glyph-cycle"),r=Date.now(),a=rA(o,r),s=gy(e),l=Qw*s,p=r+l;if(o){let c=ly.get(o);c!==void 0&&(p=Math.max(p,c)),ly.set(o,p+a)}lA(e,t,p)},lA=(e,t,n)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=gy(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,iA(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let s=Tu(r);e.textContent=s,r=s,nA(e),setTimeout(a,o)};setTimeout(a,o)},my=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))hy(n)},dA=e=>e.nodeType===1,cA={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:Jw,bufferContent(e){if(e.length<eA)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(ta.get(e.id)??0)>0},onAttach(e){my(e);let t=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))dA(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?hy(r):my(r))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};sr(cA);var en=typeof document<"u"?document.currentScript?.src??null:null;om(()=>{let e=en?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===en?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${en??"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)});Uf(()=>{let e=en?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===en?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${en??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});ka().catch(e=>{typeof console<"u"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});Um(()=>{let e=en?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===en?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${en??"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)});Ym(()=>{let e=en?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===en?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${en??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});Zm(()=>{let e=en?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===en?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${en??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});return mb(pA);})();
|
|
214
214
|
/*! Bundled license information:
|
|
215
215
|
|
|
216
216
|
lucide/dist/esm/icons/activity.mjs:
|