@runtypelabs/persona 4.15.0 → 4.16.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 +283 -9
- package/dist/context-mentions.d.ts +283 -9
- package/dist/index.cjs +68 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +299 -10
- package/dist/index.d.ts +299 -10
- package/dist/index.global.js +57 -57
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +69 -69
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +283 -9
- package/dist/smart-dom-reader.d.ts +283 -9
- package/dist/testing.cjs +3 -3
- package/dist/testing.d.cts +7 -0
- package/dist/testing.d.ts +7 -0
- package/dist/testing.js +3 -3
- package/dist/theme-editor-preview.cjs +64 -64
- package/dist/theme-editor-preview.d.cts +283 -9
- package/dist/theme-editor-preview.d.ts +283 -9
- package/dist/theme-editor-preview.js +56 -56
- package/dist/theme-editor.cjs +10 -10
- package/dist/theme-editor.d.cts +283 -10
- package/dist/theme-editor.d.ts +283 -10
- package/dist/theme-editor.js +10 -10
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +66 -3
- package/dist/theme-reference.d.ts +66 -3
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/components/artifact-pane.test.ts +27 -0
- package/src/components/artifact-pane.ts +7 -3
- package/src/components/header-builder.ts +27 -2
- package/src/components/header-layouts.test.ts +56 -0
- package/src/components/header-layouts.ts +29 -9
- package/src/components/launcher-surface.test.ts +403 -0
- package/src/components/launcher.ts +297 -2
- package/src/components/panel.ts +69 -74
- package/src/components/suggestions.test.ts +40 -0
- package/src/components/suggestions.ts +213 -153
- package/src/components/welcome.test.ts +121 -0
- package/src/components/welcome.ts +305 -0
- package/src/components/widget-view.test.ts +5 -3
- package/src/components/widget-view.ts +14 -7
- package/src/defaults.ts +2 -2
- package/src/index-core.ts +12 -1
- package/src/launcher-global.ts +10 -7
- package/src/plugins/types.ts +66 -1
- package/src/styles/widget-styles.test.ts +220 -0
- package/src/styles/widget.css +353 -9
- package/src/testing/mock-stream.test.ts +19 -0
- package/src/testing/mock-stream.ts +20 -0
- package/src/theme-editor/sections.ts +30 -1
- package/src/theme-reference.ts +26 -4
- package/src/types/theme.ts +40 -3
- package/src/types.ts +164 -6
- package/src/ui.body-top-slot.test.ts +95 -0
- package/src/ui.content-width.test.ts +91 -0
- package/src/ui.docked.test.ts +7 -4
- package/src/ui.launcher-teaser.test.ts +162 -0
- package/src/ui.rebuild-composer.test.ts +491 -0
- package/src/ui.render-welcome.test.ts +505 -0
- package/src/ui.scroll-additive.test.ts +91 -21
- package/src/ui.scroll.test.ts +302 -14
- package/src/ui.suggest-replies.test.ts +46 -0
- package/src/ui.ts +747 -136
- package/src/ui.welcome.test.ts +504 -0
- package/src/utils/artifact-gate.test.ts +27 -0
- package/src/utils/artifact-gate.ts +9 -0
- package/src/utils/attachment-manager.test.ts +37 -0
- package/src/utils/attachment-manager.ts +15 -0
- package/src/utils/auto-follow.test.ts +23 -0
- package/src/utils/auto-follow.ts +11 -1
- package/src/utils/config-merge.ts +2 -0
- package/src/utils/content-width.test.ts +37 -0
- package/src/utils/content-width.ts +17 -0
- package/src/utils/plugin-storage.test.ts +94 -0
- package/src/utils/plugin-storage.ts +98 -0
- package/src/utils/theme.test.ts +137 -0
- package/src/utils/tokens.ts +49 -3
- package/src/welcome.test.ts +213 -0
- package/src/welcome.ts +130 -0
package/dist/index.global.js
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var
|
|
2
|
-
\r `.includes(e[o]);)o++};return s()},cx=km;_t.parse=cx});var dg={};sm(dg,{createReconnectController:()=>Qx});function Qx(e){let t=0,n=null,o=null,r=!1,a=()=>{if(o&&(clearTimeout(o),o=null),n){let h=n;n=null,h()}},s=()=>{let h=e.getStatus();h!=="resuming"&&h!=="paused"||a()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||s()},p=()=>{s()},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(S=>{n=S,o=setTimeout(()=>{o=null,n=null,S()},h)}),g=()=>{let h=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,d(),e.setAbortController(null);let S=!1;for(let P of e.getMessages())P.streaming&&(P.streaming=!1,S=!0);let k=e.buildErrorContent("Connection lost and the response could not be resumed.");k?e.appendMessage({id:`reconnect-failed-${h?.executionId??e.nextSequence()}`,role:"assistant",content:k,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):S&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},f=async()=>{let h=e.config.reconnect?.backoffMs??Jx,S=e.config.reconnect?.maxAttempts??h.length,k=e.config.reconnectStream;if(!k){e.setReconnecting(!1);return}for(;e.getResumable()&&t<S;){t+=1,e.setStatus("resuming");let P=e.getResumable(),M=P.lastEventId,A=new AbortController;e.setAbortController(A),e.emitReconnect({phase:"resuming",handle:P,attempt:t});let C=null;try{let E=await k({executionId:P.executionId,after:P.lastEventId,signal:A.signal});E&&E.ok&&E.body&&(C=E.body)}catch{C=null}if(A.signal.aborted)return;if(C){let E=e.getMessages().find(w=>w.id===P.assistantMessageId)?.content,R=typeof E=="string"?E:"";try{await e.resumeConnect(C,P.assistantMessageId,R)}catch{}if(A.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,d(),e.emitReconnect({phase:"resumed",handle:P});return}e.getResumable().lastEventId!==M&&(t=0)}if(e.getResumable()&&t<S&&(e.setStatus("paused"),await u(h[Math.min(t-1,h.length-1)]??1e3),A.signal.aborted))return}e.getResumable()&&g()};return{begin(){t=0,c(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,d()},wake:a}}var Jx,cg=Ob(()=>{"use strict";Jx=[1e3,2e3,4e3,8e3,8e3]});var UA={};sm(UA,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Sd,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Ad,ASK_USER_QUESTION_TOOL_NAME:()=>Ua,AgentWidgetClient:()=>ar,AgentWidgetSession:()=>qr,AttachmentManager:()=>lr,BrowserSpeechEngine:()=>Ro,DEFAULT_COMPONENTS:()=>Wp,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Oi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>fn,DEFAULT_PALETTE:()=>Rp,DEFAULT_SEMANTIC:()=>Ip,DEFAULT_WIDGET_CONFIG:()=>at,PRESETS:()=>Wu,PRESET_FULLSCREEN:()=>Iu,PRESET_MINIMAL:()=>Ru,PRESET_SHOP:()=>Pu,ReadAloudController:()=>ir,SUGGEST_REPLIES_CLIENT_TOOL:()=>ii,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>vd,SUGGEST_REPLIES_TOOL_NAME:()=>Pn,THEME_ZONES:()=>Tg,VERSION:()=>rr,WEBMCP_TOOL_PREFIX:()=>Ln,WebMcpBridge:()=>Br,accessibilityPlugin:()=>Cy,animationsPlugin:()=>wy,applyFeaturePreferences:()=>gu,applyThemeVariables:()=>dr,attachHeaderToContainer:()=>ur,brandPlugin:()=>Ay,buildComposer:()=>Qr,buildDefaultHeader:()=>Xp,buildHeader:()=>oo,buildHeaderWithLayout:()=>Jr,buildMinimalHeader:()=>Jp,builtInClientToolsForDispatch:()=>Nr,canonicalArtifactDisplayMode:()=>an,collectEnrichedPageContext:()=>xy,componentRegistry:()=>Rn,createActionManager:()=>ys,createAgentExperience:()=>Ll,createAskUserQuestionBubble:()=>qm,createBestAvailableVoiceProvider:()=>wi,createBubbleWithLayout:()=>yh,createCSATFeedback:()=>Tl,createComboButton:()=>Gi,createComponentMiddleware:()=>Xh,createComponentStreamParser:()=>Al,createDefaultSanitizer:()=>dd,createDirectivePostprocessor:()=>um,createDropdownMenu:()=>Bo,createFlexibleJsonStreamParser:()=>jm,createIconButton:()=>Mt,createImagePart:()=>Zm,createJsonStreamParser:()=>gi,createLabelButton:()=>no,createLocalStorageAdapter:()=>wl,createMarkdownProcessor:()=>Fa,createMarkdownProcessorFromConfig:()=>tr,createMessageActions:()=>ru,createNPSFeedback:()=>El,createPlainTextParser:()=>fi,createPlugin:()=>Ty,createRegexJsonParser:()=>mi,createSlashCommandsSource:()=>ly,createStandardBubble:()=>Yr,createStaticMentionSource:()=>iy,createTextPart:()=>Lo,createTheme:()=>Qa,createThemeObserver:()=>zr,createToggleGroup:()=>Gr,createTypingIndicator:()=>fr,createVoiceProvider:()=>Po,createWidgetHostLayout:()=>xs,createXmlParser:()=>hi,defaultActionHandlers:()=>xr,defaultJsonActionParser:()=>hs,defaultMentionFilter:()=>Rl,defaultParseRules:()=>ku,detectColorScheme:()=>Ya,directivePostprocessor:()=>fm,ensureAskUserQuestionSheet:()=>Or,escapeHtml:()=>Fn,extractComponentDirectiveFromMessage:()=>Ml,fileToImagePart:()=>eg,formatEnrichedContext:()=>vy,generateAssistantMessageId:()=>ko,generateMessageId:()=>Xm,generateStableSelector:()=>Lu,generateUserMessageId:()=>_r,getActiveTheme:()=>Io,getColorScheme:()=>Vi,getDisplayText:()=>Qm,getHeaderLayout:()=>Qp,getImageParts:()=>Ym,getPreset:()=>ky,hasComponentDirective:()=>bs,hasImages:()=>xi,headerLayouts:()=>ll,highContrastPlugin:()=>My,initAgentWidget:()=>ay,isAskUserQuestionMessage:()=>Yn,isComponentDirectiveType:()=>Kh,isDockedMountMode:()=>Et,isSuggestRepliesMessage:()=>or,isVoiceSupported:()=>Ga,isWebMcpToolName:()=>vo,latestAgentSuggestions:()=>li,listRegisteredStreamAnimations:()=>$p,loadMarkdownParsers:()=>Da,markdownPostprocessor:()=>ld,mergeWithDefaults:()=>Vr,normalizeContent:()=>Jm,normalizeMediaType:()=>Co,onMarkdownParsersReady:()=>Wr,parseAskUserQuestionPayload:()=>Zn,parseSuggestRepliesPayload:()=>wd,parseWidgetPreferenceSlice:()=>mu,pickBestVoice:()=>Ur,pluginRegistry:()=>gs,reducedMotionPlugin:()=>Sy,registerStreamAnimationPlugin:()=>pr,removeAskUserQuestionSheet:()=>So,renderComponentDirective:()=>Sl,renderLoadingIndicatorWithFallback:()=>nu,renderLucideIcon:()=>ae,resolveArtifactDisplay:()=>fd,resolveArtifactDisplayMode:()=>On,resolveConfigPreferences:()=>ms,resolveDockConfig:()=>sn,resolveSanitizer:()=>Hr,resolveTokens:()=>Ui,stripWebMcpPrefix:()=>ei,themeToCssVariables:()=>qi,unregisterStreamAnimationPlugin:()=>zp,validateImageFile:()=>tg,validateTheme:()=>Hp});var Ir=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:_b,load:Ub,provide:KA,getSync:id}=Ir({fallbackImport:()=>import("./markdown-parsers-entry")}),Ys=new Set,qb=()=>{let e=[...Ys];Ys.clear();for(let t of e)try{t()}catch{}},lm=_b,Da=()=>{let e=id();return e?Promise.resolve(e):Ub().then(t=>(qb(),t))},Wr=e=>id()?()=>{}:(Ys.add(e),Da().catch(()=>{}),()=>{Ys.delete(e)});var Jn=id;var Vb=e=>{if(e)return e},Fa=e=>{let t=null;return n=>{let o=Jn();if(!o)return Fn(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=Vb(e?.renderer);s&&t.use({renderer:s})}return t.parse(n)}},tr=e=>e?Fa({markedOptions:e.options,renderer:e.renderer}):Fa(),zb=Fa(),ld=e=>zb(e),Fn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),cm=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),dm=e=>`%%FORM_PLACEHOLDER_${e}%%`,pm=(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=dm(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=dm(t.length);return t.push({token:a,type:r}),a}),n},um=e=>{let t=tr(e);return n=>{let o=[],r=pm(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="${cm(l)}"></div>`;a=a.replace(p,d)}),a}},fm=e=>{let t=[],n=pm(e,t),o=ld(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="${cm(a)}"></div>`;o=o.replace(s,p)}),o};var $b={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"]},jb=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,dd=()=>{let e=null;return t=>{let n=Jn();if(!n)return Fn(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:")&&!jb.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,$b)}},Hr=e=>e===!1?null:typeof e=="function"?e:dd();var mm=/^\s*\|?[\s:|-]*-[\s:|-]*$/,gm=e=>e.includes("|"),hm=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())},Gb=e=>`| ${e.join(" | ")} |`,Kb=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Xb=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),ym=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(!
|
|
4
|
-
`):e};var
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var Jx=Object.create;var hi=Object.defineProperty;var Qx=Object.getOwnPropertyDescriptor;var Yx=Object.getOwnPropertyNames;var Zx=Object.getPrototypeOf,ev=Object.prototype.hasOwnProperty;var es=(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 tv=(e,t)=>()=>(e&&(t=e(e=0)),t);var rg=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ag=(e,t)=>{for(var n in t)hi(e,n,{get:t[n],enumerable:!0})},sg=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Yx(t))!ev.call(e,r)&&r!==n&&hi(e,r,{get:()=>t[r],enumerable:!(o=Qx(t,r))||o.enumerable});return e};var ko=(e,t,n)=>(n=e!=null?Jx(Zx(e)):{},sg(t||!e||!e.__esModule?hi(n,"default",{value:e,enumerable:!0}):n,e)),nv=e=>sg(hi({},"__esModule",{value:!0}),e);var Qc=rg(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.Allow=ve.ALL=ve.COLLECTION=ve.ATOM=ve.SPECIAL=ve.INF=ve._INFINITY=ve.INFINITY=ve.NAN=ve.BOOL=ve.NULL=ve.OBJ=ve.ARR=ve.NUM=ve.STR=void 0;ve.STR=1;ve.NUM=2;ve.ARR=4;ve.OBJ=8;ve.NULL=16;ve.BOOL=32;ve.NAN=64;ve.INFINITY=128;ve._INFINITY=256;ve.INF=ve.INFINITY|ve._INFINITY;ve.SPECIAL=ve.NULL|ve.BOOL|ve.INF|ve.NAN;ve.ATOM=ve.STR|ve.NUM|ve.SPECIAL;ve.COLLECTION=ve.ARR|ve.OBJ;ve.ALL=ve.ATOM|ve.COLLECTION;ve.Allow={STR:ve.STR,NUM:ve.NUM,ARR:ve.ARR,OBJ:ve.OBJ,NULL:ve.NULL,BOOL:ve.BOOL,NAN:ve.NAN,INFINITY:ve.INFINITY,_INFINITY:ve._INFINITY,INF:ve.INF,SPECIAL:ve.SPECIAL,ATOM:ve.ATOM,COLLECTION:ve.COLLECTION,ALL:ve.ALL};ve.default=ve.Allow});var wi=rg(_t=>{"use strict";var Sv=_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]})),Mv=_t&&_t.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&Sv(t,e,n)};Object.defineProperty(_t,"__esModule",{value:!0});_t.Allow=_t.MalformedJSON=_t.PartialJSON=_t.parseJSON=_t.parse=void 0;var Zt=Qc();Object.defineProperty(_t,"Allow",{enumerable:!0,get:function(){return Zt.Allow}});Mv(Qc(),_t);var vi=class extends Error{};_t.PartialJSON=vi;var Ci=class extends Error{};_t.MalformedJSON=Ci;function Eg(e,t=Zt.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return Tv(e.trim(),t)}_t.parseJSON=Eg;var Tv=(e,t)=>{let n=e.length,o=0,r=g=>{throw new vi(`${g} at position ${o}`)},a=g=>{throw new Ci(`${g} at position ${o}`)},s=()=>(f(),o>=n&&r("Unexpected end of input"),e[o]==='"'?l():e[o]==="{"?p():e[o]==="["?d():e.substring(o,o+4)==="null"||Zt.Allow.NULL&t&&n-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Zt.Allow.BOOL&t&&n-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Zt.Allow.BOOL&t&&n-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Zt.Allow.INFINITY&t&&n-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Zt.Allow._INFINITY&t&&1<n-o&&n-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Zt.Allow.NAN&t&&n-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):c()),l=()=>{let g=o,m=!1;for(o++;o<n&&(e[o]!=='"'||m&&e[o-1]==="\\");)m=e[o]==="\\"?!m:!1,o++;if(e.charAt(o)=='"')try{return JSON.parse(e.substring(g,++o-Number(m)))}catch(b){a(String(b))}else if(Zt.Allow.STR&t)try{return JSON.parse(e.substring(g,o-Number(m))+'"')}catch{return JSON.parse(e.substring(g,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},p=()=>{o++,f();let g={};try{for(;e[o]!=="}";){if(f(),o>=n&&Zt.Allow.OBJ&t)return g;let m=l();f(),o++;try{let b=s();g[m]=b}catch(b){if(Zt.Allow.OBJ&t)return g;throw b}f(),e[o]===","&&o++}}catch{if(Zt.Allow.OBJ&t)return g;r("Expected '}' at end of object")}return o++,g},d=()=>{o++;let g=[];try{for(;e[o]!=="]";)g.push(s()),f(),e[o]===","&&o++}catch{if(Zt.Allow.ARR&t)return g;r("Expected ']' at end of array")}return o++,g},c=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(m){if(Zt.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(m))}}let g=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==n&&!(Zt.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(b){a(String(b))}}},f=()=>{for(;o<n&&`
|
|
2
|
+
\r `.includes(e[o]);)o++};return s()},Ev=Eg;_t.parse=Ev});var lh={};ag(lh,{createReconnectController:()=>mC});function mC(e){let t=0,n=null,o=null,r=!1,a=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},s=()=>{let b=e.getStatus();b!=="resuming"&&b!=="paused"||a()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||s()},p=()=>{s()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",p),r=!0)},c=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},f=b=>new Promise(w=>{n=w,o=setTimeout(()=>{o=null,n=null,w()},b)}),g=()=>{let b=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let w=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,w=!0);let T=e.buildErrorContent("Connection lost and the response could not be resumed.");T?e.appendMessage({id:`reconnect-failed-${b?.executionId??e.nextSequence()}`,role:"assistant",content:T,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):w&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},m=async()=>{let b=e.config.reconnect?.backoffMs??fC,w=e.config.reconnect?.maxAttempts??b.length,T=e.config.reconnectStream;if(!T){e.setReconnecting(!1);return}for(;e.getResumable()&&t<w;){t+=1,e.setStatus("resuming");let L=e.getResumable(),A=L.lastEventId,S=new AbortController;e.setAbortController(S),e.emitReconnect({phase:"resuming",handle:L,attempt:t});let C=null;try{let M=await T({executionId:L.executionId,after:L.lastEventId,signal:S.signal});M&&M.ok&&M.body&&(C=M.body)}catch{C=null}if(S.signal.aborted)return;if(C){let M=e.getMessages().find(R=>R.id===L.assistantMessageId)?.content,P=typeof M=="string"?M:"";try{await e.resumeConnect(C,L.assistantMessageId,P)}catch{}if(S.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:L});return}e.getResumable().lastEventId!==A&&(t=0)}if(e.getResumable()&&t<w&&(e.setStatus("paused"),await f(b[Math.min(t-1,b.length-1)]??1e3),S.signal.aborted))return}e.getResumable()&&g()};return{begin(){t=0,d(),m()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:a}}var fC,ch=tv(()=>{"use strict";fC=[1e3,2e3,4e3,8e3,8e3]});var b0={};ag(b0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>id,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>sd,ASK_USER_QUESTION_TOOL_NAME:()=>ss,AgentWidgetClient:()=>vr,AgentWidgetSession:()=>ca,AttachmentManager:()=>Ar,BrowserSpeechEngine:()=>_o,DEFAULT_COMPONENTS:()=>hu,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>ol,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>mn,DEFAULT_PALETTE:()=>mu,DEFAULT_SEMANTIC:()=>gu,DEFAULT_WIDGET_CONFIG:()=>rt,PRESETS:()=>wf,PRESET_FULLSCREEN:()=>Cf,PRESET_MINIMAL:()=>vf,PRESET_SHOP:()=>xf,ReadAloudController:()=>wr,SUGGEST_REPLIES_CLIENT_TOOL:()=>Ti,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>od,SUGGEST_REPLIES_TOOL_NAME:()=>On,THEME_ZONES:()=>Mh,VERSION:()=>xr,WEBMCP_TOOL_PREFIX:()=>Dn,WebMcpBridge:()=>na,accessibilityPlugin:()=>Pb,animationsPlugin:()=>Rb,applyFeaturePreferences:()=>of,applyThemeVariables:()=>Sr,attachHeaderToContainer:()=>kr,brandPlugin:()=>Ib,buildComposer:()=>Lr,buildDefaultHeader:()=>Du,buildHeader:()=>fo,buildHeaderWithLayout:()=>ya,buildMinimalHeader:()=>Fu,builtInClientToolsForDispatch:()=>sa,canonicalArtifactDisplayMode:()=>sn,collectEnrichedPageContext:()=>kb,componentRegistry:()=>Nn,createActionManager:()=>Fs,createAgentExperience:()=>Jl,createAskUserQuestionBubble:()=>Ug,createBestAvailableVoiceProvider:()=>Ui,createBubbleWithLayout:()=>py,createCSATFeedback:()=>Gl,createComboButton:()=>ul,createComponentMiddleware:()=>rb,createComponentStreamParser:()=>zl,createDefaultSanitizer:()=>jc,createDirectivePostprocessor:()=>pg,createDropdownMenu:()=>$o,createFlexibleJsonStreamParser:()=>$g,createIconButton:()=>Tt,createImagePart:()=>Yg,createJsonStreamParser:()=>Hi,createLabelButton:()=>po,createLocalStorageAdapter:()=>Vl,createMarkdownProcessor:()=>ns,createMarkdownProcessorFromConfig:()=>hr,createMessageActions:()=>qu,createNPSFeedback:()=>Kl,createPlainTextParser:()=>Ii,createPlugin:()=>Bb,createRegexJsonParser:()=>Wi,createSlashCommandsSource:()=>yb,createStandardBubble:()=>ba,createStaticMentionSource:()=>hb,createTextPart:()=>Oo,createTheme:()=>hs,createThemeObserver:()=>pa,createToggleGroup:()=>ma,createTypingIndicator:()=>Pr,createVoiceProvider:()=>No,createWidgetHostLayout:()=>Ns,createXmlParser:()=>Bi,defaultActionHandlers:()=>Dr,defaultJsonActionParser:()=>Ds,defaultMentionFilter:()=>Yl,defaultParseRules:()=>yf,detectColorScheme:()=>ys,directivePostprocessor:()=>ug,ensureAskUserQuestionSheet:()=>aa,escapeHtml:()=>Vn,extractComponentDirectiveFromMessage:()=>jl,fileToImagePart:()=>Zg,formatEnrichedContext:()=>Lb,generateAssistantMessageId:()=>Fo,generateMessageId:()=>Kg,generateStableSelector:()=>bf,generateUserMessageId:()=>ia,getActiveTheme:()=>Uo,getColorScheme:()=>ll,getDisplayText:()=>Jg,getHeaderLayout:()=>Ou,getImageParts:()=>Qg,getPreset:()=>Fb,hasComponentDirective:()=>Os,hasImages:()=>Oi,headerLayouts:()=>Tl,highContrastPlugin:()=>Hb,initAgentWidget:()=>mb,isAskUserQuestionMessage:()=>so,isComponentDirectiveType:()=>ob,isDockedMountMode:()=>St,isSuggestRepliesMessage:()=>br,isVoiceSupported:()=>us,isWebMcpToolName:()=>Lo,isWelcomeVisible:()=>Xo,latestAgentSuggestions:()=>Ei,listRegisteredStreamAnimations:()=>Lu,loadMarkdownParsers:()=>ts,markdownPostprocessor:()=>$c,mergeWithDefaults:()=>da,normalizeContent:()=>Xg,normalizeMediaType:()=>Po,onMarkdownParsersReady:()=>ea,parseAskUserQuestionPayload:()=>io,parseSuggestRepliesPayload:()=>ad,parseWidgetPreferenceSlice:()=>nf,pickBestVoice:()=>la,pluginRegistry:()=>Bs,reducedMotionPlugin:()=>Wb,registerStreamAnimationPlugin:()=>Er,removeAskUserQuestionSheet:()=>Wo,renderComponentDirective:()=>$l,renderLoadingIndicatorWithFallback:()=>Uu,renderLucideIcon:()=>ae,resolveArtifactDisplay:()=>Jc,resolveArtifactDisplayMode:()=>zn,resolveConfigPreferences:()=>Hs,resolveDockConfig:()=>ln,resolveSanitizer:()=>ta,resolveTokens:()=>sl,resolveWelcomeConfig:()=>mo,stripWebMcpPrefix:()=>xi,themeToCssVariables:()=>il,unregisterStreamAnimationPlugin:()=>ku,validateImageFile:()=>eh,validateTheme:()=>yu});var Zr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,a=null;return{setLoader:c=>{o=c,n&&(r=null,a=null)},load:()=>r?Promise.resolve(r):a||(a=(o??t)().then(f=>(r=f,f)).catch(f=>{throw a=null,f}),a),provide:c=>{r=c},getSync:()=>r}};var{setLoader:ov,load:rv,provide:M0,getSync:zc}=Zr({fallbackImport:()=>import("./markdown-parsers-entry")}),yi=new Set,av=()=>{let e=[...yi];yi.clear();for(let t of e)try{t()}catch{}},ig=ov,ts=()=>{let e=zc();return e?Promise.resolve(e):rv().then(t=>(av(),t))},ea=e=>zc()?()=>{}:(yi.add(e),ts().catch(()=>{}),()=>{yi.delete(e)});var ao=zc;var sv=e=>{if(e)return e},ns=e=>{let t=null;return n=>{let o=ao();if(!o)return Vn(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=sv(e?.renderer);s&&t.use({renderer:s})}return t.parse(n)}},hr=e=>e?ns({markedOptions:e.options,renderer:e.renderer}):ns(),iv=ns(),$c=e=>iv(e),Vn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),cg=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),lg=e=>`%%FORM_PLACEHOLDER_${e}%%`,dg=(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=lg(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=lg(t.length);return t.push({token:a,type:r}),a}),n},pg=e=>{let t=hr(e);return n=>{let o=[],r=dg(n,o),a=t(r);return o.forEach(({token:s,type:l})=>{let p=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${cg(l)}"></div>`;a=a.replace(p,c)}),a}},ug=e=>{let t=[],n=dg(e,t),o=$c(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="${cg(a)}"></div>`;o=o.replace(s,p)}),o};var lv={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"]},cv=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,jc=()=>{let e=null;return t=>{let n=ao();if(!n)return Vn(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:")&&!cv.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,lv)}},ta=e=>e===!1?null:typeof e=="function"?e:jc();var fg=/^\s*\|?[\s:|-]*-[\s:|-]*$/,mg=e=>e.includes("|"),gg=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())},dv=e=>`| ${e.join(" | ")} |`,pv=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,uv=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),hg=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(!mg(r)||fg.test(r)||!fg.test(a))continue;let s=gg(r).length;if(s<1)continue;let l=pv(s);t[o+1]!==l&&(t[o+1]=l,n=!0);let p=o+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!mg(d))break;let c=dv(uv(gg(d),s));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
|
|
4
|
+
`):e};var yg="var(--persona-md-table-scroll-fade, 24px)",bg=new WeakSet;function vg(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 xg(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":yg),e.style.setProperty("--persona-fade-r",r<=1?"0px":yg)}function Gc(e){bg.has(e)||(bg.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&xg(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(xg)}var Dn="webmcp:",Kc=new Map,Cg=e=>{Kc.clear();for(let t of e){let n=t.title?.trim();n&&Kc.set(t.name,n)}},os=e=>Kc.get(xi(e)),bi={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Xc=null,Ag=e=>{Xc=e};function Sg(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}:${fv(t.join(""))}`}function wg(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 fv(e){let t=wg(e,0).toString(36),n=wg(e,2654435761).toString(36);return`${t}.${n}`}var na=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 bi.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Cg(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=gv(r.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Bn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return Bn(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let a=xi(t),s;try{s=await r.getTools()}catch(b){let w=b instanceof Error?b.message:String(b);return Bn(`Failed to read WebMCP registry: ${w}`)}Cg(s);let l=s.find(b=>b.name===a);if(!l)return Bn(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return Bn(`WebMCP tool not allowed by client allowlist: ${a}`);if(o?.aborted)return Bn("Aborted by cancel()");let p=os(a),d={toolName:a,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return Bn("User declined the tool call.");if(o?.aborted)return Bn("Aborted by cancel()");let c=new AbortController,f=!1,g=setTimeout(()=>{f=!0,c.abort()},this.timeoutMs),m=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",m,{once:!0}));try{let b=await r.executeTool(l,xv(n),{signal:c.signal});return hv(b)}catch(b){if(f)return Bn(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Bn("Aborted by cancel()");let w=b instanceof Error?b.message:String(b);return Bn(w)}finally{clearTimeout(g),o&&o.removeEventListener("abort",m)}}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}(Xc?await Xc():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){bi.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,bi.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??yv;try{return await n(t)}catch(o){return bi.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=>mv(t,o))}},xi=e=>e.startsWith(Dn)?e.slice(Dn.length):e,Lo=e=>e.startsWith(Dn),mv=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},gv=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},hv=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:vv(t)}]}},Bn=e=>({isError:!0,content:[{type:"text",text:e}]}),yv=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=bv(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)},tx=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)}},nx=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},ox=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function an(e){return e==="card"?"collapsed":e}function Co(e){return e.split(";",1)[0].trim().toLowerCase()}function rx(e,t){if(!e)return;let n=Object.entries(e);for(let[r,a]of n)if(Co(r)===t)return{mode:an(a),selector:Co(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,a]of n)if(Co(r)===o)return{mode:an(a),selector:o}}function fd(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:an(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Co(t.file.mimeType):void 0,p=l?rx(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:an(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:an(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=o.byType?.[t.artifactType];if(a)return{mode:an(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:an(s),matchedBy:{type:"preferredMode"}}:o.default?{mode:an(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function On(e,t){return fd(e,t).mode}function Na(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 ax="agent_",sx="flow_";function Tm(e){return e.startsWith(ax)?{kind:"agentId",agentId:e}:e.startsWith(sx)?{kind:"flowId",flowId:e}:null}function Em(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=Tm(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=Tm(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 wo=xo(oi(),1);var x=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Lm=()=>document.createDocumentFragment(),Ie=(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},Qn=(...e)=>e.filter(Boolean).join(" ");var Ua="ask_user_question",_a=8,Dr="data-persona-ask-sheet-for",px="Other",ux="Other\u2026",Rm="Type your own answer here",Im="Send",fx="Next",mx="Back",gx="Submit all",hx="Skip",yx=3,gd="data-ask-current-index",hd="data-ask-question-count",Wm="data-ask-answers",yd="data-ask-grouped",Hm="data-ask-layout",bx=e=>e.layout==="pills"?"pills":"rows",xx=e=>e.getAttribute(Hm)==="pills"?"pills":"rows",Pm=!1,Bm=e=>e.replace(/["\\]/g,"\\$&"),Yn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ua,ri=e=>e?.features?.askUserQuestion??{},Zn=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,wo.parse)(r,wo.STR|wo.OBJ|wo.ARR);if(a&&typeof a=="object")return{payload:a,complete:n}}catch{}return{payload:null,complete:n}},qa=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>_a&&!Pm&&(Pm=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${_a}.`)),t.slice(0,_a)},vx=e=>qa(e)[0]??null,Cx=(e,t)=>qa(e)[t]??null,Dm=(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))},Fm=(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},wx=(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 c=x("span","persona-ask-row-description");c.textContent=e.description,s.appendChild(c)}a.appendChild(s);let p=Fm(n,o,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Ax=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},Sx=(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(d=>d&&typeof d.label=="string"&&d.label.length>0);if(p.length===0&&!n){for(let d=0;d<yx;d++)a.appendChild(Ax(o));return a}if(p.forEach((d,u)=>{a.appendChild(wx(d,u,o,s))}),e?.allowFreeText!==!1){let d=o==="rows"?px:ux;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??Rm,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??d),g.appendChild(f),u.appendChild(g);let h=Fm(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??d,a.appendChild(u)}}return a},Om=(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??Rm,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??Im,a.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(a)}return o},Mx=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??Im,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Tx=(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??mx,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??hx,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??gx:n.nextLabel??fx,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,a.appendChild(l),o.appendChild(a),o},nr=e=>{let t=e.getAttribute(Wm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Nm=(e,t)=>{e.setAttribute(Wm,JSON.stringify(t))},Cn=e=>{let t=Number(e.getAttribute(gd)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Ex=(e,t)=>{e.setAttribute(gd,String(Math.max(0,Math.floor(t))))},Fr=e=>{let t=Number(e.getAttribute(hd)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ao=e=>e.getAttribute(yd)==="true",kx=(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},Lx=(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)))},ai=(e,t)=>{let{payload:n}=Zn(t),o=qa(n),r=nr(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},_m=e=>{let t=nr(e),n=Cn(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="")},Um=e=>{if(!Ao(e))return;let t=nr(e),n=Cn(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}},bd=(e,t,n)=>{let o=ri(n),r=xx(e),{payload:a,complete:s}=Zn(t),l=Ao(e),p=Cn(e),c=Fr(e),d=l?Cx(a,p):vx(a),u=!!d?.multiSelect,g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=l?`${p+1}/${c}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let M=typeof d?.question=="string"?d.question:"";h.textContent=M,h.classList.toggle("persona-ask-question-skeleton",!M&&!s)}let S=e.querySelector('[data-ask-pill-list="true"]');if(S){let M=Sx(d,o,s,r);S.replaceWith(M)}if(r!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(Om(o,r))}let k=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!k?e.appendChild(Mx(o)):(!u||l)&&k&&k.remove(),e.setAttribute("data-multi-select",u?"true":"false");let P=e.querySelector('[data-ask-nav-row="true"]');if(l){let M=Tx(p,c,o);P?P.replaceWith(M):e.appendChild(M)}else P&&P.remove();_m(e),Um(e)},Px=(e,t,n)=>{let o=ri(t),r=bx(o),a=e.toolCall.id,s=qa(n),l=Math.max(1,s.length),p=l>1,c=kx(e,s),d=p?Lx(e,l):0,u=x("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Dr,a),u.setAttribute("data-tool-call-id",a),u.setAttribute("data-message-id",e.id),u.setAttribute(hd,String(l)),u.setAttribute(gd,String(d)),u.setAttribute(yd,p?"true":"false"),u.setAttribute(Hm,r),Nm(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`),Dm(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 k=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 k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),u.appendChild(k),r!=="rows"&&u.appendChild(Om(o,r)),bd(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Rx=(e,t,n)=>{let{payload:o}=Zn(t),r=Math.max(1,qa(o).length);r>Fr(e)&&(e.setAttribute(hd,String(r)),r>1&&!Ao(e)&&e.setAttribute(yd,"true")),bd(e,t,n)},qm=(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=ri(t);Dm(n,o);let r=x("span","persona-ask-stub-label"),{complete:a}=Zn(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Or=(e,t,n)=>{if(!n||!Yn(e)||ri(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Dr}]`).forEach(c=>{c.getAttribute(Dr)!==r&&c.remove()});let s=n.querySelector(`[${Dr}="${Bm(r)}"]`);if(s){Rx(s,e,t);return}let{payload:l}=Zn(e),p=Px(e,t,l);n.appendChild(p)},So=(e,t)=>{if(!e)return;let n=t?`[${Dr}="${Bm(t)}"]`:`[${Dr}]`;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)})},xd=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),Mo=(e,t)=>{let n=nr(e),o=Cn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Nm(e,n),_m(e),Um(e)},si=(e,t,n,o)=>{let r=Fr(e),a=Math.max(0,Math.min(r-1,o));Ex(e,a),bd(e,t,n)};var Pn="suggest_replies";var vd={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},ii={name:Pn,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:vd,origin:"sdk",annotations:{readOnlyHint:!0}},Cd=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),or=e=>e.variant==="tool"&&e.toolCall?.name===Pn,wd=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.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let a=r;if(typeof a.label!="string"||!a.label.trim())return[];let s={label:a.label.trim()};return typeof a.prompt=="string"&&a.prompt.trim()&&(s.prompt=a.prompt.trim()),typeof a.description=="string"&&a.description.trim()&&(s.description=a.description.trim()),[s]});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},li=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!or(n))continue;let o=wd(n.toolCall?.args);return o.length>0?o:null}return null},Vm=new Set,Ix=(e,t,n)=>{let o=`${e}:${t}:${n}`;Vm.has(o)||(Vm.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},To=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=s=>{let l=t?.[s],p=n?.[s];l===void 0||p===void 0||l!==p&&Ix(s,p,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,a=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:a}};var Ad={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:_a,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},Sd={name:Ua,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:Ad,origin:"sdk",annotations:{readOnlyHint:!0}},Nr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Sd),To(e).expose&&t.push(ii),t};var eo=xo(oi(),1),di=e=>e.replace(/\\n/g,`
|
|
10
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
9
|
+
${e.description}`:"");return window.confirm(n)},bv=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)}},xv=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},vv=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function sn(e){return e==="card"?"collapsed":e}function Po(e){return e.split(";",1)[0].trim().toLowerCase()}function Cv(e,t){if(!e)return;let n=Object.entries(e);for(let[r,a]of n)if(Po(r)===t)return{mode:sn(a),selector:Po(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,a]of n)if(Po(r)===o)return{mode:sn(a),selector:o}}function Jc(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:sn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Po(t.file.mimeType):void 0,p=l?Cv(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:sn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:sn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=o.byType?.[t.artifactType];if(a)return{mode:sn(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:sn(s),matchedBy:{type:"preferredMode"}}:o.default?{mode:sn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function zn(e,t){return Jc(e,t).mode}function rs(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 wv="agent_",Av="flow_";function Mg(e){return e.startsWith(wv)?{kind:"agentId",agentId:e}:e.startsWith(Av)?{kind:"flowId",flowId:e}:null}function Tg(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=Mg(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=Mg(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 Ro=ko(wi(),1);var v=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var kg=()=>document.createDocumentFragment(),ke=(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},Fn=(...e)=>e.filter(Boolean).join(" ");var ss="ask_user_question",as=8,oa="data-persona-ask-sheet-for",kv="Other",Lv="Other\u2026",Pg="Type your own answer here",Rg="Send",Pv="Next",Rv="Back",Iv="Submit all",Wv="Skip",Hv=3,Yc="data-ask-current-index",Zc="data-ask-question-count",Ig="data-ask-answers",ed="data-ask-grouped",Wg="data-ask-layout",Bv=e=>e.layout==="pills"?"pills":"rows",Dv=e=>e.getAttribute(Wg)==="pills"?"pills":"rows",Lg=!1,Hg=e=>e.replace(/["\\]/g,"\\$&"),so=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ss,Ai=e=>e?.features?.askUserQuestion??{},io=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,Ro.parse)(r,Ro.STR|Ro.OBJ|Ro.ARR);if(a&&typeof a=="object")return{payload:a,complete:n}}catch{}return{payload:null,complete:n}},is=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>as&&!Lg&&(Lg=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${as}.`)),t.slice(0,as)},Fv=e=>is(e)[0]??null,Ov=(e,t)=>is(e)[t]??null,Bg=(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))},Dg=(e,t,n)=>{if(e!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Nv=(e,t,n,o)=>{let a=v("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=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=e.label,s.appendChild(l),e.description){let d=v("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let p=Dg(n,o,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},_v=e=>{let n=v("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},Uv=(e,t,n,o)=>{let a=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");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<Hv;c++)a.appendChild(_v(o));return a}if(p.forEach((c,f)=>{a.appendChild(Nv(c,f,o,s))}),e?.allowFreeText!==!1){let c=o==="rows"?kv:Lv;if(o==="rows"){let f=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(p.length)),f.setAttribute("data-ask-other-row","true");let g=v("span","persona-ask-row-content"),m=document.createElement("input");m.type="text",m.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",m.placeholder=t.freeTextPlaceholder??Pg,m.setAttribute("data-ask-free-text-input","true"),m.setAttribute("aria-label",t.freeTextLabel??c),g.appendChild(m),f.appendChild(g);let b=Dg(o,s,p.length);b&&f.appendChild(b),a.appendChild(f)}else{let f=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=t.freeTextLabel??c,a.appendChild(f)}}return a},Fg=(e,t)=>{let o=v("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??Pg,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let a=v("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??Rg,a.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(a)}return o},qv=e=>{let t=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Rg,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Vv=(e,t,n)=>{let o=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Rv,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let a=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=v("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=n.skipLabel??Wv,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??Iv:n.nextLabel??Pv,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,a.appendChild(l),o.appendChild(a),o},yr=e=>{let t=e.getAttribute(Ig);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Og=(e,t)=>{e.setAttribute(Ig,JSON.stringify(t))},Sn=e=>{let t=Number(e.getAttribute(Yc)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},zv=(e,t)=>{e.setAttribute(Yc,String(Math.max(0,Math.floor(t))))},ra=e=>{let t=Number(e.getAttribute(Zc)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Io=e=>e.getAttribute(ed)==="true",$v=(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},jv=(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)))},Si=(e,t)=>{let{payload:n}=io(t),o=is(n),r=yr(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},Ng=e=>{let t=yr(e),n=Sn(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="")},_g=e=>{if(!Io(e))return;let t=yr(e),n=Sn(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}},td=(e,t,n)=>{let o=Ai(n),r=Dv(e),{payload:a,complete:s}=io(t),l=Io(e),p=Sn(e),d=ra(e),c=l?Ov(a,p):Fv(a),f=!!c?.multiSelect,g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=l?`${p+1}/${d}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let A=typeof c?.question=="string"?c.question:"";b.textContent=A,b.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let w=e.querySelector('[data-ask-pill-list="true"]');if(w){let A=Uv(c,o,s,r);w.replaceWith(A)}if(r!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(Fg(o,r))}let T=e.querySelector('[data-ask-multi-actions="true"]');!l&&f&&!T?e.appendChild(qv(o)):(!f||l)&&T&&T.remove(),e.setAttribute("data-multi-select",f?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(l){let A=Vv(p,d,o);L?L.replaceWith(A):e.appendChild(A)}else L&&L.remove();Ng(e),_g(e)},Gv=(e,t,n)=>{let o=Ai(t),r=Bv(o),a=e.toolCall.id,s=is(n),l=Math.max(1,s.length),p=l>1,d=$v(e,s),c=p?jv(e,l):0,f=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(oa,a),f.setAttribute("data-tool-call-id",a),f.setAttribute("data-message-id",e.id),f.setAttribute(Zc,String(l)),f.setAttribute(Yc,String(c)),f.setAttribute(ed,p?"true":"false"),f.setAttribute(Wg,r),Og(f,d),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Bg(f,o);let g=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=v("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",g.appendChild(m);let b=v("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",g.appendChild(b),f.appendChild(g);let T=v("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),f.appendChild(T),r!=="rows"&&f.appendChild(Fg(o,r)),td(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Kv=(e,t,n)=>{let{payload:o}=io(t),r=Math.max(1,is(o).length);r>ra(e)&&(e.setAttribute(Zc,String(r)),r>1&&!Io(e)&&e.setAttribute(ed,"true")),td(e,t,n)},Ug=(e,t)=>{let n=v("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=Ai(t);Bg(n,o);let r=v("span","persona-ask-stub-label"),{complete:a}=io(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},aa=(e,t,n)=>{if(!n||!so(e)||Ai(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${oa}]`).forEach(d=>{d.getAttribute(oa)!==r&&d.remove()});let s=n.querySelector(`[${oa}="${Hg(r)}"]`);if(s){Kv(s,e,t);return}let{payload:l}=io(e),p=Gv(e,t,l);n.appendChild(p)},Wo=(e,t)=>{if(!e)return;let n=t?`[${oa}="${Hg(t)}"]`:`[${oa}]`;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)})},nd=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=yr(e),o=Sn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Og(e,n),Ng(e),_g(e)},Mi=(e,t,n,o)=>{let r=ra(e),a=Math.max(0,Math.min(r-1,o));zv(e,a),td(e,t,n)};var On="suggest_replies";var od={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},Ti={name:On,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:od,origin:"sdk",annotations:{readOnlyHint:!0}},rd=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),br=e=>e.variant==="tool"&&e.toolCall?.name===On,ad=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.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let a=r;if(typeof a.label!="string"||!a.label.trim())return[];let s={label:a.label.trim()};return typeof a.prompt=="string"&&a.prompt.trim()&&(s.prompt=a.prompt.trim()),typeof a.description=="string"&&a.description.trim()&&(s.description=a.description.trim()),[s]});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},Ei=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!br(n))continue;let o=ad(n.toolCall?.args);return o.length>0?o:null}return null},qg=new Set,Xv=(e,t,n)=>{let o=`${e}:${t}:${n}`;qg.has(o)||(qg.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Bo=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=s=>{let l=t?.[s],p=n?.[s];l===void 0||p===void 0||l!==p&&Xv(s,p,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,a=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:a}};var sd={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:as,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},id={name:ss,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:sd,origin:"sdk",annotations:{readOnlyHint:!0}},sa=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(id),Bo(e).expose&&t.push(Ti),t};var lo=ko(wi(),1),ki=e=>e.replace(/\\n/g,`
|
|
10
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Do=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)}},Jv=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`},Vg=e=>e.status==="complete"?Jv(e):e.status==="pending"?"Waiting":"",Qv=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 zg=e=>e.status==="complete"?Qv(e):"Using tool...",Li=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},cs=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 Li(t)},Pi=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Li(t)},ld=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=cs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Ri=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=r.exec(n))!==null;)s.index>a&&ls(o,n.slice(a,s.index),[]),s[1]!==void 0?ls(o,s[1],["bold"]):s[2]!==void 0?ls(o,s[2],["italic"]):s[3]!==void 0&&ls(o,s[3],["dim"]),a=s.index+s[0].length;return a<n.length&&ls(o,n.slice(a),[]),o},ls=(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})},Yv=()=>{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()=>{}}},$a=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},fi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},mi=()=>{let e=Bx();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},gi=()=>{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,eo.parse)(n,eo.STR|eo.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?di(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=di(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},jm=e=>{let t=null,n=0,r=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?di(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?di(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,eo.parse)(a,eo.STR|eo.OBJ),p=r(l);p!==null&&(t=p)}catch{}return n=a.length,{text:t||"",raw:a}},close:()=>{}}},hi=()=>{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 Gm="4.15.0";var rr=Gm;var Fx="https://api.runtype.com/v1/dispatch",yi="https://api.runtype.com";function Ox(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var Td=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Nx(e){switch(e){case"json":return gi;case"regex-json":return mi;case"xml":return hi;default:return fi}}var Km=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=Km(n);if(!Km(o))return e;if(!r||o===n||o.startsWith(n))return t;let s=$a(e);return $a(t)!==null&&s===null?t:e}var ar=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Fx,this.headers={"Content-Type":"application/json","X-Persona-Version":rr,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Nx(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Br(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=Em(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$/,"")||yi}/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":rr},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$/,"")||yi}/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":rr},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(Td).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":rr},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$/,"")||yi}/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?Mm(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(/\/+$/,"")||yi}/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=[...Nr(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(Td).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=[...Nr(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(Td).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=[...Nr(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=T=>{let $=T.reasoning?{...T.reasoning,chunks:[...T.reasoning.chunks]}:void 0,b=T.toolCall?{...T.toolCall,chunks:T.toolCall.chunks?[...T.toolCall.chunks]:void 0}:void 0,W=T.tools?T.tools.map(B=>({...B,chunks:B.chunks?[...B.chunks]:void 0})):void 0;return{...T,reasoning:$,toolCall:b,tools:W}},g=T=>{if(T.role!=="assistant"||T.variant)return!0;let $=Array.isArray(T.contentParts)&&T.contentParts.length>0,b=typeof T.rawContent=="string"&&T.rawContent.trim()!=="";return typeof T.content=="string"&&T.content.trim()!==""||$||b||!!T.stopReason},f=T=>{g(T)&&n({type:"message",message:u(T)})},h=null,S=null,k={current:null},P={current:null},M=null,A="",C=new Map,E=new Map,R=new Map,w=new Map,H=new Map,F={lastId:null,byStep:new Map},K={lastId:null,byCall:new Map},D=T=>{if(T==null)return null;try{return String(T)}catch{return null}},q=T=>D(T.stepId??T.step_id??T.step??T.parentId??T.flowStepId??T.flow_step_id),Y=T=>D(T.callId??T.call_id??T.requestId??T.request_id??T.toolCallId??T.tool_call_id??T.stepId??T.step_id),de=o,be=!1,pe=()=>{if(h)return h;let T,$="",b=M;return!be&&de?(T=de,be=!0,$=r??""):de&&b?T=`${de}_${b}`:T=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:T,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},f(h),h},te=(T,$)=>{F.lastId=$,T&&F.byStep.set(T,$)},me=(T,$)=>{let b=T.reasoningId??T.id,W=q(T);if(b){let _=String(b);return te(W,_),_}if(W){let _=F.byStep.get(W);if(_)return F.lastId=_,_}if(F.lastId&&!$)return F.lastId;if(!$)return null;let B=`reason-${d()}`;return te(W,B),B},oe=T=>{let $=w.get(T);if($)return $;let b={id:`reason-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:T,status:"streaming",chunks:[]}};return w.set(T,b),f(b),b},le=(T,$)=>{K.lastId=$,T&&K.byCall.set(T,$)},Z=new Set,he=new Map,Ce=new Set,ve=new Map,we=T=>{if(!T)return!1;let $=T.replace(/_+/g,"_").replace(/^_|_$/g,"");return $==="emit_artifact_markdown"||$==="emit_artifact_component"},Ee=(T,$)=>{let b=T.toolId??T.id,W=Y(T);if(b){let _=String(b);return le(W,_),_}if(W){let _=K.byCall.get(W);if(_)return K.lastId=_,_}if(K.lastId&&!$)return K.lastId;if(!$)return null;let B=`tool-${d()}`;return le(W,B),B},ke=T=>{let $=H.get(T);if($)return $;let b={id:`tool-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:T,status:"pending"}};return H.set(T,b),f(b),b},Se=T=>{if(typeof T=="number"&&Number.isFinite(T))return T;if(typeof T=="string"){let $=Number(T);if(!Number.isNaN($)&&Number.isFinite($))return $;let b=Date.parse(T);if(!Number.isNaN(b))return b}return Date.now()},Ge=T=>{if(typeof T=="string")return T;if(T==null)return"";try{return JSON.stringify(T)}catch{return String(T)}},ze=new Map,Me=new Map,Re=new Map,Ke=(T,$,b)=>{let W=Re.get(T);W||(W=[],Re.set(T,W));let B=0,_=W.length;for(;B<_;){let O=B+_>>>1;W[O].seq<$?B=O+1:_=O}W[B]?.seq===$?W[B]={seq:$,text:b}:W.splice(B,0,{seq:$,text:b});let U="";for(let O=0;O<W.length;O++)U+=W[O].text;return U},Bt=(T,$)=>{let b=Ge($),W=Me.get(T.id),B=_x(W,b);T.rawContent=B;let _=ze.get(T.id),U=ye=>{let ot=T.content??"";ye.trim()!==""&&(ot.trim().length===0||ye.startsWith(ot)||ye.trimStart().startsWith(ot.trim()))&&(T.content=ye)},O=()=>{if(_){let ye=_.close?.();ye instanceof Promise&&ye.catch(()=>{})}ze.delete(T.id),Me.delete(T.id),T.streaming=!1,f(T)};if(!_){U(b),O();return}let J=$a(B);if(J!==null&&J.trim()!==""){U(J),O();return}let se=ye=>{let ot=typeof ye=="string"?ye:ye?.text??null;if(ot!==null&&ot.trim()!=="")return ot;let nt=_.getExtractedText();return nt!==null&&nt.trim()!==""?nt:b},Te;try{Te=_.processChunk(B)}catch{U(b),O();return}if(Te instanceof Promise){Te.then(ye=>{U(se(ye)),O()}).catch(()=>{U(b),O()});return}U(se(Te)),O()},Wt=null,Kt=(T,$,b,W)=>{T.rawContent=$,ze.has(T.id)||ze.set(T.id,this.createStreamParser());let B=ze.get(T.id),_=$.trim().startsWith("{")||$.trim().startsWith("[");if(_&&Me.set(T.id,$),B.__isPlainTextParser===!0){T.content=W!==void 0?$:T.content+b,Me.delete(T.id),ze.delete(T.id),T.rawContent=void 0,f(T);return}let O=B.processChunk($);if(O instanceof Promise)O.then(J=>{let se=typeof J=="string"?J:J?.text??null;se!==null&&se.trim()!==""?(T.content=se,f(T)):!_&&!$.trim().startsWith("<")&&(T.content=W!==void 0?$:T.content+b,Me.delete(T.id),ze.delete(T.id),T.rawContent=void 0,f(T))}).catch(()=>{T.content=W!==void 0?$:T.content+b,Me.delete(T.id),ze.delete(T.id),T.rawContent=void 0,f(T)});else{let J=typeof O=="string"?O:O?.text??null;J!==null&&J.trim()!==""?(T.content=J,f(T)):!_&&!$.trim().startsWith("<")&&(T.content=W!==void 0?$:T.content+b,Me.delete(T.id),ze.delete(T.id),T.rawContent=void 0,f(T))}},wt=(T,$)=>{let b=$??T.content;if(b==null||b===""){T.streaming=!1,f(T);return}let B=Me.get(T.id)??Ge(b);T.rawContent=B;let _=ze.get(T.id),U=null,O=!1;if(_&&(U=_.getExtractedText(),U===null&&(U=$a(B)),U===null)){let J=_.processChunk(B);J instanceof Promise?(O=!0,J.then(se=>{let Te=typeof se=="string"?se:se?.text??null;Te!==null&&(T.content=Te,T.streaming=!1,ze.delete(T.id),Me.delete(T.id),f(T))}).catch(()=>{})):U=typeof J=="string"?J:J?.text??null}if(!O){U!==null&&U.trim()!==""?T.content=U:Me.has(T.id)||(T.content=Ge(b));let J=ze.get(T.id);if(J){let se=J.close?.();se instanceof Promise&&se.catch(()=>{}),ze.delete(T.id)}Me.delete(T.id),T.streaming=!1,f(T)}},De=(T,$,b)=>{let W=E.get(T);if(W)return W;let B={id:`nested-${$}-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...b?{variant:b}:{},...b==="reasoning"?{reasoning:{id:T,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:$}};return E.set(T,B),f(B),B},ue=[],Qe,He=new Map,fe=0,ie="agent",We=!1,Xt=null,ut=null,ht=new Map,j=this.config.iterationDisplay??"separate";for(Qe=()=>{for(let T=0;T<ue.length;T++){let $=ue[T].payloadType,b=ue[T].payload;if(!We&&ie!=="flow"&&typeof b.stepType=="string"&&(ie="flow"),$==="reasoning_start"){let W=typeof b.id=="string"?b.id:null,B=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(W&&B){C.set(W,B),De(W,B,"reasoning");continue}let _=me(b,!0)??`reason-${d()}`,U=oe(_);U.reasoning=U.reasoning??{id:_,status:"streaming",chunks:[]},U.reasoning.startedAt=U.reasoning.startedAt??Se(b.startedAt??b.timestamp),U.reasoning.completedAt=void 0,U.reasoning.durationMs=void 0,(b.scope==="loop"||b.scope==="turn")&&(U.reasoning.scope=b.scope),U.streaming=!0,U.reasoning.status="streaming",f(U)}else if($==="reasoning_delta"){let W=typeof b.id=="string"?b.id:null;if(W&&C.has(W)&&E.has(W)){let O=E.get(W),J=b.reasoningText??b.text??b.delta??"";J&&b.hidden!==!0&&O.reasoning&&(O.reasoning.chunks.push(String(J)),f(O));continue}let B=me(b,!1)??me(b,!0)??`reason-${d()}`,_=oe(B);_.reasoning=_.reasoning??{id:B,status:"streaming",chunks:[]},_.reasoning.startedAt=_.reasoning.startedAt??Se(b.startedAt??b.timestamp);let U=b.reasoningText??b.text??b.delta??"";if(U&&b.hidden!==!0){let O=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(O!==void 0){let J=Ke(B,O,String(U));_.reasoning.chunks=[J]}else _.reasoning.chunks.push(String(U))}if(_.reasoning.status=b.done?"complete":"streaming",b.done){_.reasoning.completedAt=Se(b.completedAt??b.timestamp);let O=_.reasoning.startedAt??Date.now();_.reasoning.durationMs=Math.max(0,(_.reasoning.completedAt??Date.now())-O)}_.streaming=_.reasoning.status!=="complete",f(_)}else if($==="reasoning_complete"){let W=typeof b.id=="string"?b.id:null;if(W&&C.has(W)&&E.has(W)){let J=E.get(W);if(J.reasoning){let se=typeof b.text=="string"?b.text:"";se&&J.reasoning.chunks.length===0&&J.reasoning.chunks.push(se),J.reasoning.status="complete",J.streaming=!1,f(J)}C.delete(W),E.delete(W);continue}let B=me(b,!1)??me(b,!0)??`reason-${d()}`,_=typeof b.text=="string"?b.text:"";!w.get(B)&&(_||b.scope==="loop")&&oe(B);let U=w.get(B);if(U?.reasoning){(b.scope==="loop"||b.scope==="turn")&&(U.reasoning.scope=b.scope),_&&U.reasoning.chunks.length===0&&U.reasoning.chunks.push(_),U.reasoning.status="complete",U.reasoning.completedAt=Se(b.completedAt??b.timestamp);let J=U.reasoning.startedAt??Date.now();U.reasoning.durationMs=Math.max(0,(U.reasoning.completedAt??Date.now())-J),U.streaming=!1,f(U)}let O=q(b);O&&F.byStep.delete(O)}else if($==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof b.iteration=="number"&&(fe=b.iteration);let W=(typeof b.toolCallId=="string"?b.toolCallId:void 0)??Ee(b,!0)??`tool-${d()}`,B=b.toolName??b.name;if(we(B)){Z.add(W);continue}le(Y(b),W);let _=ke(W),U=_.toolCall??{id:W,status:"pending"};U.name=B??U.name,U.status="running",b.parameters!==void 0?U.args=b.parameters:b.args!==void 0&&(U.args=b.args),U.startedAt=U.startedAt??Se(b.startedAt??b.timestamp),U.completedAt=void 0,U.durationMs=void 0,_.toolCall=U,_.streaming=!0,b.executionId&&(_.agentMetadata={executionId:b.executionId,iteration:b.iteration}),f(_)}else if($==="tool_output_delta"){let W=Ee(b,!1)??Ee(b,!0)??`tool-${d()}`;if(Z.has(W))continue;let B=ke(W),_=B.toolCall??{id:W,status:"running"};_.startedAt=_.startedAt??Se(b.startedAt??b.timestamp);let U=b.text??b.delta??b.message??"";U&&(_.chunks=_.chunks??[],_.chunks.push(String(U))),_.status="running",B.toolCall=_,B.streaming=!0;let O=b.agentContext;(O||b.executionId)&&(B.agentMetadata=B.agentMetadata??{executionId:O?.executionId??b.executionId,iteration:O?.iteration??b.iteration}),f(B)}else if($==="tool_complete"){let W=Ee(b,!1)??Ee(b,!0)??`tool-${d()}`;if(Z.has(W)){Z.delete(W);continue}let B=ke(W),_=B.toolCall??{id:W,status:"running"};_.status="complete",b.result!==void 0&&(_.result=b.result),typeof b.duration=="number"&&(_.duration=b.duration),_.completedAt=Se(b.completedAt??b.timestamp);let U=b.duration??b.executionTime;if(typeof U=="number")_.durationMs=U;else{let se=_.startedAt??Date.now();_.durationMs=Math.max(0,(_.completedAt??Date.now())-se)}B.toolCall=_,B.streaming=!1;let O=b.agentContext;(O||b.executionId)&&(B.agentMetadata=B.agentMetadata??{executionId:O?.executionId??b.executionId,iteration:O?.iteration??b.iteration}),f(B);let J=Y(b);J&&K.byCall.delete(J)}else if($==="await"&&b.toolName){let W=typeof b.toolCallId=="string"&&b.toolCallId.length>0?b.toolCallId:void 0,B=W??b.toolId??`local-${d()}`,_=ke(B),U=b.toolName,O=b.origin==="webmcp"&&!vo(U)?`webmcp:${U}`:U,J=vo(O),se=_.toolCall??{id:B,status:"pending"};se.name=O,se.args=b.parameters,se.status=J?"running":"complete",se.chunks=se.chunks??[],se.startedAt=se.startedAt??Se(b.startedAt??b.timestamp??b.awaitedAt),J?(se.completedAt=void 0,se.duration=void 0,se.durationMs=void 0):se.completedAt=se.completedAt??se.startedAt,_.toolCall=se,_.streaming=!1,_.agentMetadata={..._.agentMetadata,executionId:b.executionId??_.agentMetadata?.executionId,awaitingLocalTool:!0,...W?{webMcpToolCallId:W}:{}},f(_)}else if($==="text_start"){let W=typeof b.id=="string"?b.id:null,B=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(W&&B){C.set(W,B);continue}let _=h;_&&(ie==="flow"?(wt(_),Wt=_):(_.streaming=!1,f(_)),h=null),M=typeof b.id=="string"?b.id:M,A=""}else if($==="text_delta"){let W=typeof b.id=="string"?b.id:null,B=W?C.get(W):void 0;if(W&&B){let U=typeof b.delta=="string"?b.delta:"",O=(R.get(W)??"")+U;if(R.set(W,O),O.trim()==="")continue;let J=De(W,B);J.agentMetadata={...J.agentMetadata,executionId:b.executionId,parentToolId:B},Kt(J,O,U,void 0);continue}if(M=typeof b.id=="string"?b.id:M,ie==="flow"){let U=typeof b.delta=="string"?b.delta:"";if(A+=U,A.trim()==="")continue;let O=pe();O.agentMetadata={executionId:b.executionId,iteration:b.iteration},Kt(O,A,U,void 0),S=O;continue}let _=pe();_.content+=b.delta??"",_.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:Xt??void 0,agentName:ut?.agentName},S=_,f(_)}else if($==="text_complete"){let W=typeof b.id=="string"?b.id:null;if(W&&C.has(W)){let _=E.get(W);_&&wt(_),C.delete(W),R.delete(W),E.delete(W);continue}let B=h;B&&(ie==="flow"?(wt(B),Wt=B):((B.content??"")===""&&typeof b.text=="string"&&(B.content=b.text),B.streaming=!1,f(B)),h=null),M=null,A=""}else if($==="step_complete"){let W=b.stepType,B=b.executionType;if(W==="tool"||B==="context")continue;if(b.success===!1){let _=b.error,U=typeof _=="string"&&_!==""?_:_!=null&&typeof _=="object"&&Reflect.has(_,"message")?String(_.message??"Step failed"):"Step failed";n({type:"error",error:new Error(U)});let O=h;O&&O.streaming&&(O.streaming=!1,f(O)),n({type:"status",status:"idle"});continue}{let _=Wt;Wt=null;let U=b.stopReason,O=b.result?.response;if(_)U&&(_.stopReason=U),O!=null?Bt(_,O):_.streaming!==!1&&(ze.delete(_.id),Me.delete(_.id),_.streaming=!1,f(_));else{let J=O!=null&&O!=="";if(J||U){let se=pe();U&&(se.stopReason=U),J?wt(se,O):(se.streaming=!1,f(se))}}continue}}else if($==="execution_start")ie=b.kind==="flow"?"flow":"agent",We=!0,ie==="agent"&&(ut={executionId:b.executionId,agentId:b.agentId??"virtual",agentName:b.agentName??"",status:"running",currentIteration:0,maxTurns:b.maxTurns??1,startedAt:Se(b.startedAt)});else if($==="turn_start"){let W=typeof b.iteration=="number"?b.iteration:fe;if(W!==fe){if(ut&&(ut.currentIteration=W),j==="separate"&&W>1){let B=h;B&&(B.streaming=!1,f(B),ht.set(W-1,B),h=null)}fe=W}Xt=typeof b.id=="string"?b.id:null,S=null}else if($==="tool_input_delta"){let W=b.toolCallId??K.lastId;if(W){let B=H.get(W);B?.toolCall&&(B.toolCall.chunks=B.toolCall.chunks??[],B.toolCall.chunks.push(b.delta??""),f(B))}}else{if($==="tool_input_complete")continue;if($==="turn_complete"){let W=b.stopReason,B=h??S;if(W&&B!==null){let _=b.id;(!_||B.agentMetadata?.turnId===_)&&(B.stopReason=W,f(B))}Xt===b.id&&(Xt=null)}else if($==="media_start"){let W=String(b.id);He.set(W,{mediaType:typeof b.mediaType=="string"?b.mediaType:void 0,role:typeof b.role=="string"?b.role:void 0,toolCallId:b.toolCallId,parts:[]})}else if($==="media_delta"){let W=He.get(String(b.id));W&&typeof b.delta=="string"&&W.parts.push(b.delta)}else if($==="media_complete"){let W=String(b.id),B=He.get(W);He.delete(W);let _=(typeof b.mediaType=="string"?b.mediaType:void 0)??B?.mediaType??"application/octet-stream",U=typeof b.data=="string"?b.data:void 0,O=typeof b.url=="string"?b.url:B&&B.parts.length>0?B.parts.join(""):void 0,J=null;if(U)J={type:"media",data:U,mediaType:_};else if(O){let ot=_.toLowerCase();J={type:ot==="image"||ot.startsWith("image/")?"image-url":"file-url",url:O,mediaType:_}}let se=b.toolCallId??B?.toolCallId,Te=J?[J]:[],ye=[];for(let ot of Te){if(!ot||typeof ot!="object")continue;let nt=ot,Ue=typeof nt.type=="string"?nt.type:void 0,Ye=typeof nt.mediaType=="string"?nt.mediaType.toLowerCase():"",G=null,qe="";if(Ue==="media"){let Fe=typeof nt.data=="string"?nt.data:void 0;if(!Fe)continue;qe=Ye.length>0?Ye:"application/octet-stream",G=`data:${qe};base64,${Fe}`}else if(Ue==="image-url"){let Fe=typeof nt.url=="string"?nt.url:void 0;if(!Fe)continue;qe=Ye,G=Fe}else if(Ue==="file-url"){let Fe=typeof nt.url=="string"?nt.url:void 0;if(!Fe)continue;qe=Ye,G=Fe}else continue;if(G)if(Ue==="image-url"||qe.startsWith("image/"))ye.push({type:"image",image:G,...qe.includes("/")?{mimeType:qe}:{}});else if(qe.startsWith("audio/"))ye.push({type:"audio",audio:G,mimeType:qe});else if(qe.startsWith("video/"))ye.push({type:"video",video:G,mimeType:qe});else{let Fe=qe||"application/octet-stream";ye.push({type:"file",data:G,mimeType:Fe,filename:Ox(Fe)})}}if(ye.length>0){let ot=d(),nt=se,Ye={id:`agent-media-${typeof nt=="string"&&nt.length>0?`${nt}-${ot}`:String(ot)}`,role:"assistant",content:"",contentParts:ye,createdAt:new Date().toISOString(),streaming:!1,sequence:ot,agentMetadata:{executionId:b.executionId,iteration:typeof b.iteration=="number"?b.iteration:fe}};f(Ye);let G=h;G&&(G.streaming=!1,f(G)),h=null,k.current=null}}else if($==="execution_complete"){let W=b.kind??ie;W==="agent"&&ut&&(ut.status=b.success?"complete":"error",ut.completedAt=Se(b.completedAt),ut.stopReason=b.stopReason);let B=h;B&&(W==="flow"&&B.streaming!==!1?wt(B):(B.streaming=!1,f(B)),h=null),M=null,A="",Wt=null,n({type:"status",status:"idle",terminal:!0})}else if($==="execution_error"){let W=typeof b.error=="string"?b.error:b.error?.message??"Execution error";n({type:"error",error:new Error(W)})}else if($!=="ping"){if($==="approval_start"){let W=b.approvalId??`approval-${d()}`,B={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:W,status:"pending",agentId:ut?.agentId??"virtual",executionId:b.executionId??ut?.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(B)}else if($==="step_await"&&b.awaitReason==="approval_required"){let W=b.approvalId??`approval-${d()}`,B={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:W,status:"pending",agentId:ut?.agentId??"virtual",executionId:b.executionId??ut?.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(B)}else if($==="approval_complete"){let W=b.approvalId;if(W){let _={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:W,status:b.decision??"approved",agentId:ut?.agentId??"virtual",executionId:b.executionId??ut?.executionId??"",toolName:b.toolName??"",description:b.description??"",resolvedAt:Date.now()}};f(_)}}else if($==="artifact_start"||$==="artifact_delta"||$==="artifact_update"||$==="artifact_complete"){if($==="artifact_start"){let W=b.artifactType,B=String(b.id),_=typeof b.title=="string"?b.title:void 0,U=b.file,O;U&&typeof U=="object"&&!Array.isArray(U)&&typeof U.path=="string"&&typeof U.mimeType=="string"&&(O={path:U.path,mimeType:U.mimeType,...typeof U.language=="string"?{language:U.language}:{}}),n({type:"artifact_start",id:B,artifactType:W,title:_,component:typeof b.component=="string"?b.component:void 0,...O?{file:O}:{}});let J=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?{...b.props}:void 0;if(ve.set(B,{markdown:"",title:_,file:O,...J?{props:J}:{}}),!Ce.has(B)){Ce.add(B);let se=On(this.config.features?.artifacts,{artifactType:W,...O?{file:O}:{}}),Te=typeof b.component=="string"?b.component:void 0,ye={id:`artifact-ref-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:Na(se,{artifactId:B,title:_,artifactType:W,status:"streaming",...O?{file:O}:{},...Te?{component:Te}:{}})};he.set(B,ye),f(ye)}}else if($==="artifact_delta"){let W=String(b.id),B=typeof b.delta=="string"?b.delta:String(b.delta??"");n({type:"artifact_delta",id:W,artDelta:B});let _=ve.get(W);_&&(_.markdown+=B)}else if($==="artifact_update"){let W=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};n({type:"artifact_update",id:String(b.id),props:W,component:typeof b.component=="string"?b.component:void 0});let B=ve.get(String(b.id));B&&(B.props={...B.props??{},...W})}else if($==="artifact_complete"){let W=String(b.id);n({type:"artifact_complete",id:W});let B=he.get(W);if(B){B.streaming=!1;try{let _=JSON.parse(B.rawContent??"{}");if(_.props){_.props.status="complete";let U=ve.get(W);U?.markdown&&(_.props.markdown=U.markdown),U?.file&&(_.props.file=U.file),_.component==="PersonaArtifactInline"&&U?.props&&Object.keys(U.props).length>0&&(_.props.componentProps=U.props)}B.rawContent=JSON.stringify(_)}catch{}ve.delete(W),f(B),he.delete(W)}}}else if($==="transcript_insert"){let W=b.message;if(!W||typeof W!="object")continue;let B=String(W.id??`msg-${d()}`),_=W.role,O={id:B,role:_==="user"?"user":_==="system"?"system":"assistant",content:typeof W.content=="string"?W.content:"",rawContent:typeof W.rawContent=="string"?W.rawContent:void 0,createdAt:typeof W.createdAt=="string"?W.createdAt:new Date().toISOString(),streaming:W.streaming===!0,...typeof W.variant=="string"?{variant:W.variant}:{},sequence:d()};if(f(O),O.rawContent)try{let se=JSON.parse(O.rawContent)?.props?.artifactId;typeof se=="string"&&Ce.add(se)}catch{}h=null,k.current=null,ze.delete(B),Me.delete(B)}else if($==="error"){if(b.recoverable===!1&&b.error!=null&&b.error!==""){let W=typeof b.error=="string"?b.error:b.error?.message!=null?String(b.error.message):"Execution error";n({type:"error",error:new Error(W)});let B=h;B&&B.streaming&&(B.streaming=!1,f(B)),n({type:"status",status:"idle"})}}else if($==="step_error"||$==="dispatch_error"||$==="flow_error"){let W=null;if(b.error instanceof Error)W=b.error;else if($==="dispatch_error"){let B=b.message??b.error;B!=null&&B!==""&&(W=new Error(String(B)))}else{let B=b.error;typeof B=="string"&&B!==""?W=new Error(B):B!=null&&typeof B=="object"&&Reflect.has(B,"message")&&(W=new Error(String(B.message??B)))}if(W){n({type:"error",error:W});let B=h;B&&B.streaming&&(B.streaming=!1,f(B)),n({type:"status",status:"idle"})}}}}}ue.length=0};;){let{done:T,value:$}=await a.read();if(T)break;l+=s.decode($,{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()=>{}}},ds=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ii=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Wi=()=>{let e=Yv();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)}},Hi=()=>{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,lo.parse)(n,lo.STR|lo.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?ki(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=ki(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},$g=e=>{let t=null,n=0,r=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?ki(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?ki(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,lo.parse)(a,lo.STR|lo.OBJ),p=r(l);p!==null&&(t=p)}catch{}return n=a.length,{text:t||"",raw:a}},close:()=>{}}},Bi=()=>{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 jg="4.16.0";var xr=jg;var eC="https://api.runtype.com/v1/dispatch",Di="https://api.runtype.com";function tC(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 cd=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 nC(e){switch(e){case"json":return Hi;case"regex-json":return Wi;case"xml":return Bi;default:return Ii}}var Gg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function oC(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=Gg(n);if(!Gg(o))return e;if(!r||o===n||o.startsWith(n))return t;let s=ds(e);return ds(t)!==null&&s===null?t:e}var vr=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??eC,this.headers={"Content-Type":"application/json","X-Persona-Version":xr,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??nC(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 na(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=Tg(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$/,"")||Di}/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":xr},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$/,"")||Di}/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":xr},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(cd).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":xr},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 f=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:f}),f}if(l.status===429){let f=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:f}),f}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$/,"")||Di}/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?Sg(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=a&&l&&this.lastSentClientToolsFingerprint===s,d=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,f;for(let g=0;;g++){if(f=await o({...a&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),f.status===409&&g===0&&a&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,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(/\/+$/,"")||Di}/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=[...sa(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:f}=await this.sendWithClientToolsDiff(s,d,g=>{let m={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token resume",m),fetch(a,{method:"POST",headers:l,body:JSON.stringify(m),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&f(),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(cd).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=[...sa(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(cd).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=[...sa(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 f={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=f,r(f),f},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++,f=I=>{let B=I.reasoning?{...I.reasoning,chunks:[...I.reasoning.chunks]}:void 0,y=I.toolCall?{...I.toolCall,chunks:I.toolCall.chunks?[...I.toolCall.chunks]:void 0}:void 0,D=I.tools?I.tools.map(H=>({...H,chunks:H.chunks?[...H.chunks]:void 0})):void 0;return{...I,reasoning:B,toolCall:y,tools:D}},g=I=>{if(I.role!=="assistant"||I.variant)return!0;let B=Array.isArray(I.contentParts)&&I.contentParts.length>0,y=typeof I.rawContent=="string"&&I.rawContent.trim()!=="";return typeof I.content=="string"&&I.content.trim()!==""||B||y||!!I.stopReason},m=I=>{g(I)&&n({type:"message",message:f(I)})},b=null,w=null,T={current:null},L={current:null},A=null,S="",C=new Map,M=new Map,P=new Map,R=new Map,F=new Map,O={lastId:null,byStep:new Map},$={lastId:null,byCall:new Map},E=I=>{if(I==null)return null;try{return String(I)}catch{return null}},G=I=>E(I.stepId??I.step_id??I.step??I.parentId??I.flowStepId??I.flow_step_id),Q=I=>E(I.callId??I.call_id??I.requestId??I.request_id??I.toolCallId??I.tool_call_id??I.stepId??I.step_id),Z=o,J=!1,fe=()=>{if(b)return b;let I,B="",y=A;return!J&&Z?(I=Z,J=!0,B=r??""):Z&&y?I=`${Z}_${y}`:I=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:I,role:"assistant",content:B,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},m(b),b},ne=(I,B)=>{O.lastId=B,I&&O.byStep.set(I,B)},ge=(I,B)=>{let y=I.reasoningId??I.id,D=G(I);if(y){let N=String(y);return ne(D,N),N}if(D){let N=O.byStep.get(D);if(N)return O.lastId=N,N}if(O.lastId&&!B)return O.lastId;if(!B)return null;let H=`reason-${c()}`;return ne(D,H),H},ie=I=>{let B=R.get(I);if(B)return B;let y={id:`reason-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:I,status:"streaming",chunks:[]}};return R.set(I,y),m(y),y},ue=(I,B)=>{$.lastId=B,I&&$.byCall.set(I,B)},oe=new Set,me=new Map,Se=new Set,Ce=new Map,Be=I=>{if(!I)return!1;let B=I.replace(/_+/g,"_").replace(/^_|_$/g,"");return B==="emit_artifact_markdown"||B==="emit_artifact_component"},ut=(I,B)=>{let y=I.toolId??I.id,D=Q(I);if(y){let N=String(y);return ue(D,N),N}if(D){let N=$.byCall.get(D);if(N)return $.lastId=N,N}if($.lastId&&!B)return $.lastId;if(!B)return null;let H=`tool-${c()}`;return ue(D,H),H},Je=I=>{let B=F.get(I);if(B)return B;let y={id:`tool-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:I,status:"pending"}};return F.set(I,y),m(y),y},Qe=I=>{if(typeof I=="number"&&Number.isFinite(I))return I;if(typeof I=="string"){let B=Number(I);if(!Number.isNaN(B)&&Number.isFinite(B))return B;let y=Date.parse(I);if(!Number.isNaN(y))return y}return Date.now()},Ne=I=>{if(typeof I=="string")return I;if(I==null)return"";try{return JSON.stringify(I)}catch{return String(I)}},_e=new Map,Ae=new Map,Me=new Map,qe=(I,B,y)=>{let D=Me.get(I);D||(D=[],Me.set(I,D));let H=0,N=D.length;for(;H<N;){let V=H+N>>>1;D[V].seq<B?H=V+1:N=V}D[H]?.seq===B?D[H]={seq:B,text:y}:D.splice(H,0,{seq:B,text:y});let K="";for(let V=0;V<D.length;V++)K+=D[V].text;return K},Jt=(I,B)=>{let y=Ne(B),D=Ae.get(I.id),H=oC(D,y);I.rawContent=H;let N=_e.get(I.id),K=de=>{let Pe=I.content??"";de.trim()!==""&&(Pe.trim().length===0||de.startsWith(Pe)||de.trimStart().startsWith(Pe.trim()))&&(I.content=de)},V=()=>{if(N){let de=N.close?.();de instanceof Promise&&de.catch(()=>{})}_e.delete(I.id),Ae.delete(I.id),I.streaming=!1,m(I)};if(!N){K(y),V();return}let X=ds(H);if(X!==null&&X.trim()!==""){K(X),V();return}let ce=de=>{let Pe=typeof de=="string"?de:de?.text??null;if(Pe!==null&&Pe.trim()!=="")return Pe;let ze=N.getExtractedText();return ze!==null&&ze.trim()!==""?ze:y},Ve;try{Ve=N.processChunk(H)}catch{K(y),V();return}if(Ve instanceof Promise){Ve.then(de=>{K(ce(de)),V()}).catch(()=>{K(y),V()});return}K(ce(Ve)),V()},gt=null,Bt=(I,B,y,D)=>{I.rawContent=B,_e.has(I.id)||_e.set(I.id,this.createStreamParser());let H=_e.get(I.id),N=B.trim().startsWith("{")||B.trim().startsWith("[");if(N&&Ae.set(I.id,B),H.__isPlainTextParser===!0){I.content=D!==void 0?B:I.content+y,Ae.delete(I.id),_e.delete(I.id),I.rawContent=void 0,m(I);return}let V=H.processChunk(B);if(V instanceof Promise)V.then(X=>{let ce=typeof X=="string"?X:X?.text??null;ce!==null&&ce.trim()!==""?(I.content=ce,m(I)):!N&&!B.trim().startsWith("<")&&(I.content=D!==void 0?B:I.content+y,Ae.delete(I.id),_e.delete(I.id),I.rawContent=void 0,m(I))}).catch(()=>{I.content=D!==void 0?B:I.content+y,Ae.delete(I.id),_e.delete(I.id),I.rawContent=void 0,m(I)});else{let X=typeof V=="string"?V:V?.text??null;X!==null&&X.trim()!==""?(I.content=X,m(I)):!N&&!B.trim().startsWith("<")&&(I.content=D!==void 0?B:I.content+y,Ae.delete(I.id),_e.delete(I.id),I.rawContent=void 0,m(I))}},Tn=(I,B)=>{let y=B??I.content;if(y==null||y===""){I.streaming=!1,m(I);return}let H=Ae.get(I.id)??Ne(y);I.rawContent=H;let N=_e.get(I.id),K=null,V=!1;if(N&&(K=N.getExtractedText(),K===null&&(K=ds(H)),K===null)){let X=N.processChunk(H);X instanceof Promise?(V=!0,X.then(ce=>{let Ve=typeof ce=="string"?ce:ce?.text??null;Ve!==null&&(I.content=Ve,I.streaming=!1,_e.delete(I.id),Ae.delete(I.id),m(I))}).catch(()=>{})):K=typeof X=="string"?X:X?.text??null}if(!V){K!==null&&K.trim()!==""?I.content=K:Ae.has(I.id)||(I.content=Ne(y));let X=_e.get(I.id);if(X){let ce=X.close?.();ce instanceof Promise&&ce.catch(()=>{}),_e.delete(I.id)}Ae.delete(I.id),I.streaming=!1,m(I)}},En=(I,B,y)=>{let D=M.get(I);if(D)return D;let H={id:`nested-${B}-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...y?{variant:y}:{},...y==="reasoning"?{reasoning:{id:I,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:B}};return M.set(I,H),m(H),H},et=[],Le,he=new Map,tt=0,Te="agent",be=!1,re=null,xe=null,kn=new Map,ee=this.config.iterationDisplay??"separate";for(Le=()=>{for(let I=0;I<et.length;I++){let B=et[I].payloadType,y=et[I].payload;if(!be&&Te!=="flow"&&typeof y.stepType=="string"&&(Te="flow"),B==="reasoning_start"){let D=typeof y.id=="string"?y.id:null,H=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(D&&H){C.set(D,H),En(D,H,"reasoning");continue}let N=ge(y,!0)??`reason-${c()}`,K=ie(N);K.reasoning=K.reasoning??{id:N,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Qe(y.startedAt??y.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(y.scope==="loop"||y.scope==="turn")&&(K.reasoning.scope=y.scope),K.streaming=!0,K.reasoning.status="streaming",m(K)}else if(B==="reasoning_delta"){let D=typeof y.id=="string"?y.id:null;if(D&&C.has(D)&&M.has(D)){let V=M.get(D),X=y.reasoningText??y.text??y.delta??"";X&&y.hidden!==!0&&V.reasoning&&(V.reasoning.chunks.push(String(X)),m(V));continue}let H=ge(y,!1)??ge(y,!0)??`reason-${c()}`,N=ie(H);N.reasoning=N.reasoning??{id:H,status:"streaming",chunks:[]},N.reasoning.startedAt=N.reasoning.startedAt??Qe(y.startedAt??y.timestamp);let K=y.reasoningText??y.text??y.delta??"";if(K&&y.hidden!==!0){let V=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(V!==void 0){let X=qe(H,V,String(K));N.reasoning.chunks=[X]}else N.reasoning.chunks.push(String(K))}if(N.reasoning.status=y.done?"complete":"streaming",y.done){N.reasoning.completedAt=Qe(y.completedAt??y.timestamp);let V=N.reasoning.startedAt??Date.now();N.reasoning.durationMs=Math.max(0,(N.reasoning.completedAt??Date.now())-V)}N.streaming=N.reasoning.status!=="complete",m(N)}else if(B==="reasoning_complete"){let D=typeof y.id=="string"?y.id:null;if(D&&C.has(D)&&M.has(D)){let X=M.get(D);if(X.reasoning){let ce=typeof y.text=="string"?y.text:"";ce&&X.reasoning.chunks.length===0&&X.reasoning.chunks.push(ce),X.reasoning.status="complete",X.streaming=!1,m(X)}C.delete(D),M.delete(D);continue}let H=ge(y,!1)??ge(y,!0)??`reason-${c()}`,N=typeof y.text=="string"?y.text:"";!R.get(H)&&(N||y.scope==="loop")&&ie(H);let K=R.get(H);if(K?.reasoning){(y.scope==="loop"||y.scope==="turn")&&(K.reasoning.scope=y.scope),N&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(N),K.reasoning.status="complete",K.reasoning.completedAt=Qe(y.completedAt??y.timestamp);let X=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-X),K.streaming=!1,m(K)}let V=G(y);V&&O.byStep.delete(V)}else if(B==="tool_start"){b&&(b.streaming=!1,m(b),b=null),typeof y.iteration=="number"&&(tt=y.iteration);let D=(typeof y.toolCallId=="string"?y.toolCallId:void 0)??ut(y,!0)??`tool-${c()}`,H=y.toolName??y.name;if(Be(H)){oe.add(D);continue}ue(Q(y),D);let N=Je(D),K=N.toolCall??{id:D,status:"pending"};K.name=H??K.name,K.status="running",y.parameters!==void 0?K.args=y.parameters:y.args!==void 0&&(K.args=y.args),K.startedAt=K.startedAt??Qe(y.startedAt??y.timestamp),K.completedAt=void 0,K.durationMs=void 0,N.toolCall=K,N.streaming=!0,y.executionId&&(N.agentMetadata={executionId:y.executionId,iteration:y.iteration}),m(N)}else if(B==="tool_output_delta"){let D=ut(y,!1)??ut(y,!0)??`tool-${c()}`;if(oe.has(D))continue;let H=Je(D),N=H.toolCall??{id:D,status:"running"};N.startedAt=N.startedAt??Qe(y.startedAt??y.timestamp);let K=y.text??y.delta??y.message??"";K&&(N.chunks=N.chunks??[],N.chunks.push(String(K))),N.status="running",H.toolCall=N,H.streaming=!0;let V=y.agentContext;(V||y.executionId)&&(H.agentMetadata=H.agentMetadata??{executionId:V?.executionId??y.executionId,iteration:V?.iteration??y.iteration}),m(H)}else if(B==="tool_complete"){let D=ut(y,!1)??ut(y,!0)??`tool-${c()}`;if(oe.has(D)){oe.delete(D);continue}let H=Je(D),N=H.toolCall??{id:D,status:"running"};N.status="complete",y.result!==void 0&&(N.result=y.result),typeof y.duration=="number"&&(N.duration=y.duration),N.completedAt=Qe(y.completedAt??y.timestamp);let K=y.duration??y.executionTime;if(typeof K=="number")N.durationMs=K;else{let ce=N.startedAt??Date.now();N.durationMs=Math.max(0,(N.completedAt??Date.now())-ce)}H.toolCall=N,H.streaming=!1;let V=y.agentContext;(V||y.executionId)&&(H.agentMetadata=H.agentMetadata??{executionId:V?.executionId??y.executionId,iteration:V?.iteration??y.iteration}),m(H);let X=Q(y);X&&$.byCall.delete(X)}else if(B==="await"&&y.toolName){let D=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:void 0,H=D??y.toolId??`local-${c()}`,N=Je(H),K=y.toolName,V=y.origin==="webmcp"&&!Lo(K)?`webmcp:${K}`:K,X=Lo(V),ce=N.toolCall??{id:H,status:"pending"};ce.name=V,ce.args=y.parameters,ce.status=X?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??Qe(y.startedAt??y.timestamp??y.awaitedAt),X?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,N.toolCall=ce,N.streaming=!1,N.agentMetadata={...N.agentMetadata,executionId:y.executionId??N.agentMetadata?.executionId,awaitingLocalTool:!0,...D?{webMcpToolCallId:D}:{}},m(N)}else if(B==="text_start"){let D=typeof y.id=="string"?y.id:null,H=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(D&&H){C.set(D,H);continue}let N=b;N&&(Te==="flow"?(Tn(N),gt=N):(N.streaming=!1,m(N)),b=null),A=typeof y.id=="string"?y.id:A,S=""}else if(B==="text_delta"){let D=typeof y.id=="string"?y.id:null,H=D?C.get(D):void 0;if(D&&H){let K=typeof y.delta=="string"?y.delta:"",V=(P.get(D)??"")+K;if(P.set(D,V),V.trim()==="")continue;let X=En(D,H);X.agentMetadata={...X.agentMetadata,executionId:y.executionId,parentToolId:H},Bt(X,V,K,void 0);continue}if(A=typeof y.id=="string"?y.id:A,Te==="flow"){let K=typeof y.delta=="string"?y.delta:"";if(S+=K,S.trim()==="")continue;let V=fe();V.agentMetadata={executionId:y.executionId,iteration:y.iteration},Bt(V,S,K,void 0),w=V;continue}let N=fe();N.content+=y.delta??"",N.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:re??void 0,agentName:xe?.agentName},w=N,m(N)}else if(B==="text_complete"){let D=typeof y.id=="string"?y.id:null;if(D&&C.has(D)){let N=M.get(D);N&&Tn(N),C.delete(D),P.delete(D),M.delete(D);continue}let H=b;H&&(Te==="flow"?(Tn(H),gt=H):((H.content??"")===""&&typeof y.text=="string"&&(H.content=y.text),H.streaming=!1,m(H)),b=null),A=null,S=""}else if(B==="step_complete"){let D=y.stepType,H=y.executionType;if(D==="tool"||H==="context")continue;if(y.success===!1){let N=y.error,K=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(K)});let V=b;V&&V.streaming&&(V.streaming=!1,m(V)),n({type:"status",status:"idle"});continue}{let N=gt;gt=null;let K=y.stopReason,V=y.result?.response;if(N)K&&(N.stopReason=K),V!=null?Jt(N,V):N.streaming!==!1&&(_e.delete(N.id),Ae.delete(N.id),N.streaming=!1,m(N));else{let X=V!=null&&V!=="";if(X||K){let ce=fe();K&&(ce.stopReason=K),X?Tn(ce,V):(ce.streaming=!1,m(ce))}}continue}}else if(B==="execution_start")Te=y.kind==="flow"?"flow":"agent",be=!0,Te==="agent"&&(xe={executionId:y.executionId,agentId:y.agentId??"virtual",agentName:y.agentName??"",status:"running",currentIteration:0,maxTurns:y.maxTurns??1,startedAt:Qe(y.startedAt)});else if(B==="turn_start"){let D=typeof y.iteration=="number"?y.iteration:tt;if(D!==tt){if(xe&&(xe.currentIteration=D),ee==="separate"&&D>1){let H=b;H&&(H.streaming=!1,m(H),kn.set(D-1,H),b=null)}tt=D}re=typeof y.id=="string"?y.id:null,w=null}else if(B==="tool_input_delta"){let D=y.toolCallId??$.lastId;if(D){let H=F.get(D);H?.toolCall&&(H.toolCall.chunks=H.toolCall.chunks??[],H.toolCall.chunks.push(y.delta??""),m(H))}}else{if(B==="tool_input_complete")continue;if(B==="turn_complete"){let D=y.stopReason,H=b??w;if(D&&H!==null){let N=y.id;(!N||H.agentMetadata?.turnId===N)&&(H.stopReason=D,m(H))}re===y.id&&(re=null)}else if(B==="media_start"){let D=String(y.id);he.set(D,{mediaType:typeof y.mediaType=="string"?y.mediaType:void 0,role:typeof y.role=="string"?y.role:void 0,toolCallId:y.toolCallId,parts:[]})}else if(B==="media_delta"){let D=he.get(String(y.id));D&&typeof y.delta=="string"&&D.parts.push(y.delta)}else if(B==="media_complete"){let D=String(y.id),H=he.get(D);he.delete(D);let N=(typeof y.mediaType=="string"?y.mediaType:void 0)??H?.mediaType??"application/octet-stream",K=typeof y.data=="string"?y.data:void 0,V=typeof y.url=="string"?y.url:H&&H.parts.length>0?H.parts.join(""):void 0,X=null;if(K)X={type:"media",data:K,mediaType:N};else if(V){let Pe=N.toLowerCase();X={type:Pe==="image"||Pe.startsWith("image/")?"image-url":"file-url",url:V,mediaType:N}}let ce=y.toolCallId??H?.toolCallId,Ve=X?[X]:[],de=[];for(let Pe of Ve){if(!Pe||typeof Pe!="object")continue;let ze=Pe,Ue=typeof ze.type=="string"?ze.type:void 0,We=typeof ze.mediaType=="string"?ze.mediaType.toLowerCase():"",we=null,nt="";if(Ue==="media"){let wt=typeof ze.data=="string"?ze.data:void 0;if(!wt)continue;nt=We.length>0?We:"application/octet-stream",we=`data:${nt};base64,${wt}`}else if(Ue==="image-url"){let wt=typeof ze.url=="string"?ze.url:void 0;if(!wt)continue;nt=We,we=wt}else if(Ue==="file-url"){let wt=typeof ze.url=="string"?ze.url:void 0;if(!wt)continue;nt=We,we=wt}else continue;if(we)if(Ue==="image-url"||nt.startsWith("image/"))de.push({type:"image",image:we,...nt.includes("/")?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))de.push({type:"audio",audio:we,mimeType:nt});else if(nt.startsWith("video/"))de.push({type:"video",video:we,mimeType:nt});else{let wt=nt||"application/octet-stream";de.push({type:"file",data:we,mimeType:wt,filename:tC(wt)})}}if(de.length>0){let Pe=c(),ze=ce,We={id:`agent-media-${typeof ze=="string"&&ze.length>0?`${ze}-${Pe}`:String(Pe)}`,role:"assistant",content:"",contentParts:de,createdAt:new Date().toISOString(),streaming:!1,sequence:Pe,agentMetadata:{executionId:y.executionId,iteration:typeof y.iteration=="number"?y.iteration:tt}};m(We);let we=b;we&&(we.streaming=!1,m(we)),b=null,T.current=null}}else if(B==="execution_complete"){let D=y.kind??Te;D==="agent"&&xe&&(xe.status=y.success?"complete":"error",xe.completedAt=Qe(y.completedAt),xe.stopReason=y.stopReason);let H=b;H&&(D==="flow"&&H.streaming!==!1?Tn(H):(H.streaming=!1,m(H)),b=null),A=null,S="",gt=null,n({type:"status",status:"idle",terminal:!0})}else if(B==="execution_error"){let D=typeof y.error=="string"?y.error:y.error?.message??"Execution error";n({type:"error",error:new Error(D)})}else if(B!=="ping"){if(B==="approval_start"){let D=y.approvalId??`approval-${c()}`,H={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:"pending",agentId:xe?.agentId??"virtual",executionId:y.executionId??xe?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};m(H)}else if(B==="step_await"&&y.awaitReason==="approval_required"){let D=y.approvalId??`approval-${c()}`,H={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:"pending",agentId:xe?.agentId??"virtual",executionId:y.executionId??xe?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};m(H)}else if(B==="approval_complete"){let D=y.approvalId;if(D){let N={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:y.decision??"approved",agentId:xe?.agentId??"virtual",executionId:y.executionId??xe?.executionId??"",toolName:y.toolName??"",description:y.description??"",resolvedAt:Date.now()}};m(N)}}else if(B==="artifact_start"||B==="artifact_delta"||B==="artifact_update"||B==="artifact_complete"){if(B==="artifact_start"){let D=y.artifactType,H=String(y.id),N=typeof y.title=="string"?y.title:void 0,K=y.file,V;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(V={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:H,artifactType:D,title:N,component:typeof y.component=="string"?y.component:void 0,...V?{file:V}:{}});let X=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?{...y.props}:void 0;if(Ce.set(H,{markdown:"",title:N,file:V,...X?{props:X}:{}}),!Se.has(H)){Se.add(H);let ce=zn(this.config.features?.artifacts,{artifactType:D,...V?{file:V}:{}}),Ve=typeof y.component=="string"?y.component:void 0,de={id:`artifact-ref-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:rs(ce,{artifactId:H,title:N,artifactType:D,status:"streaming",...V?{file:V}:{},...Ve?{component:Ve}:{}})};me.set(H,de),m(de)}}else if(B==="artifact_delta"){let D=String(y.id),H=typeof y.delta=="string"?y.delta:String(y.delta??"");n({type:"artifact_delta",id:D,artDelta:H});let N=Ce.get(D);N&&(N.markdown+=H)}else if(B==="artifact_update"){let D=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};n({type:"artifact_update",id:String(y.id),props:D,component:typeof y.component=="string"?y.component:void 0});let H=Ce.get(String(y.id));H&&(H.props={...H.props??{},...D})}else if(B==="artifact_complete"){let D=String(y.id);n({type:"artifact_complete",id:D});let H=me.get(D);if(H){H.streaming=!1;try{let N=JSON.parse(H.rawContent??"{}");if(N.props){N.props.status="complete";let K=Ce.get(D);K?.markdown&&(N.props.markdown=K.markdown),K?.file&&(N.props.file=K.file),N.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(N.props.componentProps=K.props)}H.rawContent=JSON.stringify(N)}catch{}Ce.delete(D),m(H),me.delete(D)}}}else if(B==="transcript_insert"){let D=y.message;if(!D||typeof D!="object")continue;let H=String(D.id??`msg-${c()}`),N=D.role,V={id:H,role:N==="user"?"user":N==="system"?"system":"assistant",content:typeof D.content=="string"?D.content:"",rawContent:typeof D.rawContent=="string"?D.rawContent:void 0,createdAt:typeof D.createdAt=="string"?D.createdAt:new Date().toISOString(),streaming:D.streaming===!0,...typeof D.variant=="string"?{variant:D.variant}:{},sequence:c()};if(m(V),V.rawContent)try{let ce=JSON.parse(V.rawContent)?.props?.artifactId;typeof ce=="string"&&Se.add(ce)}catch{}b=null,T.current=null,_e.delete(H),Ae.delete(H)}else if(B==="error"){if(y.recoverable===!1&&y.error!=null&&y.error!==""){let D=typeof y.error=="string"?y.error:y.error?.message!=null?String(y.error.message):"Execution error";n({type:"error",error:new Error(D)});let H=b;H&&H.streaming&&(H.streaming=!1,m(H)),n({type:"status",status:"idle"})}}else if(B==="step_error"||B==="dispatch_error"||B==="flow_error"){let D=null;if(y.error instanceof Error)D=y.error;else if(B==="dispatch_error"){let H=y.message??y.error;H!=null&&H!==""&&(D=new Error(String(H)))}else{let H=y.error;typeof H=="string"&&H!==""?D=new Error(H):H!=null&&typeof H=="object"&&Reflect.has(H,"message")&&(D=new Error(String(H.message??H)))}if(D){n({type:"error",error:D});let H=b;H&&H.streaming&&(H.streaming=!1,m(H)),n({type:"status",status:"idle"})}}}}}et.length=0};;){let{done:I,value:B}=await a.read();if(I)break;l+=s.decode(B,{stream:!0});let y=l.split(`
|
|
13
13
|
|
|
14
|
-
`);l=
|
|
15
|
-
`),_="message",U="",O=null;for(let ye of B)ye.startsWith("event:")?_=ye.replace("event:","").trim():ye.startsWith("data:")?U+=ye.replace("data:","").trim():ye.startsWith("id:")&&(O=ye.slice(3).trim());let J=()=>{O!==null&&O!==""&&n({type:"cursor",id:O})};if(!U){J();continue}let se;try{se=JSON.parse(U)}catch(ye){n({type:"error",error:ye instanceof Error?ye:new Error("Failed to parse chat stream payload")});continue}let Te=_!=="message"?_:se.type??"message";if(this.onSSEEvent?.(Te,se),this.parseSSEEvent){k.current=h;let ye=await this.handleCustomSSEEvent(se,n,k,f,d,P);if(k.current&&k.current!==h&&(h=k.current),ye){J();continue}}ue.push({payloadType:Te,payload:se}),Qe(),J()}}Qe()}};function Xm(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function _r(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ko(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var bi="[Image]";function Jm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Qm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function xi(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Ym(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Lo(e){return{type:"text",text:e}}function Zm(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function eg(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 tg(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 ng=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ux=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],to=[...ng,...Ux];function qx(e){return ng.includes(e)||e.startsWith("image/")}function vi(e){return qx(e.type)}async function og(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;vi(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 rg(e,t=to,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Vx(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function ag(e,t){let n=Vx(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Ci=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 sg=16e3,zx=24e3,$x=4096,jx=1380533830;function Gx(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===jx?new Uint8Array(e,44):new Uint8Array(e)}function Kx(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var ja=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:sg,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:sg});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ci(zx);if(r!==this.callGeneration){p.destroy(),a.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let c=`${Kx(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($x,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=Gx(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var sr=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 Po(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ja(e.runtype);case"browser":if(!sr.isSupported())throw new Error("Browser speech recognition not supported");return new sr(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 wi(e){if(e?.type==="custom"&&e.custom)return Po({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Po({type:"runtype",runtype:e.runtype});if(sr.isSupported())return Po({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ga(e){try{return wi(e),!0}catch{return!1}}function Ur(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 Ro=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):Ur(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 ir=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 Ed(e){if(!e)return"";let t=Xx(e);return ig(t!==null?t:e)}function Xx(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function ig(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=y.pop()??"";for(let D of y){let H=D.split(`
|
|
15
|
+
`),N="message",K="",V=null;for(let de of H)de.startsWith("event:")?N=de.replace("event:","").trim():de.startsWith("data:")?K+=de.replace("data:","").trim():de.startsWith("id:")&&(V=de.slice(3).trim());let X=()=>{V!==null&&V!==""&&n({type:"cursor",id:V})};if(!K){X();continue}let ce;try{ce=JSON.parse(K)}catch(de){n({type:"error",error:de instanceof Error?de:new Error("Failed to parse chat stream payload")});continue}let Ve=N!=="message"?N:ce.type??"message";if(this.onSSEEvent?.(Ve,ce),this.parseSSEEvent){T.current=b;let de=await this.handleCustomSSEEvent(ce,n,T,m,c,L);if(T.current&&T.current!==b&&(b=T.current),de){X();continue}}et.push({payloadType:Ve,payload:ce}),Le(),X()}}Le()}};function Kg(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ia(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Fo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Fi="[Image]";function Xg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Jg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Oi(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Qg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Oo(e){return{type:"text",text:e}}function Yg(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Zg(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 eh(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 th=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],rC=["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"],co=[...th,...rC];function aC(e){return th.includes(e)||e.startsWith("image/")}function Ni(e){return aC(e.type)}async function nh(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ni(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 oh(e,t=co,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 sC(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function rh(e,t){let n=sC(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 _i=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 ah=16e3,iC=24e3,lC=4096,cC=1380533830;function dC(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===cC?new Uint8Array(e,44):new Uint8Array(e)}function pC(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 ps=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:ah,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){a.getTracks().forEach(f=>f.stop());return}this.mediaStream=a;let s=window.AudioContext||window.webkitAudioContext,l=new s({sampleRate:ah});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new _i(iC);if(r!==this.callGeneration){p.destroy(),a.getTracks().forEach(f=>f.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=`${pC(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=f=>this.handleMessage(f,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=f=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(f.code!==1e3){let g=f.code?` (code ${f.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(lC,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 f=Math.max(-1,Math.min(1,p[c]));d[c]=f<0?f*32768:f*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=dC(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 Cr=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 No(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ps(e.runtype);case"browser":if(!Cr.isSupported())throw new Error("Browser speech recognition not supported");return new Cr(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 Ui(e){if(e?.type==="custom"&&e.custom)return No({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return No({type:"runtype",runtype:e.runtype});if(Cr.isSupported())return No({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function us(e){try{return Ui(e),!0}catch{return!1}}function la(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 _o=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):la(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 wr=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 dd(e){if(!e)return"";let t=uC(e);return sh(t!==null?t:e)}function uC(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 sh(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 pd=null,ih=e=>{pd=e},ud=()=>pd?pd():import("./runtype-tts-entry");var gC=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function hC(e,t){return gC.some(n=>e[n]!==t[n])}function fd(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 Ka=e=>({isError:!0,content:[{type:"text",text:e}]}),pg=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ug=e=>vo(e)||e===Pn,qr=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 ir(()=>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&&(vo(n.name)||n.name===Pn&&To(this.config).enabled);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 ar(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Ld().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Ga(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=Ro.isSupported()?new Ro({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,a=this.config.clientToken,s=t.browserFallback!==!1;if(o&&r&&a)return Ld().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let c=new l({host:o,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return s&&n?new p(c,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):c});if(s&&n)return a&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Po(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(!Zx(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 ar(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"?_r():n==="assistant"?ko():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:c,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...d!==void 0&&{voiceProcessing:d},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:a,llmContent:s,contentParts:l,id:p,createdAt:c,sequence:d,streaming:u=!1,voiceProcessing:g,rawContent:f}=o,S={id:p??(r==="user"?_r():r==="assistant"?ko():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:c??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...l!==void 0&&{contentParts:l},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(S)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:a,id:s,createdAt:l,sequence:p}=t,c={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(c),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let a=r.blocks.join(`
|
|
19
|
+
_Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]}),dh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ph=e=>Lo(e)||e===On,ca=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 wr(()=>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&&(Lo(n.name)||n.name===On&&Bo(this.config).enabled);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 vr(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||ud().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 us(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=_o.isSupported()?new _o({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 ud().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=No(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(!hC(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 vr(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:d=!1,voiceProcessing:c,rawContent:f}=t,m={id:s??(n==="user"?ia():n==="assistant"?Fo():`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},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}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:f=!1,voiceProcessing:g,rawContent:m}=o,w={id:p??(r==="user"?ia():r==="assistant"?Fo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:f,...s!==void 0&&{llmContent:s},...l!==void 0&&{contentParts:l},...g!==void 0&&{voiceProcessing:g},...m!==void 0&&{rawContent:m}};n.push(w)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:a,id:s,createdAt:l,sequence:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let a=r.blocks.join(`
|
|
20
20
|
|
|
21
21
|
`),s=[a,n].filter(Boolean).join(`
|
|
22
22
|
|
|
23
|
-
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(l){let c=[];a&&c.push(Lo(a)),c.push(...r.contentParts),c.push(...t.contentParts),t.contentParts=c}else if(p){let c=[];s&&c.push(Lo(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=_r(),a=ko();this.activeAssistantMessageId=null;let s=n?.contentParts&&xi(n.contentParts)?bi:"",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=Pd(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=ko();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=Pd(r,this.config.errorMessage);if(s){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:s,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,a||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let a of this.messages)a.streaming&&a.id!==o&&(a.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(a){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(a instanceof Error?a:new Error(String(a)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(a=>a.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,a={...t,status:n,resolvedAt:Date.now()},s=this.messages.find(d=>d.id===r),l={id:r,role:"assistant",content:"",createdAt:s?.createdAt??new Date().toISOString(),...s?.sequence!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,c=p&&typeof p=="object"?p.onDecision:void 0;try{let d;if(c?d=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):d=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),d){let u=null;if(d instanceof Response){if(!d.ok){let g=await d.json().catch(()=>null);throw new Error(g?.error??`Approval request failed: ${d.status}`)}u=d.body}else d instanceof ReadableStream&&(u=d);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(d=>d.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,a=t.toolCall?.name;if(!r||!a){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof n=="string"?void 0:n;if(s===void 0&&typeof n=="string"){let d=t.toolCall?.args,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===1){let g=typeof u[0]?.question=="string"?u[0].question:"";g&&(s={[g]:n})}}this.markAskUserQuestionResolved(t,s),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,p=t.toolCall?.args,c=Array.isArray(p?.questions)?p.questions:[];if(c.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([u,g])=>`${u}: ${Array.isArray(g)?g.join(", "):g}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let d=s??{};c.forEach((u,g)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let h=d[f],S=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";this.appendMessage({id:`ask-user-q-${l}-${g}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${g}`,role:"user",content:S||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let d=await this.client.resumeFlow(r,{[a]:n});if(!d.ok){let u=await d.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${d.status}`)}d.body?await this.connectStream(d.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let a=this.webMcpEpoch;queueMicrotask(()=>{a===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Pn?!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===Pn)return{dedupeKey:u,resumeKey:f,output:Cd(),toolMessage:p,startedAt:g,completedAt:Date.now()};let h=new AbortController;this.webMcpResolveControllers.add(h),r.push(h);let S=this.client.executeWebMcpToolCall(c,p.toolCall?.args,h.signal),k;if(!S)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await S}catch(P){let M=P instanceof Error&&(P.name==="AbortError"||P.message.includes("aborted")||P.message.includes("abort"));return M||this.callbacks.onError?.(P instanceof Error?P:new Error(String(P))),this.markWebMcpToolComplete(p,Ka(M?"Aborted by cancel()":pg(P)),g),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,Ka("Aborted by cancel()"),g),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:k,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===Pn?{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,Ka("Aborted by cancel()"),d.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let h=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h))return;this.webMcpInflightKeys.add(h);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(h)}catch(S){this.callbacks.onError?.(S instanceof Error?S:new Error(String(S)))}finally{this.webMcpInflightKeys.delete(h)}return}let a=`${n}:${r}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let c=o===Pn,d=t.toolCall?.args,u=c?null:this.client.executeWebMcpToolCall(o,d,p),g="execute",f=s;try{let h;if(c?h=Cd():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,Ka("Aborted by cancel()"),s);return}let S=t.agentMetadata?.webMcpToolCallId??o;g="resume",await this.resumeWithToolOutput(n,S,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,h,s,f,c?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(h){let S=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));(g==="execute"||S||p.aborted)&&this.markWebMcpToolComplete(t,Ka(S||p.aborted?"Aborted by cancel()":pg(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}:{},...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=On(this.config.features?.artifacts,t),r=Na(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=On(this.config.features?.artifacts,n),a=Na(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(()=>(cg(),dg)).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=>Pd(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=ko(),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=Ed(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ur(t)}toggleReadAloud(t){let n=this.messages.find(a=>a.id===t);if(!n||n.role!=="assistant")return;let o=Ed(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&&ug(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&&ug(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 Rd=[["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 Id=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Wd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Hd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var Bd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Dd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Fd=[["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 Od=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var Nd=[["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 _d=[["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 Ud=[["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 qd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var Vd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var zd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var $d=[["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 Ai=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16"}],["path",{d:"M18 17V9"}],["path",{d:"M13 17V5"}],["path",{d:"M8 17v-3"}]];var jd=[["path",{d:"M20 6 9 17l-5-5"}]];var Gd=[["path",{d:"m6 9 6 6 6-6"}]];var Kd=[["path",{d:"m15 18-6-6 6-6"}]];var Xd=[["path",{d:"m9 18 6-6-6-6"}]];var Jd=[["path",{d:"m18 15-6-6-6 6"}]];var Si=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var Mi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var Qd=[["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 Yd=[["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 Zd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var Ti=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var ec=[["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 tc=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var nc=[["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 oc=[["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 Ei=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var ki=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var rc=[["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 ac=[["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 sc=[["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 ic=[["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 lc=[["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 dc=[["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 cc=[["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 pc=[["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 uc=[["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 fc=[["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 mc=[["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 gc=[["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 Li=[["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 hc=[["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 yc=[["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 bc=[["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 xc=[["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 vc=[["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 Cc=[["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 Pi=[["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 wc=[["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 Ac=[["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 Sc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Mc=[["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 Tc=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"}],["path",{d:"M9 18h6"}],["path",{d:"M10 22h4"}]];var Ec=[["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 Ri=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var kc=[["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 Pc=[["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 Rc=[["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 Ic=[["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 Wc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Hc=[["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 Bc=[["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 Dc=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Fc=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Oc=[["path",{d:"M5 12h14"}]];var Nc=[["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 _c=[["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 Uc=[["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 qc=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Vc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var Ii=[["path",{d:"M13 21h8"}],["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"}]];var zc=[["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 $c=[["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 jc=[["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 Gc=[["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 Kc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Xc=[["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 Jc=[["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 Qc=[["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 Yc=[["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 Zc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var ep=[["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 tp=[["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 np=[["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 op=[["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 rp=[["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 Wi=[["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 ap=[["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 sp=[["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 ip=[["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 lp=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Hi=[["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 dp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var cp=[["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 pp=[["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 up=[["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 fp=[["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 mp=[["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 gp=[["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 hp=[["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 yp=[["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 bp=[["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 Bi=[["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 xp=[["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 vp=[["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 Cp=[["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 wp=[["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 Ap=[["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 Sp=[["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 Mp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Tp=[["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 ev={activity:Rd,"arrow-down":Id,"arrow-up":Dd,"arrow-up-right":Bd,bot:Ud,"chevron-down":Gd,"chevron-up":Jd,"chevron-right":Xd,"chevron-left":Kd,check:jd,clipboard:Yd,"clipboard-copy":Qd,"code-xml":Ti,copy:ec,file:cc,"file-code":ic,"file-spreadsheet":lc,"file-text":dc,"image-plus":wc,loader:kc,"loader-circle":Ri,mic:Dc,paperclip:qc,"refresh-cw":Jc,search:Zc,send:ep,"shield-alert":op,"shield-check":rp,"shield-x":Wi,square:dp,"thumbs-down":mp,"thumbs-up":gp,upload:vp,"volume-2":wp,x:Mp,user:Cp,mail:Pc,phone:jc,calendar:zd,clock:Zd,building:qd,"map-pin":Rc,lock:Lc,key:Mc,"credit-card":tc,"at-sign":Fd,hash:bc,globe:yc,link:Ec,"circle-check":Si,"circle-x":Mi,"triangle-alert":Bi,info:Sc,ban:Od,shield:ap,"arrow-left":Wd,"arrow-right":Hd,"external-link":ac,ellipsis:ki,"ellipsis-vertical":Ei,menu:Wc,house:Pi,plus:Kc,minus:Oc,pencil:zc,"pen-line":Ii,trash:bp,"trash-2":yp,save:Yc,download:oc,share:np,funnel:Li,settings:tp,"rotate-cw":Qc,maximize:Ic,minimize:Fc,"shopping-cart":ip,"shopping-bag":sp,package:Uc,truck:xp,tag:fp,gift:hc,receipt:Xc,wallet:Sp,store:pp,"dollar-sign":nc,percent:$c,play:Gc,pause:Vc,"volume-x":Ap,camera:$d,image:Ac,film:uc,headphones:xc,"message-circle":Hc,"message-square":Bc,bell:Nd,heart:vc,star:cp,eye:sc,"eye-off":rc,bookmark:_d,"calendar-days":Vd,history:Cc,timer:hp,folder:gc,"folder-open":mc,files:pc,"chart-column":Ai,sparkles:Hi,zap:Tp,sun:up,moon:_c,flag:fc,lightbulb:Tc,monitor:Nc,smartphone:lp},ae=(e,t=24,n="currentColor",o=2)=>{let r=ev[e];return r?tv(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 tv(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 Di={allowedTypes:to,maxFileSize:10*1024*1024,maxFiles:4};function nv(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ov(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 lr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Di.allowedTypes,maxFileSize:t.maxFileSize??Di.maxFileSize,maxFiles:t.maxFiles??Di.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:Di.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=rg(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 og(n),a=vi(n)?URL.createObjectURL(n):null,s={id:nv(),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=vi(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=ov(t.file.type),p=ae(l,20,"var(--persona-muted, #6b7280)",1.5);p&&s.appendChild(p);let c=x("span");c.textContent=ag(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=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=ae("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 fg=/\s/;function rv(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(C.trigger):!1),a=(A,C)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:C}))}catch{}},s=Ie("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,c=e.textarea,d=null,u=null,g=null,f=null,h=()=>{if(l)return Promise.resolve(l);if(p)return p;let A=Pp().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===A&&(p=null),null));return p=A,A},S=()=>{Cg().then(A=>{let C=A.mountInlineComposer({textarea:e.textarea,renderToken:R=>Xa(R,{render:t.renderMentionToken}),onMentionRemoved:R=>l?.untrackMention(R)});d=C.input,u=C.destroy;let E=c;E.replaceWith(C.element),c=C.element,f={next:C.element,prev:E},g?.(C.element,E),l?l.rebindComposer(C.input):p&&p.then(R=>R?.rebindComposer(C.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};t.display==="inline"&&S();let k=[],P=new Map;for(let A of n){if(!A.showButton)continue;let C=bg({config:{...t,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{h().then(E=>E?.openMenu(A.trigger))}});k.push(C),P.set(A.trigger,C.button)}let M=(A,C,E)=>{let R=P.get(C);R&&(R.setAttribute("aria-expanded",A?"true":"false"),A?R.setAttribute("aria-controls",E):R.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(A=>A.wrapper),contextRow:s,handleInput:A=>{if(l){l.handleInput();return}if(!gg(A))return;let C=c,E=C.selectionStart??0;mg(C.value,E,n)&&h().then(R=>R?.handleInput())},handleKeydown:A=>{if(l?.isMenuOpen())return l.handleKeydown(A);if(A.key==="Backspace"&&l?.hasMentions()&&!f){let C=c,E=C.selectionStart===0&&C.selectionEnd===0;if((C.value.length===0||E)&&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:()=>{Pp().catch(()=>{})},onComposerSwap:A=>{g=A,f&&A(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let A of k)A.wrapper.remove();s.remove()}}}var Ag=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ja(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];Ag(a)&&Ag(r)?n[o]=Ja(a,r):n[o]=r}return n}var fn="min(440px, calc(100vw - 24px))",Oi="440px",fv={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:fn,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)"},at={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:fv,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:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Sg(e,t){if(!(!e&&!t))return e?t?Ja(e,t):e:t}function Vr(e){return e?{...at,...e,theme:Sg(at.theme,e.theme),darkTheme:Sg(at.darkTheme,e.darkTheme),launcher:{...at.launcher,...e.launcher,dock:{...at.launcher?.dock,...e.launcher?.dock},clearChat:{...at.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...at.copy,...e.copy},sendButton:{...at.sendButton,...e.sendButton},statusIndicator:{...at.statusIndicator,...e.statusIndicator},voiceRecognition:{...at.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=at.features?.artifacts,n=e.features?.artifacts,o=at.features?.scrollToBottom,r=e.features?.scrollToBottom,a=at.features?.scrollBehavior,s=e.features?.scrollBehavior,l=at.features?.streamAnimation,p=e.features?.streamAnimation,c=at.features?.askUserQuestion,d=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},g=o===void 0&&r===void 0?void 0:{...o,...r},f=a===void 0&&s===void 0?void 0:{...a,...s},h=l===void 0&&p===void 0?void 0:{...l,...p},S=c===void 0&&d===void 0?void 0:{...c,...d,styles:{...c?.styles,...d?.styles}};return{...at.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??at.suggestionChips,suggestionChipsConfig:{...at.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...at.layout,...e.layout,header:{...at.layout?.header,...e.layout?.header},messages:{...at.layout?.messages,...e.layout?.messages,avatar:{...at.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...at.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...at.layout?.slots,...e.layout?.slots}},markdown:{...at.markdown,...e.markdown,options:{...at.markdown?.options,...e.markdown?.options}},messageActions:{...at.messageActions,...e.messageActions}}:at}var Ni="16px",_i="transparent",Rp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Ip={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Wp={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:fn,maxWidth:Oi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ni,canvasBackground:_i},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"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},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 Zt(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."))?Zt(e,o):o}function Ui(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=Zt(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 Hp(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 Mg(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]=Mg(a,r):n[o]=r}return n}function mv(e,t){return t?Mg(e,t):e}function Qa(e,t={}){let n={palette:Rp,semantic:Ip,components:Wp},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:mv(n.components,e?.components)};if(t.validate!==!1){let r=Hp(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 qi(e){let t=Ui(e),n={};for(let[w,H]of Object.entries(t)){let F=w.replace(/\./g,"-");n[`--persona-${F}`]=H.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"]??Ni,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??_i,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-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",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"]=Zt(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 H=Zt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=H}}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"]=Zt(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"]=Zt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Zt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Zt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Zt(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"]=Zt(e,h.background)??h.background));let S=n["--persona-surface"],k=n["--persona-container"],P=n["--persona-palette-colors-gray-100"]??"#f3f4f6",M=n["--persona-palette-colors-gray-200"]??"#e5e7eb",A=n["--persona-palette-colors-gray-300"]??"#d1d5db",C=!k||k===S,E=C?P:k,R=C?M:k;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??E,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??R,C&&(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"]??E,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??E,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??E,n}var Tg={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 gv={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"}}},Eg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ya=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",hv=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ya()},Vi=e=>hv(e),yv=e=>Qa(e),bv=e=>Qa({...e,palette:{...e?.palette,colors:{...gv.colors,...e?.palette?.colors}}},{validate:!1}),Io=e=>{let t=Vi(e),n=Eg(e?.theme),o=Eg(e?.darkTheme);return t==="dark"?bv(Ja(n??{},o??{})):yv(n)},xv=e=>qi(e),dr=(e,t)=>{let n=Io(t),o=xv(n);for(let[r,a]of Object.entries(o))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",Vi(t))},zr=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ya())});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(Ya());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 Nn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function kg(e){let t=Nn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function zi(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
23
|
+
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(l){let d=[];a&&d.push(Oo(a)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];s&&d.push(Oo(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=ia(),a=Fo();this.activeAssistantMessageId=null;let s=n?.contentParts&&Oi(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 c=this.messages.find(f=>f.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 f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!f){let g=fd(c,this.config.errorMessage);if(g){let m={id:a,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(m)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f||(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=Fo();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=fd(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 f=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}`)}f=c.body}else c instanceof ReadableStream&&(f=c);f?await this.connectStream(f,{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 f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||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,f=Array.isArray(c?.questions)?c.questions:[];if(f.length===1){let g=typeof f[0]?.question=="string"?f[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(([f,g])=>`${f}: ${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((f,g)=>{let m=typeof f?.question=="string"?f.question:"";if(!m)return;let b=c[m],w=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${g}`,role:"assistant",content:m,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${g}`,role:"user",content:w||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[a]:n});if(!c.ok){let f=await c.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||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!==On?!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 f=`${t}:${c}`;if(this.webMcpInflightKeys.has(f)||this.webMcpResolvedKeys.has(f)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(f),o.push(f);let g=this.markWebMcpToolRunning(p),m=p.agentMetadata?.webMcpToolCallId??d;if(d===On)return{dedupeKey:f,resumeKey:m,output:rd(),toolMessage:p,startedAt:g,completedAt:Date.now()};let b=new AbortController;this.webMcpResolveControllers.add(b),r.push(b);let w=this.client.executeWebMcpToolCall(d,p.toolCall?.args,b.signal),T;if(!w)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await w}catch(L){let A=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));return A||this.callbacks.onError?.(L instanceof Error?L:new Error(String(L))),this.markWebMcpToolComplete(p,fs(A?"Aborted by cancel()":dh(L)),g),this.webMcpInflightKeys.delete(f),null}return b.signal.aborted?(this.markWebMcpToolComplete(p,fs("Aborted by cancel()"),g),this.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:m,output:T,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===On?{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,fs("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 b=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b))return;this.webMcpInflightKeys.add(b);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(b)}catch(w){this.callbacks.onError?.(w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(b)}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===On,c=t.toolCall?.args,f=d?null:this.client.executeWebMcpToolCall(o,c,p),g="execute",m=s;try{let b;if(d?b=rd():f?b=await f:b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),p.aborted){this.markWebMcpToolComplete(t,fs("Aborted by cancel()"),s);return}let w=t.agentMetadata?.webMcpToolCallId??o;g="resume",await this.resumeWithToolOutput(n,w,b,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,b,s,m,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(b){let w=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));(g==="execute"||w||p.aborted)&&this.markWebMcpToolComplete(t,fs(w||p.aborted?"Aborted by cancel()":dh(b)),s),w||this.callbacks.onError?.(b instanceof Error?b:new Error(String(b)))}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=zn(this.config.features?.artifacts,t),r=rs(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=zn(this.config.features?.artifacts,n),a=rs(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(()=>(ch(),lh)).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=>fd(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=Fo(),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=dd(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return la(t)}toggleReadAloud(t){let n=this.messages.find(a=>a.id===t);if(!n||n.role!=="assistant")return;let o=dd(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,f=n.approval;s.approval={...c,...f,executionId:f.executionId||c.executionId,toolName:f.toolName||c.toolName,description:f.description||c.description,toolType:f.toolType??c.toolType,reason:f.reason??c.reason,parameters:f.parameters??c.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&ph(l)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,f=this.webMcpInflightKeys.has(c),g=this.webMcpResolvedKeys.has(c),m=r.toolCall?.name,b=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&m!==void 0&&ph(m)&&r.toolCall?.status==="complete";(f||g||b)&&(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 md=[["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 gd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var hd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var yd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var bd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var xd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var vd=[["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 Cd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var wd=[["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 Ad=[["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 Sd=[["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 Md=[["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 Td=[["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 Ed=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var kd=[["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 qi=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16"}],["path",{d:"M18 17V9"}],["path",{d:"M13 17V5"}],["path",{d:"M8 17v-3"}]];var Ld=[["path",{d:"M20 6 9 17l-5-5"}]];var Pd=[["path",{d:"m6 9 6 6 6-6"}]];var Rd=[["path",{d:"m15 18-6-6 6-6"}]];var Id=[["path",{d:"m9 18 6-6-6-6"}]];var Wd=[["path",{d:"m18 15-6-6-6 6"}]];var Vi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var zi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var Hd=[["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 Bd=[["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 Dd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var $i=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Fd=[["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 Od=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Nd=[["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 _d=[["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 ji=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Gi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Ud=[["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 qd=[["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 Vd=[["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 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"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var $d=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var jd=[["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 Gd=[["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 Kd=[["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 Xd=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var Jd=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var Qd=[["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 Yd=[["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 Ki=[["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 Zd=[["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 ep=[["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 tp=[["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 np=[["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 op=[["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 rp=[["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 Xi=[["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 ap=[["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 sp=[["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 ip=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var lp=[["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 cp=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"}],["path",{d:"M9 18h6"}],["path",{d:"M10 22h4"}]];var dp=[["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 Ji=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var pp=[["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 up=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var fp=[["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 mp=[["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 gp=[["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 hp=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var yp=[["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 bp=[["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 xp=[["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 vp=[["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 Cp=[["path",{d:"M5 12h14"}]];var wp=[["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 Ap=[["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 Sp=[["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 Mp=[["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 Tp=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var Qi=[["path",{d:"M13 21h8"}],["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"}]];var Ep=[["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 kp=[["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 Lp=[["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 Pp=[["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 Rp=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Ip=[["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 Wp=[["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 Hp=[["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 Bp=[["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 Dp=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Fp=[["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 Op=[["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 Np=[["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 _p=[["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 Up=[["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 Yi=[["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 qp=[["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 Vp=[["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 zp=[["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 $p=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Zi=[["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 jp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Gp=[["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 Kp=[["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 Xp=[["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 Jp=[["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 Qp=[["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 Yp=[["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 Zp=[["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 eu=[["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 tu=[["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 el=[["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 nu=[["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 ou=[["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 ru=[["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 au=[["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 su=[["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 iu=[["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 lu=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var cu=[["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 yC={activity:md,"arrow-down":gd,"arrow-up":xd,"arrow-up-right":bd,bot:Sd,"chevron-down":Pd,"chevron-up":Wd,"chevron-right":Id,"chevron-left":Rd,check:Ld,clipboard:Bd,"clipboard-copy":Hd,"code-xml":$i,copy:Fd,file:Gd,"file-code":zd,"file-spreadsheet":$d,"file-text":jd,"image-plus":ap,loader:pp,"loader-circle":Ji,mic:xp,paperclip:Mp,"refresh-cw":Wp,search:Dp,send:Fp,"shield-alert":_p,"shield-check":Up,"shield-x":Yi,square:jp,"thumbs-down":Qp,"thumbs-up":Yp,upload:ou,"volume-2":au,x:lu,user:ru,mail:fp,phone:Lp,calendar:Ed,clock:Dd,building:Md,"map-pin":mp,lock:up,key:lp,"credit-card":Od,"at-sign":vd,hash:tp,globe:ep,link:dp,"circle-check":Vi,"circle-x":zi,"triangle-alert":el,info:ip,ban:Cd,shield:qp,"arrow-left":hd,"arrow-right":yd,"external-link":qd,ellipsis:Gi,"ellipsis-vertical":ji,menu:hp,house:Xi,plus:Rp,minus:Cp,pencil:Ep,"pen-line":Qi,trash:tu,"trash-2":eu,save:Bp,download:_d,share:Np,funnel:Ki,settings:Op,"rotate-cw":Hp,maximize:gp,minimize:vp,"shopping-cart":zp,"shopping-bag":Vp,package:Sp,truck:nu,tag:Jp,gift:Zd,receipt:Ip,wallet:iu,store:Kp,"dollar-sign":Nd,percent:kp,play:Pp,pause:Tp,"volume-x":su,camera:kd,image:sp,film:Xd,headphones:np,"message-circle":yp,"message-square":bp,bell:wd,heart:op,star:Gp,eye:Vd,"eye-off":Ud,bookmark:Ad,"calendar-days":Td,history:rp,timer:Zp,folder:Yd,"folder-open":Qd,files:Kd,"chart-column":qi,sparkles:Zi,zap:cu,sun:Xp,moon:Ap,flag:Jd,lightbulb:cp,monitor:wp,smartphone:$p},ae=(e,t=24,n="currentColor",o=2)=>{let r=yC[e];return r?bC(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 bC(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 tl={allowedTypes:co,maxFileSize:10*1024*1024,maxFiles:4};function xC(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function vC(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 Ar=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??tl.allowedTypes,maxFileSize:t.maxFileSize??tl.maxFileSize,maxFiles:t.maxFiles??tl.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:tl.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=oh(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 nh(n),a=Ni(n)?URL.createObjectURL(n):null,s={id:xC(),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=Ni(t.file),o=v("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=v("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=v("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=vC(t.file.type),p=ae(l,20,"var(--persona-muted, #6b7280)",1.5);p&&s.appendChild(p);let d=v("span");d.textContent=rh(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=v("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=ae("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 uh=/\s/;function CC(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===""||uh.test(o)}function wC(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 CC(e,a,o)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(s===`
|
|
25
|
+
`||s==="\uFFFC"||!r&&uh.test(s))return null;a--}return null}function fh(e,t,n){for(let o of n){let r=wC(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function mh(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function gh(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}var Ht={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Ut=1e5,nl=Ut+1;var AC=8,SC=8,du=10,pu=new WeakMap,hh=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,MC=e=>{let t=e.getRootNode?.();return hh(t)?t:e.ownerDocument.body},uu=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function qt(e){pu.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:a=AC,viewportPadding:s=SC}=e,l=()=>t.ownerDocument,p=()=>l().defaultView??window,d=null,c=null,f=null,g=!1,m=!1,b=!1,w=()=>(typeof o=="function"?o():o).trim(),T=()=>{f?.(),f=null,d?.remove(),d=null,c=null},L=()=>{if(!d)return;let $=l(),E=p(),G=t.getBoundingClientRect(),Q=d.getBoundingClientRect(),Z=$.documentElement.clientWidth||E.innerWidth,J=$.documentElement.clientHeight||E.innerHeight,fe=Z-s-Q.width,ne=G.left+G.width/2-Q.width/2,ge=uu(ne,s,fe),ie=G.top-s,ue=J-s-G.bottom,oe=Q.height+a,me=ie>=oe||ie>=ue?"top":"bottom",Se=me==="top"?G.top-a-Q.height:G.bottom+a,Ce=J-s-Q.height,Be=uu(Se,s,Ce),ut=G.left+G.width/2,Je=Math.max(du,Q.width-du),Qe=uu(ut-ge,du,Je);d.dataset.placement=me,d.style.left=`${ge}px`,d.style.top=`${Be}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${Qe}px`)},A=()=>{if(b||!r||d||!t.isConnected)return;let $=w(),E=MC(t);if(!$||!E)return;let G=l(),Q=p();d=G.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(nl),c=G.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=$,d.appendChild(c);let Z=G.createElement("span");Z.className="persona-control-tooltip__arrow",d.appendChild(Z),E.appendChild(d),L(),d.dataset.state="open";let J=()=>{if(!t.isConnected){T();return}c&&(c.textContent=w()),L()};Q.addEventListener("scroll",J,!0),Q.addEventListener("resize",J);let fe=t.getRootNode(),ne=hh(fe)?fe:G.documentElement,ge=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||T()});ge?.observe(ne,{childList:!0,subtree:!0}),f=()=>{Q.removeEventListener("scroll",J,!0),Q.removeEventListener("resize",J),ge?.disconnect()}},S=()=>{g||m?A():T()},C=()=>{let $=p();(!$.matchMedia||!$.matchMedia("(hover: none)").matches)&&(g=!0,S())},M=()=>{g=!1,S()},P=()=>{m=!0,S()},R=()=>{m=!1,S()},F=$=>{$.key==="Escape"&&(g=!1,m=!1,T())};n.addEventListener("mouseenter",C),n.addEventListener("mouseleave",M),t.addEventListener("focus",P),t.addEventListener("blur",R),t.addEventListener("keydown",F);let O={get isOpen(){return d!==null},show:A,hide:T,reposition:L,destroy:()=>{b||(b=!0,T(),n.removeEventListener("mouseenter",C),n.removeEventListener("mouseleave",M),t.removeEventListener("focus",P),t.removeEventListener("blur",R),t.removeEventListener("keydown",F),pu.delete(t))}};return pu.set(t,O),O}function yh(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=v("div","persona-send-button-wrapper"),d=ke("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=ae(s,a,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),n()}),p.appendChild(d),qt({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??l}),{button:d,wrapper:p}}var{setLoader:TC,load:EC}=Zr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),bh=TC,fu=EC;var{setLoader:kC,load:LC}=Zr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),xh=kC,vh=LC;function ms(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=ke("span",{className:Fn("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=ae(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=v("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(ke("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Ch(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=gh(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(P=>P.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=ke("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,d=e.textarea,c=null,f=null,g=null,m=null,b=()=>{if(l)return Promise.resolve(l);if(p)return p;let S=fu().then(C=>(l=C.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:A,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},w=()=>{vh().then(S=>{let C=S.mountInlineComposer({textarea:e.textarea,renderToken:P=>ms(P,{render:t.renderMentionToken}),onMentionRemoved:P=>l?.untrackMention(P)});c=C.input,f=C.destroy;let M=d;M.replaceWith(C.element),d=C.element,m={next:C.element,prev:M},g?.(C.element,M),l?l.rebindComposer(C.input):p&&p.then(P=>P?.rebindComposer(C.input))}).catch(S=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",S)})};t.display==="inline"&&w();let T=[],L=new Map;for(let S of n){if(!S.showButton)continue;let C=yh({config:{...t,buttonIconName:S.buttonIconName,buttonTooltipText:S.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{b().then(M=>M?.openMenu(S.trigger))}});T.push(C),L.set(S.trigger,C.button)}let A=(S,C,M)=>{let P=L.get(C);P&&(P.setAttribute("aria-expanded",S?"true":"false"),S?P.setAttribute("aria-controls",M):P.removeAttribute("aria-controls"))};return{affordanceButtons:T.map(S=>S.wrapper),contextRow:s,handleInput:S=>{if(l){l.handleInput();return}if(!mh(S))return;let C=d,M=C.selectionStart??0;fh(C.value,M,n)&&b().then(P=>P?.handleInput())},handleKeydown:S=>{if(l?.isMenuOpen())return l.handleKeydown(S);if(S.key==="Backspace"&&l?.hasMentions()&&!m){let C=d,M=C.selectionStart===0&&C.selectionEnd===0;if((C.value.length===0||M)&&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 b())?.dispatchInlineCommand(S)??null:null,clear:()=>l?.clear(),prefetch:()=>{fu().catch(()=>{})},onComposerSwap:S=>{g=S,m&&S(m.next,m.prev)},destroy:()=>{l?.destroy(),f?.();for(let S of T)S.wrapper.remove();s.remove()}}}var wh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function gs(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];wh(a)&&wh(r)?n[o]=gs(a,r):n[o]=r}return n}var mn="min(440px, calc(100vw - 24px))",ol="440px",PC={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:mn,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)"},rt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:PC,copy:{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:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Ah(e,t){if(!(!e&&!t))return e?t?gs(e,t):e:t}function da(e){return e?{...rt,...e,theme:Ah(rt.theme,e.theme),darkTheme:Ah(rt.darkTheme,e.darkTheme),launcher:{...rt.launcher,...e.launcher,dock:{...rt.launcher?.dock,...e.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=rt.features?.artifacts,n=e.features?.artifacts,o=rt.features?.scrollToBottom,r=e.features?.scrollToBottom,a=rt.features?.scrollBehavior,s=e.features?.scrollBehavior,l=rt.features?.streamAnimation,p=e.features?.streamAnimation,d=rt.features?.askUserQuestion,c=e.features?.askUserQuestion,f=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},m=a===void 0&&s===void 0?void 0:{...a,...s},b=l===void 0&&p===void 0?void 0:{...l,...p},w=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...rt.features,...e.features,...g!==void 0?{scrollToBottom:g}:{},...m!==void 0?{scrollBehavior:m}:{},...f!==void 0?{artifacts:f}:{},...b!==void 0?{streamAnimation:b}:{},...w!==void 0?{askUserQuestion:w}:{}}})(),suggestionChips:e.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...rt.layout?.header,...e.layout?.header},messages:{...rt.layout?.messages,...e.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...e.layout?.slots}},markdown:{...rt.markdown,...e.markdown,options:{...rt.markdown?.options,...e.markdown?.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}var rl="16px",al="transparent",mu={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"}},gu={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"}},hu={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:mn,maxWidth:ol,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:rl,canvasBackground:al},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"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function en(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."))?en(e,o):o}function sl(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=en(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 yu(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 Sh(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]=Sh(a,r):n[o]=r}return n}function RC(e,t){return t?Sh(e,t):e}function hs(e,t={}){let n={palette:mu,semantic:gu,components:hu},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:RC(n.components,e?.components)};if(t.validate!==!1){let r=yu(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 il(e){let t=sl(e),n={};for(let[E,G]of Object.entries(t)){let Q=E.replace(/\./g,"-");n[`--persona-${Q}`]=G.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"]??rl,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??al,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-title-color"]??n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??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";let r=n["--persona-components-introCard-background"],a=n["--persona-components-introCard-shadow"],s=(!r||r==="transparent"||r==="none")&&(!a||a==="none"),l=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=s&&l==="1.5rem"?"1.5rem 0":l,n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-intro-card-border"]=n["--persona-components-introCard-border"]??"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-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-composer-border-color"]=n["--persona-components-composer-borderColor"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-thumb"]=n["--persona-components-scrollbar-thumb"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-track"]=n["--persona-components-scrollbar-track"]??"transparent",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 p=n["--persona-components-markdown-heading-h1-fontSize"];p&&(n["--persona-md-h1-size"]=p);let d=n["--persona-components-markdown-heading-h1-fontWeight"];d&&(n["--persona-md-h1-weight"]=d);let c=n["--persona-components-markdown-heading-h2-fontSize"];c&&(n["--persona-md-h2-size"]=c);let f=n["--persona-components-markdown-heading-h2-fontWeight"];f&&(n["--persona-md-h2-weight"]=f);let g=n["--persona-components-markdown-prose-fontFamily"];g&&g!=="inherit"&&(n["--persona-md-prose-font-family"]=g),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-code-block-border-radius"]=n["--persona-components-markdown-codeBlock-borderRadius"]??n["--persona-radius-md"]??"0.375rem",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 m=e.components,b=m?.iconButton;b&&(b.background&&(n["--persona-icon-btn-bg"]=b.background),b.border&&(n["--persona-icon-btn-border"]=b.border),b.color&&(n["--persona-icon-btn-color"]=b.color),b.padding&&(n["--persona-icon-btn-padding"]=b.padding),b.borderRadius&&(n["--persona-icon-btn-radius"]=b.borderRadius),b.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=b.hoverBackground),b.hoverColor&&(n["--persona-icon-btn-hover-color"]=b.hoverColor),b.activeBackground&&(n["--persona-icon-btn-active-bg"]=b.activeBackground),b.activeBorder&&(n["--persona-icon-btn-active-border"]=b.activeBorder));let w=m?.labelButton;w&&(w.background&&(n["--persona-label-btn-bg"]=w.background),w.border&&(n["--persona-label-btn-border"]=w.border),w.color&&(n["--persona-label-btn-color"]=w.color),w.padding&&(n["--persona-label-btn-padding"]=w.padding),w.borderRadius&&(n["--persona-label-btn-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-label-btn-hover-bg"]=w.hoverBackground),w.fontSize&&(n["--persona-label-btn-font-size"]=w.fontSize),w.gap&&(n["--persona-label-btn-gap"]=w.gap));let T=m?.toggleGroup;T&&(T.gap&&(n["--persona-toggle-group-gap"]=T.gap),T.borderRadius&&(n["--persona-toggle-group-radius"]=T.borderRadius));let L=m?.artifact;if(L?.toolbar){let E=L.toolbar;E.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=E.iconHoverColor),E.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=E.iconHoverBackground),E.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=E.iconPadding),E.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=E.iconBorderRadius),E.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=E.iconBorder),E.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=E.toggleGroupGap),E.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=E.toggleBorderRadius),E.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=E.toggleGroupPadding),E.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=E.toggleGroupBorder),E.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=E.toggleGroupBorderRadius),E.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=en(e,E.toggleGroupBackground)??E.toggleGroupBackground),E.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=E.copyBackground),E.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=E.copyBorder),E.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=E.copyColor),E.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=E.copyBorderRadius),E.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=E.copyPadding),E.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=E.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??E.copyMenuBackground),E.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=E.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??E.copyMenuBorder),E.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=E.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??E.copyMenuShadow),E.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=E.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??E.copyMenuBorderRadius),E.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=E.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??E.copyMenuItemHoverBackground),E.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=E.iconBackground),E.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=E.toolbarBorder)}if(L?.tab){let E=L.tab;E.background&&(n["--persona-artifact-tab-bg"]=E.background),E.activeBackground&&(n["--persona-artifact-tab-active-bg"]=E.activeBackground),E.activeBorder&&(n["--persona-artifact-tab-active-border"]=E.activeBorder),E.borderRadius&&(n["--persona-artifact-tab-radius"]=E.borderRadius),E.textColor&&(n["--persona-artifact-tab-color"]=E.textColor),E.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=E.hoverBackground),E.listBackground&&(n["--persona-artifact-tab-list-bg"]=E.listBackground),E.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=E.listBorderColor),E.listPadding&&(n["--persona-artifact-tab-list-padding"]=E.listPadding)}if(L?.pane){let E=L.pane;if(E.toolbarBackground){let G=en(e,E.toolbarBackground)??E.toolbarBackground;n["--persona-artifact-toolbar-bg"]=G}}if(L?.card){let E=L.card;E.background&&(n["--persona-artifact-card-bg"]=E.background),E.border&&(n["--persona-artifact-card-border"]=E.border),E.borderRadius&&(n["--persona-artifact-card-radius"]=E.borderRadius),E.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=E.hoverBackground),E.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=E.hoverBorderColor)}if(L?.inline){let E=L.inline;E.background&&(n["--persona-artifact-inline-bg"]=en(e,E.background)??E.background),E.border&&(n["--persona-artifact-inline-border"]=E.border),E.borderRadius&&(n["--persona-artifact-inline-radius"]=E.borderRadius),E.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=en(e,E.chromeBackground)??E.chromeBackground),E.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=en(e,E.chromeBorder)??E.chromeBorder),E.titleColor&&(n["--persona-artifact-inline-title-color"]=en(e,E.titleColor)??E.titleColor),E.mutedColor&&(n["--persona-artifact-inline-muted-color"]=en(e,E.mutedColor)??E.mutedColor),E.frameHeight&&(n["--persona-artifact-inline-frame-height"]=E.frameHeight)}let A=m?.code;A&&(A.keywordColor&&(n["--persona-code-keyword-color"]=A.keywordColor),A.stringColor&&(n["--persona-code-string-color"]=A.stringColor),A.commentColor&&(n["--persona-code-comment-color"]=A.commentColor),A.numberColor&&(n["--persona-code-number-color"]=A.numberColor),A.tagColor&&(n["--persona-code-tag-color"]=A.tagColor),A.attrColor&&(n["--persona-code-attr-color"]=A.attrColor),A.propertyColor&&(n["--persona-code-property-color"]=A.propertyColor),A.lineNumberColor&&(n["--persona-code-line-number-color"]=A.lineNumberColor),A.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=A.gutterBorderColor),A.background&&(n["--persona-code-bg"]=en(e,A.background)??A.background));let S=n["--persona-surface"],C=n["--persona-container"],M=n["--persona-palette-colors-gray-100"]??"#f3f4f6",P=n["--persona-palette-colors-gray-200"]??"#e5e7eb",R=n["--persona-palette-colors-gray-300"]??"#d1d5db",F=!C||C===S,O=F?M:C,$=F?P:C;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??O,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??$,F&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??R),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??O,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??O,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??O,n}var Mh={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 IC={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"}}},Th=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ys=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",WC=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":ys()},ll=e=>WC(e),HC=e=>hs(e),BC=e=>hs({...e,palette:{...e?.palette,colors:{...IC.colors,...e?.palette?.colors}}},{validate:!1}),Uo=e=>{let t=ll(e),n=Th(e?.theme),o=Th(e?.darkTheme);return t==="dark"?BC(gs(n??{},o??{})):HC(n)},DC=e=>il(e),Sr=(e,t)=>{let n=Uo(t),o=DC(n);for(let[r,a]of Object.entries(o))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",ll(t))},pa=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(ys())});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(ys());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())}};var qo=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");function $n(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Eh(e){let t=$n(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function cl(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,
|
|
29
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Mr(e){let t=Eh(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 Vo(e){switch(Mr(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Eh(e.path);return t?t.toUpperCase():"File"}}}function kh(e){let t=e.markdown??"";return e.file?{filename:$n(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:cl(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var bu="http://www.w3.org/2000/svg";function Lh(e){let t=document.createElementNS(bu,"svg");t.setAttribute("class",Fn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(bu,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(bu,"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 zo=(e,t,n)=>{let o=n;for(let r of t){let a=v("span","persona-tool-char");a.style.setProperty("--char-index",String(o)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),o++}return o};function Ph(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)),zo(e,t,0)}var xu="persona-artifact-status-label",Rh="persona-artifact-status-detail",Ih="data-artifact-status-label",vu=new Map,Wh=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function ua(e){e&&vu.delete(e)}function FC(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Vo(t):e.artifactType==="component"?"Component":"Document"}function fa(e,t,n){let o=FC(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=vu.get(s);e.status!=="complete"&&l===void 0&&(l=Wh(),vu.set(s,l));let p=l===void 0?0:Math.max(0,Wh()-l),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",f=d?0:c.length,g=d||c===""?0:c.split(`
|
|
30
|
+
`).length,m=e.artifactType==="markdown"?e.file:void 0,b={artifactId:s,artifactType:e.artifactType,title:e.title,typeLabel:o,file:m,chars:f,lines:g,elapsedMs:p,content:()=>d?"":c,surface:n};try{let w=a(b);return typeof w=="string"?{label:w}:w&&typeof w=="object"&&typeof w.label=="string"?{label:w.label,detail:typeof w.detail=="string"?w.detail:void 0}:{label:r}}catch{return{label:r}}}function OC(e){e.className=xu,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 Tr(e,t,n){let o=e.querySelector(`:scope > .${xu}`);o||(o=v("span",xu),e.appendChild(o)),o.getAttribute(Ih)!==t.label&&(OC(o),Ph(o,t.label,n),o.setAttribute(Ih,t.label));let r=e.querySelector(`:scope > .${Rh}`),a=t.detail;a?(r||(r=v("span",Rh),e.appendChild(r)),r.textContent!==a&&(r.textContent=a)):r&&r.remove()}var NC={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"},_C=15e4,dl={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 UC(e,t){let n=(e||"").trim().toLowerCase();if(n&&dl[n])return dl[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(dl[r])return dl[r]}}return null}function pl(e,t){let n=[],o=0,r=0,a=s=>{s>r&&n.push({type:"plain",value:e.slice(r,s)})};for(;o<e.length;){let s=!1;for(let l of t){l.re.lastIndex=o;let p=l.re.exec(e);if(p&&p.index===o&&p[0].length>0){a(o);let d=l.map?l.map(p[0]):l.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,s=!0;break}}s||(o+=1)}return a(e.length),n}var qC=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"]),VC=[{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=>qC.has(e)?"keyword":"plain"}];function Hh(e){return pl(e,VC)}var zC=[{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 $C(e){let t=pl(e,zC);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 jC=[{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 Bh(e){let t=pl(e,jC),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 GC=[{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 KC(e){let t=[],n=(a,s)=>{s&&t.push({type:a,value:s})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let s=e.indexOf("-->",r+4),l=s===-1?o:s+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let s=e.indexOf(">",r),l=s===-1?o:s+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let s=e.indexOf(">",r),l=s===-1?o:s+1,p=e.slice(r,l);for(let c of pl(p,GC))t.push(c);r=l;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),g=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),m=g?r+g.index:o,b=e.slice(r,m),w=c==="script"?Hh(b):Bh(b);for(let T of w)t.push(T);r=m}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 XC(e,t){switch(t){case"html":return KC(e);case"css":return Bh(e);case"js":return Hh(e);case"json":return $C(e)}}function JC(e){let t=kg(),n=v("span","persona-code-line"),o=(r,a)=>{if(!a)return;let s=NC[r];if(s){let l=v("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 Fg(e,t,n){let o=e.length<=Av?Sv(t,n):null,r=o?Iv(e,o):[{type:"plain",value:e}];return Wv(r)}function Bo(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(Fi)):(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 k=document.createElement("hr");s.appendChild(k)}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 k=ae(f.icon,16,"currentColor",1.5);k&&h.appendChild(k)}let S=document.createElement("span");S.textContent=f.label,h.appendChild(S),h.addEventListener("click",k=>{k.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=x("button","persona-icon-btn"+(a?" "+a:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let c=ae(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 no(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=x("button",c);if(d.type="button",d.setAttribute("aria-label",n),t){let g=ae(t,a??14,"currentColor",2);g&&d.appendChild(g)}let u=x("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 Gr(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 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=x("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 Gi(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:a="bottom-left",portal:s,className:l,hover:p}=e,c=x("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=x("span","persona-combo-btn-label");d.textContent=t,c.appendChild(d);let u=ae(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=Bo({items:o,onSelect:f=>{c.setAttribute("aria-expanded","false"),r(f)},anchor:c,position:a,portal:s});return s||c.appendChild(g.element),c.addEventListener("click",f=>{f.stopPropagation();let h=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",h?"false":"true"),g.toggle()}),c.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),c.click())}),{element:c,setLabel:f=>{d.textContent=f,c.setAttribute("aria-label",f)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let f=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",f?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var Ki="persona-artifact-custom-action-btn";function Kr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Ki+(n?" persona-artifact-doc-copy-btn":"");o=x("button",r)}else{let r="persona-icon-btn "+Ki+(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=no({icon:e.icon,label:e.label,className:Ki+(n?" persona-artifact-doc-copy-btn":"")}):o=Mt({icon:e.icon,label:e.label,className:Ki+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function es(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 Og(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?Nn(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?Wo(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 S=t?.config?.features?.artifacts,k={id:a,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},P=jr(k,S,"card");cr(h,P,S)}else a&&$r(a),h.textContent=c;if(g.append(f,h),d.append(u,g),s==="complete"){let S=t?.config?.features?.artifacts?.cardActions;if(S&&S.length>0){let P={artifactId:a||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let M of S)try{if(M.visible===void 0||M.visible(P)){let A=Kr(M);A.setAttribute("data-artifact-custom-action",M.id),A.className=`${A.className} persona-flex-shrink-0`,d.append(A)}}catch{}}let k=no({label:"Download",className:"persona-flex-shrink-0"});k.title=`Download ${r}`,k.setAttribute("data-download-artifact",a),d.append(k)}return d}var Xi=(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:()=>Og(e,t)});if(l)return l}return Og(e,t)};var Do=new WeakMap;function Op(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=Do.get(r);if(!a)return;let s=o.get(r.getAttribute("data-artifact-inline")??"");s&&a(s,n)})}function Vg(e){return Do.has(e)}function Hv(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 Ng(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Nn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Wo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Bv(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 _g=180,Dv=240,Fv=.8,Ov=300,Nv=500,_v="cubic-bezier(0.2, 0, 0, 1)",Ug=240,Uv=.35;function qv(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:_g,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let P of s)P.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(Nv,Math.max(Ov,Dv+c*Fv))),u=Math.round(d*Uv),g=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=g?g.animate([{opacity:0},{opacity:1}],{duration:Ug,delay:u,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:d,easing:_v});e.style.height=`${p}px`;let S=!1,k=()=>{S||(S=!0,l(),r())};Promise.allSettled([h.finished,f?.finished].filter(Boolean)).then(k),window.setTimeout(k,Math.max(d,u+Ug)+120)},_g)}function Vv(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 ts="--persona-artifact-inline-body-height";function zv(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 qg(e,t){let n=Hv(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:a,showExpand:s,showViewToggle:l}=Vv(o),p=o?.inlineActions??[],c=zv(o),d=c.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=oe=>Xi(Bv(oe),t),S=oe=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(ts),f.replaceChildren(h(oe)),Do.set(f,le=>{f.replaceChildren(h(le))})};if(d&&n.status==="complete")return S(n),f;let k=Ji(n,{config:t.config,bodyLayout:c,resolveViewMode:()=>u??c.viewMode}),P=x("div","persona-artifact-inline-body");P.appendChild(k.el);let M=oe=>{let le=oe.status!=="complete",Z=le?c.streamingHeight:c.completeHeight,he=typeof Z=="number";he?f.style.setProperty(ts,`${Z}px`):f.style.removeProperty(ts);let Ce=!!k.el.querySelector(".persona-code-pre"),ve=!!k.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");P.classList.toggle("persona-artifact-content-flush",Ce),P.classList.toggle("persona-artifact-inline-body--sized",he&&ve),P.classList.toggle("persona-artifact-inline-body--cap",!le&&!ve&&typeof c.completeHeight=="number")},A=n.status,C=(oe,le)=>{A!=="complete"&&oe.status==="complete"?(typeof c.completeHeight=="number"?f.style.setProperty(ts,`${c.completeHeight}px`):f.style.removeProperty(ts),$g(P,le?.suppressTransition?"none":c.transition,oe.id,()=>{k.update(oe),M(oe)})):k.update(oe),M(oe),A=oe.status};M(n);let E=c.overflow==="clip"&&s&&!!n.id;if(E&&(P.setAttribute("data-expand-artifact-inline",n.id),P.setAttribute("role","button"),P.setAttribute("tabindex","0"),P.classList.add("persona-cursor-pointer"),P.setAttribute("aria-label",`Open ${Ng(n).title} in panel`)),!r)return f.appendChild(P),Do.set(f,C),f;let R=x("div","persona-artifact-inline-chrome");R.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=x("div","persona-artifact-inline-chrome-lead"),H=x("span","persona-flex persona-items-center persona-flex-shrink-0"),F=ae("file-text",16,"currentColor",2);F&&H.appendChild(F);let K=x("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),D=x("span","persona-artifact-inline-type");w.append(H,K,D);let q=x("div","persona-artifact-inline-chrome-actions"),Y=x("span","persona-flex persona-items-center persona-gap-1"),de=()=>u??c.viewMode,be=l?Gr({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:oe=>{let le=oe==="source"?"source":"rendered";le!==de()&&(u=le,k.update(g),M(g))}}):null,pe=a?Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;pe&&n.id&&pe.setAttribute("data-copy-artifact",n.id);let te=s?Mt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;te&&n.id&&te.setAttribute("data-expand-artifact-inline",n.id),q.appendChild(Y),be&&q.appendChild(be.element),pe&&q.appendChild(pe),te&&q.appendChild(te),R.append(w,q),f.append(R,P);let me=oe=>{let{title:le,typeLabel:Z}=Ng(oe);K.textContent=le,K.title=le,E&&P.setAttribute("aria-label",`Open ${le} in panel`);let he=oe.status!=="complete";if(he){D.classList.contains("persona-artifact-inline-status")||(D.className="persona-artifact-inline-status",D.removeAttribute("data-preserve-animation"),D.replaceChildren());let Ce=jr(oe,o,"inline-chrome");cr(D,Ce,o)}else $r(oe.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=Z;if(pe&&pe.classList.toggle("persona-hidden",he),be){let Ce=oe.artifactType==="markdown"?oe.file:void 0,ve=!1;if(!he&&Ce&&c.viewMode!=="source"){let we=Za(Ce);we==="markdown"?ve=!0:(we==="html"||we==="svg")&&(ve=o?.filePreview?.enabled!==!1)}be.element.classList.toggle("persona-hidden",!ve),be.setSelected(de())}if(Y.replaceChildren(),!he&&p.length>0){let Ce=es(oe);if(Ce)for(let ve of p)try{if(ve.visible===void 0||ve.visible(Ce)){let we=Kr(ve,{documentChrome:!0});we.setAttribute("data-artifact-custom-action",ve.id),we.classList.add("persona-flex-shrink-0"),Y.appendChild(we)}}catch{}}};return me(n),Do.set(f,(oe,le)=>{if(d&&A!=="complete"&&oe.status==="complete"){let Z=f.isConnected?f.getBoundingClientRect().height:0;A="complete";let he=oe,Ce=!1,ve=we=>{he=we,Ce=!0};Do.set(f,ve),qv(f,Z,{swap:()=>{S(he),Ce=!1,Do.set(f,ve)},onSettled:()=>{Ce?S(he):Do.set(f,we=>{f.replaceChildren(h(we))})}});return}(oe.status!=="complete"||oe.id!==g.id)&&(u=null),g=oe,C(oe,le),me(oe)}),f}var zg=(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:()=>qg(e,t)});if(l)return l}return qg(e,t)};var Np=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)})}},Rn=new Np;Rn.register("PersonaArtifactCard",Xi,{bubbleChrome:!1});Rn.register("PersonaArtifactInline",zg,{bubbleChrome:!1});function ns(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?zi(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var _p=!1;function $v(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function $g(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"||_p||a){o();return}_p=!0;let s=$v(n);e.style.setProperty("view-transition-name",s);let l=()=>{_p=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var jv="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Gv="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Kv(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 Xv(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 Jv=220;function Qv(){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 Yv(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 Zv(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(Pg());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 eC(e,t,n,o,r,a){let s=null,l=0,p=!1,c=new Set,d=()=>{c.forEach(A=>clearTimeout(A)),c.clear()},u=(A,C)=>{let E=setTimeout(()=>{c.delete(E),A()},C);c.add(E)},g=()=>{s&&s.parentElement&&s.remove(),s=null},f=()=>{if(s||p)return;let A=Zv(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,Jv))},S=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",P):t.removeEventListener("load",M)},k=()=>{if(p||(p=!0,S(),d(),!s))return;let A=Math.max(0,o.minVisibleMs-(Date.now()-l));A>0?u(h,A):h()};function P(A){if(n===null)return;let C=A.data;!C||C.persona!=="artifact-preview-ready"||C.token!==n||A.source===t.contentWindow&&k()}function M(){let A=C=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>C()):setTimeout(C,0)};A(()=>A(()=>k()))}return u(f,o.delayMs),u(k,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",P):t.addEventListener("load",M),()=>{p=!0,d(),S(),g()}}function Ji(e,t){let{config:n}=t,o=t.registry??Rn,r=t.bodyLayout,a=n.markdown?tr(n.markdown):null,s=Hr(n.sanitize),l=e,p=!1,c=te=>{let me=Jn()!==null;a&&!me&&!p&&(p=!0,Wr(()=>pe(l)));let oe=a?a(te):Fn(te);return a&&me&&s?s(oe):oe},d=x("div","persona-artifact-preview-body"),u=null,g=null,f=null,h=()=>{f&&(f(),f=null),u=null,g=null},S=null,k=null,P=null,M=!1,A=()=>{S=null,k=null,P=null,M=!1},C=null,E=null,R=()=>{C=null,E=null},w=40,H=0,F=te=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>te()):setTimeout(te,0),K=te=>te.scrollHeight-te.clientHeight-te.scrollTop<=w,D=te=>{if(!r)return;let me=te.scrollHeight-te.clientHeight>1,oe=te.scrollHeight-te.clientHeight-te.scrollTop;te.classList.toggle("persona-artifact-fade-top",r.fadeTop&&me&&te.scrollTop>1),te.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&me&&oe>1)},q=te=>{H||(H=F(()=>{H=0,te.scrollTop=te.scrollHeight,D(te)}))},Y=(te,me,oe,le)=>{let Z=!!r,he=oe.id+"|"+(Z?"w":"p");if(!S||P!==he||S.parentElement!==d){h(),R(),d.replaceChildren();let we=x("pre",jv+" persona-code-pre"),Ee=x("code","persona-code");if(we.appendChild(Ee),Z){let ke=x("div","persona-artifact-source-window");if(ke.appendChild(we),d.appendChild(ke),!(r?.overflow==="clip")&&typeof ke.addEventListener=="function"){let Ge=()=>ke.scrollHeight-ke.clientHeight>1;ke.addEventListener("scroll",()=>{K(ke)&&(M=!1),D(ke)},{passive:!0}),ke.addEventListener("wheel",ze=>{Ge()&&ze.deltaY<0&&(M=!0)},{passive:!0}),ke.addEventListener("touchmove",()=>{Ge()&&(M=!0)},{passive:!0})}S=ke}else d.appendChild(we),S=we;k=Ee,P=he}let Ce=Z?S:null;Ce&&(Ce.classList.toggle("persona-artifact-source-window--fixed",le),Ce.classList.toggle("persona-artifact-source-window--clip",le&&r?.overflow==="clip"));let ve=Ce?K(Ce):!0;if(k.replaceChildren(Fg(te,me?.language,me?.path)),Ce){let we=oe.status!=="complete";le&&we&&r?.followOutput&&!M&&ve?q(Ce):we||(M=!1),D(Ce)}},de=te=>{h(),A(),R(),d.replaceChildren();let me=x("div",Gv);me.innerHTML=c(te),d.appendChild(me)},be=te=>{let me=te.id,oe=n.features?.artifacts,le=jr(te,oe,"status-body");if(C&&E===me&&C.parentElement===d){let Ce=C.querySelector(".persona-artifact-status-view-text");Ce&&cr(Ce,le,oe);return}h(),A(),d.replaceChildren();let Z=x("div","persona-artifact-status-view"),he=x("div","persona-artifact-status-view-text");cr(he,le,oe),Z.appendChild(he),d.appendChild(Z),C=Z,E=me},pe=te=>{l=te;let me=t.resolveViewMode?.(te)??r?.viewMode??"rendered",oe=te.artifactType==="markdown"?te.file:void 0,le=te.status!=="complete";le||$r(te.id);let Z=le?r?.streamingHeight:r?.completeHeight,he=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&le){be(te);return}if(oe){let ve=zi(te.markdown??""),we=Za(oe),Ee=n.features?.artifacts?.filePreview?.enabled!==!1;if(!le&&me==="rendered"&&Ee&&(we==="html"||we==="svg")){let Se=te.id+"\0"+ve;if(u&&g===Se&&u.parentElement===d)return;A(),R(),h(),d.replaceChildren();let Ge=n.features?.artifacts?.filePreview,ze=Ge?.iframeSandbox??"allow-scripts";!Ge?.dangerouslyAllowSameOrigin&&ze.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."),ze=ze.split(/\s+/).filter(Wt=>Wt&&Wt!=="allow-same-origin").join(" "));let Me=Xv(Ge?.loading),Re=x("div","persona-artifact-frame"),Ke=x("iframe","persona-artifact-iframe");Ke.setAttribute("sandbox",ze),Ke.setAttribute("data-artifact-id",te.id);let Bt=null;Me.enabled&&Me.injectReadySignal?(Bt=Qv(),Ke.srcdoc=ve+Yv(Bt)):Ke.srcdoc=ve,Re.appendChild(Ke),d.appendChild(Re),Me.enabled&&(f=eC(Re,Ke,Bt,Me,te.id,n)),u=Re,g=Se;return}if(h(),!le&&we==="markdown"&&me==="rendered"){de(ve);return}Y(ve,{language:oe.language,path:oe.path},te,he);return}if(te.artifactType==="markdown"){if(me==="source"){h(),Y(te.markdown??"",void 0,te,he);return}de(te.markdown??"");return}h(),A(),R(),d.replaceChildren();let Ce=te.component?o.get(te.component):void 0;if(Ce){let we={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ee=Ce(te.props??{},we);if(Ee){d.appendChild(Ee);return}}catch{}}d.appendChild(Kv(te))};return pe(e),{el:d,update(te){pe(te)}}}var jg=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:g=>g.getAttribute("im-preserve")==="true",shouldReAppend:g=>g.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function n(g,f,h={}){g=d(g);let S=u(f),k=c(g,S,h),P=r(k,()=>l(k,g,S,M=>M.morphStyle==="innerHTML"?(a(M,g,S),Array.from(g.childNodes)):o(M,g,S)));return k.pantry.remove(),P}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:k,selectionEnd:P}=h,M=f();return S&&S!==document.activeElement?.getAttribute("id")&&(h=g.target.querySelector(`[id="${S}"]`),h?.focus()),h&&!h.selectionEnd&&P&&h.setSelectionRange(k,P),M}let a=(function(){function g(C,E,R,w=null,H=null){E instanceof HTMLTemplateElement&&R instanceof HTMLTemplateElement&&(E=E.content,R=R.content),w||(w=E.firstChild);for(let F of R.childNodes){if(w&&w!=H){let D=h(C,F,w,H);if(D){D!==w&&k(C,w,D),s(D,F,C),w=D.nextSibling;continue}}if(F instanceof Element){let D=F.getAttribute("id");if(C.persistentIds.has(D)){let q=P(E,D,w,C);s(q,F,C),w=q.nextSibling;continue}}let K=f(E,F,w,C);K&&(w=K.nextSibling)}for(;w&&w!=H;){let F=w;w=w.nextSibling,S(C,F)}}function f(C,E,R,w){if(w.callbacks.beforeNodeAdded(E)===!1)return null;if(w.idMap.has(E)){let H=document.createElement(E.tagName);return C.insertBefore(H,R),s(H,E,w),w.callbacks.afterNodeAdded(H),H}else{let H=document.importNode(E,!0);return C.insertBefore(H,R),w.callbacks.afterNodeAdded(H),H}}let h=(function(){function C(w,H,F,K){let D=null,q=H.nextSibling,Y=0,de=F;for(;de&&de!=K;){if(R(de,H)){if(E(w,de,H))return de;D===null&&(w.idMap.has(de)||(D=de))}if(D===null&&q&&R(de,q)&&(Y++,q=q.nextSibling,Y>=2&&(D=void 0)),w.activeElementAndParents.includes(de))break;de=de.nextSibling}return D||null}function E(w,H,F){let K=w.idMap.get(H),D=w.idMap.get(F);if(!D||!K)return!1;for(let q of K)if(D.has(q))return!0;return!1}function R(w,H){let F=w,K=H;return F.nodeType===K.nodeType&&F.tagName===K.tagName&&(!F.getAttribute?.("id")||F.getAttribute?.("id")===K.getAttribute?.("id"))}return C})();function S(C,E){if(C.idMap.has(E))A(C.pantry,E,null);else{if(C.callbacks.beforeNodeRemoved(E)===!1)return;E.parentNode?.removeChild(E),C.callbacks.afterNodeRemoved(E)}}function k(C,E,R){let w=E;for(;w&&w!==R;){let H=w;w=w.nextSibling,S(C,H)}return w}function P(C,E,R,w){let H=w.target.getAttribute?.("id")===E&&w.target||w.target.querySelector(`[id="${E}"]`)||w.pantry.querySelector(`[id="${E}"]`);return M(H,w),A(C,H,R),H}function M(C,E){let R=C.getAttribute("id");for(;C=C.parentNode;){let w=E.idMap.get(C);w&&(w.delete(R),w.size||E.idMap.delete(C))}}function A(C,E,R){if(C.moveBefore)try{C.moveBefore(E,R)}catch{C.insertBefore(E,R)}else C.insertBefore(E,R)}return g})(),s=(function(){function g(M,A,C){return C.ignoreActive&&M===document.activeElement?null:(C.callbacks.beforeNodeMorphed(M,A)===!1||(M instanceof HTMLHeadElement&&C.head.ignore||(M instanceof HTMLHeadElement&&C.head.style!=="morph"?p(M,A,C):(f(M,A,C),P(M,C)||a(C,M,A))),C.callbacks.afterNodeMorphed(M,A)),M)}function f(M,A,C){let E=A.nodeType;if(E===1){let R=M,w=A,H=R.attributes,F=w.attributes;for(let K of F)k(K.name,R,"update",C)||R.getAttribute(K.name)!==K.value&&R.setAttribute(K.name,K.value);for(let K=H.length-1;0<=K;K--){let D=H[K];if(D&&!w.hasAttribute(D.name)){if(k(D.name,R,"remove",C))continue;R.removeAttribute(D.name)}}P(R,C)||h(R,w,C)}(E===8||E===3)&&M.nodeValue!==A.nodeValue&&(M.nodeValue=A.nodeValue)}function h(M,A,C){if(M instanceof HTMLInputElement&&A instanceof HTMLInputElement&&A.type!=="file"){let E=A.value,R=M.value;S(M,A,"checked",C),S(M,A,"disabled",C),A.hasAttribute("value")?R!==E&&(k("value",M,"update",C)||(M.setAttribute("value",E),M.value=E)):k("value",M,"remove",C)||(M.value="",M.removeAttribute("value"))}else if(M instanceof HTMLOptionElement&&A instanceof HTMLOptionElement)S(M,A,"selected",C);else if(M instanceof HTMLTextAreaElement&&A instanceof HTMLTextAreaElement){let E=A.value,R=M.value;if(k("value",M,"update",C))return;E!==R&&(M.value=E),M.firstChild&&M.firstChild.nodeValue!==E&&(M.firstChild.nodeValue=E)}}function S(M,A,C,E){let R=A[C],w=M[C];if(R!==w){let H=k(C,M,"update",E);H||(M[C]=A[C]),R?H||M.setAttribute(C,""):k(C,M,"remove",E)||M.removeAttribute(C)}}function k(M,A,C,E){return M==="value"&&E.ignoreActiveValue&&A===document.activeElement?!0:E.callbacks.beforeAttributeUpdated(M,A,C)===!1}function P(M,A){return!!A.ignoreActiveValue&&M===document.activeElement&&M!==document.body}return g})();function l(g,f,h,S){if(g.head.block){let k=f.querySelector("head"),P=h.querySelector("head");if(k&&P){let M=p(k,P,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=[],k=[],P=[],M=[],A=new Map;for(let E of f.children)A.set(E.outerHTML,E);for(let E of g.children){let R=A.has(E.outerHTML),w=h.head.shouldReAppend(E),H=h.head.shouldPreserve(E);R||H?w?k.push(E):(A.delete(E.outerHTML),P.push(E)):h.head.style==="append"?w&&(k.push(E),M.push(E)):h.head.shouldRemove(E)!==!1&&k.push(E)}M.push(...A.values());let C=[];for(let E of M){let R=document.createRange().createContextualFragment(E.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(R)!==!1){if("href"in R&&R.href||"src"in R&&R.src){let w,H=new Promise(function(F){w=F});R.addEventListener("load",function(){w()}),C.push(H)}g.appendChild(R),h.callbacks.afterNodeAdded(R),S.push(R)}}for(let E of k)h.callbacks.beforeNodeRemoved(E)!==!1&&(g.removeChild(E),h.callbacks.afterNodeRemoved(E));return h.head.afterHeadMorphed(g,{added:S,kept:P,removed:k}),C}let c=(function(){function g(C,E,R){let{persistentIds:w,idMap:H}=M(C,E),F=f(R),K=F.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(K))throw`Do not understand how to morph style ${K}`;return{target:C,newContent:E,config:F,morphStyle:K,ignoreActive:F.ignoreActive,ignoreActiveValue:F.ignoreActiveValue,restoreFocus:F.restoreFocus,idMap:H,persistentIds:w,pantry:h(),activeElementAndParents:S(C),callbacks:F.callbacks,head:F.head}}function f(C){let E=Object.assign({},t);return Object.assign(E,C),E.callbacks=Object.assign({},t.callbacks,C.callbacks),E.head=Object.assign({},t.head,C.head),E}function h(){let C=document.createElement("div");return C.hidden=!0,document.body.insertAdjacentElement("afterend",C),C}function S(C){let E=[],R=document.activeElement;if(R?.tagName!=="BODY"&&C.contains(R))for(;R&&(E.push(R),R!==C);)R=R.parentElement;return E}function k(C){let E=Array.from(C.querySelectorAll("[id]"));return C.getAttribute?.("id")&&E.push(C),E}function P(C,E,R,w){for(let H of w){let F=H.getAttribute("id");if(E.has(F)){let K=H;for(;K;){let D=C.get(K);if(D==null&&(D=new Set,C.set(K,D)),D.add(F),K===R)break;K=K.parentElement}}}}function M(C,E){let R=k(C),w=k(E),H=A(R,w),F=new Map;P(F,H,C,R);let K=E.__idiomorphRoot||E;return P(F,H,K,w),{persistentIds:H,idMap:F}}function A(C,E){let R=new Set,w=new Map;for(let{id:F,tagName:K}of C)w.has(F)?R.add(F):w.set(F,K);let H=new Set;for(let{id:F,tagName:K}of E)H.has(F)?R.add(F):w.get(F)===K&&H.add(F);for(let F of R)H.delete(F);return H}return g})(),{normalizeElement:d,normalizeParent:u}=(function(){let g=new WeakSet;function f(P){return P instanceof Document?P.documentElement:P}function h(P){if(P==null)return document.createElement("div");if(typeof P=="string")return h(k(P));if(g.has(P))return P;if(P instanceof Node){if(P.parentNode)return new S(P);{let M=document.createElement("div");return M.append(P),M}}else{let M=document.createElement("div");for(let A of[...P])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,C)=>{if(C instanceof Element){C.matches(M)&&A.push(C);let E=C.querySelectorAll(M);for(let R=0;R<E.length;R++)A.push(E[R])}return A},[])}insertBefore(M,A){return this.realParentNode.insertBefore(M,A)}moveBefore(M,A){return this.realParentNode.moveBefore(M,A)}get __idiomorphRoot(){return this.originalNode}}function k(P){let M=new DOMParser,A=P.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(A.match(/<\/html>/)||A.match(/<\/head>/)||A.match(/<\/body>/)){let C=M.parseFromString(P,"text/html");if(A.match(/<\/html>/))return g.add(C),C;{let E=C.firstChild;return E&&g.add(E),E}}else{let E=M.parseFromString("<body><template>"+P+"</template></body>","text/html").body.querySelector("template").content;return g.add(E),E}}return{normalizeElement:f,normalizeParent:h}})();return{morph:n,defaults:t}})();var Qi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;jg.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 Gg=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Up={index:-1,draft:""};function Kg(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 Xg(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 Jg(){return new Map}function Qg(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Yg(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Zg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function eh(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 Yi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function _n(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Fo(e,t){return _n(e)-e.scrollTop<=t}function Zi(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 el(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 th(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function nh(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 oh(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var os={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},tC=["pre","code","a","script","style"],tl=e=>({type:e?.type??os.type,placeholder:e?.placeholder??os.placeholder,speed:e?.speed??os.speed,duration:e?.duration??os.duration,buffer:e?.buffer??os.buffer}),ah=[{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"}],rs=new Map;for(let e of ah)rs.set(e.name,e);var pr=e=>{rs.set(e.name,e)},zp=e=>{ah.some(t=>t.name===e)||rs.delete(e)},$p=()=>Array.from(rs.keys()),Xr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:rs.get(e)??null,nl=(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},nC=(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},oC=(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},qp=/\s/,rC=(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},aC=(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(qp.test(a[l])){let p=l;for(;p<a.length&&qp.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&&!qp.test(a[c]);)p.appendChild(nC(o,a[c],t,n.value)),n.value+=1,c+=1;s.appendChild(p),l=c}r.replaceChild(s,e)},sC=(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(oC(o,p,t,n.value)),n.value+=1));r.replaceChild(s,e)},as=(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??tC).map(u=>u.toLowerCase())),s=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=s.nextNode();for(;p;)rC(p,a)||l.push(p),p=s.nextNode();let c={value:o?.startIndex??0},d=t==="char"?aC:sC;for(let u of l)d(u,n,c);return r.innerHTML},ol=(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},ss=(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},rh=new WeakMap,iC=(e,t)=>{if(!e.styles)return;let n=rh.get(t);if(n||(n=new Set,rh.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)},Vp=new WeakMap,lC=(e,t)=>{if(!e.onAttach)return;let n=Vp.get(t);if(n||(n=new Map,Vp.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},sh=e=>{let t=Vp.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},rl=(e,t)=>{iC(e,t),lC(e,t)};function jp(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 is=0,Oo=null;function Gp(e=document){if(is++,is===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Oo={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,is=Math.max(0,is-1),is===0&&Oo)){let n=e.body,o=e.defaultView??window;n.style.overflow=Oo.originalOverflow,n.style.position=Oo.originalPosition,n.style.top=Oo.originalTop,n.style.width=Oo.originalWidth,o.scrollTo(0,Oo.scrollY),Oo=null}}}var ls={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Et=e=>(e?.launcher?.mountMode??"floating")==="docked",No=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",sn=e=>{let t=e?.launcher?.dock;return{side:t?.side??ls.side,width:t?.width??ls.width,animate:t?.animate??ls.animate,reveal:t?.reveal??ls.reveal,maxHeight:t?.maxHeight??ls.maxHeight}};var Kp=e=>e==="followUp"?"follow-up":e,dC=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},cC=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},ih=new WeakSet,pC=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,uC=e=>{pC()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},al=e=>{let t=[],n=[],o=null,r=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){a();return}let d=Math.max(0,e.scrollWidth-e.clientWidth);if(d<=1){a();return}let u=getComputedStyle(e).direction==="rtl",g=Math.min(d,Math.max(0,Math.abs(e.scrollLeft))),f=4,h=g<=f,S=g>=d-f,k=u?!S:!h,P=u?!h:!S;e.toggleAttribute("data-scroll-left",k),e.toggleAttribute("data-scroll-right",P)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&s();return}r=requestAnimationFrame(s)};e.addEventListener("scroll",l,{passive:!0});let p=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return p?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),p?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(d,u,g,f,h,S)=>{e.replaceChildren(),t.length=0,n.length=0;let k=S?.source??"config",P=S?.surface??(k==="config"?"starter":"followUp"),M=P==="followUp",A=S?.variant??"chip",C=S?.behavior??"send",E=S?.overflow??"wrap",R=S?.config??{},w=S?.plugins??[],H=typeof S?.maxItems=="number"?Math.max(0,Math.floor(S.maxItems)):void 0,F=M?"followUps":"starters";!ih.has(R)&&R.debug===!0&&A!=="chip"&&R.suggestions?.[F]?.overflow!==void 0&&(ih.add(R),console.info(`[persona] suggestions.${F}.overflow applies to the "chip" variant only; the "${A}" variant manages its own stacking.`));let K=pe=>pe.map(dC).filter(te=>te!==null).map(te=>({...te,behavior:te.behavior??C})),D=K(d??[]);w.forEach(pe=>{pe.transformSuggestions&&(D=K(pe.transformSuggestions({suggestions:D.map(te=>({...te})),surface:P,source:k,config:R})))});let q=H===void 0?D:D.slice(0,H);if(!q.length){e.hidden=!0,o=null,a();return}if(!M&&(f??u.getMessages()).some(te=>te.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Kp(P),e.dataset.variant=A,e.dataset.overflow=E;let Y=document.createDocumentFragment(),de=u.isStreaming();q.forEach((pe,te)=>{var Ce,ve,we;let me=pe.behavior,oe=()=>{if(u.isStreaming())return;let Ee={suggestion:{...pe},surface:P,source:k,behavior:me},ke=e.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:Ee,bubbles:!0,composed:!0,cancelable:!0}));if(M&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:pe.prompt},bubbles:!0,composed:!0})),!!ke){for(let Se of w)if(Se.onSuggestionSelect?.({suggestion:{...pe},surface:P,source:k,variant:A,config:R})===!1)return;if(me==="fill"){g.value=pe.prompt,g.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),g.focus();return}g.value="",u.sendMessage(pe.prompt)}},le=()=>{let Ee=x("button",`persona-suggestion persona-suggestion--${A}`);if(Ee.type="button",Ee.disabled=de,Ee.dataset.suggestionId=pe.id,Ee.dataset.emphasis=pe.emphasis,Ee.dataset.behavior=me,A==="chip"&&(h?.fontFamily&&(Ee.style.fontFamily=cC(h.fontFamily)),h?.fontWeight&&(Ee.style.fontWeight=h.fontWeight),h?.paddingX&&(Ee.style.paddingLeft=h.paddingX,Ee.style.paddingRight=h.paddingX),h?.paddingY&&(Ee.style.paddingTop=h.paddingY,Ee.style.paddingBottom=h.paddingY)),pe.icon){let Se=ae(pe.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);Se&&(Se.classList.add("persona-suggestion__icon"),pe.iconColor&&(Se.style.color=pe.iconColor),Ee.appendChild(Se))}let ke=x("span","persona-suggestion__copy");if(ke.appendChild(Ie("span",{className:"persona-suggestion__label",text:pe.label})),pe.description&&ke.appendChild(Ie("span",{className:"persona-suggestion__description",text:pe.description})),Ee.appendChild(ke),A!=="chip"){let Se=ae("arrow-right",16,"currentColor",1.8);Se&&(Se.classList.add("persona-suggestion__arrow"),Ee.appendChild(Se))}return Ee.addEventListener("click",oe),Ee},Z=null;for(let Ee of w)if(Ee.renderSuggestion&&(Z=Ee.renderSuggestion({suggestion:{...pe},index:te,surface:P,source:k,variant:A,streaming:de,config:R,defaultRenderer:le,select:oe}),Z))break;Z??(Z=le()),(Ce=Z.dataset).suggestionId||(Ce.suggestionId=pe.id),(ve=Z.dataset).behavior||(ve.behavior=me),(we=Z.dataset).emphasis||(we.emphasis=pe.emphasis),Z instanceof HTMLButtonElement||Z.setAttribute("aria-disabled",de?"true":"false"),Y.appendChild(Z),n.push(Z),[...Z instanceof HTMLButtonElement?[Z]:[],...Array.from(Z.querySelectorAll("button"))].forEach(Ee=>{t.includes(Ee)||(Ee.disabled=de,t.push(Ee))})}),e.appendChild(Y),s(),l();let be=JSON.stringify({normalized:q,surface:P,variant:A,source:k});be!==o&&(o=be,uC(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:q.map(pe=>({...pe})),surface:P,source:k,variant:A},bubbles:!0,composed:!0})),M&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:q.map(pe=>pe.prompt)},bubbles:!0,composed:!0})))}}};var In={"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 fC="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",sl=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=fC,buttonSize:r,iconSize:a="28px"}=t,s=e?.launcher??{},l=r??s.closeButtonSize??"32px",p=x("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=Ie("button",{className:Qn("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||en.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=ae(u,a,"currentColor",1);return S?(S.style.display="block",h.appendChild(S)):h.textContent=g,p.appendChild(h),Ut({anchor:h,trigger:p,text:()=>h.getAttribute("aria-label")??c,enabled:d}),{button:h,wrapper:p}},mC="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",il=(e,t={})=>{let{wrapperClassName:n=mC,buttonSize:o,iconSize:r="20px"}=t,s=(e?.launcher??{}).clearChat??{},l=o??s.size??"32px",p=s.iconName??"refresh-cw",c=s.iconColor??"",d=s.backgroundColor??"",u=s.borderWidth??"",g=s.borderColor??"",f=s.borderRadius??"",h=s.paddingX??"",S=s.paddingY??"",k=s.tooltipText??"Clear chat",P=s.showTooltip??!0,M=x("div",n),A=!!(u||g),C=Ie("button",{className:Qn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"hover:persona-bg-gray-100",!A&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":k},style:{height:l,width:l,color:c||en.actionIconColor,backgroundColor:d||void 0,border:A?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:S||void 0,paddingBottom:S||void 0}}),E=ae(p,r,"currentColor",1);return E&&(E.style.display="block",C.appendChild(E)),M.appendChild(C),Ut({anchor:C,trigger:M,text:()=>C.getAttribute("aria-label")??k,enabled:P}),{button:C,wrapper:M}};var en={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))"},oo=e=>{let{config:t,showClose:n=!0}=e,o=Ie("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=Ie("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 E=parseFloat(a)||24,R=ae(p,E*.6,"currentColor",1);R?c.replaceChildren(R):c.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let E=x("img");E.src=t.launcher.iconUrl,E.alt="",E.className="persona-rounded-xl persona-object-cover",E.style.height=a,E.style.width=a,c.replaceChildren(E)}else c.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let d=x("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Ie("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:en.titleColor}}),g=Ie("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:en.subtitleColor}});d.append(u,g),l?o.append(d):o.append(c,d);let f=r.clearChat??{},h=f.enabled??!0,S=f.placement??"inline",k=null,P=null;if(h){let R=il(t,{wrapperClassName:S==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=R.button,P=R.wrapper,S==="top-right"&&(P.style.right="48px"),S==="inline"&&o.appendChild(P)}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:C}=sl(t,{showClose:n,wrapperClassName:M});return s!=="top-right"&&o.appendChild(C),{header:o,iconHolder:c,headerTitle:u,headerSubtitle:g,closeButton:A,closeButtonWrapper:C,clearChatButton:k,clearChatButtonWrapper:P}},ur=(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 Xp=e=>{let t=oo({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 gC(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=ae(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=Bo({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 Jp=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,c,d;if(p)c=Gi({label:s.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=en.titleColor,d=c.querySelector(".persona-combo-btn-label")??c;else{if(c=x("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=x("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=en.titleColor,d.textContent=s.title??"Chat Assistant",c.appendChild(d),gC(c,r?.trailingActions,r?.onAction??a),r?.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let A=r.onTitleClick;c.addEventListener("click",C=>{C.target.closest("button")||A()}),c.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),A())})}let M=r?.titleRowHover;M&&(c.style.borderRadius=M.borderRadius??"10px",c.style.padding=M.padding??"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{c.style.backgroundColor=M.background??"",c.style.borderColor=M.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}l.appendChild(c);let u=s.closeButtonSize??"32px",g=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||en.actionIconColor;let h=s.closeButtonIconName??"x",S=ae(h,"28px","currentColor",1);S?f.appendChild(S):f.textContent="\xD7",o&&f.addEventListener("click",o),g.appendChild(f),l.appendChild(g);let k=x("div");k.style.display="none";let P=x("span");return P.style.display="none",{header:l,iconHolder:k,headerTitle:d,headerSubtitle:P,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},ll={default:Xp,minimal:Jp},Qp=e=>ll[e]??ll.default,Jr=(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"),c=x("span"),d=x("button");d.style.display="none";let u=x("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 dl=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-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,r=()=>{let p=t.ownerDocument?.defaultView;if(!p?.getComputedStyle)return o;let c=p.getComputedStyle(t).lineHeight;if(!c||!c.trim().endsWith("px"))return o;let d=parseFloat(c);return Number.isFinite(d)&&d>0?d:o},a=`${n*o}px`;t.style.maxHeight=a,t.style.overflowY="auto";let s=()=>{let p=t.style.maxHeight;if(p!==a){let d=parseFloat(p);if(Number.isFinite(d)&&d>0)return d}let c=n*r();return a=`${c}px`,t.style.maxHeight=a,c},l=()=>{t.addEventListener("input",()=>{t.style.height="auto";let p=Math.min(t.scrollHeight,s());t.style.height=`${p}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:l}},cl=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=x("div","persona-send-button-wrapper"),S=Ie("button",{className:Qn("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:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),k=null,P=null;if(n){let C=parseFloat(t.iconSize??"")||Math.round((parseFloat(u)||24)*.5),E=t.iconStrokeWidth??2,R=f?.trim()||"currentColor";r?(k=ae(r,C,R,E),k?S.appendChild(k):S.textContent=o):S.textContent=o,P=ae(a,C,R,E)}else S.textContent=p;S.setAttribute("aria-label",s),h.appendChild(S),Ut({anchor:S,trigger:h,text:()=>S.getAttribute("aria-label")??"",enabled:d});let M="send";return{button:S,wrapper:h,setMode:C=>{if(C===M)return;M=C;let E=C==="stop"?l:s;if(S.setAttribute("aria-label",E),n){if(k&&P){let R=C==="stop"?P:k;S.replaceChildren(R)}}else S.textContent=C==="stop"?c:p}}},pl=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=x("div","persona-send-button-wrapper"),f=Ie("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}}),S=ae(l,c,u||"currentColor",1.5);S?f.appendChild(S):f.textContent="\u{1F3A4}",g.appendChild(f);let k=t.tooltipText??"Start voice recognition",P=t.showTooltip??!1;return Ut({anchor:f,trigger:g,text:()=>f.getAttribute("aria-label")??k,enabled:P}),{button:f,wrapper:g}},ul=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??to).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=x("div","persona-send-button-wrapper"),d=Ie("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=ae(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}},fl=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},ml=()=>Ie("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Qr=e=>{let{config:t}=e,n=Ie("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=ml(),r=Ie("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}=dl(t);s();let l=cl(t),p=pl(t),c=ul(t),d=fl(t);c&&(c.previewsContainer.style.gap="8px",r.append(c.previewsContainer,c.input)),r.append(a);let u=Ie("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 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 lh=()=>{let e=Ie("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=ae("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=ae("chevron-up",16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,o,r),{root:e,textNode:o}},dh=e=>{let{config:t}=e,n=Ie("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ml(),r=fl(t);r.style.display="none";let{textarea:a,attachAutoResize:s}=dl(t);a.style.maxHeight="100px",s();let l=cl(t),p=pl(t),c=ul(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let d=Ie("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");c&&u.append(c.wrapper);let g=x("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 ch=e=>{let t=e?.launcher?.enabled??!0,n=Et(e);if(No(e)){let d=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=d.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Gt);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=d.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Gt),{wrapper:u,panel:g,pillRoot:f}}if(n){let d=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 d.appendChild(u),{wrapper:d,panel:u}}if(!t){let d=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 d.style.width=g,u.style.width="100%",d.appendChild(u),{wrapper:d,panel:u}}let r=e?.launcher??{},a=r.position&&In[r.position]?In[r.position]:In["bottom-right"],s=x("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String(e?.launcher?.zIndex??Gt);let l=x("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=e?.launcher?.width??e?.launcherWidth??fn;return l.style.width=c,l.style.maxWidth=c,s.appendChild(l),{wrapper:s,panel:l}},gl=e=>{let t=Ie("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Kp(e)}});return t.hidden=!0,t},hC=(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}=sl(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 R=il(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=R.button,l=R.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=Ie("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Ie("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=Ie("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Ie("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),g=gl("starter"),f=Ie("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,g),h=x("div","persona-flex persona-flex-col persona-gap-3"),S=gl("followUp"),k=e?.layout?.contentMaxWidth;k&&(h.style.maxWidth=k,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(f.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(f,h,S);let M=Ie("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"}}),A=dh({config:e}),{root:C,textNode:E}=lh();return n.append(p,r,c,M),l&&n.appendChild(l),{container:n,body:c,messagesWrapper:h,starterSuggestions:g,transcriptSuggestions:S,composerOverlay:M,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,introTitle:d,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:s,clearChatButtonWrapper:l,iconHolder:x("span"),headerTitle:x("span"),headerSubtitle:x("span"),header:p,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:C,peekTextNode:E}},ph=(e,t=!0)=>{if(No(e))return hC(e,t);let n=Ie("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?Jr(e,o,{showClose:t}):oo({config:e,showClose:t}),s=Ie("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=Ie("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Ie("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),c=gl("starter"),d=Ie("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,c),u=x("div","persona-flex persona-flex-col persona-gap-3"),g=gl("followUp"),f=e?.layout?.contentMaxWidth;f&&(u.style.maxWidth=f,u.style.marginLeft="auto",u.style.marginRight="auto",u.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,u,g);let S=Qr({config:e}),k=e?.layout?.showFooter!==!1;r?ur(n,a,e):(a.header.style.display="none",ur(n,a,e)),n.append(s);let P=Ie("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 k||(S.footer.style.display="none"),n.append(S.footer),n.append(P),{container:n,body:s,messagesWrapper:u,starterSuggestions:c,transcriptSuggestions:g,composerOverlay:P,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.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:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode}};var Yp=(e,t)=>{let n=x("button");n.type="button",n.innerHTML=`
|
|
32
|
+
`)),n=v("span","persona-code-line")),o(r.type,a[s])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Dh(e,t,n){let o=e.length<=_C?UC(t,n):null,r=o?XC(e,o):[{type:"plain",value:e}];return JC(r)}function $o(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:a}=e,s=v("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(nl)):(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 m of t){if(m.dividerBefore){let T=document.createElement("hr");s.appendChild(T)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",m.id),m.destructive&&b.setAttribute("data-destructive",""),m.icon){let T=ae(m.icon,16,"currentColor",1.5);T&&b.appendChild(T)}let w=document.createElement("span");w.textContent=m.label,b.appendChild(w),b.addEventListener("click",T=>{T.stopPropagation(),c(),n(m.id)}),s.appendChild(b)}let l=null;function p(){if(!a)return;let m=o.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,r==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function d(){p(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=b=>{!s.contains(b.target)&&!o.contains(b.target)&&c()};document.addEventListener("click",m,!0),l=()=>document.removeEventListener("click",m,!0)})}function c(){s.classList.add("persona-hidden"),l?.(),l=null}function f(){s.classList.contains("persona-hidden")?d():c()}function g(){c(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:c,toggle:f,destroy:g}}function Tt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:a,onClick:s,aria:l}=e,p=v("button","persona-icon-btn"+(a?" "+a:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ae(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),s&&p.addEventListener("click",s),l)for(let[c,f]of Object.entries(l))p.setAttribute(c,f);return p}function po(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=v("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let g=ae(t,a??14,"currentColor",2);g&&c.appendChild(g)}let f=v("span");if(f.textContent=n,c.appendChild(f),l&&c.addEventListener("click",l),p)for(let[g,m]of Object.entries(p))c.setAttribute(g,m);return c}function ma(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,a=v("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 f;c.icon?f=Tt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{s=c.id,p(),o(c.id)}}):(f=v("button","persona-icon-btn"+(c.className?" "+c.className:"")),f.type="button",f.setAttribute("aria-label",c.label),f.title=c.label,f.textContent=c.label,f.addEventListener("click",()=>{s=c.id,p(),o(c.id)})),f.setAttribute("aria-pressed",c.id===s?"true":"false"),l.push({id:c.id,btn:f}),a.appendChild(f)}function d(c){s=c,p()}return{element:a,setSelected:d}}function ul(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:a="bottom-left",portal:s,className:l,hover:p}=e,d=v("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=v("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let f=ae(n,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",d.appendChild(f)),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=$o({items:o,onSelect:m=>{d.setAttribute("aria-expanded","false"),r(m)},anchor:d,position:a,portal:s});return s||d.appendChild(g.element),d.addEventListener("click",m=>{m.stopPropagation();let b=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",b?"false":"true"),g.toggle()}),d.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),d.click())}),{element:d,setLabel:m=>{c.textContent=m,d.setAttribute("aria-label",m)},open:()=>{d.setAttribute("aria-expanded","true"),g.show()},close:()=>{d.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let m=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",m?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),d.remove()}}}var fl="persona-artifact-custom-action-btn";function ga(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 "+fl+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+fl+(n?" persona-artifact-doc-icon-btn":"");o=v("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=v("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=po({icon:e.icon,label:e.label,className:fl+(n?" persona-artifact-doc-copy-btn":"")}):o=Tt({icon:e.icon,label:e.label,className:fl+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function bs(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 Fh(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?$n(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,d=n?Vo(n):l==="component"?"Component":"Document",c=document.createElement("div");c.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),a&&c.setAttribute("data-open-artifact",a);let f=document.createElement("div");f.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-muted, #9ca3af)",f.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 m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=r;let b=document.createElement("div");if(b.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",b.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let w=t?.config?.features?.artifacts,T={id:a,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},L=fa(T,w,"card");Tr(b,L,w)}else a&&ua(a),b.textContent=d;if(g.append(m,b),c.append(f,g),s==="complete"){let w=t?.config?.features?.artifacts?.cardActions;if(w&&w.length>0){let L={artifactId:a||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let A of w)try{if(A.visible===void 0||A.visible(L)){let S=ga(A);S.setAttribute("data-artifact-custom-action",A.id),S.className=`${S.className} persona-flex-shrink-0`,c.append(S)}}catch{}}let T=po({label:"Download",className:"persona-flex-shrink-0"});T.title=`Download ${r}`,T.setAttribute("data-download-artifact",a),c.append(T)}return c}var ml=(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:()=>Fh(e,t)});if(l)return l}return Fh(e,t)};var jo=new WeakMap;function Cu(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=jo.get(r);if(!a)return;let s=o.get(r.getAttribute("data-artifact-inline")??"");s&&a(s,n)})}function qh(e){return jo.has(e)}function QC(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 Oh(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?$n(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Vo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function YC(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 Nh=180,ZC=240,ew=.8,tw=300,nw=500,ow="cubic-bezier(0.2, 0, 0, 1)",_h=240,rw=.35;function aw(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:Nh,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let L of s)L.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(nw,Math.max(tw,ZC+d*ew))),f=Math.round(c*rw),g=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,m=g?g.animate([{opacity:0},{opacity:1}],{duration:_h,delay:f,easing:"ease-out",fill:"backwards"}):null,b=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:ow});e.style.height=`${p}px`;let w=!1,T=()=>{w||(w=!0,l(),r())};Promise.allSettled([b.finished,m?.finished].filter(Boolean)).then(T),window.setTimeout(T,Math.max(c,f+_h)+120)},Nh)}function sw(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 xs="--persona-artifact-inline-body-height";function iw(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,f=t?.fadeMask;f===!0?(d=!0,c=!0):f===!1?(d=!1,c=!1):f&&typeof f=="object"?(d=f.top===!0,c=f.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let g=t?.transition==="none"?"none":"auto",m=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:m}}function Uh(e,t){let n=QC(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:a,showExpand:s,showViewToggle:l}=sw(o),p=o?.inlineActions??[],d=iw(o),c=d.completeDisplay==="card",f=null,g=n,m=v("div","persona-artifact-inline persona-w-full persona-max-w-full");m.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&m.setAttribute("data-artifact-inline",n.id);let b=ie=>ml(YC(ie),t),w=ie=>{m.classList.add("persona-artifact-inline--card"),m.style.removeProperty(xs),m.replaceChildren(b(ie)),jo.set(m,ue=>{m.replaceChildren(b(ue))})};if(c&&n.status==="complete")return w(n),m;let T=gl(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>f??d.viewMode}),L=v("div","persona-artifact-inline-body");L.appendChild(T.el);let A=ie=>{let ue=ie.status!=="complete",oe=ue?d.streamingHeight:d.completeHeight,me=typeof oe=="number";me?m.style.setProperty(xs,`${oe}px`):m.style.removeProperty(xs);let Se=!!T.el.querySelector(".persona-code-pre"),Ce=!!T.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");L.classList.toggle("persona-artifact-content-flush",Se),L.classList.toggle("persona-artifact-inline-body--sized",me&&Ce),L.classList.toggle("persona-artifact-inline-body--cap",!ue&&!Ce&&typeof d.completeHeight=="number")},S=n.status,C=(ie,ue)=>{S!=="complete"&&ie.status==="complete"?(typeof d.completeHeight=="number"?m.style.setProperty(xs,`${d.completeHeight}px`):m.style.removeProperty(xs),zh(L,ue?.suppressTransition?"none":d.transition,ie.id,()=>{T.update(ie),A(ie)})):T.update(ie),A(ie),S=ie.status};A(n);let M=d.overflow==="clip"&&s&&!!n.id;if(M&&(L.setAttribute("data-expand-artifact-inline",n.id),L.setAttribute("role","button"),L.setAttribute("tabindex","0"),L.classList.add("persona-cursor-pointer"),L.setAttribute("aria-label",`Open ${Oh(n).title} in panel`)),!r)return m.appendChild(L),jo.set(m,C),m;let P=v("div","persona-artifact-inline-chrome");P.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let R=v("div","persona-artifact-inline-chrome-lead"),F=v("span","persona-flex persona-items-center persona-flex-shrink-0"),O=ae("file-text",16,"currentColor",2);O&&F.appendChild(O);let $=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),E=v("span","persona-artifact-inline-type");R.append(F,$,E);let G=v("div","persona-artifact-inline-chrome-actions"),Q=v("span","persona-flex persona-items-center persona-gap-1"),Z=()=>f??d.viewMode,J=l?ma({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:Z(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ie=>{let ue=ie==="source"?"source":"rendered";ue!==Z()&&(f=ue,T.update(g),A(g))}}):null,fe=a?Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;fe&&n.id&&fe.setAttribute("data-copy-artifact",n.id);let ne=s?Tt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ne&&n.id&&ne.setAttribute("data-expand-artifact-inline",n.id),G.appendChild(Q),J&&G.appendChild(J.element),fe&&G.appendChild(fe),ne&&G.appendChild(ne),P.append(R,G),m.append(P,L);let ge=ie=>{let{title:ue,typeLabel:oe}=Oh(ie);$.textContent=ue,$.title=ue,M&&L.setAttribute("aria-label",`Open ${ue} in panel`);let me=ie.status!=="complete";if(me){E.classList.contains("persona-artifact-inline-status")||(E.className="persona-artifact-inline-status",E.removeAttribute("data-preserve-animation"),E.replaceChildren());let Se=fa(ie,o,"inline-chrome");Tr(E,Se,o)}else ua(ie.id),E.className="persona-artifact-inline-type",E.removeAttribute("data-preserve-animation"),E.replaceChildren(),E.textContent=oe;if(fe&&fe.classList.toggle("persona-hidden",me),J){let Se=ie.artifactType==="markdown"?ie.file:void 0,Ce=!1;if(!me&&Se&&d.viewMode!=="source"){let Be=Mr(Se);Be==="markdown"?Ce=!0:(Be==="html"||Be==="svg")&&(Ce=o?.filePreview?.enabled!==!1)}J.element.classList.toggle("persona-hidden",!Ce),J.setSelected(Z())}if(Q.replaceChildren(),!me&&p.length>0){let Se=bs(ie);if(Se)for(let Ce of p)try{if(Ce.visible===void 0||Ce.visible(Se)){let Be=ga(Ce,{documentChrome:!0});Be.setAttribute("data-artifact-custom-action",Ce.id),Be.classList.add("persona-flex-shrink-0"),Q.appendChild(Be)}}catch{}}};return ge(n),jo.set(m,(ie,ue)=>{if(c&&S!=="complete"&&ie.status==="complete"){let oe=m.isConnected?m.getBoundingClientRect().height:0;S="complete";let me=ie,Se=!1,Ce=Be=>{me=Be,Se=!0};jo.set(m,Ce),aw(m,oe,{swap:()=>{w(me),Se=!1,jo.set(m,Ce)},onSettled:()=>{Se?w(me):jo.set(m,Be=>{m.replaceChildren(b(Be))})}});return}(ie.status!=="complete"||ie.id!==g.id)&&(f=null),g=ie,C(ie,ue),ge(ie)}),m}var Vh=(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:()=>Uh(e,t)});if(l)return l}return Uh(e,t)};var wu=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)})}},Nn=new wu;Nn.register("PersonaArtifactCard",ml,{bubbleChrome:!1});Nn.register("PersonaArtifactInline",Vh,{bubbleChrome:!1});function vs(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?cl(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Au=!1;function lw(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function zh(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"||Au||a){o();return}Au=!0;let s=lw(n);e.style.setProperty("view-transition-name",s);let l=()=>{Au=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var cw="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",dw="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function pw(e){let t=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=v("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function uw(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 fw=220;function mw(){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 gw(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 hw(e,t,n){let o=v("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=v("div","persona-artifact-frame-loading-indicator");r.appendChild(Lh());let a=null;return n.label!==!1&&(a=v("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 yw(e,t,n,o,r,a){let s=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(S=>clearTimeout(S)),d.clear()},f=(S,C)=>{let M=setTimeout(()=>{d.delete(M),S()},C);d.add(M)},g=()=>{s&&s.parentElement&&s.remove(),s=null},m=()=>{if(s||p)return;let S=hw(r,a,o);s=S.el,e.appendChild(s),l=Date.now(),o.label!==!1&&f(S.revealLabel,o.labelDelayMs)},b=()=>{s&&(s.classList.add("persona-artifact-frame-loading--out"),f(g,fw))},w=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",L):t.removeEventListener("load",A)},T=()=>{if(p||(p=!0,w(),c(),!s))return;let S=Math.max(0,o.minVisibleMs-(Date.now()-l));S>0?f(b,S):b()};function L(S){if(n===null)return;let C=S.data;!C||C.persona!=="artifact-preview-ready"||C.token!==n||S.source===t.contentWindow&&T()}function A(){let S=C=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>C()):setTimeout(C,0)};S(()=>S(()=>T()))}return f(m,o.delayMs),f(T,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",L):t.addEventListener("load",A),()=>{p=!0,c(),w(),g()}}function gl(e,t){let{config:n}=t,o=t.registry??Nn,r=t.bodyLayout,a=n.markdown?hr(n.markdown):null,s=ta(n.sanitize),l=e,p=!1,d=ne=>{let ge=ao()!==null;a&&!ge&&!p&&(p=!0,ea(()=>fe(l)));let ie=a?a(ne):Vn(ne);return a&&ge&&s?s(ie):ie},c=v("div","persona-artifact-preview-body"),f=null,g=null,m=null,b=()=>{m&&(m(),m=null),f=null,g=null},w=null,T=null,L=null,A=!1,S=()=>{w=null,T=null,L=null,A=!1},C=null,M=null,P=()=>{C=null,M=null},R=40,F=0,O=ne=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ne()):setTimeout(ne,0),$=ne=>ne.scrollHeight-ne.clientHeight-ne.scrollTop<=R,E=ne=>{if(!r)return;let ge=ne.scrollHeight-ne.clientHeight>1,ie=ne.scrollHeight-ne.clientHeight-ne.scrollTop;ne.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ge&&ne.scrollTop>1),ne.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ge&&ie>1)},G=ne=>{F||(F=O(()=>{F=0,ne.scrollTop=ne.scrollHeight,E(ne)}))},Q=(ne,ge,ie,ue)=>{let oe=!!r,me=ie.id+"|"+(oe?"w":"p");if(!w||L!==me||w.parentElement!==c){b(),P(),c.replaceChildren();let Be=v("pre",cw+" persona-code-pre"),ut=v("code","persona-code");if(Be.appendChild(ut),oe){let Je=v("div","persona-artifact-source-window");if(Je.appendChild(Be),c.appendChild(Je),!(r?.overflow==="clip")&&typeof Je.addEventListener=="function"){let Ne=()=>Je.scrollHeight-Je.clientHeight>1;Je.addEventListener("scroll",()=>{$(Je)&&(A=!1),E(Je)},{passive:!0}),Je.addEventListener("wheel",_e=>{Ne()&&_e.deltaY<0&&(A=!0)},{passive:!0}),Je.addEventListener("touchmove",()=>{Ne()&&(A=!0)},{passive:!0})}w=Je}else c.appendChild(Be),w=Be;T=ut,L=me}let Se=oe?w:null;Se&&(Se.classList.toggle("persona-artifact-source-window--fixed",ue),Se.classList.toggle("persona-artifact-source-window--clip",ue&&r?.overflow==="clip"));let Ce=Se?$(Se):!0;if(T.replaceChildren(Dh(ne,ge?.language,ge?.path)),Se){let Be=ie.status!=="complete";ue&&Be&&r?.followOutput&&!A&&Ce?G(Se):Be||(A=!1),E(Se)}},Z=ne=>{b(),S(),P(),c.replaceChildren();let ge=v("div",dw);ge.innerHTML=d(ne),c.appendChild(ge)},J=ne=>{let ge=ne.id,ie=n.features?.artifacts,ue=fa(ne,ie,"status-body");if(C&&M===ge&&C.parentElement===c){let Se=C.querySelector(".persona-artifact-status-view-text");Se&&Tr(Se,ue,ie);return}b(),S(),c.replaceChildren();let oe=v("div","persona-artifact-status-view"),me=v("div","persona-artifact-status-view-text");Tr(me,ue,ie),oe.appendChild(me),c.appendChild(oe),C=oe,M=ge},fe=ne=>{l=ne;let ge=t.resolveViewMode?.(ne)??r?.viewMode??"rendered",ie=ne.artifactType==="markdown"?ne.file:void 0,ue=ne.status!=="complete";ue||ua(ne.id);let oe=ue?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof oe=="number";if(r?.streamingView==="status"&&ue){J(ne);return}if(ie){let Ce=cl(ne.markdown??""),Be=Mr(ie),ut=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ue&&ge==="rendered"&&ut&&(Be==="html"||Be==="svg")){let Qe=ne.id+"\0"+Ce;if(f&&g===Qe&&f.parentElement===c)return;S(),P(),b(),c.replaceChildren();let Ne=n.features?.artifacts?.filePreview,_e=Ne?.iframeSandbox??"allow-scripts";!Ne?.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(gt=>gt&>!=="allow-same-origin").join(" "));let Ae=uw(Ne?.loading),Me=v("div","persona-artifact-frame"),qe=v("iframe","persona-artifact-iframe");qe.setAttribute("sandbox",_e),qe.setAttribute("data-artifact-id",ne.id);let Jt=null;Ae.enabled&&Ae.injectReadySignal?(Jt=mw(),qe.srcdoc=Ce+gw(Jt)):qe.srcdoc=Ce,Me.appendChild(qe),c.appendChild(Me),Ae.enabled&&(m=yw(Me,qe,Jt,Ae,ne.id,n)),f=Me,g=Qe;return}if(b(),!ue&&Be==="markdown"&&ge==="rendered"){Z(Ce);return}Q(Ce,{language:ie.language,path:ie.path},ne,me);return}if(ne.artifactType==="markdown"){if(ge==="source"){b(),Q(ne.markdown??"",void 0,ne,me);return}Z(ne.markdown??"");return}b(),S(),P(),c.replaceChildren();let Se=ne.component?o.get(ne.component):void 0;if(Se){let Be={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let ut=Se(ne.props??{},Be);if(ut){c.appendChild(ut);return}}catch{}}c.appendChild(pw(ne))};return fe(e),{el:c,update(ne){fe(ne)}}}var $h=(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,m,b={}){g=c(g);let w=f(m),T=d(g,w,b),L=r(T,()=>l(T,g,w,A=>A.morphStyle==="innerHTML"?(a(A,g,w),Array.from(g.childNodes)):o(A,g,w)));return T.pantry.remove(),L}function o(g,m,b){let w=f(m);return a(g,w,b,m,m.nextSibling),Array.from(w.childNodes)}function r(g,m){if(!g.config.restoreFocus)return m();let b=document.activeElement;if(!(b instanceof HTMLInputElement||b instanceof HTMLTextAreaElement))return m();let{id:w,selectionStart:T,selectionEnd:L}=b,A=m();return w&&w!==document.activeElement?.getAttribute("id")&&(b=g.target.querySelector(`[id="${w}"]`),b?.focus()),b&&!b.selectionEnd&&L&&b.setSelectionRange(T,L),A}let a=(function(){function g(C,M,P,R=null,F=null){M instanceof HTMLTemplateElement&&P instanceof HTMLTemplateElement&&(M=M.content,P=P.content),R||(R=M.firstChild);for(let O of P.childNodes){if(R&&R!=F){let E=b(C,O,R,F);if(E){E!==R&&T(C,R,E),s(E,O,C),R=E.nextSibling;continue}}if(O instanceof Element){let E=O.getAttribute("id");if(C.persistentIds.has(E)){let G=L(M,E,R,C);s(G,O,C),R=G.nextSibling;continue}}let $=m(M,O,R,C);$&&(R=$.nextSibling)}for(;R&&R!=F;){let O=R;R=R.nextSibling,w(C,O)}}function m(C,M,P,R){if(R.callbacks.beforeNodeAdded(M)===!1)return null;if(R.idMap.has(M)){let F=document.createElement(M.tagName);return C.insertBefore(F,P),s(F,M,R),R.callbacks.afterNodeAdded(F),F}else{let F=document.importNode(M,!0);return C.insertBefore(F,P),R.callbacks.afterNodeAdded(F),F}}let b=(function(){function C(R,F,O,$){let E=null,G=F.nextSibling,Q=0,Z=O;for(;Z&&Z!=$;){if(P(Z,F)){if(M(R,Z,F))return Z;E===null&&(R.idMap.has(Z)||(E=Z))}if(E===null&&G&&P(Z,G)&&(Q++,G=G.nextSibling,Q>=2&&(E=void 0)),R.activeElementAndParents.includes(Z))break;Z=Z.nextSibling}return E||null}function M(R,F,O){let $=R.idMap.get(F),E=R.idMap.get(O);if(!E||!$)return!1;for(let G of $)if(E.has(G))return!0;return!1}function P(R,F){let O=R,$=F;return O.nodeType===$.nodeType&&O.tagName===$.tagName&&(!O.getAttribute?.("id")||O.getAttribute?.("id")===$.getAttribute?.("id"))}return C})();function w(C,M){if(C.idMap.has(M))S(C.pantry,M,null);else{if(C.callbacks.beforeNodeRemoved(M)===!1)return;M.parentNode?.removeChild(M),C.callbacks.afterNodeRemoved(M)}}function T(C,M,P){let R=M;for(;R&&R!==P;){let F=R;R=R.nextSibling,w(C,F)}return R}function L(C,M,P,R){let F=R.target.getAttribute?.("id")===M&&R.target||R.target.querySelector(`[id="${M}"]`)||R.pantry.querySelector(`[id="${M}"]`);return A(F,R),S(C,F,P),F}function A(C,M){let P=C.getAttribute("id");for(;C=C.parentNode;){let R=M.idMap.get(C);R&&(R.delete(P),R.size||M.idMap.delete(C))}}function S(C,M,P){if(C.moveBefore)try{C.moveBefore(M,P)}catch{C.insertBefore(M,P)}else C.insertBefore(M,P)}return g})(),s=(function(){function g(A,S,C){return C.ignoreActive&&A===document.activeElement?null:(C.callbacks.beforeNodeMorphed(A,S)===!1||(A instanceof HTMLHeadElement&&C.head.ignore||(A instanceof HTMLHeadElement&&C.head.style!=="morph"?p(A,S,C):(m(A,S,C),L(A,C)||a(C,A,S))),C.callbacks.afterNodeMorphed(A,S)),A)}function m(A,S,C){let M=S.nodeType;if(M===1){let P=A,R=S,F=P.attributes,O=R.attributes;for(let $ of O)T($.name,P,"update",C)||P.getAttribute($.name)!==$.value&&P.setAttribute($.name,$.value);for(let $=F.length-1;0<=$;$--){let E=F[$];if(E&&!R.hasAttribute(E.name)){if(T(E.name,P,"remove",C))continue;P.removeAttribute(E.name)}}L(P,C)||b(P,R,C)}(M===8||M===3)&&A.nodeValue!==S.nodeValue&&(A.nodeValue=S.nodeValue)}function b(A,S,C){if(A instanceof HTMLInputElement&&S instanceof HTMLInputElement&&S.type!=="file"){let M=S.value,P=A.value;w(A,S,"checked",C),w(A,S,"disabled",C),S.hasAttribute("value")?P!==M&&(T("value",A,"update",C)||(A.setAttribute("value",M),A.value=M)):T("value",A,"remove",C)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&S instanceof HTMLOptionElement)w(A,S,"selected",C);else if(A instanceof HTMLTextAreaElement&&S instanceof HTMLTextAreaElement){let M=S.value,P=A.value;if(T("value",A,"update",C))return;M!==P&&(A.value=M),A.firstChild&&A.firstChild.nodeValue!==M&&(A.firstChild.nodeValue=M)}}function w(A,S,C,M){let P=S[C],R=A[C];if(P!==R){let F=T(C,A,"update",M);F||(A[C]=S[C]),P?F||A.setAttribute(C,""):T(C,A,"remove",M)||A.removeAttribute(C)}}function T(A,S,C,M){return A==="value"&&M.ignoreActiveValue&&S===document.activeElement?!0:M.callbacks.beforeAttributeUpdated(A,S,C)===!1}function L(A,S){return!!S.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return g})();function l(g,m,b,w){if(g.head.block){let T=m.querySelector("head"),L=b.querySelector("head");if(T&&L){let A=p(T,L,g);return Promise.all(A).then(()=>{let S=Object.assign(g,{head:{block:!1,ignore:!0}});return w(S)})}}return w(g)}function p(g,m,b){let w=[],T=[],L=[],A=[],S=new Map;for(let M of m.children)S.set(M.outerHTML,M);for(let M of g.children){let P=S.has(M.outerHTML),R=b.head.shouldReAppend(M),F=b.head.shouldPreserve(M);P||F?R?T.push(M):(S.delete(M.outerHTML),L.push(M)):b.head.style==="append"?R&&(T.push(M),A.push(M)):b.head.shouldRemove(M)!==!1&&T.push(M)}A.push(...S.values());let C=[];for(let M of A){let P=document.createRange().createContextualFragment(M.outerHTML).firstChild;if(b.callbacks.beforeNodeAdded(P)!==!1){if("href"in P&&P.href||"src"in P&&P.src){let R,F=new Promise(function(O){R=O});P.addEventListener("load",function(){R()}),C.push(F)}g.appendChild(P),b.callbacks.afterNodeAdded(P),w.push(P)}}for(let M of T)b.callbacks.beforeNodeRemoved(M)!==!1&&(g.removeChild(M),b.callbacks.afterNodeRemoved(M));return b.head.afterHeadMorphed(g,{added:w,kept:L,removed:T}),C}let d=(function(){function g(C,M,P){let{persistentIds:R,idMap:F}=A(C,M),O=m(P),$=O.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes($))throw`Do not understand how to morph style ${$}`;return{target:C,newContent:M,config:O,morphStyle:$,ignoreActive:O.ignoreActive,ignoreActiveValue:O.ignoreActiveValue,restoreFocus:O.restoreFocus,idMap:F,persistentIds:R,pantry:b(),activeElementAndParents:w(C),callbacks:O.callbacks,head:O.head}}function m(C){let M=Object.assign({},t);return Object.assign(M,C),M.callbacks=Object.assign({},t.callbacks,C.callbacks),M.head=Object.assign({},t.head,C.head),M}function b(){let C=document.createElement("div");return C.hidden=!0,document.body.insertAdjacentElement("afterend",C),C}function w(C){let M=[],P=document.activeElement;if(P?.tagName!=="BODY"&&C.contains(P))for(;P&&(M.push(P),P!==C);)P=P.parentElement;return M}function T(C){let M=Array.from(C.querySelectorAll("[id]"));return C.getAttribute?.("id")&&M.push(C),M}function L(C,M,P,R){for(let F of R){let O=F.getAttribute("id");if(M.has(O)){let $=F;for(;$;){let E=C.get($);if(E==null&&(E=new Set,C.set($,E)),E.add(O),$===P)break;$=$.parentElement}}}}function A(C,M){let P=T(C),R=T(M),F=S(P,R),O=new Map;L(O,F,C,P);let $=M.__idiomorphRoot||M;return L(O,F,$,R),{persistentIds:F,idMap:O}}function S(C,M){let P=new Set,R=new Map;for(let{id:O,tagName:$}of C)R.has(O)?P.add(O):R.set(O,$);let F=new Set;for(let{id:O,tagName:$}of M)F.has(O)?P.add(O):R.get(O)===$&&F.add(O);for(let O of P)F.delete(O);return F}return g})(),{normalizeElement:c,normalizeParent:f}=(function(){let g=new WeakSet;function m(L){return L instanceof Document?L.documentElement:L}function b(L){if(L==null)return document.createElement("div");if(typeof L=="string")return b(T(L));if(g.has(L))return L;if(L instanceof Node){if(L.parentNode)return new w(L);{let A=document.createElement("div");return A.append(L),A}}else{let A=document.createElement("div");for(let S of[...L])A.append(S);return A}}class w{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],S=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;S&&S!=this.nextSibling;)A.push(S),S=S.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((S,C)=>{if(C instanceof Element){C.matches(A)&&S.push(C);let M=C.querySelectorAll(A);for(let P=0;P<M.length;P++)S.push(M[P])}return S},[])}insertBefore(A,S){return this.realParentNode.insertBefore(A,S)}moveBefore(A,S){return this.realParentNode.moveBefore(A,S)}get __idiomorphRoot(){return this.originalNode}}function T(L){let A=new DOMParser,S=L.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(S.match(/<\/html>/)||S.match(/<\/head>/)||S.match(/<\/body>/)){let C=A.parseFromString(L,"text/html");if(S.match(/<\/html>/))return g.add(C),C;{let M=C.firstChild;return M&&g.add(M),M}}else{let M=A.parseFromString("<body><template>"+L+"</template></body>","text/html").body.querySelector("template").content;return g.add(M),M}}return{normalizeElement:m,normalizeParent:b}})();return{morph:n,defaults:t}})();var hl=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;$h.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 jh=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Su={index:-1,draft:""};function Gh(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 Kh(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 Xh(){return new Map}function Jh(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Qh(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Yh(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Zh(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 yl(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function jn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function uo(e,t){return jn(e)-e.scrollTop<=t}function bl(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 xl(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 ey(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Mu(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function ty(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Cs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},bw=["pre","code","a","script","style"],vl=e=>({type:e?.type??Cs.type,placeholder:e?.placeholder??Cs.placeholder,speed:e?.speed??Cs.speed,duration:e?.duration??Cs.duration,buffer:e?.buffer??Cs.buffer}),oy=[{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"}],ws=new Map;for(let e of oy)ws.set(e.name,e);var Er=e=>{ws.set(e.name,e)},ku=e=>{oy.some(t=>t.name===e)||ws.delete(e)},Lu=()=>Array.from(ws.keys()),ha=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:ws.get(e)??null,Cl=(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},xw=(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},vw=(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},Tu=/\s/,Cw=(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},ww=(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(Tu.test(a[l])){let p=l;for(;p<a.length&&Tu.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&&!Tu.test(a[d]);)p.appendChild(xw(o,a[d],t,n.value)),n.value+=1,d+=1;s.appendChild(p),l=d}r.replaceChild(s,e)},Aw=(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(vw(o,p,t,n.value)),n.value+=1));r.replaceChild(s,e)},As=(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??bw).map(f=>f.toLowerCase())),s=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=s.nextNode();for(;p;)Cw(p,a)||l.push(p),p=s.nextNode();let d={value:o?.startIndex??0},c=t==="char"?ww:Aw;for(let f of l)c(f,n,d);return r.innerHTML},wl=(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},Ss=(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},ny=new WeakMap,Sw=(e,t)=>{if(!e.styles)return;let n=ny.get(t);if(n||(n=new Set,ny.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)},Eu=new WeakMap,Mw=(e,t)=>{if(!e.onAttach)return;let n=Eu.get(t);if(n||(n=new Map,Eu.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},ry=e=>{let t=Eu.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Al=(e,t)=>{Sw(e,t),Mw(e,t)};function Pu(e,t=Ut){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 Ms=0,Go=null;function Ru(e=document){if(Ms++,Ms===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Go={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,Ms=Math.max(0,Ms-1),Ms===0&&Go)){let n=e.body,o=e.defaultView??window;n.style.overflow=Go.originalOverflow,n.style.position=Go.originalPosition,n.style.top=Go.originalTop,n.style.width=Go.originalWidth,o.scrollTo(0,Go.scrollY),Go=null}}}var Ts={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},St=e=>(e?.launcher?.mountMode??"floating")==="docked",Ko=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",ln=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 Iu=e=>e==="followUp"?"follow-up":e,Wu=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},Tw=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},ay=new WeakSet,Ew=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,kw=e=>{Ew()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Hu=e=>{var A,S,C;let{item:t,index:n,surface:o,source:r,variant:a,streaming:s,config:l,plugins:p,chipsConfig:d,session:c,getTextarea:f,eventTarget:g}=e,m=o==="followUp",b=t.behavior,w=()=>{if(c.isStreaming())return;let M={suggestion:{...t},surface:o,source:r,behavior:b},P=g.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:M,bubbles:!0,composed:!0,cancelable:!0}));if(m&&g.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!P)return;for(let F of p)if(F.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:a,config:l})===!1)return;let R=f();if(b==="fill"){R.value=t.prompt,R.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),R.focus();return}R.value="",c.sendMessage(t.prompt)},T=()=>{let M=v("button",`persona-suggestion persona-suggestion--${a}`);if(M.type="button",M.disabled=s,M.dataset.suggestionId=t.id,M.dataset.emphasis=t.emphasis,M.dataset.behavior=b,a==="chip"&&(d?.fontFamily&&(M.style.fontFamily=Tw(d.fontFamily)),d?.fontWeight&&(M.style.fontWeight=d.fontWeight),d?.paddingX&&(M.style.paddingLeft=d.paddingX,M.style.paddingRight=d.paddingX),d?.paddingY&&(M.style.paddingTop=d.paddingY,M.style.paddingBottom=d.paddingY)),t.icon){let R=ae(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);R&&(R.classList.add("persona-suggestion__icon"),t.iconColor&&(R.style.color=t.iconColor),M.appendChild(R))}let P=v("span","persona-suggestion__copy");if(P.appendChild(ke("span",{className:"persona-suggestion__label",text:t.label})),t.description&&a!=="chip"&&P.appendChild(ke("span",{className:"persona-suggestion__description",text:t.description})),M.appendChild(P),a!=="chip"){let R=ae("arrow-right",16,"currentColor",1.8);R&&(R.classList.add("persona-suggestion__arrow"),M.appendChild(R))}return M.addEventListener("click",w),M},L=null;for(let M of p)if(M.renderSuggestion&&(L=M.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:a,streaming:s,config:l,defaultRenderer:T,select:w}),L))break;return L??(L=T()),(A=L.dataset).suggestionId||(A.suggestionId=t.id),(S=L.dataset).behavior||(S.behavior=b),(C=L.dataset).emphasis||(C.emphasis=t.emphasis),L instanceof HTMLButtonElement||L.setAttribute("aria-disabled",s?"true":"false"),L},Es=e=>{let t=[],n=[],o=null,r=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){a();return}let c=Math.max(0,e.scrollWidth-e.clientWidth);if(c<=1){a();return}let f=getComputedStyle(e).direction==="rtl",g=Math.min(c,Math.max(0,Math.abs(e.scrollLeft))),m=4,b=g<=m,w=g>=c-m,T=f?!w:!b,L=f?!b:!w;e.toggleAttribute("data-scroll-left",T),e.toggleAttribute("data-scroll-right",L)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&s();return}r=requestAnimationFrame(s)};e.addEventListener("scroll",l,{passive:!0});let p=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return p?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),p?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(c,f,g,m,b,w)=>{e.replaceChildren(),t.length=0,n.length=0;let T=w?.source??"config",L=w?.surface??(T==="config"?"starter":"followUp"),A=L==="followUp",S=w?.variant??"chip",C=w?.behavior??"send",M=w?.overflow??"wrap",P=w?.config??{},R=w?.plugins??[],F=typeof w?.maxItems=="number"?Math.max(0,Math.floor(w.maxItems)):void 0,O=A?"followUps":"starters";!ay.has(P)&&P.debug===!0&&S!=="chip"&&P.suggestions?.[O]?.overflow!==void 0&&(ay.add(P),console.info(`[persona] suggestions.${O}.overflow applies to the "chip" variant only; the "${S}" variant manages its own stacking.`));let $=fe=>fe.map(Wu).filter(ne=>ne!==null).map(ne=>({...ne,behavior:ne.behavior??C})),E=$(c??[]);R.forEach(fe=>{fe.transformSuggestions&&(E=$(fe.transformSuggestions({suggestions:E.map(ne=>({...ne})),surface:L,source:T,config:P})))});let G=F===void 0?E:E.slice(0,F);if(!G.length){e.hidden=!0,o=null,a();return}if(!A&&(m??f.getMessages()).some(ne=>ne.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Iu(L),e.dataset.variant=S,e.dataset.overflow=M;let Q=document.createDocumentFragment(),Z=f.isStreaming();G.forEach((fe,ne)=>{let ge=Hu({item:fe,index:ne,surface:L,source:T,variant:S,streaming:Z,config:P,plugins:R,chipsConfig:b,session:f,getTextarea:()=>g,eventTarget:e});Q.appendChild(ge),n.push(ge),[...ge instanceof HTMLButtonElement?[ge]:[],...Array.from(ge.querySelectorAll("button"))].forEach(ue=>{t.includes(ue)||(ue.disabled=Z,t.push(ue))})}),e.appendChild(Q),s(),l();let J=JSON.stringify({normalized:G,surface:L,variant:S,source:T});J!==o&&(o=J,kw(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:G.map(fe=>({...fe})),surface:L,source:T,variant:S},bubbles:!0,composed:!0})),A&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:G.map(fe=>fe.prompt)},bubbles:!0,composed:!0})))}}};var gn={"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 Lw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Sl=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Lw,buttonSize:r,iconSize:a="28px"}=t,s=e?.launcher??{},l=r??s.closeButtonSize??"32px",p=v("div",o),d=s.closeButtonTooltipText??"Close chat",c=s.closeButtonShowTooltip??!0,f=s.closeButtonIconName??"x",g=s.closeButtonIconText??"\xD7",m=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),b=ke("button",{className:Fn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:s.closeButtonColor||Xt.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:m?`${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}}),w=ae(f,a,"currentColor",1);return w?(w.style.display="block",b.appendChild(w)):b.textContent=g,p.appendChild(b),qt({anchor:b,trigger:p,text:()=>b.getAttribute("aria-label")??d,enabled:c}),{button:b,wrapper:p}},Pw="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ml=(e,t={})=>{let{wrapperClassName:n=Pw,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??"",f=s.borderWidth??"",g=s.borderColor??"",m=s.borderRadius??"",b=s.paddingX??"",w=s.paddingY??"",T=s.tooltipText??"Clear chat",L=s.showTooltip??!0,A=v("div",n),S=!!(f||g),C=ke("button",{className:Fn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!S&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:l,width:l,color:d||Xt.actionIconColor,backgroundColor:c||void 0,border:S?`${f||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:w||void 0,paddingBottom:w||void 0}}),M=ae(p,r,"currentColor",1);return M&&(M.style.display="block",C.appendChild(M)),A.appendChild(C),qt({anchor:C,trigger:A,text:()=>C.getAttribute("aria-label")??T,enabled:L}),{button:C,wrapper:A}};var Xt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Bu={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},Rw={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},fo=e=>{let{config:t,showClose:n=!0}=e,o=ke("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=ke("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 M=parseFloat(a)||24,P=ae(p,M*.6,"currentColor",1);P?d.replaceChildren(P):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let M=v("img");M.src=t.launcher.iconUrl,M.alt="",M.className="persona-rounded-xl persona-object-cover",M.style.height=a,M.style.width=a,d.replaceChildren(M)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=ke("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Xt.titleColor,...Bu}}),g=ke("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Xt.subtitleColor,...Rw}});c.append(f,g),l?o.append(c):o.append(d,c);let m=r.clearChat??{},b=m.enabled??!0,w=m.placement??"inline",T=null,L=null;if(b){let P=Ml(t,{wrapperClassName:w==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=P.button,L=P.wrapper,w==="top-right"&&(L.style.right="48px"),w==="inline"&&o.appendChild(L)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&w==="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}=Sl(t,{showClose:n,wrapperClassName:A});return s!=="top-right"&&o.appendChild(C),{header:o,iconHolder:d,headerTitle:f,headerSubtitle:g,closeButton:S,closeButtonWrapper:C,clearChatButton:T,clearChatButtonWrapper:L}},kr=(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 Du=e=>{let t=fo({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 Iw(e,t,n){if(t?.length)for(let o of t){let r=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0");if(r.type="button",r.style.height="32px",r.style.width="32px",r.style.color=Xt.actionIconColor,r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let a=ae(o.icon,16,"currentColor",2);a&&r.appendChild(a)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let a=v("div","persona-relative");a.appendChild(r);let s=$o({items:o.menuItems,onSelect:l=>n?.(l),anchor:a,position:"bottom-right"});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 Fu=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:a}=e,s=t?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.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=ul({label:s.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Xt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=v("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Xt.titleColor,Object.assign(c.style,Bu),c.textContent=s.title??"Chat Assistant",d.appendChild(c),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let C=r.onTitleClick;d.addEventListener("click",M=>{M.target.closest("button")||C()}),d.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),C())})}let S=r?.titleRowHover;S&&(d.style.borderRadius=S.borderRadius??"10px",d.style.padding=S.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=S.background??"",d.style.borderColor=S.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let f=s.closeButtonSize??"32px",g=v("div",""),m=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=s.closeButtonColor||Xt.actionIconColor;let b=s.closeButtonIconName??"x",w=ae(b,"28px","currentColor",1);w?m.appendChild(w):m.textContent="\xD7",o&&m.addEventListener("click",o),g.appendChild(m);let T=v("div","persona-flex persona-items-center persona-gap-1");p||Iw(T,r?.trailingActions,r?.onAction??a),T.appendChild(g),l.appendChild(T);let L=v("div");L.style.display="none";let A=v("span");return A.style.display="none",{header:l,iconHolder:L,headerTitle:c,headerSubtitle:A,closeButton:m,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Tl={default:Du,minimal:Fu},Ou=e=>Tl[e]??Tl.default,ya=(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=v("div");l.style.display="none";let p=v("span"),d=v("span"),c=v("button");c.style.display="none";let f=v("div");return f.style.display="none",{header:s,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",a=Ou(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 El=e=>{let t=v("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,r=()=>{let p=t.ownerDocument?.defaultView;if(!p?.getComputedStyle)return o;let d=p.getComputedStyle(t).lineHeight;if(!d||!d.trim().endsWith("px"))return o;let c=parseFloat(d);return Number.isFinite(c)&&c>0?c:o},a=`${n*o}px`;t.style.maxHeight=a,t.style.overflowY="auto";let s=()=>{let p=t.style.maxHeight;if(p!==a){let c=parseFloat(p);if(Number.isFinite(c)&&c>0)return c}let d=n*r();return a=`${d}px`,t.style.maxHeight=a,d},l=()=>{t.addEventListener("input",()=>{t.style.height="auto";let p=Math.min(t.scrollHeight,s());t.style.height=`${p}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:l}},kl=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,f=t.size??"40px",g=t.backgroundColor,m=t.textColor,b=v("div","persona-send-button-wrapper"),w=ke("button",{className:Fn("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&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:n&&g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),T=null,L=null;if(n){let C=parseFloat(t.iconSize??"")||Math.round((parseFloat(f)||24)*.5),M=t.iconStrokeWidth??2,P=m?.trim()||"currentColor";r?(T=ae(r,C,P,M),T?w.appendChild(T):w.textContent=o):w.textContent=o,L=ae(a,C,P,M)}else w.textContent=p;w.setAttribute("aria-label",s),b.appendChild(w),qt({anchor:w,trigger:b,text:()=>w.getAttribute("aria-label")??"",enabled:c});let A="send";return{button:w,wrapper:b,setMode:C=>{if(C===A)return;A=C;let M=C==="stop"?l:s;if(w.setAttribute("aria-label",M),n){if(T&&L){let P=C==="stop"?L:T;w.replaceChildren(P)}}else w.textContent=C==="stop"?d:p}}},Ll=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,f=t.iconColor??e?.sendButton?.textColor,g=v("div","persona-send-button-wrapper"),m=ke("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:f||"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}}),w=ae(l,d,f||"currentColor",1.5);w?m.appendChild(w):m.textContent="\u{1F3A4}",g.appendChild(m);let T=t.tooltipText??"Start voice recognition",L=t.showTooltip??!1;return qt({anchor:m,trigger:g,text:()=>m.getAttribute("aria-label")??T,enabled:L}),{button:m,wrapper:g}},Pl=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=v("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=v("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??co).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=v("div","persona-send-button-wrapper"),c=ke("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"}}),f=ae(a,p,"currentColor",1.5);f?c.appendChild(f):c.textContent="\u{1F4CE}",c.addEventListener("click",m=>{m.preventDefault(),r.click()}),d.appendChild(c);let g=t.buttonTooltipText??"Attach file";return qt({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??g}),{button:c,wrapper:d,input:r,previewsContainer:o}},Rl=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let a=t.idleText??"Online";if(t.idleLink){let s=v("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},Il=()=>ke("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Lr=e=>{let{config:t}=e,n=ke("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=Il(),r=ke("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}=El(t);s();let l=kl(t),p=Ll(t),d=Pl(t),c=Rl(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(a);let f=ke("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&g.append(d.wrapper),p&&m.append(p.wrapper),m.append(l.wrapper),f.append(g,m),r.append(f),r.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&b.target!==d?.button&&b.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:f,leftActions:g,rightActions:m,setSendButtonMode:l.setMode}};var sy=()=>{let e=ke("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=v("span","persona-pill-peek__icon"),n=ae("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),a=ae("chevron-up",16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,o,r),{root:e,textNode:o}},Wl=e=>{let{config:t}=e,n=ke("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Il(),r=Rl(t);r.style.display="none";let{textarea:a,attachAutoResize:s}=El(t);a.style.maxHeight="100px",s();let l=kl(t),p=Ll(t),d=Pl(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=ke("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=v("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&f.append(d.wrapper);let g=v("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&g.append(p.wrapper),g.append(l.wrapper),c.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&a.focus()}),d&&c.append(d.input),c.append(f,a,g),d&&n.append(d.previewsContainer),n.append(o,c,r);let m=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:m,leftActions:f,rightActions:g,setSendButtonMode:l.setMode}};var Ww=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}},Hw=(e,t)=>{if(!e)return null;let n=Ww(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Bw=(e,t)=>{let n=v("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},Dw=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Nu=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(":"))},_u=320,dy=320,Fw=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Ow=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Nw=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),_w=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Uw=e=>{if(!e||e.length===0)return null;let t=ke("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=ke("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),a=ae(n.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),o.appendChild(r),o.appendChild(ke("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},qw=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(ms(o.ref,{readonly:!0,render:t}))}return n},iy="\uE000",ly="\uE001",Vw=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),a=g=>`${iy}${r}:${g}${ly}`,s=t.map((g,m)=>g.kind==="text"?g.text:a(m)).join(""),l=n(s);if(!t.every((g,m)=>g.kind==="text"||l.includes(a(m)))){e.replaceChildren(qw(t,o));return}e.innerHTML=l;let d=new RegExp(`${iy}${r}:(\\d+)${ly}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),f=[];for(let g=c.nextNode();g;g=c.nextNode())f.push(g);for(let g of f){let m=g;for(let b=d.exec(m.data);b;b=d.exec(m.data)){let w=t[Number(b[1])],T=m.splitText(b.index);T.data=T.data.slice(b[0].length),w?.kind==="mention"&&T.parentNode?.insertBefore(ms(w.ref,{readonly:!0,render:o}),T),m=T}}},zw=(e,t,n)=>{if(e.length===0)return null;try{let o=v("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=v("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=`${_u}px`,d.style.maxHeight=`${dy}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}),Dw(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}},$w=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Nu(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${_u}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},jw=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Nu(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${_u}px`,r.style.maxHeight=`${dy}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}},Gw=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Nu(o.data))return;let r=v("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Pr=()=>{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},Uu=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Pr};if(t){let r=t(o);if(r!==null)return r}return Pr()},Kw=(e,t)=>{let n=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=v("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},cy=(e,t,n="div")=>{let o=v(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},ks=(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},qu=(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 b=v("div");return b.style.display="none",b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id),b}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],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],g=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${f} ${l==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let m=(b,w,T)=>{let L=Tt({icon:b,label:w,size:14,className:"persona-message-action-btn"});return L.setAttribute("data-action",T),L};return o&&g.appendChild(m("copy","Copy message","copy")),s&&g.appendChild(m("volume-2","Read aloud","read-aloud")),r&&g.appendChild(m("thumbs-up","Upvote","upvote")),a&&g.appendChild(m("thumbs-down","Downvote","downvote")),g},ba=(e,t,n,o,r,a)=>{let s=n??{},l=s.layout??"bubble",p=s.avatar,d=s.timestamp,c=p?.show??!1,f=d?.show??!1,g=p?.position??"left",m=d?.position??"below",b=ks(e.role,l),w=v("div",b.join(" "));w.id=`bubble-${e.id}`,w.setAttribute("data-message-id",e.id),w.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(w.style.backgroundColor="transparent",w.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(w.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",w.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(w.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",w.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Fw(e),L=e.content?.trim()??"",S=T.length>0&&L===Fi,C=vl(a?.widgetConfig?.features?.streamAnimation),M=a?.widgetConfig?.features?.streamAnimation?.plugins,P=e.role==="assistant"&&C.type!=="none"?ha(C.type,M):null,R=e.role==="assistant"&&P?.isAnimating?.(e)===!0,F=e.role==="assistant"&&P!==null&&(!!e.streaming||R);F&&P?.bubbleClass&&w.classList.add(P.bubbleClass);let O=document.createElement("div");O.classList.add("persona-message-content"),e.streaming&&O.classList.add("persona-content-streaming"),F&&P&&(P.containerClass&&O.classList.add(P.containerClass),O.style.setProperty("--persona-stream-step",`${C.speed}ms`),O.style.setProperty("--persona-stream-duration",`${C.duration}ms`));let $=F?Cl(e.content??"",C.buffer,P,e,!!e.streaming):e.content??"",E=()=>{let oe=t({text:$,message:e,streaming:!!e.streaming,raw:e.rawContent});return F&&P?.wrap==="char"?As(oe,"char",e.id,{skipTags:P.skipTags}):F&&P?.wrap==="word"?As(oe,"word",e.id,{skipTags:P.skipTags}):oe},G=null;if(S?(G=document.createElement("div"),G.innerHTML=E(),G.style.display="none",O.appendChild(G)):e.contentSegments?.length?Vw(O,e.contentSegments,oe=>t({text:oe,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):O.innerHTML=E(),F&&P?.useCaret&&!S&&L){let oe=wl(),me=O.querySelectorAll(".persona-stream-char, .persona-stream-word"),Se=me[me.length-1];if(Se?.parentNode)Se.parentNode.insertBefore(oe,Se.nextSibling);else{let Ce=O.lastElementChild;Ce?Ce.appendChild(oe):O.appendChild(oe)}}if(f&&m==="inline"&&e.createdAt){let oe=cy(e,d,"span");oe.classList.add("persona-timestamp-inline");let me=O.lastElementChild;me?me.appendChild(oe):O.appendChild(oe)}if(T.length>0){let oe=zw(T,!S&&!!L,()=>{S&&G&&(G.style.display="")});oe?w.appendChild(oe):S&&G&&(G.style.display="")}let Q=Ow(e);if(Q.length>0){let oe=$w(Q);oe&&w.appendChild(oe)}let Z=Nw(e);if(Z.length>0){let oe=jw(Z);oe&&w.appendChild(oe)}let J=_w(e);if(J.length>0){let oe=Gw(J);oe&&w.appendChild(oe)}let fe=e.contentSegments?.length?null:Uw(e.contextMentions);if(fe&&w.appendChild(fe),w.appendChild(O),f&&m==="below"&&e.createdAt){let oe=cy(e,d);oe.classList.add("persona-mt-1"),w.appendChild(oe)}let ne=e.role==="assistant"?Hw(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let oe=!!($&&$.trim()),me=C.placeholder==="skeleton",Se=me&&C.buffer==="line"&&oe;if(oe)Se&&w.appendChild(Ss());else if(me)w.appendChild(Ss());else{let Ce=Uu("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);Ce&&w.appendChild(Ce)}}if(ne&&e.stopReason&&!e.streaming&&(L||(O.style.display="none"),w.appendChild(Bw(e.stopReason,ne))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let oe=qu(e,o,r);w.appendChild(oe)}if(!c||e.role==="system")return w;let ie=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ue=Kw(p,e.role);return g==="right"||g==="left"&&e.role==="user"?ie.append(w,ue):ie.append(ue,w),ie},py=(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}):ba(e,t,n,o,r,a)};var Xw=40,Jw=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=ae(t.name,Xw);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(ke("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(ke("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},uy=(e,t,n={})=>{let o=ke("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("h2","persona-welcome-title"),a=v("p","persona-welcome-subtitle");return{host:ke("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},o,r,a,t),iconHolder:o,title:r,subtitle:a,starterSuggestions:t}},xa=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},Bl=(e,t)=>{e.title.textContent=t.title,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",Jw(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss)},Qw="data-persona-welcome-plugin",fy="data-persona-welcome-overlay",Hl="persona-welcome-overlay-active",Vu=new WeakMap,my=(e,t,n)=>{n.setAttribute(Qw,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(fy,""),e.classList.contains(Hl)||(Vu.set(e,e.scrollTop),e.classList.add(Hl),e.scrollTop=0)},gy=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(fy),e.classList.contains(Hl)&&(e.classList.remove(Hl),e.scrollTop=Vu.get(e)??e.scrollTop,Vu.delete(e))},hy=()=>{let e=ke("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Dl=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=ke("div",{className:ks("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(ke("div",{className:"persona-flex"},r)),e.hidden=!1},Yw=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,yy=(e,t)=>{if(Yw()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.animate([{opacity:"1",transform:"none"},{opacity:"0",transform:"translateY(-4px)"}],{duration:180,easing:"ease-out",fill:"forwards"}),o=!1,r=()=>{o||(o=!0,t(n))};return n.finished.then(r).catch(r),n};var Zw="Hello \u{1F44B}",eA="I can answer questions and help you get things done here.",by=new WeakSet,Mn=(e,t)=>!!e&&e[t]!==void 0,tA=(e,t)=>{!e||e.debug!==!0||!t.length||by.has(e)||(by.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},mo=e=>{let t=e?.welcome,n=e?.copy,o=Mn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":Mn(t,"dismiss")?t.dismiss:"never",a=[];return Mn(t,"title")&&Mn(n,"welcomeTitle")&&a.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Mn(t,"subtitle")&&Mn(n,"welcomeSubtitle")&&a.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Mn(t,"variant")&&Mn(n,"showWelcomeCard")&&a.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&Mn(t,"message")&&a.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&Mn(t,"dismiss")&&t.dismiss!=="on-first-message"&&a.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),tA(e,a),{title:Mn(t,"title")?t.title:n?.welcomeTitle??Zw,subtitle:Mn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??eA,icon:t?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:t?.message}},Xo=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var xy=e=>{let t=e?.launcher?.enabled??!0,n=St(e);if(Ko(e)){let c=e?.launcher?.composerBar??{},f=v("div","persona-widget-wrapper persona-fixed persona-transition");f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Ut);let g=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");g.style.width="100%",f.appendChild(g);let m=v("div","persona-widget-pill-root");return m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=c.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??Ut),{wrapper:f,panel:g,pillRoot:m}}if(n){let c=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),f=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(f),{wrapper:c,panel:f}}if(!t){let c=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),f=v("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,f.style.width="100%",c.appendChild(f),{wrapper:c,panel:f}}let r=e?.launcher??{},a=r.position&&gn[r.position]?gn[r.position]:gn["bottom-right"],s=v("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String(e?.launcher?.zIndex??Ut);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??mn;return l.style.width=d,l.style.maxWidth=d,s.appendChild(l),{wrapper:s,panel:l}},zu=e=>{let t=ke("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Iu(e)}});return t.hidden=!0,t},vy=(e,t)=>{let n=zu("starter"),o=uy(e,n,{flatShadow:St(e)}),r=mo(e);Bl(o,r),xa(t,o.host,Xo(r,e?.initialMessages));let a=hy();return Dl(a,r.message,e),{welcome:o,greetingHost:a}},nA=(e,t)=>{let n=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Sl(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 R=Ml(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=R.button,l=R.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=ke("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=ke("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{welcome:c,greetingHost:f}=vy(e,d),{host:g,title:m,subtitle:b}=c,w=c.starterSuggestions,T=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),L=zu("followUp"),A=qo(e,!0);A&&(T.style.maxWidth=A,T.style.marginLeft="auto",T.style.marginRight="auto",T.style.width="100%"),d.append(g,f,T,L);let S=ke("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"}}),C=Wl({config:e}),{root:M,textNode:P}=sy();return n.append(p,r,d,S),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:T,starterSuggestions:w,transcriptSuggestions:L,composerOverlay:S,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,welcomeHost:g,welcomeIconHolder:c.iconHolder,greetingHost:f,introTitle:m,introSubtitle:b,closeButton:o,closeButtonWrapper:r,clearChatButton:s,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:p,footer:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode,peekBanner:M,peekTextNode:P}},Cy=(e,t=!0)=>{if(Ko(e))return nA(e,t);let n=ke("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?ya(e,o,{showClose:t}):fo({config:e,showClose:t}),s=ke("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{welcome:l,greetingHost:p}=vy(e,s),{host:d,title:c,subtitle:f}=l,g=l.starterSuggestions,m=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),b=zu("followUp"),w=qo(e,!1);w&&(m.style.maxWidth=w,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),s.append(d,p,m,b);let T=Lr({config:e}),L=e?.layout?.showFooter!==!1;r?kr(n,a,e):(a.header.style.display="none",kr(n,a,e)),n.append(s);let A=ke("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 L||(T.footer.style.display="none"),n.append(T.footer),n.append(A),{container:n,body:s,messagesWrapper:m,starterSuggestions:g,transcriptSuggestions:b,composerOverlay:A,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:d,welcomeIconHolder:l.iconHolder,greetingHost:p,introTitle:c,introSubtitle:f,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode}};var $u=(e,t)=>{let n=v("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 Ka=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=Et(a),p=n.querySelector("[data-role='launcher-title']");if(p){let A=s.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let A=s.subtitle??"Here to help you get answers fast";c.textContent=A,c.setAttribute("title",A)}let d=n.querySelector(".persona-flex-col");d&&(s.textHidden||l?d.style.display="none":d.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(s.agentIconHidden)u.style.display="none";else{let A=s.agentIconSize??"40px";if(u.style.height=A,u.style.width=A,s.agentIconBackgroundColor?(u.style.backgroundColor=s.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",s.agentIconName){let C=parseFloat(A)||24,E=ae(s.agentIconName,C*.6,"var(--persona-text-inverse, #ffffff)",2);E?(u.appendChild(E),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 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 E=parseFloat(A)||24,R=Math.max(E-C,8),w=ae(s.callToActionIconName,R,"currentColor",2);w?f.appendChild(w):f.textContent=s.callToActionIconText??"\u2197"}else f.textContent=s.callToActionIconText??"\u2197"}let h=s.position&&In[s.position]?In[s.position]:In["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",k="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?k:`${S} ${h}`,l||(n.style.zIndex=String(s.zIndex??Gt));let P="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??P,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 uh=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=ch(e),a=ph(e,t),s={wrapper:n,panel:o,pillRoot:r},l={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,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:()=>Yp(e,n).element,onToggle:n});if(a)return{instance:null,element:a}}let r=Yp(e,n);return{instance:r,element:r.element}};var yC=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}},bC=(e,t)=>{if(!e)return null;let n=yC(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},xC=(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},vC=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},eu=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(":"))},tu=320,hh=320,CC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),wC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),AC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),SC=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),MC=e=>{if(!e||e.length===0)return null;let t=Ie("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Ie("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=x("span","persona-mention-chip-icon"),a=ae(n.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),o.appendChild(r),o.appendChild(Ie("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},TC=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Xa(o.ref,{readonly:!0,render:t}))}return n},fh="\uE000",mh="\uE001",EC=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),a=g=>`${fh}${r}:${g}${mh}`,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(TC(t,o));return}e.innerHTML=l;let c=new RegExp(`${fh}${r}:(\\d+)${mh}`),d=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let g=d.nextNode();g;g=d.nextNode())u.push(g);for(let g of u){let f=g;for(let h=c.exec(f.data);h;h=c.exec(f.data)){let S=t[Number(h[1])],k=f.splitText(h.index);k.data=k.data.slice(h[0].length),S?.kind==="mention"&&k.parentNode?.insertBefore(Xa(S.ref,{readonly:!0,render:o}),k),f=k}}},kC=(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 c=x("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=`${tu}px`,c.style.maxHeight=`${hh}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}),vC(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}},LC=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(!eu(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=`${tu}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},PC=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(!eu(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=`${tu}px`,r.style.maxHeight=`${hh}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}},RC=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(!eu(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}},fr=()=>{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},nu=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:fr};if(t){let r=t(o);if(r!==null)return r}return fr()},IC=(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},gh=(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},ou=(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},ru=(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",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=x("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${d} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(h,S,k)=>{let P=Mt({icon:h,label:S,size:14,className:"persona-message-action-btn"});return P.setAttribute("data-action",k),P};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},Yr=(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=ou(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=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, 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-container))",S.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=CC(e),P=e.content?.trim()??"",A=k.length>0&&P===bi,C=tl(a?.widgetConfig?.features?.streamAnimation),E=a?.widgetConfig?.features?.streamAnimation?.plugins,R=e.role==="assistant"&&C.type!=="none"?Xr(C.type,E):null,w=e.role==="assistant"&&R?.isAnimating?.(e)===!0,H=e.role==="assistant"&&R!==null&&(!!e.streaming||w);H&&R?.bubbleClass&&S.classList.add(R.bubbleClass);let F=document.createElement("div");F.classList.add("persona-message-content"),e.streaming&&F.classList.add("persona-content-streaming"),H&&R&&(R.containerClass&&F.classList.add(R.containerClass),F.style.setProperty("--persona-stream-step",`${C.speed}ms`),F.style.setProperty("--persona-stream-duration",`${C.duration}ms`));let K=H?nl(e.content??"",C.buffer,R,e,!!e.streaming):e.content??"",D=()=>{let Z=t({text:K,message:e,streaming:!!e.streaming,raw:e.rawContent});return H&&R?.wrap==="char"?as(Z,"char",e.id,{skipTags:R.skipTags}):H&&R?.wrap==="word"?as(Z,"word",e.id,{skipTags:R.skipTags}):Z},q=null;if(A?(q=document.createElement("div"),q.innerHTML=D(),q.style.display="none",F.appendChild(q)):e.contentSegments?.length?EC(F,e.contentSegments,Z=>t({text:Z,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):F.innerHTML=D(),H&&R?.useCaret&&!A&&P){let Z=ol(),he=F.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ce=he[he.length-1];if(Ce?.parentNode)Ce.parentNode.insertBefore(Z,Ce.nextSibling);else{let ve=F.lastElementChild;ve?ve.appendChild(Z):F.appendChild(Z)}}if(u&&f==="inline"&&e.createdAt){let Z=gh(e,c,"span");Z.classList.add("persona-timestamp-inline");let he=F.lastElementChild;he?he.appendChild(Z):F.appendChild(Z)}if(k.length>0){let Z=kC(k,!A&&!!P,()=>{A&&q&&(q.style.display="")});Z?S.appendChild(Z):A&&q&&(q.style.display="")}let Y=wC(e);if(Y.length>0){let Z=LC(Y);Z&&S.appendChild(Z)}let de=AC(e);if(de.length>0){let Z=PC(de);Z&&S.appendChild(Z)}let be=SC(e);if(be.length>0){let Z=RC(be);Z&&S.appendChild(Z)}let pe=e.contentSegments?.length?null:MC(e.contextMentions);if(pe&&S.appendChild(pe),S.appendChild(F),u&&f==="below"&&e.createdAt){let Z=gh(e,c);Z.classList.add("persona-mt-1"),S.appendChild(Z)}let te=e.role==="assistant"?bC(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Z=!!(K&&K.trim()),he=C.placeholder==="skeleton",Ce=he&&C.buffer==="line"&&Z;if(Z)Ce&&S.appendChild(ss());else if(he)S.appendChild(ss());else{let ve=nu("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);ve&&S.appendChild(ve)}}if(te&&e.stopReason&&!e.streaming&&(P||(F.style.display="none"),S.appendChild(xC(e.stopReason,te))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Z=ru(e,o,r);S.appendChild(Z)}if(!d||e.role==="system")return S;let oe=x("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),le=IC(p,e.role);return g==="right"||g==="left"&&e.role==="user"?oe.append(S,le):oe.append(le,S),oe},yh=(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}):Yr(e,t,n,o,r,a)};var Zr=new Set,WC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),HC=(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
|
-
`):""},su=(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)"},FC=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",a=DC(e,o?.previewMaxLines??3),s=n?$m(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=Md(n,p.activeTextTemplate,c):!l&&p.completeTextTemplate&&(c=Md(n,p.completeTextTemplate,c)),{summary:c,previewText:a,isActive:l}},xh=(e,t,n)=>{let o=ea.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=ae(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")},iu=(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&&ea.has(e.id),{summary:p,previewText:c,isActive:d}=FC(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=za(n),D},k=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:c,collapsedMode:a.collapsedMode??"tool-call",isActive:d,config:t??{},elapsed:za(n),createElapsedElement:S});typeof k=="string"&&k.trim()?(f.textContent=k,g.appendChild(f)):k instanceof HTMLElement?g.appendChild(k):(f.textContent=p,g.appendChild(f));let P=a.loadingAnimation??"none",M=o.activeTextTemplate,A=o.completeTextTemplate,C=d?M:A,E=k instanceof HTMLElement,R=(D,q)=>{f.textContent="";let Y=n.name?.trim()||"tool",de=ui(D,Y),be=0;for(let pe of de){let te=pe.styles.length>0?(()=>{let me=x("span",pe.styles.map(oe=>`persona-tool-text-${oe}`).join(" "));return f.appendChild(me),me})():f;if(pe.isDuration&&d)te.appendChild(S());else{let me=pe.isDuration?za(n):pe.text;q?be=Ho(te,me,be):te.appendChild(document.createTextNode(me))}}};if(!E)if(d&&P!=="none"){let D=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),P==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),C&&R(C,!1);else if(f.classList.add(`persona-tool-loading-${P}`),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),P==="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)R(C,!0);else{let q=f.textContent||p;f.textContent="",Ho(f,q,0)}}else C&&R(C,!1);let w=null;if(s){w=x("div","persona-flex persona-items-center");let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",q=ae(l?"chevron-up":"chevron-down",16,D,2);q?w.appendChild(q):w.textContent=l?"Hide":"Show";let Y=x("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Y.append(w),u.append(g,Y)}else u.append(g);let H=x("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","tool"),H.style.display="none",H.style.whiteSpace="pre-wrap",!l&&d&&a.activePreview&&c){let D=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:c,isActive:d,config:t??{}});BC(H,D)||(H.textContent=c),H.style.display=""}if(!l&&d&&a.activeMinHeight&&(r.style.minHeight=a.activeMinHeight),!s)return r.append(u,H),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"),q=x("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(q.style.color=o.labelTextColor),q.textContent="Arguments";let Y=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");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",su(Y,o),Y.textContent=Eo(n.args),D.append(q,Y),F.appendChild(D)}if(n.chunks&&n.chunks.length){let D=x("div","persona-space-y-1"),q=x("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(q.style.color=o.labelTextColor),q.textContent="Activity";let Y=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");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",su(Y,o),Y.textContent=n.chunks.join(""),D.append(q,Y),F.appendChild(D)}if(n.status==="complete"&&n.result!==void 0){let D=x("div","persona-space-y-1"),q=x("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(q.style.color=o.labelTextColor),q.textContent="Result";let Y=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");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",su(Y,o),Y.textContent=Eo(n.result),D.append(q,Y),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"),w){w.innerHTML="";let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",q=ae(l?"chevron-up":"chevron-down",16,D,2);q?w.appendChild(q):w.textContent=l?"Hide":"Show"}F.style.display=l?"":"none",H.style.display=l?"none":H.textContent||H.childNodes.length?"":"none"})(),r.append(u,H,F),r};var mr=new Map,hl=e=>{let n=(e.startsWith(Ln)?e.slice(Ln.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)},vh=e=>e?.approval!==!1?e?.approval:void 0,Ch=(e,t)=>{let n=vh(t)?.detailsDisplay??"collapsed";return mr.get(e)??n==="expanded"},wh=(e,t,n)=>{let o=vh(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=ae(t?"chevron-up":"chevron-down",14,"currentColor",2);s&&a.appendChild(s)}},Ah=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let a=Ch(e,n);wh(o,a,n),r.style.display=a?"":"none"};var yl=(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",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=ae(p,20,c,2);d&&l.appendChild(d);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 w=x("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 S=n.toolType==="webmcp"||n.toolName.startsWith(Ln)?Oa(n.toolName):void 0,k=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...S?{displayTitle:S}:{},...n.reason?{reason:n.reason}:{}}),P=!n.toolName,M=k||(P?n.description:`The assistant wants to use \u201C${S??hl(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 w=x("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 H=x("span","persona-font-medium");H.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(H),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let C=o?.detailsDisplay??"collapsed",E=!!n.description&&!P,R=E||!!n.parameters;if(C!=="hidden"&&R){let w=Ch(e.id,t),H=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");H.type="button",H.setAttribute("data-expand-header","true"),H.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(H.style.color=o.descriptionColor);let F=x("span");F.setAttribute("data-approval-details-label","true");let K=x("span","persona-inline-flex persona-items-center");K.setAttribute("data-approval-details-chevron","true"),H.append(F,K),wh(H,w,t),u.appendChild(H);let D=x("div");if(D.setAttribute("data-approval-details","true"),D.style.display=w?"":"none",E){let q=x("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(q.style.color=o.descriptionColor),q.textContent=n.description,D.appendChild(q)}if(n.parameters){let q=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&&(q.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(q.style.color=o.parameterTextColor),q.style.fontSize="0.75rem",q.style.lineHeight="1rem",q.textContent=Eo(n.parameters),D.appendChild(q)}u.appendChild(D)}if(r){let w=x("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let H=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");H.type="button",H.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",H.style.color=o?.approveButtonTextColor??"#ffffff",H.setAttribute("data-approval-action","approve");let F=ae("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);F&&(F.style.marginRight="4px",H.appendChild(F));let K=document.createTextNode(o?.approveLabel??"Approve");H.appendChild(K);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 q=ae("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);q&&(q.style.marginRight="4px",D.appendChild(q));let Y=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(Y),w.append(H,D),u.appendChild(w)}return s.append(l,u),a.appendChild(s),a};function OC(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Sh(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??OC(t),g=!1,f=null,h=()=>{if(!g)return;let P=t.getBoundingClientRect();n.style.position="fixed",a&&(n.style.minWidth=`${P.width}px`),s&&(n.style.maxWidth=`${P.width}px`);let M=n.getBoundingClientRect(),A=l?.()??null,C=A!=null?P.top+A:P.top,E=o==="top-start"||o==="top-end"?C-r-M.height:P.bottom+r,w=o==="bottom-end"||o==="top-end"?P.right-M.width:P.left,H=s?.()??null;if(H!=null){let F=Math.max(P.left,P.right-M.width);w=Math.min(Math.max(P.left+H,P.left),F)}n.style.top=`${E}px`,n.style.left=`${w}px`},S=()=>{g&&(g=!1,f&&(f(),f=null),n.remove())},k=()=>{if(g)return;g=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),h();let P=(t.ownerDocument??document).defaultView??window,M=t.ownerDocument??document,A=()=>{if(!t.isConnected){S(),d?.("anchor-removed");return}h()},C=R=>{let w=typeof R.composedPath=="function"?R.composedPath():[];w.includes(n)||w.includes(t)||(S(),d?.("outside"))},E=P.setTimeout(()=>{M.addEventListener("pointerdown",C,!0)},0);P.addEventListener("scroll",A,!0),P.addEventListener("resize",A),f=()=>{P.clearTimeout(E),M.removeEventListener("pointerdown",C,!0),P.removeEventListener("scroll",A,!0),P.removeEventListener("resize",A)},c?.()};return{get isOpen(){return g},open:k,close:S,toggle:()=>g?S():k(),reposition:h,destroy:S}}function Mh(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var NC=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Th=(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))},gr=(e,t)=>{Th(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)},_C=e=>e?.approval!==!1?e?.approval:void 0,UC=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return mr.get(e)??n==="expanded"},lu=e=>{let t=x("span","persona-approval-kbd");return t.textContent=e,t},qC=(e,t)=>{let n=x("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Ln)?Oa(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??hl(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},VC=e=>{let t=x("div","persona-approval-resolved"),n=ae("ban",15,"currentColor",2);n&&t.appendChild(n);let o=x("span","persona-approval-resolved-name");return o.textContent=e.toolName?hl(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},zC=(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",c=!!n.description&&p!=="hidden",d=n.parameters!=null&&p!=="hidden",u=c||d,g=u&&UC(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 k=x("span","persona-approval-logo"),P=ae("shield-check",16,"currentColor",2);P&&k.appendChild(P),S.appendChild(k);let M=qC(n,o);if(u){let H=x("span","persona-approval-toggle");H.setAttribute("aria-hidden","true");let F=ae("chevron-down",14,"currentColor",2);F&&H.appendChild(F),M.append(" "),M.appendChild(H)}S.appendChild(M),l.appendChild(S);let A=x("div","persona-approval-body");if(u){let H=x("div","persona-approval-details");if(H.setAttribute("data-role","params"),H.hidden=!g,c){let F=x("p","persona-approval-desc");o?.descriptionColor&&(F.style.color=o.descriptionColor),F.textContent=n.description,H.appendChild(F)}if(d){let F=x("pre","persona-approval-params");o?.parameterBackgroundColor&&(F.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(F.style.color=o.parameterTextColor),F.textContent=Eo(n.parameters),H.appendChild(F)}A.appendChild(H)}if(n.reason){let H=x("p","persona-approval-reason");o?.reasonColor?H.style.color=o.reasonColor:o?.descriptionColor&&(H.style.color=o.descriptionColor);let F=x("span","persona-approval-reason-label");F.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,H.append(F,document.createTextNode(n.reason)),A.appendChild(H)}let C=x("div","persona-approval-actions"),E=null,R=H=>{o?.approveButtonColor&&(H.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(H.style.color=o.approveButtonTextColor)},w=x("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 H=x("div","persona-approval-split"),F=x("button","persona-approval-primary");F.type="button",F.setAttribute("data-action","always"),R(F),F.append(o?.approveLabel??"Always allow",lu("\u23CE"));let K=x("button","persona-approval-caret");K.type="button",K.setAttribute("data-action","toggle-menu"),K.setAttribute("aria-label","More options"),R(K);let D=ae("chevron-down",15,"currentColor",2);D&&K.appendChild(D),H.append(F,K),C.append(H,w),w.append(lu("Esc"));let q=x("div","persona-approval-menu"),Y=x("button","persona-approval-menu-item");Y.type="button",Y.append("Allow once",lu("\u2318\u23CE")),q.appendChild(Y),E=Sh({anchor:H,content:q,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,E),Y.addEventListener("click",()=>{gr(e,t.id),r()})}else{let H=x("button","persona-approval-primary persona-approval-primary--solo");H.type="button",H.setAttribute("data-action","allow"),R(H),H.append(o?.approveLabel??"Allow"),C.append(H,w)}return A.appendChild(C),l.appendChild(A),l.addEventListener("click",H=>{let F=H.target instanceof Element?H.target.closest("[data-action]"):null;if(!F)return;let K=F.getAttribute("data-action");if(K==="toggle-params"){let D=l.querySelector('[data-role="params"]');if(D){let q=D.hidden;D.hidden=!q,S.setAttribute("aria-expanded",q?"true":"false"),S.setAttribute("aria-label",q?h:f),mr.set(t.id,q)}return}if(K==="toggle-menu"){E?.toggle();return}if(K==="always"){gr(e,t.id),r({remember:!0});return}if(K==="allow"){gr(e,t.id),r();return}if(K==="deny"){gr(e,t.id),a();return}}),l},Eh=()=>{let e=NC();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=_C(s);if(l.status!=="pending"){if(gr(e,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return VC(l)}Th(e,o.id);let c=p?.enableAlwaysAllow===!0,d=zC(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=>{Mh(g)||o.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),gr(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()])gr(e,o);e.latestPendingApprovalId=null}}};var ds=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 cs=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 $C=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),jC=new Set(["step_start","execution_start"]),GC=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),KC=new Set(["step_complete","agent_turn_complete"]),XC=new Set(["flow_complete","agent_complete"]),kh=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Ph=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,hr=(e,t)=>{let n=e[t];return Ph(n)?n:void 0};function du(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function bl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function JC(e,t){return typeof t.type=="string"?t.type:e}function QC(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 YC(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=hr(e,"result"),n=[hr(e,"tokens"),hr(e,"totalTokens"),t?hr(t,"tokens"):void 0,hr(e,"usage"),t?hr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=mn(o.output)??mn(o.outputTokens)??mn(o.completionTokens);if(r!==void 0)return r}return mn(e.outputTokens)??mn(e.completionTokens)??(t?mn(t.outputTokens)??mn(t.completionTokens):void 0)}function ZC(e){let t=hr(e,"result");return mn(e.executionTime)??mn(e.executionTimeMs)??mn(e.execution_time)??mn(e.duration)??(t?mn(t.executionTime)??mn(t.executionTimeMs):void 0)}function ew(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var ps=class{constructor(t=ew){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:bl(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(!Ph(n)){kh.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=JC(t,n),r=this.now();if($C.has(o)){this.startRun(r);return}if(jC.has(o)){this.run||this.startRun(r);return}if(GC.has(o)){if(!YC(o,n))return;let a=QC(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+du(s.visibleCharCount),p=r-s.firstDeltaAt;this.metric={status:"running",tokensPerSecond:bl(l,p),outputTokens:l,durationMs:p,source:s.exactOutputTokens>0?"usage":"estimate"};return}if(KC.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+du(a.visibleCharCount),c=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:bl(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+du(a.visibleCharCount),p=s!==void 0||a.exactOutputTokens>0?"usage":"estimate",c=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:bl(l,c),outputTokens:l,durationMs:c,source:p},this.run=null;return}if(kh.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:ZC(n)??o-t.startedAt}};function ta(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var tw={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)"}},nw={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},ow=["flowName","stepName","reasoningText","text","name","tool","toolName"],rw=100;function aw(e,t){let n={...tw,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return nw}function sw(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function iw(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 lw(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 dw(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 cw(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 pw(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function uw(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 fw(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 cu(e,t,n,o,r,a,s,l){let p=r.has(e.id),c=x("div","persona-border-b persona-border-persona-divider persona-text-xs");ta(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=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=ae(p?"chevron-down":"chevron-right","14px","currentColor",2);S&&h.appendChild(S);let k=x("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),P=o.timestampFormat??"relative";k.textContent=P==="relative"?sw(e.timestamp,n):iw(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=aw(e.type,o.badgeColors),C=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");C.style.backgroundColor=A.bg,C.style.color=A.text,C.style.borderColor=A.text+"50",C.textContent=e.type;let E=o.descriptionFields??ow,R=lw(e.payload,E),w=null;R&&(w=x("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=R);let H=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"),K=ae("clipboard","12px","currentColor",1.5);return K&&F.appendChild(K),F.addEventListener("click",async D=>{D.stopPropagation(),await dw(cw(e)),F.innerHTML="";let q=ae("check","12px","currentColor",1.5);q&&F.appendChild(q),setTimeout(()=>{F.innerHTML="";let Y=ae("clipboard","12px","currentColor",1.5);Y&&F.appendChild(Y)},1500)}),f.appendChild(h),f.appendChild(k),M&&f.appendChild(M),f.appendChild(C),w&&f.appendChild(w),f.appendChild(H),f.appendChild(F),g.appendChild(f),p&&g.appendChild(fw(e,s,l)),g}}function Rh(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:a=[],getThroughput:s}=e,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,c=l?.iconName??"arrow-down",d=l?.label??"",u=r?.features?.eventStream??{},g=a.find(h=>h.renderEventStreamView);if(g?.renderEventStreamView&&r){let h=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(h)return{element:h,update:()=>{},destroy:()=>{}}}return f();function f(){let h=u.classNames,S=x("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ta(S,h?.panel);let k=[],P="",M="",A=null,C=[],E={},R=0,w=Yi(),H=0,F=0,K=!1,D=null,q=!1,Y=0,de=new Set,be=new Map,pe="",te="",me=null,oe,le,Z,he,Ce=null,ve=null,we=null;function Ee(){let O=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(ta(J,h?.headerBar),s){ve=x("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ve.style.cursor="help",Ce=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"),Ce.textContent="-- tok/s",we=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"),we.style.display="none",we.style.pointerEvents="none";let Fe=ve,Dt=we,vt=()=>{if(!Dt.textContent)return;let Cs=Fe.getBoundingClientRect(),ao=O.getBoundingClientRect();Dt.style.left=`${Cs.left-ao.left}px`,Dt.style.top=`${Cs.bottom-ao.top+4}px`,Dt.style.display="block"},Jt=()=>{Dt.style.display="none"};ve.addEventListener("mouseenter",vt),ve.addEventListener("mouseleave",Jt),ve.appendChild(Ce)}let se=x("div","persona-flex-1");oe=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 Te=x("option","");Te.value="",Te.textContent="All events (0)",oe.appendChild(Te),le=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"),le.type="button",le.title="Copy All";let ot=ae("clipboard-copy","12px","currentColor",1.5);ot&&le.appendChild(ot);let nt=x("span","persona-event-copy-all persona-text-xs");nt.textContent="Copy All",le.appendChild(nt),ve&&J.appendChild(ve),J.appendChild(se),J.appendChild(oe),J.appendChild(le);let Ue=x("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ta(Ue,h?.searchBar);let Ye=ae("search","14px","var(--persona-muted, #9ca3af)",1.5),G=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");Ye&&G.appendChild(Ye),Z=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"),ta(Z,h?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",he=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"),he.type="button",he.style.display="none";let qe=ae("x","12px","currentColor",2);return qe&&he.appendChild(qe),Ue.appendChild(G),Ue.appendChild(Z),Ue.appendChild(he),O.appendChild(J),O.appendChild(Ue),we&&O.appendChild(we),O}let ke,Se=a.find(O=>O.renderEventStreamToolbar);Se?.renderEventStreamToolbar&&r?ke=Se.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ee(),eventCount:t.getSize(),filteredCount:0,onFilterChange:J=>{P=J,Qe(),ie()},onSearchChange:J=>{M=J,Qe(),ie()}})??Ee():ke=Ee();let Ge=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");Ge.style.display="none";function ze(){if(!s||!Ce||!ve)return;let O=s(),J=pw(O);Ce.textContent=J;let se=uw(O);we&&(we.textContent=se,se||(we.style.display="none")),ve.setAttribute("aria-label",se?`Throughput: ${J}, ${se}`:`Throughput: ${J}`)}let Me=x("div","persona-flex-1 persona-min-h-0 persona-relative"),Re=x("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Re.style.height="100%";let Ke=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");ta(Ke,h?.scrollIndicator),Ke.style.display="none",Ke.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false");let Bt=ae(c,"14px","currentColor",2);Bt&&Ke.appendChild(Bt);let Wt=x("span","");Wt.textContent=d,Ke.appendChild(Wt);let Kt=x("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(Re),Me.appendChild(Kt),Me.appendChild(Ke),S.setAttribute("tabindex","0"),S.appendChild(ke),S.appendChild(Ge),S.appendChild(Me);function wt(){let O=t.getAll(),J={};for(let Ue of O)J[Ue.type]=(J[Ue.type]||0)+1;let se=Object.keys(J).sort(),Te=se.length!==C.length||!se.every((Ue,Ye)=>Ue===C[Ye]),ye=!Te&&se.some(Ue=>J[Ue]!==E[Ue]),ot=O.length!==Object.values(E).reduce((Ue,Ye)=>Ue+Ye,0);if(!Te&&!ye&&!ot||(C=se,E=J,!oe))return;let nt=oe.value;if(oe.options[0].textContent=`All events (${O.length})`,Te){for(;oe.options.length>1;)oe.remove(1);for(let Ue of se){let Ye=x("option","");Ye.value=Ue,Ye.textContent=`${Ue} (${J[Ue]||0})`,oe.appendChild(Ye)}nt&&se.includes(nt)?oe.value=nt:nt&&(oe.value="",P="")}else for(let Ue=1;Ue<oe.options.length;Ue++){let Ye=oe.options[Ue];Ye.textContent=`${Ye.value} (${J[Ye.value]||0})`}}function De(){let O=t.getAll();if(P&&(O=O.filter(J=>J.type===P)),M){let J=M.toLowerCase();O=O.filter(se=>se.type.toLowerCase().includes(J)||se.payload.toLowerCase().includes(J))}return O}function ue(){return P!==""||M!==""}function Qe(){R=0,H=0,w.resume(),Ke.style.display="none"}function He(O){de.has(O)?de.delete(O):de.add(O),me=O;let J=Re.scrollTop,se=w.isFollowing();q=!0,w.pause(),ie(),Re.scrollTop=J,se&&w.resume(),q=!1}function fe(){return Fo(Re,50)}function ie(){F=Date.now(),K=!1,ze(),wt();let O=t.getEvictedCount();O>0?(Ge.textContent=`${O.toLocaleString()} older events truncated`,Ge.style.display=""):Ge.style.display="none",k=De();let J=k.length,se=t.getSize()>0;J===0&&se&&ue()?(Kt.textContent=M?`No events matching '${M}'`:"No events matching filter",Kt.style.display="",Re.style.display="none"):(Kt.style.display="none",Re.style.display=""),le&&(le.title=ue()?`Copy Filtered (${J})`:"Copy All"),p&&!w.isFollowing()&&J>R&&(H+=J-R,Wt.textContent=d?`${d}${H>0?` (${H})`:""}`:"",Ke.style.display=""),R=J;let Te=t.getAll(),ye=Te.length>0?Te[0].timestamp:0,ot=new Set(k.map(Ye=>Ye.id));for(let Ye of de)ot.has(Ye)||de.delete(Ye);let nt=P!==pe||M!==te,Ue=be.size===0&&k.length>0;if(nt||Ue||k.length===0){Re.innerHTML="",be.clear();let Ye=document.createDocumentFragment();for(let G=0;G<k.length;G++){let qe=cu(k[G],G,ye,u,de,He,a,r);be.set(k[G].id,qe),Ye.appendChild(qe)}Re.appendChild(Ye),pe=P,te=M,me=null}else{if(me!==null){let G=be.get(me);if(G&&G.parentNode===Re){let qe=k.findIndex(Fe=>Fe.id===me);if(qe>=0){let Fe=cu(k[qe],qe,ye,u,de,He,a,r);Re.insertBefore(Fe,G),G.remove(),be.set(me,Fe)}}me=null}let Ye=new Set(k.map(G=>G.id));for(let[G,qe]of be)Ye.has(G)||(qe.remove(),be.delete(G));for(let G=0;G<k.length;G++){let qe=k[G];if(!be.has(qe.id)){let Fe=cu(qe,G,ye,u,de,He,a,r);be.set(qe.id,Fe),Re.appendChild(Fe)}}}w.isFollowing()&&(Re.scrollTop=Re.scrollHeight)}function We(){if(Date.now()-F>=rw){D!==null&&(cancelAnimationFrame(D),D=null),ie();return}K||(K=!0,D=requestAnimationFrame(()=>{D=null,ie()}))}let Xt=(O,J)=>{if(!le)return;le.innerHTML="";let se=ae(O,"12px","currentColor",1.5);se&&le.appendChild(se);let Te=x("span","persona-text-xs");Te.textContent="Copy All",le.appendChild(Te),setTimeout(()=>{le.innerHTML="";let ye=ae("clipboard-copy","12px","currentColor",1.5);ye&&le.appendChild(ye);let ot=x("span","persona-text-xs");ot.textContent="Copy All",le.appendChild(ot),le.disabled=!1},J)},ut=async()=>{if(le){le.disabled=!0;try{let O;ue()?O=k:n?(O=await n(),O.length===0&&(O=t.getAll())):O=t.getAll();let J=O.map(se=>{try{return JSON.parse(se.payload)}catch{return se.payload}});await navigator.clipboard.writeText(JSON.stringify(J,null,2)),Xt("check",1500)}catch{Xt("x",1500)}}},ht=()=>{oe&&(P=oe.value,Qe(),ie())},j=()=>{!Z||!he||(he.style.display=Z.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{M=Z.value,Qe(),ie()},150))},T=()=>{!Z||!he||(Z.value="",M="",he.style.display="none",A&&clearTimeout(A),Qe(),ie())},$=()=>{if(q)return;let O=Re.scrollTop,{action:J,nextLastScrollTop:se}=Zi({following:w.isFollowing(),currentScrollTop:O,lastScrollTop:Y,nearBottom:fe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Y=se,J==="resume"?(w.resume(),H=0,Ke.style.display="none"):J==="pause"&&(w.pause(),p&&(Wt.textContent=d,Ke.style.display=""))},b=O=>{let J=el({following:w.isFollowing(),deltaY:O.deltaY,nearBottom:fe(),resumeWhenNearBottom:!0});J==="pause"?(w.pause(),p&&(Wt.textContent=d,Ke.style.display="")):J==="resume"&&(w.resume(),H=0,Ke.style.display="none")},W=()=>{p&&(Re.scrollTop=Re.scrollHeight,w.resume(),H=0,Ke.style.display="none")},B=O=>{let J=O.target;if(!J||J.closest("button"))return;let se=J.closest("[data-event-id]");if(!se)return;let Te=se.getAttribute("data-event-id");Te&&He(Te)},_=O=>{if((O.metaKey||O.ctrlKey)&&O.key==="f"){O.preventDefault(),Z?.focus(),Z?.select();return}O.key==="Escape"&&(Z&&document.activeElement===Z?(T(),Z.blur(),S.focus()):o&&o())};le&&le.addEventListener("click",ut),oe&&oe.addEventListener("change",ht),Z&&Z.addEventListener("input",j),he&&he.addEventListener("click",T),Re.addEventListener("scroll",$),Re.addEventListener("wheel",b,{passive:!0}),Re.addEventListener("click",B),Ke.addEventListener("click",W),S.addEventListener("keydown",_);function U(){A&&clearTimeout(A),D!==null&&(cancelAnimationFrame(D),D=null),K=!1,be.clear(),le&&le.removeEventListener("click",ut),oe&&oe.removeEventListener("change",ht),Z&&Z.removeEventListener("input",j),he&&he.removeEventListener("click",T),Re.removeEventListener("scroll",$),Re.removeEventListener("wheel",b),Re.removeEventListener("click",B),Ke.removeEventListener("click",W),S.removeEventListener("keydown",_)}return{element:S,update:We,destroy:U}}}function Ih(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let a=[],s=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let g=u;return a.findIndex(f=>f===g||f.contains(g))},c=u=>{let g=p(u.target);if(g<0)return;let f=g;if(u.key===r)f=Math.min(g+1,a.length-1);else if(u.key===o)f=Math.max(g-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=a.length-1;else return;u.preventDefault(),f!==g&&t.onSelect(f)},d=u=>{let g=p(u.target);g>=0&&l(a[g])};return e.addEventListener("keydown",c),e.addEventListener("focusin",d),{beforeRender(){s=typeof document<"u"&&e.contains(document.activeElement)},render(u,g){if(a=u,u.forEach((f,h)=>{f.setAttribute("role","tab");let S=h===g;f.setAttribute("aria-selected",S?"true":"false"),f.tabIndex=S||g<0&&h===0?0:-1}),s){let f=(g>=0?u[g]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){e.removeEventListener("keydown",c),e.removeEventListener("focusin",d)}}}function Wh(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=j=>({start:j===!1?!1:typeof j=="object"&&j?j.start!==!1:!0,end:j===!1?!1:typeof j=="object"&&j?j.end!==!1:!0}),{start:d,end:u}=c(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"),q?.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 k=x("span","persona-text-xs persona-font-medium persona-truncate");k.textContent=a;let P=Mt({icon:"x",label:s});P.addEventListener("click",()=>{f(),t.onDismiss?.()});let M="rendered",A=Gr({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:j=>{M=j==="source"?"source":"rendered",Xt()}}),C=x("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=n?.documentToolbarShowCopyLabel===!0,R=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,H=!!(R&&w&&w.length>0),F=null,K,D=null,q=null;if(r&&(E||R)&&!H){if(K=E?no({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let j=ae("chevron-down",14,"currentColor",2);j&&K.appendChild(j)}}else r&&H?(F=x("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),K=E?no({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(K,D)):r?K=Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(K=Mt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&K.classList.add("persona-hidden"));let Y=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 pe=x("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),te=e.features?.artifacts?.toolbarActions??[],me=()=>{let j=Me.find(W=>W.id===Re)??Me[Me.length-1],T=j?.id??null,$=j?.artifactType==="markdown"?j.markdown??"":"",b=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:$,jsonPayload:b,id:T}},oe=async()=>{let j=Me.find(T=>T.id===Re)??Me[Me.length-1];try{await navigator.clipboard.writeText(ns(j))}catch{}};if(K.addEventListener("click",async()=>{let j=n?.onDocumentToolbarCopyMenuSelect;if(j&&H){let{markdown:T,jsonPayload:$,id:b}=me();try{await j({actionId:"primary",artifactId:b,markdown:T,jsonPayload:$})}catch{}return}await oe()}),D&&w?.length){let j=()=>h.closest("[data-persona-root]")??document.body,T=()=>{q=Bo({items:w.map($=>({id:$.id,label:$.label})),onSelect:async $=>{let{markdown:b,jsonPayload:W,id:B}=me(),_=n?.onDocumentToolbarCopyMenuSelect;try{_?await _({actionId:$,artifactId:B,markdown:b,jsonPayload:W}):$==="markdown"||$==="md"?await navigator.clipboard.writeText(b):$==="json"||$==="source"?await navigator.clipboard.writeText(W):await navigator.clipboard.writeText(b||W)}catch{}},anchor:F??D,position:"bottom-right",portal:j()})};h.isConnected?T():requestAnimationFrame(T),D.addEventListener("click",$=>{$.stopPropagation(),q?.toggle()})}Y.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Xt()}),de.addEventListener("click",()=>{f(),t.onDismiss?.()});let le=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?C.append(F,Y,de):C.append(K,Y,de),C.insertBefore(pe,de),C.insertBefore(be,de),S.append(A.element,le,C);else{let j=x("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");j.append(K,pe,be,P),S.appendChild(k),S.appendChild(j)}l&&(S.style.paddingLeft=l,S.style.paddingRight=l);let Z=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&&Z.style.setProperty("--persona-artifact-tab-fade-size",p);let he=e.features?.artifacts?.renderTabBar,Ce=x("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ve=Ih(Z,{onSelect:j=>t.onSelect(Me[j].id)}),we=j=>{let T=j.scrollWidth-j.clientWidth,$=T>1,b=Math.abs(j.scrollLeft);j.classList.toggle("persona-artifact-tab-fade-start",d&&$&&b>1),j.classList.toggle("persona-artifact-tab-fade-end",u&&$&&b<T-1)},Ee=0,ke=()=>{if(Ee)return;let j=()=>{Ee=0,we(Z)};Ee=typeof requestAnimationFrame=="function"?requestAnimationFrame(j):setTimeout(j,0)};Z.addEventListener("scroll",()=>ke(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>we(Z)).observe(Z);let Se=x("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ge=()=>{Se.scrollLeft=0},ze=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ge):setTimeout(Ge,0)};if(l){for(let j of[Z,Ce])j.style.paddingLeft=l,j.style.paddingRight=l;Se.style.padding=l}h.appendChild(S),h.appendChild(Z),h.appendChild(Ce),h.appendChild(Se);let Me=[],Re=null,Ke=!1,Bt=!1,Wt=!0,Kt=!1,wt=null,De="",ue=null,Qe=!1,He=j=>j.artifactType==="markdown"&&!!j.file||r?M:"rendered",fe=j=>{r||(j&&!Qe?(S.insertBefore(A.element,k),Qe=!0):!j&&Qe&&(A.element.remove(),Qe=!1))},ie=()=>Re&&Me.find(j=>j.id===Re)||Me[Me.length-1],We=()=>{let j=es(ie());if(!j){pe.replaceChildren();return}let T=te.filter($=>$.visible===void 0||$.visible(j)).map($=>Kr($,{documentChrome:r,onClick:()=>{let b=es(ie());if(b)try{Promise.resolve($.onClick(b)).catch(()=>{})}catch{}}}));pe.replaceChildren(...T)},Xt=()=>{We();let j=r&&Me.length<=1,T=!!he;if(Z.classList.toggle("persona-hidden",j||T),Ce.classList.toggle("persona-hidden",j||!T),T&&he){let W=Me.map(B=>B.id).join("|")+" "+(Re??"");if(W!==De){De=W;let B=he({records:Me,selectedId:Re,onSelect:t.onSelect});Ce.firstElementChild!==B&&Ce.replaceChildren(B)}}else{ve.beforeRender(),Z.replaceChildren();let W=[],B=-1;for(let[_,U]of Me.entries()){let O=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");O.type="button";let J=U.artifactType==="markdown"?U.file:void 0,se=J?Nn(J.path):U.title||U.id.slice(0,8),Te=J?.path||U.title||se;O.textContent=se,O.title=Te,O.setAttribute("aria-label",Te),U.id===Re&&(O.classList.add("persona-bg-persona-container","persona-border-persona-border"),B=_),O.addEventListener("click",()=>t.onSelect(U.id)),Z.appendChild(O),W.push(O)}if(ve.render(W,B),B>=0&&Re!==wt){wt=Re;let _=W[B];typeof _.scrollIntoView=="function"&&_.scrollIntoView({block:"nearest",inline:"nearest"})}we(Z)}let $=Re&&Me.find(W=>W.id===Re)||Me[Me.length-1];if(!$){Se.replaceChildren(),ue=null,fe(!1);return}let b=$.artifactType==="markdown"?$.file:void 0;if(fe(!!b),r){let W=b?Wo(b):$.artifactType==="markdown"?"MD":$.component??"Component",B=($.title||"Document").trim(),_=b?Nn(b.path):B.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${_} \xB7 ${W}`}else k.textContent=b?Nn(b.path):a;ue?(ue.el.parentElement!==Se&&Se.replaceChildren(ue.el),ue.update($)):(ue=Ji($,{config:e,resolveViewMode:He}),Se.replaceChildren(ue.el)),Se.classList.toggle("persona-artifact-content-flush",!!Se.querySelector(".persona-code-pre"))},ut=()=>{let j=Me.length>0;if(h.classList.toggle("persona-hidden",!j),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;j&&b&&Ke?(g.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},ht=()=>{Kt=!1,Xt(),ut()};return{element:h,backdrop:g,update(j){let T=j.selectedId??j.artifacts[j.artifacts.length-1]?.id??null,$=T!==Re;Me=j.artifacts,Re=T,Me.length>0&&(Ke=!0),Kt=!0,Wt&&ht(),$&&Ge()},setMobileOpen(j){Ke=j,!j&&g?(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):ut()},setExpanded(j){j!==Bt&&(Bt=j,ze());let T=ae(j?"minimize":"maximize",16,"currentColor",2);T&&be.replaceChildren(T);let $=j?"Collapse artifacts panel":"Expand artifacts panel";be.setAttribute("aria-label",$),be.title=$},setExpandToggleVisible(j){be.classList.toggle("persona-hidden",!j)},setCopyButtonVisible(j){r||K.classList.toggle("persona-hidden",!j)},setCustomActions(j){te=j,We()},setTabFade(j){let T=c(j);T.start===d&&T.end===u||(d=T.start,u=T.end,we(Z))},setRenderTabBar(j){j!==he&&(he=j,De="",Xt())},setVisible(j){j!==Wt&&(Wt=j,j&&Kt&&ht())}}}function tn(e){return e?.features?.artifacts?.enabled===!0}function Hh(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"),!tn(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 mw(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 Bh=["panel","seamless","detached"];function pu(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Bh.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function uu(e){return!e||!tn(e)?!1:pu(e)==="detached"}function us(e,t){if(!tn(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"),mw(e),Hh(e,t);return}let n=t.features?.artifacts?.layout,o=pu(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"),Hh(e,t)}function fs(e,t){for(let l of Bh)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"),!tn(t))return;let n=t.features?.artifacts?.layout,o=pu(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 Dh(e,t){return!t||!tn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var gw=new Set(["__proto__","prototype","constructor"]),hw=new Set(["collapsed","card","panel","inline"]),Fh=new Set(["markdown","component"]),yw=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,yr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vl=e=>!gw.has(e),fu=e=>typeof e=="string"&&hw.has(e),br=e=>Object.keys(e).length>0;function Un(e,t,n,o){e.push({path:t,code:n,message:o})}var bw="Ignored because this key is not part of the persisted preference schema.",xl="Ignored an unsupported value.",xw="Expected collapsed, panel, or inline.",vw='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Oh={kind:"mode",message:xl},na={kind:"string",message:"Expected a CSS length string."},ro={kind:"boolean"},Cw={paneWidth:na,paneMaxWidth:na,paneMinWidth:na,expandedPanelWidth:na,resizableMinWidth:na,resizableMaxWidth:na,expandLauncherPanelWhenOpen:ro,resizable:ro},ww={kind:"object",message:"Expected a preference object.",children:{showToolCalls:ro,showReasoning:ro,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:xl},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:xl},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:xl},expandable:ro,grouped:ro}},reasoningDisplay:{kind:"object",children:{expandable:ro,activePreview:ro}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Oh,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Oh,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Fh,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Fh}}},filePreview:{kind:"object",children:{enabled:ro}},layout:{kind:"object",children:Cw}}}}};function Nh(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Un(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Un(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Un(o,n,"invalid_value",t.message);case"mode":return fu(e)?an(e):Un(o,n,"invalid_value",t.message);case"modeMap":{if(!yr(e))return Un(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:Co(s);vl(s)&&(r?r.has(s):yw.test(p))?fu(l)?a[p]=an(l):Un(o,`${n}.${s}`,"invalid_value",xw):Un(o,`${n}.${s}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":vw)}return br(a)?a:void 0}case"object":{if(t.bareMode&&fu(e))return an(e);if(!yr(e))return Un(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))(!vl(l)||!r.includes(l))&&Un(o,a(l),"unknown_key",bw);let s={};for(let l of r){let p=t.children[l],c=Nh(e[l],p,a(l),o);if(p.deprecated&&e[l]!==void 0&&Un(o,a(l),"deprecated_key",p.deprecated),c===void 0)continue;let d=p.alias??l,u=s[d];s[d]=yr(u)&&yr(c)?{...u,...c}:c}return br(s)?s:void 0}}}function mu(e){let t=[];return{preferences:(e===null?void 0:Nh(e,ww,"",t))??{},issues:t}}function oa(e){if(Array.isArray(e))return e.map(oa);if(!yr(e))return e;let t={};for(let[n,o]of Object.entries(e))vl(n)&&o!==void 0&&(t[n]=oa(o));return t}function _h(e,t){let n=oa(e);for(let[o,r]of Object.entries(t)){if(!vl(o)||r===void 0)continue;let a=n[o];n[o]=yr(a)&&yr(r)?_h(a,r):oa(r)}return n}function Aw(e){let t={},n;for(let r of e){let a=mu(r).preferences;n=Uh(n,a.artifacts?.display),t=_h(t,a)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Sw(e,t){if(t===void 0)return e===void 0?void 0:oa(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}:{},...br(r)?{byMediaType:r}:{}};return br(a)?a:void 0}function Uh(e,t){if(t===void 0)return e===void 0?void 0:oa(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=Sw(n.files,t.files),s={...o?{default:o}:{},...br(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return br(s)?s:void 0}function gu(e={},t){let n=Aw(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=Uh(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 ms(e){let t=e.preferences;return!t||!br(t)?e:{...e,features:gu(e.features??{},[t])}}function Mw(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 Tw(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 Ew(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function kw(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function hu(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 qh(e,t,n,o,r,a){let s=Mw(r,200),l=kw(t,n,o,200);l=Math.max(s,l);let p=Tw(a);return p!==null&&(l=Math.min(l,p)),Ew(e,s,l)}var Vh={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"}},yu=(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=Vh[s]??Vh.init;a.classList.add("persona-form-card","persona-space-y-4");let p=x("div","persona-space-y-1"),c=x("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=l.title,p.appendChild(c),l.description){let h=x("p","persona-text-sm persona-text-persona-muted");h.textContent=l.description,p.appendChild(h)}let d=document.createElement("form");d.className="persona-form-grid persona-space-y-3",l.fields.forEach(h=>{let S=x("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${t.id}-${s}-${h.name}`;let k=x("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=h.label,S.appendChild(k);let P=h.type??"text",M;P==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=P),M.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",M.id=`${t.id}-${s}-${h.name}`,M.name=h.name,M.placeholder=h.placeholder??"",h.required&&(M.required=!0),S.appendChild(M),d.appendChild(S)});let u=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),d.appendChild(u),a.replaceChildren(p,d),d.addEventListener("submit",async h=>{h.preventDefault();let S=n.formEndpoint??"/form",k=new FormData(d),P={};k.forEach((M,A)=>{P[A]=M}),P.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(P)});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 bu=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()}},gs=new bu;var zh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Lw=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),$h=(e,t,n)=>{if(!zh(e)||!zh(t)||Lw.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]=$h(e[r],t[r],a)}return o};function Cl(e,t){let n=$h(e,t,"");return Vr(n)}var jh=()=>{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 Pw=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Rw=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},hs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Pw(e),n=Rw(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}},xu=e=>typeof e=="string"?e:e==null?"":String(e),xr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:xu(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=xu(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:xu(n.text)}}},Gh=e=>Array.isArray(e)?e.map(t=>String(t)):[],ys=e=>{let t=new Set(Gh(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Gh(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 Iw=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}},Ww=e=>e.map(t=>({...t,streaming:!1})),Hw=e=>e.map(t=>({...t,status:"complete"})),wl=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Iw(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Ww(n.messages):void 0,artifacts:n.artifacts?Hw(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 ra=xo(oi(),1);function Bw(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Dw(e,t){if(!Bw(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 Al(){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,ra.parse)(n,ra.STR|ra.OBJ),a=Dw(r,n);a&&(e=a)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Kh(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Sl(e,t){let{config:n,message:o,onPropsUpdate:r}=t,a=Rn.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 Xh(){let e=Al();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Jh(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 bs(e){let t=Jh(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 Ml(e){let t=Jh(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 Fw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Tl(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=Fw}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,f.appendChild(h);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,f.appendChild(S),g.appendChild(f);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let P=[];for(let R=1;R<=5;R++){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",`${R} star${R>1?"s":""}: ${c[R-1]}`),w.title=c[R-1],w.dataset.rating=String(R),w.innerHTML=`
|
|
42
|
+
`,n.addEventListener("click",t);let o=a=>{let s=a.launcher??{},l=St(a),p=n.querySelector("[data-role='launcher-title']");if(p){let S=s.title??"Chat Assistant";p.textContent=S,p.setAttribute("title",S)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let S=s.subtitle??"Here to help you get answers fast";d.textContent=S,d.setAttribute("title",S)}let c=n.querySelector(".persona-flex-col");c&&(s.textHidden||l?c.style.display="none":c.style.display="");let f=n.querySelector("[data-role='launcher-icon']");if(f)if(s.agentIconHidden)f.style.display="none";else{let S=s.agentIconSize??"40px";if(f.style.height=S,f.style.width=S,s.agentIconBackgroundColor?(f.style.backgroundColor=s.agentIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),f.innerHTML="",s.agentIconName){let C=parseFloat(S)||24,M=ae(s.agentIconName,C*.6,"var(--persona-text-inverse, #ffffff)",2);M?(f.appendChild(M),f.style.display=""):(f.textContent=s.agentIconText??"\u{1F4AC}",f.style.display="")}else s.iconUrl?f.style.display="none":(f.textContent=s.agentIconText??"\u{1F4AC}",f.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 m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let S=s.callToActionIconSize??"32px";m.style.height=S,m.style.width=S,s.callToActionIconBackgroundColor?(m.style.backgroundColor=s.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(m.style.color=s.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let C=0;if(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,C=(parseFloat(s.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),s.callToActionIconHidden)m.style.display="none";else if(m.style.display=l?"none":"",m.innerHTML="",s.callToActionIconName){let M=parseFloat(S)||24,P=Math.max(M-C,8),R=ae(s.callToActionIconName,P,"currentColor",2);R?m.appendChild(R):m.textContent=s.callToActionIconText??"\u2197"}else m.textContent=s.callToActionIconText??"\u2197"}let b=s.position&&gn[s.position]?gn[s.position]:gn["bottom-right"],w="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",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?T:`${w} ${b}`,l||(n.style.zIndex=String(s.zIndex??Ut));let L="1px solid var(--persona-border, #e5e7eb)",A="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=s.border??L,n.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:A,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=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}},oA="teaser-dismissed",Ay=new Set,wy=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${oA}`},rA=(e,t)=>{if(Ay.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},aA=(e,t)=>{if(Ay.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},sA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,iA=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||St(e??{})?null:t},Sy=(e,t)=>{let n=v("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,a=null,s=null,l=null,p=null,d=!1,c=!1,f=!1,g=!1,m=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,b=()=>{p!==null&&(clearTimeout(p),p=null)},w=()=>{!a||!d||(d=!1,a.hidden=!0)},T=J=>{b(),f=!0,w(),aA(wy(o),J&&m())},L=J=>{!r||f||T(J==="user"&&d)},A=()=>{p=null,!(!a||f||g)&&(c=!0,d=!0,a.hidden=!1,!(sA()||typeof a.animate!="function")&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},S=()=>{!r||!a||f||c||g||rA(wy(o),m())||(b(),p=setTimeout(A,Math.max(0,r.delayMs??0)))},C=()=>{T(m()),t()},M=J=>{J.stopPropagation(),T(m())},R=$u(e,()=>{L("user"),t()}),F=()=>{b(),l?.removeEventListener("click",C),s?.removeEventListener("click",M),a?.remove(),a=null,l=null,s=null,d=!1},O=()=>{l=ke("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",C),s=ke("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),s.addEventListener("click",M),a=ke("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,s),n.insertBefore(a,R.element)},$=()=>{let J=o.launcher?.position??"bottom-right",fe=gn[J]??gn["bottom-right"];if(!a){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",R.element.style.position="";return}n.className=Fn("persona-launcher-surface",fe),n.setAttribute("data-teaser",J),n.style.zIndex=String(o.launcher?.zIndex??Ut),R.element.style.position="static"},E=J=>{let fe=iA(J);if(r=fe,!fe){F();return}a||O(),l.textContent=fe.text,s.hidden=fe.dismissible===!1,s.setAttribute("aria-label",fe.dismissLabel??"Dismiss message"),S()},G=J=>{o=J,R.update(J),E(J),$()},Q=(J,fe="user")=>{g=J,J&&L(fe)},Z=()=>{F(),R.destroy(),n.remove()};return n.appendChild(R.element),e&&(E(e),$()),{element:n,launcher:R,get teaser(){return a?{element:a,show:A,dismiss:T}:null},setPanelOpen:Q,update:G,destroy:Z}};var My=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=xy(e),a=Cy(e,t),s={wrapper:n,panel:o,pillRoot:r},l={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},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}}},ju=({config:e,plugins:t,onToggle:n})=>{let o=t.find(a=>a.renderLauncher);if(o?.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>$u(e,n).element,onToggle:n});if(a)return{instance:null,element:a}}let r=Sy(e,n);return{instance:r,element:r.element}};var lA=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},cA=(e,t,n)=>`${lA(e)}plugin:${t}:${n}`,Ty=e=>{let t=new Map,n=!1,o=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let a=s=>cA(e(),r,s);return{get:s=>{let l=a(s),p=o();if(p)try{return p.getItem(l)}catch{n=!0}return t.get(l)??null},set:(s,l)=>{let p=a(s),d=o();if(d)try{d.setItem(p,l);return}catch{n=!0}t.set(p,l)},remove:s=>{let l=a(s);t.delete(l);let p=o();if(p)try{p.removeItem(l)}catch{n=!0}}}}};var va=new Set,dA=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),pA=(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
|
+
`):""},Ey=(e,t)=>{let n=va.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),a=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let d=ae(n?"chevron-up":"chevron-down",16,"currentColor",2);d?l.appendChild(d):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",a&&(a.style.display=n?"none":a.textContent||a.childNodes.length?"":"none")},Gu=(e,t)=>{let n=e.reasoning,o=v("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&&va.has(e.id),l=n.status!=="complete",p=pA(e,r.previewMaxLines??3),d=v("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",a&&(d.setAttribute("aria-expanded",s?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=v("div","persona-flex persona-flex-col persona-text-left"),f=v("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",m=t?.reasoning??{},b=String(n.startedAt??Date.now()),w=()=>{let Z=v("span","");return Z.setAttribute("data-tool-elapsed",b),Z.textContent=Pi(n),Z},T=m.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:g,previewText:p,isActive:l,config:t??{},elapsed:Pi(n),createElapsedElement:w});typeof T=="string"&&T.trim()?(f.textContent=T,c.appendChild(f)):T instanceof HTMLElement?c.appendChild(T):(f.textContent=g,c.appendChild(f));let L=v("span","persona-text-xs persona-text-persona-primary");L.textContent=Vg(n),c.appendChild(L);let A=r.loadingAnimation??"none",S=m.activeTextTemplate,C=m.completeTextTemplate,M=l?S:C,P=T instanceof HTMLElement,R=(Z,J)=>{f.textContent="";let fe=Ri(Z,""),ne=0;for(let ge of fe){let ie=ge.styles.length>0?(()=>{let ue=v("span",ge.styles.map(oe=>`persona-tool-text-${oe}`).join(" "));return f.appendChild(ue),ue})():f;if(ge.isDuration&&l)ie.appendChild(w());else{let ue=ge.isDuration?Pi(n):ge.text;J?ne=zo(ie,ue,ne):ie.appendChild(document.createTextNode(ue))}}};if(!P&&M)if(L.style.display="none",f.style.display="",l&&A!=="none"){let Z=m.loadingAnimationDuration??2e3;f.setAttribute("data-preserve-animation","true"),A==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),R(M,!1)):(f.classList.add(`persona-tool-loading-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),R(M,!0))}else R(M,!1);else if(!P&&l&&A!=="none"){f.style.display="";let Z=m.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),A==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${Z}ms`);else{f.classList.add(`persona-tool-loading-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let J=f.textContent||g;f.textContent="",zo(f,J,0)}n.status==="complete"&&(f.style.display="none")}else P||(n.status==="complete"?f.style.display="none":f.style.display="");let F=null;if(a){F=v("div","persona-flex persona-items-center");let J=ae(s?"chevron-up":"chevron-down",16,"currentColor",2);J?F.appendChild(J):F.textContent=s?"Hide":"Show";let fe=v("div","persona-flex persona-items-center persona-ml-auto");fe.append(F),d.append(c,fe)}else d.append(c);let O=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(O.setAttribute("data-persona-collapsed-preview","reasoning"),O.style.display="none",O.style.whiteSpace="pre-wrap",!s&&l&&r.activePreview&&p){let Z=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:l,config:t??{}});dA(O,Z)||(O.textContent=p),O.style.display=""}if(!s&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!a)return o.append(d,O),o;let $=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");$.style.display=s?"":"none";let E=n.chunks.join(""),G=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return G.textContent=E||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),$.appendChild(G),(()=>{if(d.setAttribute("aria-expanded",s?"true":"false"),F){F.innerHTML="";let J=ae(s?"chevron-up":"chevron-down",16,"currentColor",2);J?F.appendChild(J):F.textContent=s?"Hide":"Show"}$.style.display=s?"":"none",O.style.display=s?"none":O.textContent||O.childNodes.length?"":"none"})(),o.append(d,O,$),o};var Ca=new Set,uA=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),fA=(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=Do(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
45
|
+
`):""},Ku=(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)"},mA=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",a=fA(e,o?.previewMaxLines??3),s=n?zg(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=ld(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=ld(n,p.completeTextTemplate,d)),{summary:d,previewText:a,isActive:l}},ky=(e,t,n)=>{let o=Ca.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)",f=ae(o?"chevron-up":"chevron-down",16,c,2);f?d.appendChild(f):d.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Xu=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=v("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&&Ca.has(e.id),{summary:p,previewText:d,isActive:c}=mA(e,t),f=v("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");f.type="button",s&&(f.setAttribute("aria-expanded",l?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let g=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let b=String(n.startedAt??Date.now()),w=()=>{let E=v("span","");return E.setAttribute("data-tool-elapsed",b),E.textContent=cs(n),E},T=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:a.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:cs(n),createElapsedElement:w});typeof T=="string"&&T.trim()?(m.textContent=T,g.appendChild(m)):T instanceof HTMLElement?g.appendChild(T):(m.textContent=p,g.appendChild(m));let L=a.loadingAnimation??"none",A=o.activeTextTemplate,S=o.completeTextTemplate,C=c?A:S,M=T instanceof HTMLElement,P=(E,G)=>{m.textContent="";let Q=n.name?.trim()||"tool",Z=Ri(E,Q),J=0;for(let fe of Z){let ne=fe.styles.length>0?(()=>{let ge=v("span",fe.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return m.appendChild(ge),ge})():m;if(fe.isDuration&&c)ne.appendChild(w());else{let ge=fe.isDuration?cs(n):fe.text;G?J=zo(ne,ge,J):ne.appendChild(document.createTextNode(ge))}}};if(!M)if(c&&L!=="none"){let E=o.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),L==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${E}ms`),C&&P(C,!1);else if(m.classList.add(`persona-tool-loading-${L}`),m.style.setProperty("--persona-tool-anim-duration",`${E}ms`),L==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),C)P(C,!0);else{let G=m.textContent||p;m.textContent="",zo(m,G,0)}}else C&&P(C,!1);let R=null;if(s){R=v("div","persona-flex persona-items-center");let E=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=ae(l?"chevron-up":"chevron-down",16,E,2);G?R.appendChild(G):R.textContent=l?"Hide":"Show";let Q=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(R),f.append(g,Q)}else f.append(g);let F=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(F.setAttribute("data-persona-collapsed-preview","tool"),F.style.display="none",F.style.whiteSpace="pre-wrap",!l&&c&&a.activePreview&&d){let E=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});uA(F,E)||(F.textContent=d),F.style.display=""}if(!l&&c&&a.activeMinHeight&&(r.style.minHeight=a.activeMinHeight),!s)return r.append(f,F),r;let O=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(O.style.display=l?"":"none",o.contentBackgroundColor&&(O.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(O.style.color=o.contentTextColor),o.contentPaddingX&&(O.style.paddingLeft=o.contentPaddingX,O.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(O.style.paddingTop=o.contentPaddingY,O.style.paddingBottom=o.contentPaddingY),n.name){let E=v("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?E.style.color=o.contentTextColor:o.headerTextColor&&(E.style.color=o.headerTextColor),E.textContent=n.name,O.appendChild(E)}if(n.args!==void 0){let E=v("div","persona-space-y-1"),G=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Arguments";let Q=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Ku(Q,o),Q.textContent=Do(n.args),E.append(G,Q),O.appendChild(E)}if(n.chunks&&n.chunks.length){let E=v("div","persona-space-y-1"),G=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Activity";let Q=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Ku(Q,o),Q.textContent=n.chunks.join(""),E.append(G,Q),O.appendChild(E)}if(n.status==="complete"&&n.result!==void 0){let E=v("div","persona-space-y-1"),G=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Result";let Q=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Ku(Q,o),Q.textContent=Do(n.result),E.append(G,Q),O.appendChild(E)}if(n.status==="complete"&&typeof n.duration=="number"){let E=v("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(E.style.color=o.contentTextColor),E.textContent=`Duration: ${n.duration}ms`,O.appendChild(E)}return(()=>{if(f.setAttribute("aria-expanded",l?"true":"false"),R){R.innerHTML="";let E=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=ae(l?"chevron-up":"chevron-down",16,E,2);G?R.appendChild(G):R.textContent=l?"Hide":"Show"}O.style.display=l?"":"none",F.style.display=l?"none":F.textContent||F.childNodes.length?"":"none"})(),r.append(f,F,O),r};var Rr=new Map,Fl=e=>{let n=(e.startsWith(Dn)?e.slice(Dn.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)},Ly=e=>e?.approval!==!1?e?.approval:void 0,Py=(e,t)=>{let n=Ly(t)?.detailsDisplay??"collapsed";return Rr.get(e)??n==="expanded"},Ry=(e,t,n)=>{let o=Ly(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=ae(t?"chevron-up":"chevron-down",14,"currentColor",2);s&&a.appendChild(s)}},Iy=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let a=Py(e,n);Ry(o,a,n),r.style.display=a?"":"none"};var Ol=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",a=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${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=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=v("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let 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=ae(p,20,d,2);c&&l.appendChild(c);let f=v("div","persona-flex-1 persona-min-w-0"),g=v("div","persona-flex persona-items-center persona-gap-2"),m=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(m.style.color=o.titleColor),m.textContent=o?.title??"Approval Required",g.appendChild(m),!r){let R=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");R.setAttribute("data-approval-status",n.status),n.status==="approved"?(R.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",R.style.color="var(--persona-palette-colors-success-700, #15803d)",R.textContent="Approved"):n.status==="denied"?(R.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",R.style.color="var(--persona-palette-colors-error-700, #b91c1c)",R.textContent="Denied"):n.status==="timeout"&&(R.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",R.style.color="var(--persona-palette-colors-warning-700, #b45309)",R.textContent="Timeout"),g.appendChild(R)}f.appendChild(g);let w=n.toolType==="webmcp"||n.toolName.startsWith(Dn)?os(n.toolName):void 0,T=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...w?{displayTitle:w}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,A=T||(L?n.description:`The assistant wants to use \u201C${w??Fl(n.toolName)}\u201D.`),S=v("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=A,f.appendChild(S),n.reason){let R=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");R.setAttribute("data-approval-reason","true"),o?.reasonColor?R.style.color=o.reasonColor:o?.descriptionColor&&(R.style.color=o.descriptionColor);let F=v("span","persona-font-medium");F.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,R.appendChild(F),R.appendChild(document.createTextNode(n.reason)),f.appendChild(R)}let C=o?.detailsDisplay??"collapsed",M=!!n.description&&!L,P=M||!!n.parameters;if(C!=="hidden"&&P){let R=Py(e.id,t),F=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");F.type="button",F.setAttribute("data-expand-header","true"),F.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(F.style.color=o.descriptionColor);let O=v("span");O.setAttribute("data-approval-details-label","true");let $=v("span","persona-inline-flex persona-items-center");$.setAttribute("data-approval-details-chevron","true"),F.append(O,$),Ry(F,R,t),f.appendChild(F);let E=v("div");if(E.setAttribute("data-approval-details","true"),E.style.display=R?"":"none",M){let G=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(G.style.color=o.descriptionColor),G.textContent=n.description,E.appendChild(G)}if(n.parameters){let G=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(G.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(G.style.color=o.parameterTextColor),G.style.fontSize="0.75rem",G.style.lineHeight="1rem",G.textContent=Do(n.parameters),E.appendChild(G)}f.appendChild(E)}if(r){let R=v("div","persona-flex persona-gap-2 persona-mt-2");R.setAttribute("data-approval-buttons","true");let F=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");F.type="button",F.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",F.style.color=o?.approveButtonTextColor??"#ffffff",F.setAttribute("data-approval-action","approve");let O=ae("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);O&&(O.style.marginRight="4px",F.appendChild(O));let $=document.createTextNode(o?.approveLabel??"Approve");F.appendChild($);let E=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");E.type="button",E.style.backgroundColor=o?.denyButtonColor??"transparent",E.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",E.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,E.setAttribute("data-approval-action","deny");let G=ae("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);G&&(G.style.marginRight="4px",E.appendChild(G));let Q=document.createTextNode(o?.denyLabel??"Deny");E.appendChild(Q),R.append(F,E),f.appendChild(R)}return s.append(l,f),a.appendChild(s),a};function gA(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Wy(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,f=e.container??gA(t),g=!1,m=null,b=()=>{if(!g)return;let L=t.getBoundingClientRect();n.style.position="fixed",a&&(n.style.minWidth=`${L.width}px`),s&&(n.style.maxWidth=`${L.width}px`);let A=n.getBoundingClientRect(),S=l?.()??null,C=S!=null?L.top+S:L.top,M=o==="top-start"||o==="top-end"?C-r-A.height:L.bottom+r,R=o==="bottom-end"||o==="top-end"?L.right-A.width:L.left,F=s?.()??null;if(F!=null){let O=Math.max(L.left,L.right-A.width);R=Math.min(Math.max(L.left+F,L.left),O)}n.style.top=`${M}px`,n.style.left=`${R}px`},w=()=>{g&&(g=!1,m&&(m(),m=null),n.remove())},T=()=>{if(g)return;g=!0,p!=null&&(n.style.zIndex=String(p)),f.appendChild(n),b();let L=(t.ownerDocument??document).defaultView??window,A=t.ownerDocument??document,S=()=>{if(!t.isConnected){w(),c?.("anchor-removed");return}b()},C=P=>{let R=typeof P.composedPath=="function"?P.composedPath():[];R.includes(n)||R.includes(t)||(w(),c?.("outside"))},M=L.setTimeout(()=>{A.addEventListener("pointerdown",C,!0)},0);L.addEventListener("scroll",S,!0),L.addEventListener("resize",S),m=()=>{L.clearTimeout(M),A.removeEventListener("pointerdown",C,!0),L.removeEventListener("scroll",S,!0),L.removeEventListener("resize",S)},d?.()};return{get isOpen(){return g},open:T,close:w,toggle:()=>g?w():T(),reposition:b,destroy:w}}function Hy(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var hA=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),By=(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))},Ir=(e,t)=>{By(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)},yA=e=>e?.approval!==!1?e?.approval:void 0,bA=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Rr.get(e)??n==="expanded"},Ju=e=>{let t=v("span","persona-approval-kbd");return t.textContent=e,t},xA=(e,t)=>{let n=v("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Dn)?os(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??Fl(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},vA=e=>{let t=v("div","persona-approval-resolved"),n=ae("ban",15,"currentColor",2);n&&t.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=e.toolName?Fl(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},CA=(e,t,n,o,r,a,s)=>{let l=v("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",f=d||c,g=f&&bA(t.id,o),m=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",w=v("button","persona-approval-head");w.type="button",f?(w.setAttribute("data-action","toggle-params"),w.setAttribute("aria-expanded",g?"true":"false"),w.setAttribute("aria-label",g?b:m)):w.setAttribute("data-static","true");let T=v("span","persona-approval-logo"),L=ae("shield-check",16,"currentColor",2);L&&T.appendChild(L),w.appendChild(T);let A=xA(n,o);if(f){let F=v("span","persona-approval-toggle");F.setAttribute("aria-hidden","true");let O=ae("chevron-down",14,"currentColor",2);O&&F.appendChild(O),A.append(" "),A.appendChild(F)}w.appendChild(A),l.appendChild(w);let S=v("div","persona-approval-body");if(f){let F=v("div","persona-approval-details");if(F.setAttribute("data-role","params"),F.hidden=!g,d){let O=v("p","persona-approval-desc");o?.descriptionColor&&(O.style.color=o.descriptionColor),O.textContent=n.description,F.appendChild(O)}if(c){let O=v("pre","persona-approval-params");o?.parameterBackgroundColor&&(O.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(O.style.color=o.parameterTextColor),O.textContent=Do(n.parameters),F.appendChild(O)}S.appendChild(F)}if(n.reason){let F=v("p","persona-approval-reason");o?.reasonColor?F.style.color=o.reasonColor:o?.descriptionColor&&(F.style.color=o.descriptionColor);let O=v("span","persona-approval-reason-label");O.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,F.append(O,document.createTextNode(n.reason)),S.appendChild(F)}let C=v("div","persona-approval-actions"),M=null,P=F=>{o?.approveButtonColor&&(F.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(F.style.color=o.approveButtonTextColor)},R=v("button","persona-approval-deny");if(R.type="button",R.setAttribute("data-action","deny"),o?.denyButtonColor&&(R.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(R.style.color=o.denyButtonTextColor),R.append(o?.denyLabel??"Deny"),s){let F=v("div","persona-approval-split"),O=v("button","persona-approval-primary");O.type="button",O.setAttribute("data-action","always"),P(O),O.append(o?.approveLabel??"Always allow",Ju("\u23CE"));let $=v("button","persona-approval-caret");$.type="button",$.setAttribute("data-action","toggle-menu"),$.setAttribute("aria-label","More options"),P($);let E=ae("chevron-down",15,"currentColor",2);E&&$.appendChild(E),F.append(O,$),C.append(F,R),R.append(Ju("Esc"));let G=v("div","persona-approval-menu"),Q=v("button","persona-approval-menu-item");Q.type="button",Q.append("Allow once",Ju("\u2318\u23CE")),G.appendChild(Q),M=Wy({anchor:F,content:G,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,M),Q.addEventListener("click",()=>{Ir(e,t.id),r()})}else{let F=v("button","persona-approval-primary persona-approval-primary--solo");F.type="button",F.setAttribute("data-action","allow"),P(F),F.append(o?.approveLabel??"Allow"),C.append(F,R)}return S.appendChild(C),l.appendChild(S),l.addEventListener("click",F=>{let O=F.target instanceof Element?F.target.closest("[data-action]"):null;if(!O)return;let $=O.getAttribute("data-action");if($==="toggle-params"){let E=l.querySelector('[data-role="params"]');if(E){let G=E.hidden;E.hidden=!G,w.setAttribute("aria-expanded",G?"true":"false"),w.setAttribute("aria-label",G?b:m),Rr.set(t.id,G)}return}if($==="toggle-menu"){M?.toggle();return}if($==="always"){Ir(e,t.id),r({remember:!0});return}if($==="allow"){Ir(e,t.id),r();return}if($==="deny"){Ir(e,t.id),a();return}}),l},Dy=()=>{let e=hA();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=yA(s);if(l.status!=="pending"){if(Ir(e,o.id),l.status==="approved"){let f=document.createElement("div");return f.style.display="none",f}return vA(l)}By(e,o.id);let d=p?.enableAlwaysAllow===!0,c=CA(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 f=g=>{Hy(g)||o.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),Ir(e,o.id),g.key==="Escape"?a():g.metaKey||g.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,f),document.addEventListener("keydown",f)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])Ir(e,o);e.latestPendingApprovalId=null}}};var Ls=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 Ps=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 wA=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),AA=new Set(["step_start","execution_start"]),SA=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),MA=new Set(["step_complete","agent_turn_complete"]),TA=new Set(["flow_complete","agent_complete"]),Fy=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Ny=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Wr=(e,t)=>{let n=e[t];return Ny(n)?n:void 0};function Qu(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Nl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function EA(e,t){return typeof t.type=="string"?t.type:e}function kA(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 LA(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 Oy(e){let t=Wr(e,"result"),n=[Wr(e,"tokens"),Wr(e,"totalTokens"),t?Wr(t,"tokens"):void 0,Wr(e,"usage"),t?Wr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=hn(o.output)??hn(o.outputTokens)??hn(o.completionTokens);if(r!==void 0)return r}return hn(e.outputTokens)??hn(e.completionTokens)??(t?hn(t.outputTokens)??hn(t.completionTokens):void 0)}function PA(e){let t=Wr(e,"result");return hn(e.executionTime)??hn(e.executionTimeMs)??hn(e.execution_time)??hn(e.duration)??(t?hn(t.executionTime)??hn(t.executionTimeMs):void 0)}function RA(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Rs=class{constructor(t=RA){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:Nl(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(!Ny(n)){Fy.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=EA(t,n),r=this.now();if(wA.has(o)){this.startRun(r);return}if(AA.has(o)){this.run||this.startRun(r);return}if(SA.has(o)){if(!LA(o,n))return;let a=kA(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+Qu(s.visibleCharCount),p=r-s.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Nl(l,p),outputTokens:l,durationMs:p,source:s.exactOutputTokens>0?"usage":"estimate"};return}if(MA.has(o)){if(!this.run)return;let a=this.run,s=Oy(n);s!==void 0&&(a.exactOutputTokens+=s,a.visibleCharCount=0);let l=a.exactOutputTokens>0,p=a.exactOutputTokens+Qu(a.visibleCharCount),d=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Nl(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(TA.has(o)){if(!this.run)return;let a=this.run,s=Oy(n),l=s??a.exactOutputTokens+Qu(a.visibleCharCount),p=s!==void 0||a.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Nl(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(Fy.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:PA(n)??o-t.startedAt}};function wa(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var IA={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)"}},WA={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},HA=["flowName","stepName","reasoningText","text","name","tool","toolName"],BA=100;function DA(e,t){let n={...IA,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return WA}function FA(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function OA(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 NA(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 _A(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 UA(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 qA(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function VA(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 zA(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=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=v("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 Yu(e,t,n,o,r,a,s,l){let p=r.has(e.id),d=v("div","persona-border-b persona-border-persona-divider persona-text-xs");wa(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:()=>f(),isExpanded:p,onToggleExpand:()=>a(e.id)});if(g)return d.appendChild(g),d}return d.appendChild(f()),d;function f(){let g=v("div",""),m=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");m.setAttribute("data-event-id",e.id);let b=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),w=ae(p?"chevron-down":"chevron-right","14px","currentColor",2);w&&b.appendChild(w);let T=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=o.timestampFormat??"relative";T.textContent=L==="relative"?FA(e.timestamp,n):OA(e.timestamp);let A=null;o.showSequenceNumbers!==!1&&(A=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),A.textContent=String(t+1));let S=DA(e.type,o.badgeColors),C=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");C.style.backgroundColor=S.bg,C.style.color=S.text,C.style.borderColor=S.text+"50",C.textContent=e.type;let M=o.descriptionFields??HA,P=NA(e.payload,M),R=null;P&&(R=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),R.textContent=P);let F=v("div","persona-flex-1 persona-min-w-0"),O=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),$=ae("clipboard","12px","currentColor",1.5);return $&&O.appendChild($),O.addEventListener("click",async E=>{E.stopPropagation(),await _A(UA(e)),O.innerHTML="";let G=ae("check","12px","currentColor",1.5);G&&O.appendChild(G),setTimeout(()=>{O.innerHTML="";let Q=ae("clipboard","12px","currentColor",1.5);Q&&O.appendChild(Q)},1500)}),m.appendChild(b),m.appendChild(T),A&&m.appendChild(A),m.appendChild(C),R&&m.appendChild(R),m.appendChild(F),m.appendChild(O),g.appendChild(m),p&&g.appendChild(zA(e,s,l)),g}}function _y(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??"",f=r?.features?.eventStream??{},g=a.find(b=>b.renderEventStreamView);if(g?.renderEventStreamView&&r){let b=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(b)return{element:b,update:()=>{},destroy:()=>{}}}return m();function m(){let b=f.classNames,w=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");wa(w,b?.panel);let T=[],L="",A="",S=null,C=[],M={},P=0,R=yl(),F=0,O=0,$=!1,E=null,G=!1,Q=0,Z=new Set,J=new Map,fe="",ne="",ge=null,ie,ue,oe,me,Se=null,Ce=null,Be=null;function ut(){let V=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),X=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(wa(X,b?.headerBar),s){Ce=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),Ce.style.cursor="help",Se=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Se.textContent="-- tok/s",Be=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Be.style.display="none",Be.style.pointerEvents="none";let wt=Ce,yn=Be,Us=()=>{if(!yn.textContent)return;let bn=wt.getBoundingClientRect(),it=V.getBoundingClientRect();yn.style.left=`${bn.left-it.left}px`,yn.style.top=`${bn.bottom-it.top+4}px`,yn.style.display="block"},te=()=>{yn.style.display="none"};Ce.addEventListener("mouseenter",Us),Ce.addEventListener("mouseleave",te),Ce.appendChild(Se)}let ce=v("div","persona-flex-1");ie=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ve=v("option","");Ve.value="",Ve.textContent="All events (0)",ie.appendChild(Ve),ue=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),ue.type="button",ue.title="Copy All";let Pe=ae("clipboard-copy","12px","currentColor",1.5);Pe&&ue.appendChild(Pe);let ze=v("span","persona-event-copy-all persona-text-xs");ze.textContent="Copy All",ue.appendChild(ze),Ce&&X.appendChild(Ce),X.appendChild(ce),X.appendChild(ie),X.appendChild(ue);let Ue=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");wa(Ue,b?.searchBar);let We=ae("search","14px","var(--persona-muted, #9ca3af)",1.5),we=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");We&&we.appendChild(We),oe=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),wa(oe,b?.searchInput),oe.type="text",oe.placeholder="Search event payloads...",me=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),me.type="button",me.style.display="none";let nt=ae("x","12px","currentColor",2);return nt&&me.appendChild(nt),Ue.appendChild(we),Ue.appendChild(oe),Ue.appendChild(me),V.appendChild(X),V.appendChild(Ue),Be&&V.appendChild(Be),V}let Je,Qe=a.find(V=>V.renderEventStreamToolbar);Qe?.renderEventStreamToolbar&&r?Je=Qe.renderEventStreamToolbar({config:r,defaultRenderer:()=>ut(),eventCount:t.getSize(),filteredCount:0,onFilterChange:X=>{L=X,Le(),Te()},onSearchChange:X=>{A=X,Le(),Te()}})??ut():Je=ut();let Ne=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Ne.style.display="none";function _e(){if(!s||!Se||!Ce)return;let V=s(),X=qA(V);Se.textContent=X;let ce=VA(V);Be&&(Be.textContent=ce,ce||(Be.style.display="none")),Ce.setAttribute("aria-label",ce?`Throughput: ${X}, ${ce}`:`Throughput: ${X}`)}let Ae=v("div","persona-flex-1 persona-min-h-0 persona-relative"),Me=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Me.style.height="100%";let qe=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");wa(qe,b?.scrollIndicator),qe.style.display="none",qe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Jt=ae(d,"14px","currentColor",2);Jt&&qe.appendChild(Jt);let gt=v("span","");gt.textContent=c,qe.appendChild(gt);let Bt=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Bt.style.display="none",Ae.appendChild(Me),Ae.appendChild(Bt),Ae.appendChild(qe),w.setAttribute("tabindex","0"),w.appendChild(Je),w.appendChild(Ne),w.appendChild(Ae);function Tn(){let V=t.getAll(),X={};for(let Ue of V)X[Ue.type]=(X[Ue.type]||0)+1;let ce=Object.keys(X).sort(),Ve=ce.length!==C.length||!ce.every((Ue,We)=>Ue===C[We]),de=!Ve&&ce.some(Ue=>X[Ue]!==M[Ue]),Pe=V.length!==Object.values(M).reduce((Ue,We)=>Ue+We,0);if(!Ve&&!de&&!Pe||(C=ce,M=X,!ie))return;let ze=ie.value;if(ie.options[0].textContent=`All events (${V.length})`,Ve){for(;ie.options.length>1;)ie.remove(1);for(let Ue of ce){let We=v("option","");We.value=Ue,We.textContent=`${Ue} (${X[Ue]||0})`,ie.appendChild(We)}ze&&ce.includes(ze)?ie.value=ze:ze&&(ie.value="",L="")}else for(let Ue=1;Ue<ie.options.length;Ue++){let We=ie.options[Ue];We.textContent=`${We.value} (${X[We.value]||0})`}}function En(){let V=t.getAll();if(L&&(V=V.filter(X=>X.type===L)),A){let X=A.toLowerCase();V=V.filter(ce=>ce.type.toLowerCase().includes(X)||ce.payload.toLowerCase().includes(X))}return V}function et(){return L!==""||A!==""}function Le(){P=0,F=0,R.resume(),qe.style.display="none"}function he(V){Z.has(V)?Z.delete(V):Z.add(V),ge=V;let X=Me.scrollTop,ce=R.isFollowing();G=!0,R.pause(),Te(),Me.scrollTop=X,ce&&R.resume(),G=!1}function tt(){return uo(Me,50)}function Te(){O=Date.now(),$=!1,_e(),Tn();let V=t.getEvictedCount();V>0?(Ne.textContent=`${V.toLocaleString()} older events truncated`,Ne.style.display=""):Ne.style.display="none",T=En();let X=T.length,ce=t.getSize()>0;X===0&&ce&&et()?(Bt.textContent=A?`No events matching '${A}'`:"No events matching filter",Bt.style.display="",Me.style.display="none"):(Bt.style.display="none",Me.style.display=""),ue&&(ue.title=et()?`Copy Filtered (${X})`:"Copy All"),p&&!R.isFollowing()&&X>P&&(F+=X-P,gt.textContent=c?`${c}${F>0?` (${F})`:""}`:"",qe.style.display=""),P=X;let Ve=t.getAll(),de=Ve.length>0?Ve[0].timestamp:0,Pe=new Set(T.map(We=>We.id));for(let We of Z)Pe.has(We)||Z.delete(We);let ze=L!==fe||A!==ne,Ue=J.size===0&&T.length>0;if(ze||Ue||T.length===0){Me.innerHTML="",J.clear();let We=document.createDocumentFragment();for(let we=0;we<T.length;we++){let nt=Yu(T[we],we,de,f,Z,he,a,r);J.set(T[we].id,nt),We.appendChild(nt)}Me.appendChild(We),fe=L,ne=A,ge=null}else{if(ge!==null){let we=J.get(ge);if(we&&we.parentNode===Me){let nt=T.findIndex(wt=>wt.id===ge);if(nt>=0){let wt=Yu(T[nt],nt,de,f,Z,he,a,r);Me.insertBefore(wt,we),we.remove(),J.set(ge,wt)}}ge=null}let We=new Set(T.map(we=>we.id));for(let[we,nt]of J)We.has(we)||(nt.remove(),J.delete(we));for(let we=0;we<T.length;we++){let nt=T[we];if(!J.has(nt.id)){let wt=Yu(nt,we,de,f,Z,he,a,r);J.set(nt.id,wt),Me.appendChild(wt)}}}R.isFollowing()&&(Me.scrollTop=Me.scrollHeight)}function be(){if(Date.now()-O>=BA){E!==null&&(cancelAnimationFrame(E),E=null),Te();return}$||($=!0,E=requestAnimationFrame(()=>{E=null,Te()}))}let re=(V,X)=>{if(!ue)return;ue.innerHTML="";let ce=ae(V,"12px","currentColor",1.5);ce&&ue.appendChild(ce);let Ve=v("span","persona-text-xs");Ve.textContent="Copy All",ue.appendChild(Ve),setTimeout(()=>{ue.innerHTML="";let de=ae("clipboard-copy","12px","currentColor",1.5);de&&ue.appendChild(de);let Pe=v("span","persona-text-xs");Pe.textContent="Copy All",ue.appendChild(Pe),ue.disabled=!1},X)},xe=async()=>{if(ue){ue.disabled=!0;try{let V;et()?V=T:n?(V=await n(),V.length===0&&(V=t.getAll())):V=t.getAll();let X=V.map(ce=>{try{return JSON.parse(ce.payload)}catch{return ce.payload}});await navigator.clipboard.writeText(JSON.stringify(X,null,2)),re("check",1500)}catch{re("x",1500)}}},kn=()=>{ie&&(L=ie.value,Le(),Te())},ee=()=>{!oe||!me||(me.style.display=oe.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{A=oe.value,Le(),Te()},150))},I=()=>{!oe||!me||(oe.value="",A="",me.style.display="none",S&&clearTimeout(S),Le(),Te())},B=()=>{if(G)return;let V=Me.scrollTop,{action:X,nextLastScrollTop:ce}=bl({following:R.isFollowing(),currentScrollTop:V,lastScrollTop:Q,nearBottom:tt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Q=ce,X==="resume"?(R.resume(),F=0,qe.style.display="none"):X==="pause"&&(R.pause(),p&&(gt.textContent=c,qe.style.display=""))},y=V=>{let X=xl({following:R.isFollowing(),deltaY:V.deltaY,nearBottom:tt(),resumeWhenNearBottom:!0});X==="pause"?(R.pause(),p&&(gt.textContent=c,qe.style.display="")):X==="resume"&&(R.resume(),F=0,qe.style.display="none")},D=()=>{p&&(Me.scrollTop=Me.scrollHeight,R.resume(),F=0,qe.style.display="none")},H=V=>{let X=V.target;if(!X||X.closest("button"))return;let ce=X.closest("[data-event-id]");if(!ce)return;let Ve=ce.getAttribute("data-event-id");Ve&&he(Ve)},N=V=>{if((V.metaKey||V.ctrlKey)&&V.key==="f"){V.preventDefault(),oe?.focus(),oe?.select();return}V.key==="Escape"&&(oe&&document.activeElement===oe?(I(),oe.blur(),w.focus()):o&&o())};ue&&ue.addEventListener("click",xe),ie&&ie.addEventListener("change",kn),oe&&oe.addEventListener("input",ee),me&&me.addEventListener("click",I),Me.addEventListener("scroll",B),Me.addEventListener("wheel",y,{passive:!0}),Me.addEventListener("click",H),qe.addEventListener("click",D),w.addEventListener("keydown",N);function K(){S&&clearTimeout(S),E!==null&&(cancelAnimationFrame(E),E=null),$=!1,J.clear(),ue&&ue.removeEventListener("click",xe),ie&&ie.removeEventListener("change",kn),oe&&oe.removeEventListener("input",ee),me&&me.removeEventListener("click",I),Me.removeEventListener("scroll",B),Me.removeEventListener("wheel",y),Me.removeEventListener("click",H),qe.removeEventListener("click",D),w.removeEventListener("keydown",N)}return{element:w,update:be,destroy:K}}}function Uy(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=f=>{typeof f.scrollIntoView=="function"&&f.scrollIntoView({block:"nearest",inline:"nearest"})},p=f=>{let g=f;return a.findIndex(m=>m===g||m.contains(g))},d=f=>{let g=p(f.target);if(g<0)return;let m=g;if(f.key===r)m=Math.min(g+1,a.length-1);else if(f.key===o)m=Math.max(g-1,0);else if(f.key==="Home")m=0;else if(f.key==="End")m=a.length-1;else return;f.preventDefault(),m!==g&&t.onSelect(m)},c=f=>{let g=p(f.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(f,g){if(a=f,f.forEach((m,b)=>{m.setAttribute("role","tab");let w=b===g;m.setAttribute("aria-selected",w?"true":"false"),m.tabIndex=w||g<0&&b===0?0:-1}),s){let m=(g>=0?f[g]:void 0)??f[0];m&&typeof m.focus=="function"&&(l(m),m.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function qy(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=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:c,end:f}=d(n?.tabFade),g=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{g?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),G?.hide()};g&&g.addEventListener("click",()=>{m(),t.onDismiss?.()});let b=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let w=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");w.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&w.classList.add("persona-artifact-toolbar-document");let T=v("span","persona-text-xs persona-font-medium persona-truncate");T.textContent=a;let L=Tt({icon:"x",label:s});L.addEventListener("click",()=>{m(),t.onDismiss?.()});let A="rendered",S=ma({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:ee=>{A=ee==="source"?"source":"rendered",re()}}),C=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),M=n?.documentToolbarShowCopyLabel===!0,P=n?.documentToolbarShowCopyChevron===!0,R=n?.documentToolbarCopyMenuItems,F=!!(P&&R&&R.length>0),O=null,$,E=null,G=null;if(r&&(M||P)&&!F){if($=M?po({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let ee=ae("chevron-down",14,"currentColor",2);ee&&$.appendChild(ee)}}else r&&F?(O=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=M?po({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),E=Tt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),O.append($,E)):r?$=Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):($=Tt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&$.classList.add("persona-hidden"));let Q=r?Tt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Tt({icon:"refresh-cw",label:"Refresh"}),Z=r?Tt({icon:"x",label:s,className:"persona-artifact-doc-icon-btn"}):Tt({icon:"x",label:s}),J=Tt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&J.classList.add("persona-hidden");let fe=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ne=e.features?.artifacts?.toolbarActions??[],ge=()=>{let ee=Ae.find(D=>D.id===Me)??Ae[Ae.length-1],I=ee?.id??null,B=ee?.artifactType==="markdown"?ee.markdown??"":"",y=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"";return{markdown:B,jsonPayload:y,id:I}},ie=async()=>{let ee=Ae.find(I=>I.id===Me)??Ae[Ae.length-1];try{await navigator.clipboard.writeText(vs(ee))}catch{}};if($.addEventListener("click",async()=>{let ee=n?.onDocumentToolbarCopyMenuSelect;if(ee&&F){let{markdown:I,jsonPayload:B,id:y}=ge();try{await ee({actionId:"primary",artifactId:y,markdown:I,jsonPayload:B})}catch{}return}await ie()}),E&&R?.length){let ee=()=>b.closest("[data-persona-root]")??document.body,I=()=>{G=$o({items:R.map(B=>({id:B.id,label:B.label})),onSelect:async B=>{let{markdown:y,jsonPayload:D,id:H}=ge(),N=n?.onDocumentToolbarCopyMenuSelect;try{N?await N({actionId:B,artifactId:H,markdown:y,jsonPayload:D}):B==="markdown"||B==="md"?await navigator.clipboard.writeText(y):B==="json"||B==="source"?await navigator.clipboard.writeText(D):await navigator.clipboard.writeText(y||D)}catch{}},anchor:O??E,position:"bottom-right",portal:ee()})};b.isConnected?I():requestAnimationFrame(I),E.addEventListener("click",B=>{B.stopPropagation(),G?.toggle()})}Q.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}re()}),Z.addEventListener("click",()=>{m(),t.onDismiss?.()});let ue=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)w.replaceChildren(),O?C.append(O,Q,Z):C.append($,Q,Z),C.insertBefore(fe,Z),C.insertBefore(J,Z),w.append(S.element,ue,C);else{let ee=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ee.append($,fe,J,L),w.appendChild(T),w.appendChild(ee)}l&&(w.style.paddingLeft=l,w.style.paddingRight=l);let oe=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&oe.style.setProperty("--persona-artifact-tab-fade-size",p);let me=e.features?.artifacts?.renderTabBar,Se=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),Ce=Uy(oe,{onSelect:ee=>t.onSelect(Ae[ee].id)}),Be=ee=>{let I=ee.scrollWidth-ee.clientWidth,B=I>1,y=Math.abs(ee.scrollLeft);ee.classList.toggle("persona-artifact-tab-fade-start",c&&B&&y>1),ee.classList.toggle("persona-artifact-tab-fade-end",f&&B&&y<I-1)},ut=0,Je=()=>{if(ut)return;let ee=()=>{ut=0,Be(oe)};ut=typeof requestAnimationFrame=="function"?requestAnimationFrame(ee):setTimeout(ee,0)};oe.addEventListener("scroll",()=>Je(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Be(oe)).observe(oe);let Qe=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ne=()=>{Qe.scrollLeft=0},_e=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ne):setTimeout(Ne,0)};if(l){for(let ee of[oe,Se])ee.style.paddingLeft=l,ee.style.paddingRight=l;Qe.style.padding=l}b.appendChild(w),b.appendChild(oe),b.appendChild(Se),b.appendChild(Qe);let Ae=[],Me=null,qe=!1,Jt=!1,gt=!0,Bt=!1,Tn=null,En="",et=null,Le=!1,he=ee=>ee.artifactType==="markdown"&&!!ee.file||r?A:"rendered",tt=ee=>{r||(ee&&!Le?(w.insertBefore(S.element,T),Le=!0):!ee&&Le&&(S.element.remove(),Le=!1))},Te=()=>Me&&Ae.find(ee=>ee.id===Me)||Ae[Ae.length-1],be=()=>{let ee=bs(Te());if(!ee){fe.replaceChildren();return}let I=ne.filter(B=>B.visible===void 0||B.visible(ee)).map(B=>ga(B,{documentChrome:r,onClick:()=>{let y=bs(Te());if(y)try{Promise.resolve(B.onClick(y)).catch(()=>{})}catch{}}}));fe.replaceChildren(...I)},re=()=>{be();let ee=r&&Ae.length<=1,I=!!me;if(oe.classList.toggle("persona-hidden",ee||I),Se.classList.toggle("persona-hidden",ee||!I),I&&me){let D=Ae.map(H=>H.id).join("|")+" "+(Me??"");if(D!==En){En=D;let H=me({records:Ae,selectedId:Me,onSelect:t.onSelect});Se.firstElementChild!==H&&Se.replaceChildren(H)}}else{Ce.beforeRender(),oe.replaceChildren();let D=[],H=-1;for(let[N,K]of Ae.entries()){let V=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");V.type="button";let X=K.artifactType==="markdown"?K.file:void 0,ce=X?$n(X.path):K.title||K.id.slice(0,8),Ve=X?.path||K.title||ce;V.textContent=ce,V.title=Ve,V.setAttribute("aria-label",Ve),K.id===Me&&(V.classList.add("persona-bg-persona-container","persona-border-persona-border"),H=N),V.addEventListener("click",()=>t.onSelect(K.id)),oe.appendChild(V),D.push(V)}if(Ce.render(D,H),H>=0&&Me!==Tn){Tn=Me;let N=D[H];typeof N.scrollIntoView=="function"&&N.scrollIntoView({block:"nearest",inline:"nearest"})}Be(oe)}let B=Me&&Ae.find(D=>D.id===Me)||Ae[Ae.length-1];if(!B){Qe.replaceChildren(),et=null,tt(!1);return}let y=B.artifactType==="markdown"?B.file:void 0;if(tt(!!y&&Mr(y)!=="other"),r){let D=y?Vo(y):B.artifactType==="markdown"?"MD":B.component??"Component",H=(B.title||"Document").trim(),N=y?$n(y.path):H.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ue.textContent=`${N} \xB7 ${D}`}else T.textContent=y?$n(y.path):a;et?(et.el.parentElement!==Qe&&Qe.replaceChildren(et.el),et.update(B)):(et=gl(B,{config:e,resolveViewMode:he}),Qe.replaceChildren(et.el)),Qe.classList.toggle("persona-artifact-content-flush",!!Qe.querySelector(".persona-code-pre"))},xe=()=>{let ee=Ae.length>0;if(b.classList.toggle("persona-hidden",!ee),g){let y=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ee&&y&&qe?(g.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(g.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},kn=()=>{Bt=!1,re(),xe()};return{element:b,backdrop:g,update(ee){let I=ee.selectedId??ee.artifacts[ee.artifacts.length-1]?.id??null,B=I!==Me;Ae=ee.artifacts,Me=I,Ae.length>0&&(qe=!0),Bt=!0,gt&&kn(),B&&Ne()},setMobileOpen(ee){qe=ee,!ee&&g?(g.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):xe()},setExpanded(ee){ee!==Jt&&(Jt=ee,_e());let I=ae(ee?"minimize":"maximize",16,"currentColor",2);I&&J.replaceChildren(I);let B=ee?"Collapse artifacts panel":"Expand artifacts panel";J.setAttribute("aria-label",B),J.title=B},setExpandToggleVisible(ee){J.classList.toggle("persona-hidden",!ee)},setCopyButtonVisible(ee){r||$.classList.toggle("persona-hidden",!ee)},setCustomActions(ee){ne=ee,be()},setTabFade(ee){let I=d(ee);I.start===c&&I.end===f||(c=I.start,f=I.end,Be(oe))},setRenderTabBar(ee){ee!==me&&(me=ee,En="",re())},setVisible(ee){ee!==gt&&(gt=ee,ee&&Bt&&kn())}}}function tn(e){return e?.features?.artifacts?.enabled===!0}function Vy(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"),!tn(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 $A(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 zy=["panel","seamless","detached"];function Zu(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&zy.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function ef(e){return!e||!tn(e)?!1:Zu(e)==="detached"}function Is(e,t){if(!tn(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),$A(e),Vy(e,t);return}let n=t.features?.artifacts?.layout,o=Zu(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?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),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"),Vy(e,t)}function Ws(e,t){for(let l of zy)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"),!tn(t))return;let n=t.features?.artifacts?.layout,o=Zu(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 $y(e,t){return!t||!tn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var jA=new Set(["__proto__","prototype","constructor"]),GA=new Set(["collapsed","card","panel","inline"]),jy=new Set(["markdown","component"]),KA=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Hr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ul=e=>!jA.has(e),tf=e=>typeof e=="string"&&GA.has(e),Br=e=>Object.keys(e).length>0;function Gn(e,t,n,o){e.push({path:t,code:n,message:o})}var XA="Ignored because this key is not part of the persisted preference schema.",_l="Ignored an unsupported value.",JA="Expected collapsed, panel, or inline.",QA='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Gy={kind:"mode",message:_l},Aa={kind:"string",message:"Expected a CSS length string."},go={kind:"boolean"},YA={paneWidth:Aa,paneMaxWidth:Aa,paneMinWidth:Aa,expandedPanelWidth:Aa,resizableMinWidth:Aa,resizableMaxWidth:Aa,expandLauncherPanelWhenOpen:go,resizable:go},ZA={kind:"object",message:"Expected a preference object.",children:{showToolCalls:go,showReasoning:go,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:_l},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:_l},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:_l},expandable:go,grouped:go}},reasoningDisplay:{kind:"object",children:{expandable:go,activePreview:go}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Gy,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Gy,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:jy,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:jy}}},filePreview:{kind:"object",children:{enabled:go}},layout:{kind:"object",children:YA}}}}};function Ky(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Gn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Gn(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Gn(o,n,"invalid_value",t.message);case"mode":return tf(e)?sn(e):Gn(o,n,"invalid_value",t.message);case"modeMap":{if(!Hr(e))return Gn(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:Po(s);Ul(s)&&(r?r.has(s):KA.test(p))?tf(l)?a[p]=sn(l):Gn(o,`${n}.${s}`,"invalid_value",JA):Gn(o,`${n}.${s}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":QA)}return Br(a)?a:void 0}case"object":{if(t.bareMode&&tf(e))return sn(e);if(!Hr(e))return Gn(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))(!Ul(l)||!r.includes(l))&&Gn(o,a(l),"unknown_key",XA);let s={};for(let l of r){let p=t.children[l],d=Ky(e[l],p,a(l),o);if(p.deprecated&&e[l]!==void 0&&Gn(o,a(l),"deprecated_key",p.deprecated),d===void 0)continue;let c=p.alias??l,f=s[c];s[c]=Hr(f)&&Hr(d)?{...f,...d}:d}return Br(s)?s:void 0}}}function nf(e){let t=[];return{preferences:(e===null?void 0:Ky(e,ZA,"",t))??{},issues:t}}function Sa(e){if(Array.isArray(e))return e.map(Sa);if(!Hr(e))return e;let t={};for(let[n,o]of Object.entries(e))Ul(n)&&o!==void 0&&(t[n]=Sa(o));return t}function Xy(e,t){let n=Sa(e);for(let[o,r]of Object.entries(t)){if(!Ul(o)||r===void 0)continue;let a=n[o];n[o]=Hr(a)&&Hr(r)?Xy(a,r):Sa(r)}return n}function eS(e){let t={},n;for(let r of e){let a=nf(r).preferences;n=Jy(n,a.artifacts?.display),t=Xy(t,a)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function tS(e,t){if(t===void 0)return e===void 0?void 0:Sa(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}:{},...Br(r)?{byMediaType:r}:{}};return Br(a)?a:void 0}function Jy(e,t){if(t===void 0)return e===void 0?void 0:Sa(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=tS(n.files,t.files),s={...o?{default:o}:{},...Br(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return Br(s)?s:void 0}function of(e={},t){let n=eS(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=Jy(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 Hs(e){let t=e.preferences;return!t||!Br(t)?e:{...e,features:of(e.features??{},[t])}}function nS(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 oS(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 rS(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function aS(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function rf(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 Qy(e,t,n,o,r,a){let s=nS(r,200),l=aS(t,n,o,200);l=Math.max(s,l);let p=oS(a);return p!==null&&(l=Math.min(l,p)),rS(e,s,l)}var Yy={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"}},af=(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=Yy[s]??Yy.init;a.classList.add("persona-form-card","persona-space-y-4");let p=v("div","persona-space-y-1"),d=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let b=v("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,p.appendChild(b)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let w=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");w.htmlFor=`${t.id}-${s}-${b.name}`;let T=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=b.label,w.appendChild(T);let L=b.type??"text",A;L==="textarea"?(A=document.createElement("textarea"),A.rows=3):(A=document.createElement("input"),A.type=L),A.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",A.id=`${t.id}-${s}-${b.name}`,A.name=b.name,A.placeholder=b.placeholder??"",b.required&&(A.required=!0),w.appendChild(A),c.appendChild(w)});let f=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=l.submitLabel??"Submit",f.appendChild(g),f.appendChild(m),c.appendChild(f),a.replaceChildren(p,c),c.addEventListener("submit",async b=>{b.preventDefault();let w=n.formEndpoint??"/form",T=new FormData(c),L={};T.forEach((A,S)=>{L[S]=A}),L.type=s,m.disabled=!0,g.textContent="Submitting\u2026";try{let A=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!A.ok)throw new Error(`Form submission failed (${A.status})`);let S=await A.json();g.textContent=S.message??"Thanks! We'll be in touch soon.",S.success&&S.nextPrompt&&await o.sendMessage(String(S.nextPrompt))}catch(A){g.textContent=A instanceof Error?A.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var sf=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()}},Bs=new sf;var Zy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sS=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),eb=(e,t,n)=>{if(!Zy(e)||!Zy(t)||sS.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]=eb(e[r],t[r],a)}return o};function ql(e,t){let n=eb(e,t,"");return da(n)}var tb=()=>{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 iS=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},lS=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=iS(e),n=lS(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}},lf=e=>typeof e=="string"?e:e==null?"":String(e),Dr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:lf(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=lf(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:lf(n.text)}}},nb=e=>Array.isArray(e)?e.map(t=>String(t)):[],Fs=e=>{let t=new Set(nb(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(nb(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)},f=d(l,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!f)continue;if(f.handled){let g=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:g,resubmit:f.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var cS=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}},dS=e=>e.map(t=>({...t,streaming:!1})),pS=e=>e.map(t=>({...t,status:"complete"})),Vl=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?cS(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?dS(n.messages):void 0,artifacts:n.artifacts?pS(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 Ma=ko(wi(),1);function uS(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function fS(e,t){if(!uS(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 zl(){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,Ma.parse)(n,Ma.STR|Ma.OBJ),a=fS(r,n);a&&(e=a)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function ob(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function $l(e,t){let{config:n,message:o,onPropsUpdate:r}=t,a=Nn.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 rb(){let e=zl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ab(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 Os(e){let t=ab(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 jl(e){let t=ab(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 mS=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Gl(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=mS}=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 f=null,g=document.createElement("div");g.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,m.appendChild(b);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=r,m.appendChild(w),g.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let P=1;P<=5;P++){let R=document.createElement("button");R.type="button",R.className="persona-feedback-rating-btn persona-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${P} star${P>1?"s":""}: ${d[P-1]}`),R.title=d[P-1],R.dataset.rating=String(P),R.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
|
-
`,w.addEventListener("click",()=>{u=R,P.forEach((H,F)=>{let K=F<R;H.classList.toggle("selected",K),H.setAttribute("aria-checked",F===R-1?"true":"false")})}),P.push(w),k.appendChild(w)}g.appendChild(k);let M=null;if(p){let R=document.createElement("div");R.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=a,M.rows=3,M.setAttribute("aria-label","Additional comments"),R.appendChild(M),g.appendChild(R)}let A=document.createElement("div");A.className="persona-feedback-actions";let 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 E=document.createElement("button");return E.type="button",E.className="persona-feedback-btn persona-feedback-btn-submit",E.textContent=s,E.addEventListener("click",async()=>{if(u===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}E.disabled=!0,E.textContent="Submitting...";try{let R=M?.value.trim()||void 0;await t(u,R),d.remove()}catch(R){E.disabled=!1,E.textContent=s,console.error("[CSAT Feedback] Failed to submit:",R)}}),A.appendChild(C),A.appendChild(E),g.appendChild(A),d.appendChild(g),d}function El(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:c="Not likely",highLabel:d="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let S=document.createElement("h3");S.className="persona-feedback-title",S.textContent=o,h.appendChild(S);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=r,h.appendChild(k),f.appendChild(h);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-nps",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let A=document.createElement("span");A.className="persona-feedback-label-low",A.textContent=c;let C=document.createElement("span");C.className="persona-feedback-label-high",C.textContent=d,M.appendChild(A),M.appendChild(C);let E=document.createElement("div");E.className="persona-feedback-numbers";let R=[];for(let D=0;D<=10;D++){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 ${D} out of 10`),q.textContent=String(D),q.dataset.rating=String(D),D<=6?q.classList.add("persona-feedback-detractor"):D<=8?q.classList.add("persona-feedback-passive"):q.classList.add("persona-feedback-promoter"),q.addEventListener("click",()=>{g=D,R.forEach((Y,de)=>{Y.classList.toggle("selected",de===D),Y.setAttribute("aria-checked",de===D?"true":"false")})}),R.push(q),E.appendChild(q)}P.appendChild(M),P.appendChild(E),f.appendChild(P);let w=null;if(p){let D=document.createElement("div");D.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"),D.appendChild(w),f.appendChild(D)}let H=document.createElement("div");H.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 K=document.createElement("button");return K.type="button",K.className="persona-feedback-btn persona-feedback-btn-submit",K.textContent=s,K.addEventListener("click",async()=>{if(g===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}K.disabled=!0,K.textContent="Submitting...";try{let D=w?.value.trim()||void 0;await t(g,D),u.remove()}catch(D){K.disabled=!1,K.textContent=s,console.error("[NPS Feedback] Failed to submit:",D)}}),H.appendChild(F),H.appendChild(K),f.appendChild(H),u.appendChild(f),u}var aa="persona-chat-history",Ow=30*1e3,Nw=641,_w={"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 Uw(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=_w[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 kl(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 qw(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 Vw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var vu=e=>!e||typeof e!="object"?{}:{...e},Qh=e=>e.map(t=>({...t,streaming:!1})),Yh=(e,t,n)=>{let o=e?.markdown?tr(e.markdown):null,r=Hr(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=Jn()!==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?ym(s):s,u=o(d);c=r&&p?r(u):u}else c=Fn(s);return c}};function Zh(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=ae(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 zw=(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},$w=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:zw(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=Vr(t),r=o.features;o=ms(o);let a=gs.getForInstance(o.plugins),{plugin:s,teardown:l}=Eh();o.components&&Rn.registerAll(o.components);let p=jh(),d=o.persistState===!1?null:o.storageAdapter??wl(),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=vu(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 S=()=>u,k=i=>{u=i({...u})??{},$l()},P=o.actionParsers&&o.actionParsers.length?o.actionParsers:[hs],M=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[xr.message,xr.messageAndClick],A=ys({parsers:P,handlers:M,getSessionMetadata:S,updateSessionMetadata:k,emit:p.emit,documentRef:typeof document<"u"?document:null});A.syncFromMetadata();let C=o.launcher?.enabled??!0,E=o.launcher?.autoExpand??!1,R=o.autoFocusInput??!1,w=E,H=C,F=o.layout?.header?.layout,K=!1,D=()=>No(o),q=()=>C||D(),Y=D()?!1:C?E:!0,de=!1,be=null,pe=()=>{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)},te=Yh(o,A,pe),me=o.features?.showReasoning??!0,oe=o.features?.showToolCalls??!0,le=o.features?.showEventStreamToggle??!1,Z=o.features?.scrollToBottom??{},he=o.features?.scrollBehavior??{},ve=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,we=le?new cs(ve):null,Ee=o.features?.eventStream?.maxEvents??2e3,ke=le?new ds(Ee,we):null,Se=le?new ps:null,Ge=null,ze=!1,Me=null,Re=0;we?.open().then(()=>ke?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Ke={onCopy:i=>{p.emit("message:copy",i),V?.isClientTokenMode()&&V.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),V?.isClientTokenMode()&&V.submitMessageFeedback(i.messageId,i.type).catch(m=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",m)}),o.messageActions?.onFeedback?.(i)}},Bt=o.statusIndicator??{},Wt=i=>i==="idle"?Bt.idleText??It.idle:i==="connecting"?Bt.connectingText??It.connecting:i==="connected"?Bt.connectedText??It.connected:i==="error"?Bt.errorText??It.error:i==="paused"?Bt.pausedText??It.paused:i==="resuming"?Bt.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=uh({config:o,showClose:q()}),{wrapper:De,panel:ue,pillRoot:Qe}=wt.shell,He=wt.panelElements,{container:fe,body:ie,messagesWrapper:We,starterSuggestions:Xt,transcriptSuggestions:ut,suggestions:ht,textarea:j,sendButton:T,sendButtonWrapper:$,composerForm:b,statusText:W,introTitle:B,introSubtitle:_,closeButton:U,iconHolder:O,headerTitle:J,headerSubtitle:se,header:Te,footer:ye,actionsRow:ot,rightActions:nt}=He,Ue=He.leftActions,Ye=He.setSendButtonMode,G=He.micButton,qe=He.micButtonWrapper,Fe=He.attachmentButton,Dt=He.attachmentButtonWrapper,vt=He.attachmentInput,Jt=He.attachmentPreviewsContainer;fe.classList.add("persona-relative"),ie.classList.add("persona-relative");let Cs=12,ao=()=>Z.label??"",Oy=()=>Z.iconName??"arrow-down",Ny=()=>Z.enabled!==!1,gn=()=>he.mode??"anchor-top",so=()=>gn()==="follow"||gn()==="anchor-top"&&xa,Du=()=>he.anchorTopOffset??16,_y=()=>he.restorePosition??"bottom",Fu=()=>he.pauseOnInteraction===!0,Ou=()=>he.showActivityWhilePinned!==!1,Nu=()=>he.announce===!0,kt=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");kt.type="button",kt.style.display="none",kt.setAttribute("data-persona-scroll-to-bottom","true");let ia=x("span","persona-flex persona-items-center"),Wl=x("span",""),_o=x("span","");_o.setAttribute("data-persona-scroll-to-bottom-count",""),_o.style.display="none",kt.append(ia,Wl,_o),fe.appendChild(kt);let io=x("div","persona-stream-anchor-spacer");io.setAttribute("aria-hidden","true"),io.setAttribute("data-persona-anchor-spacer",""),io.style.flexShrink="0",io.style.pointerEvents="none",io.style.height="0px",ie.appendChild(io);let Uo=x("div","persona-sr-only");Uo.setAttribute("aria-live","polite"),Uo.setAttribute("aria-atomic","true"),Uo.setAttribute("role","status"),Uo.setAttribute("data-persona-live-region",""),Object.assign(Uo.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"}),fe.appendChild(Uo);let la=null,ws=null,_u=i=>{!Nu()||!i||(ws=i,la===null&&(la=setTimeout(()=>{la=null,ws&&Nu()&&(Uo.textContent=ws),ws=null},400)))},vr=()=>{let m=ye.style.display==="none"?0:ye.offsetHeight;kt.style.bottom=`${m+Cs}px`};vr();let Uu=()=>{let i=!!ao();kt.setAttribute("aria-label",ao()||"Jump to latest"),kt.title=ao(),kt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),ia.innerHTML="";let m=ae(Oy(),"14px","currentColor",2);m?(ia.appendChild(m),ia.style.display=""):ia.style.display="none",Wl.textContent=ao(),Wl.style.display=i?"":"none"};Uu();let At=null,ln=null,qu=null,Vu=a.find(i=>i.renderHeader);if(Vu?.renderHeader){let i=Vu.renderHeader({config:o,defaultRenderer:()=>{let m=oo({config:o,showClose:q()});return ur(fe,m,o),m.header},onClose:()=>lt(!1,"user")});if(i){let m=fe.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(i),Te=i,wt.header.element=i)}}let Hl=()=>{if(!ke)return;if(ze=!0,!Ge&&ke&&(Ge=Rh({buffer:ke,getFullHistory:()=>ke.getAllFromStore(),onClose:()=>da(),config:o,plugins:a,getThroughput:()=>Se?.getMetric()??{status:"idle"}})),Ge&&(ie.style.display="none",ye.parentNode?.insertBefore(Ge.element,ye),Ge.update()),Ze){Ze.style.boxShadow=`inset 0 0 0 1.5px ${en.actionIconColor}`;let m=o.features?.eventStream?.classNames?.toggleButtonActive;m&&m.split(/\s+/).forEach(y=>y&&Ze.classList.add(y))}let i=()=>{if(!ze)return;let m=Date.now();m-Re>=200&&(Ge?.update(),Re=m),Me=requestAnimationFrame(i)};Re=0,Me=requestAnimationFrame(i),cn(),p.emit("eventStream:opened",{timestamp:Date.now()})},da=()=>{if(ze){if(ze=!1,Ge&&Ge.element.remove(),ie.style.display="",Ze){Ze.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(m=>m&&Ze.classList.remove(m))}Me!==null&&(cancelAnimationFrame(Me),Me=null),cn(),p.emit("eventStream:closed",{timestamp:Date.now()})}},Ze=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:"");Ze=x("button",m),Ze.style.width="28px",Ze.style.height="28px",Ze.style.color=en.actionIconColor,Ze.type="button",Ze.setAttribute("aria-label","Event Stream"),Ze.title="Event Stream";let y=ae("activity","18px","currentColor",1.5);y&&Ze.appendChild(y);let v=He.clearChatButtonWrapper,L=He.closeButtonWrapper,I=v||L;I&&I.parentNode===Te?Te.insertBefore(Ze,I):Te.appendChild(Ze),Ze.addEventListener("click",()=>{ze?da():Hl()})}let Uy=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 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=x("input");L.type="file",L.setAttribute("data-persona-composer-attachment-input",""),L.accept=(m.allowedTypes??to).join(","),L.multiple=(m.maxFiles??4)>1,L.style.display="none",L.setAttribute("aria-label",m.buttonTooltipText??"Attach files"),i.appendChild(L)}},zu=a.find(i=>i.renderComposer);if(zu?.renderComposer){let i=o.composer,m=zu.renderComposer({config:o,defaultRenderer:()=>Qr({config:o}).footer,onSubmit:y=>{if(!V||V.isStreaming())return;let v=y.trim(),L=At?.hasAttachments()??!1;if(!v&&!L)return;Wf();let I;L&&(I=[],I.push(...At.getContentParts()),v&&I.push(Lo(v))),V.sendMessage(v,{contentParts:I}),L&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{vt?.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?()=>{qu?.()}:void 0});m&&(wt.replaceComposer(m),ye=wt.composer.footer)}let qy=i=>{let m=(...ce)=>{for(let re of ce){let ge=i.querySelector(re);if(ge)return ge}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]"),Q=i.querySelector("[data-persona-composer-status]");y&&(b=y),v&&(j=v),L&&(T=L),I&&(G=I,qe=I.parentElement),Q&&(W=Q);let z=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");z&&(ht=z);let X=m("[data-persona-composer-attachment-button]",".persona-attachment-button");X&&(Fe=X,Dt=X.parentElement),vt=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Jt=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ee=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ee&&(ot=ee),Ue=m(".persona-widget-composer__left-actions")};Uy(ye),qy(ye);let Wn=o.layout?.contentMaxWidth??(D()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Wn&&(We.style.maxWidth=Wn,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",Xt.style.maxWidth=Wn,ut.style.maxWidth=Wn,ut.style.marginLeft="auto",ut.style.marginRight="auto",ut.style.width="100%"),Wn&&b&&!D()&&(b.style.maxWidth=Wn,b.style.marginLeft="auto",b.style.marginRight="auto"),Wn&&ht&&!D()&&(ht.style.maxWidth=Wn,ht.style.marginLeft="auto",ht.style.marginRight="auto"),Wn&&Jt&&!D()&&(Jt.style.maxWidth=Wn,Jt.style.marginLeft="auto",Jt.style.marginRight="auto"),o.attachments?.enabled&&vt&&Jt){At=lr.fromConfig(o.attachments),At.setPreviewsContainer(Jt),vt.addEventListener("change",y=>{let v=y.target;At?.handleFileSelect(v.files),v.value=""});let i=o.attachments.dropOverlay,m=Zh(i);fe.appendChild(m)}let Vy=()=>ln?.prefetch();if(o.contextMentions?.enabled&&j&&(ln=wg({config:o,textarea:j,anchor:b??j,getMessages:()=>V.getMessages(),liveRegionHost:fe}),ln)){let i=j;i.parentElement?.insertBefore(ln.contextRow,i);let m=ln.affordanceButtons;for(let y=m.length-1;y>=0;y--){let v=m[y];Ue?Ue.insertBefore(v,Ue.firstChild):b?.appendChild(v)}}(()=>{let i=o.layout?.slots??{},m=v=>{switch(v){case"body-top":return fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return We;case"footer-top":return ht;case"composer":return b;case"footer-bottom":return W;default:return null}},y=(v,L)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")Te.insertBefore(L,Te.firstChild);else if(v==="header-right")Te.appendChild(L);else{let I=Te.querySelector(".persona-flex-col");I?I.parentNode?.insertBefore(L,I.nextSibling):Te.appendChild(L)}break;case"body-top":{let I=ie.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");I?I.replaceWith(L):ie.insertBefore(L,ie.firstChild);break}case"body-bottom":ie.appendChild(L);break;case"footer-top":ht.replaceWith(L);break;case"footer-bottom":W.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 $u=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")Zr.has(L)?Zr.delete(L):Zr.add(L),bh(L,v);else if(I==="tool")ea.has(L)?ea.delete(L):ea.add(L),xh(L,v,o);else if(I==="approval"){let z=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",X=mr.get(L)??z;mr.set(L,!X),Ah(L,v,o)}jo.delete(L)};We.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),$u(i))}),We.addEventListener("keydown",i=>{let m=i.target;(i.key==="Enter"||i.key===" ")&&m.closest('button[data-expand-header="true"]')&&(i.preventDefault(),$u(i))}),We.addEventListener("copy",i=>{let{clipboardData:m}=i;if(!m)return;let y=We.getRootNode(),v=typeof y.getSelection=="function"?y.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let L=v.toString(),I=Gg(L);!I||I===L||(m.setData("text/plain",I),i.preventDefault())});let Bl=new Map,ju=null,Gu="idle",zy={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},$y=(i,m)=>{let{icon:y,label:v}=zy[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=ae(y,14,"currentColor",2);L&&(i.innerHTML="",i.appendChild(L))},Ku=()=>{We.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{let v=m.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;$y(m,v&&v===ju?Gu:"idle")})};We.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 z=V.getMessages().find(X=>X.id===L);if(z&&Ke.onCopy){let X=z.content||"";navigator.clipboard.writeText(X).then(()=>{y.classList.add("persona-message-action-success");let ee=ae("check",14,"currentColor",2);ee&&(y.innerHTML="",y.appendChild(ee)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ce=ae("copy",14,"currentColor",2);ce&&(y.innerHTML="",y.appendChild(ce))},2e3)}).catch(ee=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ee)}),Ke.onCopy(z)}}else if(I==="read-aloud")V.toggleReadAloud(L);else if(I==="upvote"||I==="downvote"){let z=(Bl.get(L)??null)===I,X=I==="upvote"?"thumbs-up":"thumbs-down";if(z){Bl.delete(L),y.classList.remove("persona-message-action-active");let ee=ae(X,14,"currentColor",2);ee&&(y.innerHTML="",y.appendChild(ee))}else{let ee=I==="upvote"?"downvote":"upvote",ce=v.querySelector(`[data-action="${ee}"]`);if(ce){ce.classList.remove("persona-message-action-active");let et=ae(ee==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);et&&(ce.innerHTML="",ce.appendChild(et))}Bl.set(L,I),y.classList.add("persona-message-action-active");let re=ae(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 Ve=V.getMessages().find(dt=>dt.id===L);Ve&&Ke.onFeedback&&Ke.onFeedback({type:I,messageId:Ve.id,message:Ve})}}}),We.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 Q=I==="approve"?"approved":"denied",X=V.getMessages().find(ce=>ce.id===L);if(!X?.approval)return;let ee=v.querySelector("[data-approval-buttons]");ee&&ee.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),X.approval.toolType==="webmcp"?V.resolveWebMcpApproval(L,Q):V.resolveApproval(X.approval,Q)});let Xe=null,ca=null,pa=()=>{},ua="none",As=null,wn={artifacts:[],selectedId:null},Vn=!1,An=!1,fa=!1,Cr=!1,Xu=()=>Cr||wn.artifacts.some(i=>On(o.features?.artifacts,i)==="panel"),Ss=()=>wn.artifacts.length>0&&!Vn&&Xu(),st={current:null},Dl=(i,m)=>{let y=V.getArtifactById(m),v=y?.markdown,L=y?.title||"artifact",I=y?.file,Q=y?.artifactType??"markdown";if(!v){let ee=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ee){let re=V.getMessages().find(ge=>ge.id===ee);if(re?.rawContent)try{let ge=JSON.parse(re.rawContent);v=ge?.props?.markdown,L=ge?.props?.title||L,ge?.props?.file&&typeof ge.props.file=="object"&&(I=ge.props.file),!y&&typeof ge?.props?.artifactType=="string"&&(Q=ge.props.artifactType)}catch{}}}return{markdown:v,title:L,file:I,artifactType:Q}};We.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:Q,file:z}=Dl(y,v);if(!I)return;let{filename:X,mime:ee,content:ce}=Lg({title:Q,markdown:I,file:z}),re=new Blob([ce],{type:ee}),ge=URL.createObjectURL(re),Ve=document.createElement("a");Ve.href=ge,Ve.download=X,Ve.click(),URL.revokeObjectURL(ge)}),We.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]"),Q=L?L.getAttribute("data-artifact-inline"):I?.getAttribute("data-open-artifact")??null,X=(L?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(dt=>dt.id===v);if(!X)return;let{markdown:ee,title:ce,file:re,artifactType:ge}=Dl(y,Q??""),Ve={artifactId:Q,title:ce,artifactType:ge,markdown:ee,file:re};try{Promise.resolve(X.onClick(Ve)).catch(()=>{})}catch{}}),We.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=V.getArtifactById(v),I="";if(L)I=ns(L);else{let{markdown:Q,file:z,artifactType:X}=Dl(y,v);X==="markdown"&&(I=ns({id:v,artifactType:"markdown",status:"complete",markdown:Q??"",...z?{file:z}:{}}))}I&&navigator.clipboard.writeText(I).then(()=>{let Q=ae("check",16,"currentColor",2);Q&&(y.replaceChildren(Q),setTimeout(()=>{let z=ae("copy",16,"currentColor",2);z&&y.replaceChildren(z)},1500))}).catch(()=>{})}),We.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||(Vn=!1,Cr=!0,An=!0,fa=!0,V.selectArtifact(v),zn())}),We.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(),Vn=!1,Cr=!0,V.selectArtifact(v),zn())}),We.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 wr=He.composerOverlay,Ar=(i,m,y)=>{let v=m.trim();if(!v||!st.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})),So(wr,L);let Q=st.current.getMessages().find(z=>z.toolCall?.id===L);Q?.agentMetadata?.awaitingLocalTool?st.current.resolveAskUserQuestion(Q,y.structured??v):st.current.sendMessage(v)},qo=i=>{let m=st.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:ai(i,v),currentIndex:Cn(i)})},Ju=i=>Object.entries(i).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Fl=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let m=Cn(i),y=Fr(i);if(m>=y-1)return;let v=st.current?.getMessages().find(L=>L.toolCall?.id===i.getAttribute("data-tool-call-id"));v&&(si(i,v,o,m+1),qo(i))};wr.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})),So(wr,I);let Q=st.current?.getMessages().find(z=>z.toolCall?.id===I);Q?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(Q),st.current?.resolveAskUserQuestion(Q,"(dismissed)"));return}if(L==="pick"){let I=y.getAttribute("data-option-label");if(!I)return;let Q=v.getAttribute("data-multi-select")==="true",z=Ao(v);if(z&&Q){let X=nr(v)[Cn(v)],ee=new Set(Array.isArray(X)?X:[]);ee.has(I)?ee.delete(I):ee.add(I),Mo(v,Array.from(ee)),qo(v);return}if(z){Mo(v,I),qo(v),Fl(v);return}if(Q){let X=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",X?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!X);let ee=v.querySelector('[data-ask-user-action="submit-multi"]');ee&&(ee.disabled=xd(v).length===0);return}Ar(v,I,{source:"pick",values:[I]});return}if(L==="submit-multi"){let I=xd(v);if(I.length===0)return;Ar(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 Q=v.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Q.trim())return;if(Ao(v)){Mo(v,Q.trim()),qo(v),Fl(v);return}Ar(v,Q,{source:"free-text"});return}if(L==="next"||L==="back"){if(!st.current)return;let I=v.getAttribute("data-tool-call-id")??"",Q=st.current.getMessages().find(re=>re.toolCall?.id===I);if(!Q)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(X){let re=nr(v)[Cn(v)];(typeof re!="string"||re!==X)&&Mo(v,X)}let ee=L==="next"?1:-1,ce=Cn(v)+ee;si(v,Q,o,ce),qo(v);return}if(L==="submit-all"){if(!st.current)return;let I=v.getAttribute("data-tool-call-id")??"",Q=st.current.getMessages().find(re=>re.toolCall?.id===I);if(!Q)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";X&&Mo(v,X);let ee=ai(v,Q);st.current.persistAskUserQuestionProgress(Q,{answers:ee,currentIndex:Cn(v)});let ce=Ju(ee);Ar(v,ce||"(submitted)",{source:"submit-all",structured:ee});return}if(L==="skip"){if(!st.current)return;let I=v.getAttribute("data-tool-call-id")??"",Q=st.current.getMessages().find(ge=>ge.toolCall?.id===I);if(!Q)return;let z=Ao(v),X=Cn(v),ee=Fr(v),ce=X>=ee-1;if(!z){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:I},bubbles:!0,composed:!0})),So(wr,I),Q.agentMetadata?.awaitingLocalTool&&(st.current.markAskUserQuestionResolved(Q),st.current.resolveAskUserQuestion(Q,"(dismissed)"));return}Mo(v,"");let re=v.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),ce){let ge=ai(v,Q),Ve=Ju(ge);Ar(v,Ve||"(skipped)",{source:"submit-all",structured:ge});return}si(v,Q,o,X+1),qo(v);return}}),wr.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(Ao(v)){Mo(v,L.trim()),qo(v),Fl(v);return}Ar(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=wr.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 lo=null,yt=null,ma=null,Ms=null,Ol=()=>{},Yu=!1,Ts="",Es="";function Nl(){Ms?.(),Ms=null}let Zu=()=>{if(!lo||!yt)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){yt.style.removeProperty("position"),yt.style.removeProperty("left"),yt.style.removeProperty("top"),yt.style.removeProperty("bottom"),yt.style.removeProperty("width"),yt.style.removeProperty("z-index");return}let v=lo.firstElementChild;if(!v||v===yt)return;let L=10;yt.style.position="absolute",yt.style.top="0",yt.style.bottom="0",yt.style.width=`${L}px`,yt.style.zIndex="5";let I=hu(lo,m),Q=v.offsetWidth+I/2-L/2;yt.style.left=`${Math.max(0,Q)}px`},ks=()=>{},jy=()=>{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)},Ls=()=>!tn(o)||!Ss()||e.classList.contains("persona-artifact-narrow-host")||jy()||(e.ownerDocument.defaultView??window).innerWidth<Nw?"none":uu(o)?"detached":"welded",zn=()=>{if(!Xe||!tn(o))return;us(e,o),fs(e,o),ks();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,m=ue.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=i);let y=Ss();Xe.setVisible(y),Xe.update(wn),Vn?(Xe.setMobileOpen(!1),Xe.element.classList.add("persona-hidden"),Xe.backdrop?.classList.add("persona-hidden"),An=!1,fa=!1):wn.artifacts.length>0&&Xu()?(Xe.element.classList.remove("persona-hidden"),Xe.setMobileOpen(!0)):(Xe.setMobileOpen(!1),Xe.element.classList.add("persona-hidden"),Xe.backdrop?.classList.add("persona-hidden"),An=!1,fa=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Xe.setExpandToggleVisible(v),Xe.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Xe.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Xe.setTabFade(o.features?.artifacts?.layout?.tabFade),Xe.setRenderTabBar(o.features?.artifacts?.renderTabBar),!v&&!fa&&(An=!1),An!==Yu){let I=Xe.element;An?(Ts=I.style.width,Es=I.style.maxWidth,I.style.removeProperty("width"),I.style.removeProperty("max-width")):(Ts&&(I.style.width=Ts),Es&&(I.style.maxWidth=Es),Ts="",Es=""),Yu=An}e.classList.toggle("persona-artifact-expanded",An),Xe.setExpanded(An);let L=Ls();L!==ua&&(ua=L,pa()),Ol()};if(tn(o)){ue.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(fe),Xe=Wh(o,{onSelect:y=>st.current?.selectArtifact(y),onDismiss:()=>{Vn=!0,zn()},onToggleExpand:()=>{let y=!An,v=wn.selectedId??wn.artifacts[wn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:v,expanded:y})!==!0&&(An=y,y||(fa=!1),zn())}}),Xe.element.classList.add("persona-hidden"),lo=m,m.appendChild(i),m.appendChild(Xe.element),Xe.backdrop&&ue.appendChild(Xe.backdrop),ue.appendChild(m),Ol=()=>{if(!lo||!Xe)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){ma?.(),ma=null,Nl(),yt&&(yt.remove(),yt=null),Xe.element.style.removeProperty("width"),Xe.element.style.removeProperty("maxWidth");return}if(!yt){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 L=e.ownerDocument,I=L.defaultView??window,Q=z=>{if(!Xe||z.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||I.innerWidth<=640)return;z.preventDefault(),Nl();let X=z.clientX,ee=Xe.element.getBoundingClientRect().width,ce=o.features?.artifacts?.layout,re=Ve=>{let dt=lo.getBoundingClientRect().width,et=e.classList.contains("persona-artifact-welded-split"),pn=hu(lo,I),St=et?0:v.getBoundingClientRect().width||6,Pt=ee-(Ve.clientX-X),N=qh(Pt,dt,pn,St,ce?.resizableMinWidth,ce?.resizableMaxWidth);Xe.element.style.width=`${N}px`,Xe.element.style.maxWidth="none",Zu()},ge=()=>{L.removeEventListener("pointermove",re),L.removeEventListener("pointerup",ge),L.removeEventListener("pointercancel",ge),Ms=null;try{v.releasePointerCapture(z.pointerId)}catch{}};Ms=ge,L.addEventListener("pointermove",re),L.addEventListener("pointerup",ge),L.addEventListener("pointercancel",ge);try{v.setPointerCapture(z.pointerId)}catch{}};v.addEventListener("pointerdown",Q),yt=v,lo.insertBefore(v,Xe.element),ma=()=>{v.removeEventListener("pointerdown",Q)}}if(yt){let v=Ss();yt.classList.toggle("persona-hidden",!v),Zu()}},ks=()=>{if(!C||!Xe||(o.launcher?.sidebarMode??!1)||Et(o)&&sn(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||!Dh(o,C))return;let Q=o.launcher?.width??o.launcherWidth??fn,z=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Ss()?(ue.style.width=z,ue.style.maxWidth=z):(ue.style.width=Q,ue.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(ca=new ResizeObserver(()=>{zn()}),ca.observe(ue))}else ue.appendChild(fe);D()&&Qe&&(He.peekBanner&&Qe.appendChild(He.peekBanner),Qe.appendChild(ye)),e.appendChild(De),Qe&&e.appendChild(Qe);let Ps=()=>{if(D()){ue.style.width="100%",ue.style.maxWidth="100%";let Tt=o.launcher?.composerBar??{},rn=De.dataset.state==="expanded",Gs=Tt.expandedSize??"anchored";if(!(rn&&Gs!=="fullscreen")){fe.style.background="",fe.style.border="",fe.style.borderRadius="",fe.style.overflow="",fe.style.boxShadow="";return}let Wa=o.theme?.components?.panel,Ks=Io(o),Rr=(Kn,er)=>Kn==null||Kn===""?er:Zt(Ks,Kn)??Kn,Xs="1px solid var(--persona-border)",sd="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))";fe.style.background="var(--persona-surface, #ffffff)",fe.style.border=Rr(Wa?.border,Xs),fe.style.borderRadius=Rr(Wa?.borderRadius,Zo),fe.style.boxShadow=Rr(Wa?.shadow,sd),fe.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,Q=Io(o),z=(Tt,rn)=>Tt==null||Tt===""?rn:Zt(Q,Tt)??Tt,X=e.ownerDocument.defaultView??window,ee=o.launcher?.mobileFullscreen??!0,ce=o.launcher?.mobileBreakpoint??640,re=X.innerWidth<=ce,ge=ee&&re&&C,Ve=i&&ee&&re,dt=o.launcher?.position??"bottom-left",et=dt==="bottom-left"||dt==="top-left",pn=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))",Le=L&&!ge&&!Ve;Le?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Oe=Le?St:m||ge?"none":St,Ae=Le?Pt:ge?"none":m?et?"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&&!ge&&!Le&&(Ae="none",Oe="none");let Ct=Le?N:m||ge?"0":N,ct=z(I?.border,Oe),Ft=z(I?.shadow,Ae),pt=z(I?.borderRadius,Ct),on=Ls(),Rt=on==="detached",Pe=on==="welded";e.classList.toggle("persona-artifact-detached-split",Rt),e.classList.toggle("persona-artifact-welded-split",Pe);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)))))",xt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&tn(o)&&uu(o)&&v&&!i;e.classList.toggle("persona-artifact-chat-flush",xt);let it=Rt||xt?"none":Ft,ft=Rt?St:Pe?"none":ct,Je=Rt?N:pt;xt&&(ft="none",Je="0");let Be=I?.borderRadius!=null&&I.borderRadius!=="",gt=xt&&!Be?"0":pt,zt=ie.scrollTop;e.style.cssText="",De.style.cssText="",ue.style.cssText="",fe.style.cssText="",ie.style.cssText="",ye.style.cssText="",ze&&(ie.style.display="none"),(y||v)&&(e.style.minWidth="0");let vn=()=>{if(zt<=0)return;(ie.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ie.scrollTop===zt)return;let rn=ie.scrollHeight-ie.clientHeight;rn<=0||(ie.scrollTop=Math.min(zt,rn))})};if(ge){De.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"),De.style.cssText=`
|
|
49
|
+
`,R.addEventListener("click",()=>{f=P,L.forEach((F,O)=>{let $=O<P;F.classList.toggle("selected",$),F.setAttribute("aria-checked",O===P-1?"true":"false")})}),L.push(R),T.appendChild(R)}g.appendChild(T);let A=null;if(p){let P=document.createElement("div");P.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=a,A.rows=3,A.setAttribute("aria-label","Additional comments"),P.appendChild(A),g.appendChild(P)}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?.(),c.remove()});let M=document.createElement("button");return M.type="button",M.className="persona-feedback-btn persona-feedback-btn-submit",M.textContent=s,M.addEventListener("click",async()=>{if(f===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}M.disabled=!0,M.textContent="Submitting...";try{let P=A?.value.trim()||void 0;await t(f,P),c.remove()}catch(P){M.disabled=!1,M.textContent=s,console.error("[CSAT Feedback] Failed to submit:",P)}}),S.appendChild(C),S.appendChild(M),g.appendChild(S),c.appendChild(g),c}function Kl(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,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let g=null,m=document.createElement("div");m.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=o,b.appendChild(w);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=r,b.appendChild(T),m.appendChild(b);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let S=document.createElement("span");S.className="persona-feedback-label-low",S.textContent=d;let C=document.createElement("span");C.className="persona-feedback-label-high",C.textContent=c,A.appendChild(S),A.appendChild(C);let M=document.createElement("div");M.className="persona-feedback-numbers";let P=[];for(let E=0;E<=10;E++){let G=document.createElement("button");G.type="button",G.className="persona-feedback-rating-btn persona-feedback-number-btn",G.setAttribute("role","radio"),G.setAttribute("aria-checked","false"),G.setAttribute("aria-label",`Rating ${E} out of 10`),G.textContent=String(E),G.dataset.rating=String(E),E<=6?G.classList.add("persona-feedback-detractor"):E<=8?G.classList.add("persona-feedback-passive"):G.classList.add("persona-feedback-promoter"),G.addEventListener("click",()=>{g=E,P.forEach((Q,Z)=>{Q.classList.toggle("selected",Z===E),Q.setAttribute("aria-checked",Z===E?"true":"false")})}),P.push(G),M.appendChild(G)}L.appendChild(A),L.appendChild(M),m.appendChild(L);let R=null;if(p){let E=document.createElement("div");E.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=a,R.rows=3,R.setAttribute("aria-label","Additional comments"),E.appendChild(R),m.appendChild(E)}let F=document.createElement("div");F.className="persona-feedback-actions";let O=document.createElement("button");O.type="button",O.className="persona-feedback-btn persona-feedback-btn-skip",O.textContent=l,O.addEventListener("click",()=>{n?.(),f.remove()});let $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=s,$.addEventListener("click",async()=>{if(g===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let E=R?.value.trim()||void 0;await t(g,E),f.remove()}catch(E){$.disabled=!1,$.textContent=s,console.error("[NPS Feedback] Failed to submit:",E)}}),F.appendChild(O),F.appendChild($),m.appendChild(F),f.appendChild(m),f}var Ta="persona-chat-history",gS=30*1e3,hS=641,yS={"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 bS(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=yS[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 xS(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 vS(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var cf=e=>!e||typeof e!="object"?{}:{...e},sb=e=>e.map(t=>({...t,streaming:!1})),ib=(e,t,n)=>{let o=e?.markdown?hr(e.markdown):null,r=ta(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=ao()!==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?hg(s):s,f=o(c);d=r&&p?r(f):f}else d=Vn(s);return d}};function lb(e){let t=v("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=ae(n,o,r,a);if(s&&t.appendChild(s),e?.label){let l=v("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var CS=(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},wS=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:CS(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Jl=(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=da(t),r=o.features;o=Hs(o);let a=Bs.getForInstance(o.plugins),s=!1,l=Ty(()=>o),{plugin:p,teardown:d}=Dy();o.components&&Nn.registerAll(o.components);let c=tb(),g=o.persistState===!1?null:o.storageAdapter??Vl(),m={},b=null,w=!1,T=i=>{if(o.onStateLoaded)try{let u=o.onStateLoaded(i);if(u&&typeof u=="object"&&"state"in u){let{state:h,open:x}=u;return x&&(w=!0),h}return u}catch(u){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return i};if(g?.load)try{let i=g.load();if(i&&typeof i.then=="function")b=i.then(u=>T(u??{messages:[],metadata:{}}));else{let h=T(i??{messages:[],metadata:{}});h.metadata&&(m=cf(h.metadata)),h.messages?.length&&(o={...o,initialMessages:h.messages}),h.artifacts?.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:h.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=T({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let L=()=>m,A=i=>{m=i({...m})??{},yc()},S=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ds],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Dr.message,Dr.messageAndClick],M=Fs({parsers:S,handlers:C,getSessionMetadata:L,updateSessionMetadata:A,emit:c.emit,documentRef:typeof document<"u"?document:null});M.syncFromMetadata();let P=o.launcher?.enabled??!0,R=o.launcher?.autoExpand??!1,F=o.autoFocusInput??!1,O=R,$=P,E=o.layout?.header?.layout,G=!1,Q=()=>Ko(o),Z=()=>P||Q(),J=Q()?!1:P?R:!0,fe=!1,ne=null,ge=()=>{fe=!0,ne&&clearTimeout(ne),ne=setTimeout(()=>{fe&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),fe=!1)},1e4)},ie=ib(o,M,ge),ue=o.features?.showReasoning??!0,oe=o.features?.showToolCalls??!0,me=o.features?.showEventStreamToggle??!1,Se=o.features?.scrollToBottom??{},Ce=o.features?.scrollBehavior??{},ut=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Je=me?new Ps(ut):null,Qe=o.features?.eventStream?.maxEvents??2e3,Ne=me?new Ls(Qe,Je):null,_e=me?new Rs:null,Ae=null,Me=!1,qe=null,Jt=0;Je?.open().then(()=>Ne?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let gt={onCopy:i=>{c.emit("message:copy",i),q?.isClientTokenMode()&&q.submitMessageFeedback(i.id,"copy").catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",u)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{c.emit("message:feedback",i),q?.isClientTokenMode()&&q.submitMessageFeedback(i.messageId,i.type).catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",u)}),o.messageActions?.onFeedback?.(i)}},Bt=o.statusIndicator??{},Tn=i=>i==="idle"?Bt.idleText??Ht.idle:i==="connecting"?Bt.connectingText??Ht.connecting:i==="connected"?Bt.connectedText??Ht.connected:i==="error"?Bt.errorText??Ht.error:i==="paused"?Bt.pausedText??Ht.paused:i==="resuming"?Bt.resumingText??Ht.resuming:Ht[i];function En(i,u,h,x){if(x==="idle"&&h.idleLink){i.textContent="";let k=document.createElement("a");k.href=h.idleLink,k.target="_blank",k.rel="noopener noreferrer",k.textContent=u,k.style.color="inherit",k.style.textDecoration="none",i.appendChild(k)}else i.textContent=u}let et=My({config:o,showClose:Z()}),{wrapper:Le,panel:he,pillRoot:tt}=et.shell,Te=et.panelElements,{container:be,body:re,messagesWrapper:xe,starterSuggestions:kn,transcriptSuggestions:ee,suggestions:I,textarea:B,sendButton:y,sendButtonWrapper:D,composerForm:H,statusText:N,welcomeHost:K,welcomeIconHolder:V,greetingHost:X,introTitle:ce,introSubtitle:Ve,closeButton:de,iconHolder:Pe,headerTitle:ze,headerSubtitle:Ue,header:We,footer:we,actionsRow:nt,rightActions:wt}=Te,yn=Te.leftActions,Us=Te.setSendButtonMode,te=Te.micButton,bn=Te.micButtonWrapper,it=Te.attachmentButton,xn=Te.attachmentButtonWrapper,Et=Te.attachmentInput,Ln=Te.attachmentPreviewsContainer;be.classList.add("persona-relative"),re.classList.add("persona-relative");let Gb=12,ka=()=>Se.label??"",Kb=()=>Se.iconName??"arrow-down",Xb=()=>Se.enabled!==!1,cn=()=>Ce.mode??"anchor-top",ho=()=>cn()==="follow"||cn()==="anchor-top"&&Oa,La=()=>Ce.anchorTopOffset??16,Jb=()=>Ce.restorePosition??"bottom",Mf=()=>Ce.pauseOnInteraction===!0,Tf=()=>Ce.showActivityWhilePinned!==!1,Ef=()=>Ce.announce===!0,ec=()=>Ce.scrollbar??"on-scroll",Pt=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Pt.type="button",Pt.style.display="none",Pt.setAttribute("data-persona-scroll-to-bottom","true");let Pa=v("span","persona-flex persona-items-center"),tc=v("span",""),Jo=v("span","");Jo.setAttribute("data-persona-scroll-to-bottom-count",""),Jo.style.display="none",Pt.append(Pa,tc,Jo),be.appendChild(Pt);let vn=v("div","persona-stream-anchor-spacer");vn.setAttribute("aria-hidden","true"),vn.setAttribute("data-persona-anchor-spacer",""),vn.style.flexShrink="0",vn.style.pointerEvents="none",vn.style.height="0px",vn.style.display="none",re.appendChild(vn);let Qo=v("div","persona-sr-only");Qo.setAttribute("aria-live","polite"),Qo.setAttribute("aria-atomic","true"),Qo.setAttribute("role","status"),Qo.setAttribute("data-persona-live-region",""),Object.assign(Qo.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"}),be.appendChild(Qo);let Ra=null,qs=null,kf=i=>{!Ef()||!i||(qs=i,Ra===null&&(Ra=setTimeout(()=>{Ra=null,qs&&Ef()&&(Qo.textContent=qs),qs=null},400)))},Yo=()=>{let u=we.style.display==="none"?0:we.offsetHeight;Pt.style.bottom=`${u+Gb}px`};Yo();let Lf=()=>{let i=!!ka();Pt.setAttribute("aria-label",ka()||"Jump to latest"),Pt.title=ka(),Pt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Pa.innerHTML="";let u=ae(Kb(),"14px","currentColor",2);u?(Pa.appendChild(u),Pa.style.display=""):Pa.style.display="none",tc.textContent=ka(),tc.style.display=i?"":"none"};Lf();let bt=null,Qt=null,Pf=null,Rf=a.find(i=>i.renderHeader);if(Rf?.renderHeader){let i=Rf.renderHeader({config:o,defaultRenderer:()=>{let u=fo({config:o,showClose:Z()});return kr(be,u,o),u.header},onClose:()=>lt(!1,"user")});if(i){let u=be.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(i),We=i,et.header.element=i)}}let nc=()=>{if(!Ne)return;if(Me=!0,!Ae&&Ne&&(Ae=_y({buffer:Ne,getFullHistory:()=>Ne.getAllFromStore(),onClose:()=>Ia(),config:o,plugins:a,getThroughput:()=>_e?.getMetric()??{status:"idle"}})),Ae&&(re.style.display="none",we.parentNode?.insertBefore(Ae.element,we),Ae.update()),Ye){Ye.style.boxShadow=`inset 0 0 0 1.5px ${Xt.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(h=>h&&Ye.classList.add(h))}let i=()=>{if(!Me)return;let u=Date.now();u-Jt>=200&&(Ae?.update(),Jt=u),qe=requestAnimationFrame(i)};Jt=0,qe=requestAnimationFrame(i),Vt(),c.emit("eventStream:opened",{timestamp:Date.now()})},Ia=()=>{if(Me){if(Me=!1,Ae&&Ae.element.remove(),re.style.display="",Ye){Ye.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(u=>u&&Ye.classList.remove(u))}qe!==null&&(cancelAnimationFrame(qe),qe=null),Vt(),c.emit("eventStream:closed",{timestamp:Date.now()})}},Ye=null;if(me){let i=o.features?.eventStream?.classNames,u="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:"");Ye=v("button",u),Ye.style.width="28px",Ye.style.height="28px",Ye.style.color=Xt.actionIconColor,Ye.type="button",Ye.setAttribute("aria-label","Event Stream"),Ye.title="Event Stream";let h=ae("activity","18px","currentColor",1.5);h&&Ye.appendChild(h);let x=Te.clearChatButtonWrapper,k=Te.closeButtonWrapper,W=x||k;W&&W.parentNode===We?We.insertBefore(Ye,W):We.appendChild(Ye),Ye.addEventListener("click",()=>{Me?Ia():nc()})}let If=i=>{let u=o.attachments;if(!u?.enabled)return;let h=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!h){h=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let k=i.querySelector("[data-persona-composer-form]");k?.parentNode?k.parentNode.insertBefore(h,k):i.insertBefore(h,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let k=v("input");k.type="file",k.setAttribute("data-persona-composer-attachment-input",""),k.accept=(u.allowedTypes??co).join(","),k.multiple=(u.maxFiles??4)>1,k.style.display="none",k.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),i.appendChild(k)}},oc=a.find(i=>i.renderComposer),rc=!1,Wf=i=>{if(!oc?.renderComposer)return null;let u=o.composer,h=s?q.isStreaming():!1;return oc.renderComposer({config:o,defaultRenderer:i,requestRender:()=>Gx(),storage:l(oc.id),onSubmit:x=>{if(!q||q.isStreaming())return;let k=x.trim(),W=bt?.hasAttachments()??!1;if(!k&&!W)return;Hm();let z;W&&(z=[],z.push(...bt.getContentParts()),k&&z.push(Oo(k))),q.sendMessage(k,{contentParts:z}),W&&bt.clearAttachments()},streaming:h,disabled:h,openAttachmentPicker:()=>{Et?.click()},models:u?.models,selectedModelId:u?.selectedModelId,onModelChange:x=>{o.composer={...o.composer,selectedModelId:x},o.agent&&(o.agent={...o.agent,model:x})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Pf?.()}:void 0})},Hf=Wf(()=>Lr({config:o}).footer);Hf&&(et.replaceComposer(Hf),we=et.composer.footer,rc=!0);let Bf=i=>{let u=(...pe)=>{for(let le of pe){let ye=i.querySelector(le);if(ye)return ye}return null},h=i.querySelector("[data-persona-composer-form]"),x=i.querySelector("[data-persona-composer-input]"),k=i.querySelector("[data-persona-composer-submit]"),W=i.querySelector("[data-persona-composer-mic]"),z=i.querySelector("[data-persona-composer-status]");h&&(H=h),x&&(B=x),k&&(y=k),W&&(te=W,bn=W.parentElement),z&&(N=z);let U=u("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(I=U);let j=u("[data-persona-composer-attachment-button]",".persona-attachment-button");j&&(it=j,xn=j.parentElement),Et=u("[data-persona-composer-attachment-input]",'input[type="file"]'),Ln=u("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let Y=u("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");Y&&(nt=Y),yn=u(".persona-widget-composer__left-actions")};If(we),Bf(we);let Wa=qo(o,Q());Wa&&(xe.style.maxWidth=Wa,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",X.style.maxWidth=Wa,X.style.marginLeft="auto",X.style.marginRight="auto",X.style.width="100%",kn.style.maxWidth=Wa,ee.style.maxWidth=Wa,ee.style.marginLeft="auto",ee.style.marginRight="auto",ee.style.width="100%");let Df=()=>{let i=qo(o,Q());if(!(!i||Q()))for(let u of[H,I,Ln,N])u&&(u.style.maxWidth=i,u.style.marginLeft="auto",u.style.marginRight="auto")};Df();let Ff=()=>{!o.attachments?.enabled||!Et||!Ln||(bt?bt.remountPreviews(Ln):(bt=Ar.fromConfig(o.attachments),bt.setPreviewsContainer(Ln)),Et.addEventListener("change",i=>{let u=i.target;bt?.handleFileSelect(u.files),u.value=""}),be.querySelector(".persona-attachment-drop-overlay")||be.appendChild(lb(o.attachments.dropOverlay)))};Ff();let Qb=()=>Qt?.prefetch(),Of=()=>{if(!(!o.contextMentions?.enabled||!B)&&(Qt=Ch({config:o,textarea:B,anchor:H??B,getMessages:()=>q.getMessages(),liveRegionHost:be}),Qt)){let i=B;i.parentElement?.insertBefore(Qt.contextRow,i);let u=Qt.affordanceButtons;for(let h=u.length-1;h>=0;h--){let x=u[h];yn?yn.insertBefore(x,yn.firstChild):H?.appendChild(x)}}};Of(),(()=>{let i=o.layout?.slots??{},u=x=>{switch(x){case"body-top":return re.querySelector("[data-persona-intro-card]");case"messages":return xe;case"footer-top":return I;case"composer":return H;case"footer-bottom":return N;default:return null}},h=(x,k)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")We.insertBefore(k,We.firstChild);else if(x==="header-right")We.appendChild(k);else{let W=We.querySelector(".persona-flex-col");W?W.parentNode?.insertBefore(k,W.nextSibling):We.appendChild(k)}break;case"body-top":{let W=re.querySelector("[data-persona-intro-card]");W?W.replaceWith(k):re.insertBefore(k,re.firstChild);break}case"body-bottom":re.appendChild(k);break;case"footer-top":I.replaceWith(k);break;case"footer-bottom":N.replaceWith(k);break;default:break}};for(let[x,k]of Object.entries(i))if(k)try{let W=k({config:o,defaultContent:()=>u(x)});W&&h(x,W)}catch(W){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,W)}})();let Nf=i=>{let h=i.target.closest('button[data-expand-header="true"]');if(!h)return;let x=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let k=x.getAttribute("data-message-id");if(!k)return;let W=h.getAttribute("data-bubble-type");if(W==="reasoning")va.has(k)?va.delete(k):va.add(k),Ey(k,x);else if(W==="tool")Ca.has(k)?Ca.delete(k):Ca.add(k),ky(k,x,o);else if(W==="approval"){let U=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",j=Rr.get(k)??U;Rr.set(k,!j),Iy(k,x,o)}ar.delete(k)};xe.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Nf(i))}),xe.addEventListener("keydown",i=>{let u=i.target;(i.key==="Enter"||i.key===" ")&&u.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Nf(i))}),xe.addEventListener("copy",i=>{let{clipboardData:u}=i;if(!u)return;let h=xe.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let k=x.toString(),W=jh(k);!W||W===k||(u.setData("text/plain",W),i.preventDefault())});let ac=new Map,_f=null,Uf="idle",Yb={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Zb=(i,u)=>{let{icon:h,label:x}=Yb[u];i.setAttribute("aria-label",x),i.title=x,i.setAttribute("aria-pressed",u==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",u!=="idle"),i.classList.toggle("persona-message-action-loading",u==="loading");let k=ae(h,14,"currentColor",2);k&&(i.innerHTML="",i.appendChild(k))},qf=()=>{xe.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let x=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Zb(u,x&&x===_f?Uf:"idle")})};xe.addEventListener("click",i=>{let h=i.target.closest(".persona-message-action-btn[data-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.closest("[data-actions-for]");if(!x)return;let k=x.getAttribute("data-actions-for");if(!k)return;let W=h.getAttribute("data-action");if(W==="copy"){let U=q.getMessages().find(j=>j.id===k);if(U&>.onCopy){let j=U.content||"";navigator.clipboard.writeText(j).then(()=>{h.classList.add("persona-message-action-success");let Y=ae("check",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let pe=ae("copy",14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe))},2e3)}).catch(Y=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",Y)}),gt.onCopy(U)}}else if(W==="read-aloud")q.toggleReadAloud(k);else if(W==="upvote"||W==="downvote"){let U=(ac.get(k)??null)===W,j=W==="upvote"?"thumbs-up":"thumbs-down";if(U){ac.delete(k),h.classList.remove("persona-message-action-active");let Y=ae(j,14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))}else{let Y=W==="upvote"?"downvote":"upvote",pe=x.querySelector(`[data-action="${Y}"]`);if(pe){pe.classList.remove("persona-message-action-active");let ct=ae(Y==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ct&&(pe.innerHTML="",pe.appendChild(ct))}ac.set(k,W),h.classList.add("persona-message-action-active");let le=ae(j,14,"currentColor",2);le&&(le.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(le)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ge=q.getMessages().find(ht=>ht.id===k);Ge&>.onFeedback&>.onFeedback({type:W,messageId:Ge.id,message:Ge})}}}),xe.addEventListener("click",i=>{let h=i.target.closest("button[data-approval-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.closest(".persona-approval-bubble");if(!x)return;let k=x.getAttribute("data-message-id");if(!k)return;let W=h.getAttribute("data-approval-action");if(!W)return;let z=W==="approve"?"approved":"denied",j=q.getMessages().find(pe=>pe.id===k);if(!j?.approval)return;let Y=x.querySelector("[data-approval-buttons]");Y&&Y.querySelectorAll("button").forEach(le=>{le.disabled=!0,le.style.opacity="0.5",le.style.cursor="not-allowed"}),j.approval.toolType==="webmcp"?q.resolveWebMcpApproval(k,z):q.resolveApproval(j.approval,z)});let Ke=null,Ha=null,Zo=()=>{},Ba="none",Vs=null,Pn={artifacts:[],selectedId:null},Xn=!1,Rn=!1,Da=!1,Fr=!1,Vf=()=>Fr||Pn.artifacts.some(i=>zn(o.features?.artifacts,i)==="panel"),zs=()=>Pn.artifacts.length>0&&!Xn&&Vf(),at={current:null},sc=(i,u)=>{let h=q.getArtifactById(u),x=h?.markdown,k=h?.title||"artifact",W=h?.file,z=h?.artifactType??"markdown";if(!x){let Y=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(Y){let le=q.getMessages().find(ye=>ye.id===Y);if(le?.rawContent)try{let ye=JSON.parse(le.rawContent);x=ye?.props?.markdown,k=ye?.props?.title||k,ye?.props?.file&&typeof ye.props.file=="object"&&(W=ye.props.file),!h&&typeof ye?.props?.artifactType=="string"&&(z=ye.props.artifactType)}catch{}}}return{markdown:x,title:k,file:W,artifactType:z}};xe.addEventListener("click",i=>{let h=i.target.closest("[data-download-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:W,title:z,file:U}=sc(h,x);if(!W)return;let{filename:j,mime:Y,content:pe}=kh({title:z,markdown:W,file:U}),le=new Blob([pe],{type:Y}),ye=URL.createObjectURL(le),Ge=document.createElement("a");Ge.href=ye,Ge.download=j,Ge.click(),URL.revokeObjectURL(ye)}),xe.addEventListener("click",i=>{let h=i.target.closest("[data-artifact-custom-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.getAttribute("data-artifact-custom-action");if(!x)return;let k=h.closest("[data-artifact-inline]"),W=k?null:h.closest("[data-open-artifact]"),z=k?k.getAttribute("data-artifact-inline"):W?.getAttribute("data-open-artifact")??null,j=(k?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ht=>ht.id===x);if(!j)return;let{markdown:Y,title:pe,file:le,artifactType:ye}=sc(h,z??""),Ge={artifactId:z,title:pe,artifactType:ye,markdown:Y,file:le};try{Promise.resolve(j.onClick(Ge)).catch(()=>{})}catch{}}),xe.addEventListener("click",i=>{let h=i.target.closest("[data-copy-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.getAttribute("data-copy-artifact");if(!x)return;let k=q.getArtifactById(x),W="";if(k)W=vs(k);else{let{markdown:z,file:U,artifactType:j}=sc(h,x);j==="markdown"&&(W=vs({id:x,artifactType:"markdown",status:"complete",markdown:z??"",...U?{file:U}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let z=ae("check",16,"currentColor",2);z&&(h.replaceChildren(z),setTimeout(()=>{let U=ae("copy",16,"currentColor",2);U&&h.replaceChildren(U)},1500))}).catch(()=>{})}),xe.addEventListener("click",i=>{let h=i.target.closest("[data-expand-artifact-inline]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Xn=!1,Fr=!0,Rn=!0,Da=!0,q.selectArtifact(x),Jn())}),xe.addEventListener("click",i=>{let u=i.target;if(u.closest("[data-download-artifact]")||u.closest("[data-artifact-custom-action]"))return;let h=u.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(i.preventDefault(),i.stopPropagation(),Xn=!1,Fr=!0,q.selectArtifact(x),Jn())}),xe.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let u=i.target;!u.hasAttribute("data-open-artifact")&&!u.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),u.click())});let Or=Te.composerOverlay,Nr=(i,u,h)=>{let x=u.trim();if(!x||!at.current)return;let k=i.getAttribute("data-tool-call-id")??"",W=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:k,answer:x,answers:h.structured,values:h.values??(h.source==="multi"?x.split(", "):[x]),isFreeText:W,source:h.source},bubbles:!0,composed:!0})),Wo(Or,k);let z=at.current.getMessages().find(U=>U.toolCall?.id===k);z?.agentMetadata?.awaitingLocalTool?at.current.resolveAskUserQuestion(z,h.structured??x):at.current.sendMessage(x)},er=i=>{let u=at.current;if(!u)return;let h=i.getAttribute("data-tool-call-id")??"",x=u.getMessages().find(k=>k.toolCall?.id===h);x&&u.persistAskUserQuestionProgress(x,{answers:Si(i,x),currentIndex:Sn(i)})},zf=i=>Object.entries(i).map(([u,h])=>`${u}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),ic=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let u=Sn(i),h=ra(i);if(u>=h-1)return;let x=at.current?.getMessages().find(k=>k.toolCall?.id===i.getAttribute("data-tool-call-id"));x&&(Mi(i,x,o,u+1),er(i))};Or.addEventListener("click",i=>{let h=i.target.closest("[data-ask-user-action]");if(!h)return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;let k=h.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),k==="dismiss"){let W=x.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:W},bubbles:!0,composed:!0})),Wo(Or,W);let z=at.current?.getMessages().find(U=>U.toolCall?.id===W);z?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(z),at.current?.resolveAskUserQuestion(z,"(dismissed)"));return}if(k==="pick"){let W=h.getAttribute("data-option-label");if(!W)return;let z=x.getAttribute("data-multi-select")==="true",U=Io(x);if(U&&z){let j=yr(x)[Sn(x)],Y=new Set(Array.isArray(j)?j:[]);Y.has(W)?Y.delete(W):Y.add(W),Ho(x,Array.from(Y)),er(x);return}if(U){Ho(x,W),er(x),ic(x);return}if(z){let j=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",j?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!j);let Y=x.querySelector('[data-ask-user-action="submit-multi"]');Y&&(Y.disabled=nd(x).length===0);return}Nr(x,W,{source:"pick",values:[W]});return}if(k==="submit-multi"){let W=nd(x);if(W.length===0)return;Nr(x,W.join(", "),{source:"multi",values:W});return}if(k==="open-free-text"){let W=x.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"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(k==="submit-free-text"){let z=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!z.trim())return;if(Io(x)){Ho(x,z.trim()),er(x),ic(x);return}Nr(x,z,{source:"free-text"});return}if(k==="next"||k==="back"){if(!at.current)return;let W=x.getAttribute("data-tool-call-id")??"",z=at.current.getMessages().find(le=>le.toolCall?.id===W);if(!z)return;let j=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(j){let le=yr(x)[Sn(x)];(typeof le!="string"||le!==j)&&Ho(x,j)}let Y=k==="next"?1:-1,pe=Sn(x)+Y;Mi(x,z,o,pe),er(x);return}if(k==="submit-all"){if(!at.current)return;let W=x.getAttribute("data-tool-call-id")??"",z=at.current.getMessages().find(le=>le.toolCall?.id===W);if(!z)return;let j=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";j&&Ho(x,j);let Y=Si(x,z);at.current.persistAskUserQuestionProgress(z,{answers:Y,currentIndex:Sn(x)});let pe=zf(Y);Nr(x,pe||"(submitted)",{source:"submit-all",structured:Y});return}if(k==="skip"){if(!at.current)return;let W=x.getAttribute("data-tool-call-id")??"",z=at.current.getMessages().find(ye=>ye.toolCall?.id===W);if(!z)return;let U=Io(x),j=Sn(x),Y=ra(x),pe=j>=Y-1;if(!U){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:W},bubbles:!0,composed:!0})),Wo(Or,W),z.agentMetadata?.awaitingLocalTool&&(at.current.markAskUserQuestionResolved(z),at.current.resolveAskUserQuestion(z,"(dismissed)"));return}Ho(x,"");let le=x.querySelector('[data-ask-free-text-input="true"]');if(le&&(le.value=""),pe){let ye=Si(x,z),Ge=zf(ye);Nr(x,Ge||"(skipped)",{source:"submit-all",structured:ye});return}Mi(x,z,o,j+1),er(x);return}}),Or.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let h=i.target;if(!h.matches?.('[data-ask-free-text-input="true"]'))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;i.preventDefault();let k=h.value;if(k.trim()){if(Io(x)){Ho(x,k.trim()),er(x),ic(x);return}Nr(x,k,{source:"free-text"})}});let $f=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let u=i.target;if(u?.tagName==="INPUT"||u?.tagName==="TEXTAREA"||u?.isContentEditable)return;let h=Or.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let x=Number(i.key),W=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];W&&(i.preventDefault(),W.click())};document.addEventListener("keydown",$f);let yo=null,xt=null,Fa=null,$s=null,lc=()=>{},jf=!1,js="",Gs="";function cc(){$s?.(),$s=null}let Gf=()=>{if(!yo||!xt)return;let i=e.classList.contains("persona-artifact-welded-split"),u=e.ownerDocument.defaultView??window,h=u.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||h){xt.style.removeProperty("position"),xt.style.removeProperty("left"),xt.style.removeProperty("top"),xt.style.removeProperty("bottom"),xt.style.removeProperty("width"),xt.style.removeProperty("z-index");return}let x=yo.firstElementChild;if(!x||x===xt)return;let k=10;xt.style.position="absolute",xt.style.top="0",xt.style.bottom="0",xt.style.width=`${k}px`,xt.style.zIndex="5";let W=rf(yo,u),z=x.offsetWidth+W/2-k/2;xt.style.left=`${Math.max(0,z)}px`},Ks=()=>{},ex=()=>{let i=e.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!u||i.innerWidth>h?!1:P||St(o)},Xs=()=>!tn(o)||!zs()||e.classList.contains("persona-artifact-narrow-host")||ex()||(e.ownerDocument.defaultView??window).innerWidth<hS?"none":ef(o)?"detached":"welded",Jn=()=>{if(!Ke||!tn(o))return;Is(e,o),Ws(e,o),Ks();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=he.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=i);let h=zs();Ke.setVisible(h),Ke.update(Pn),Xn?(Ke.setMobileOpen(!1),Ke.element.classList.add("persona-hidden"),Ke.backdrop?.classList.add("persona-hidden"),Rn=!1,Da=!1):Pn.artifacts.length>0&&Vf()?(Ke.element.classList.remove("persona-hidden"),Ke.setMobileOpen(!0)):(Ke.setMobileOpen(!1),Ke.element.classList.add("persona-hidden"),Ke.backdrop?.classList.add("persona-hidden"),Rn=!1,Da=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ke.setExpandToggleVisible(x),Ke.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ke.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ke.setTabFade(o.features?.artifacts?.layout?.tabFade),Ke.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!Da&&(Rn=!1),Rn!==jf){let W=Ke.element;Rn?(js=W.style.width,Gs=W.style.maxWidth,W.style.removeProperty("width"),W.style.removeProperty("max-width")):(js&&(W.style.width=js),Gs&&(W.style.maxWidth=Gs),js="",Gs=""),jf=Rn}e.classList.toggle("persona-artifact-expanded",Rn),Ke.setExpanded(Rn);let k=Xs();k!==Ba&&(Ba=k,Zo()),lc()};if(tn(o)){he.style.position="relative";let i=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(be),Ke=qy(o,{onSelect:h=>at.current?.selectArtifact(h),onDismiss:()=>{Xn=!0,Jn()},onToggleExpand:()=>{let h=!Rn,x=Pn.selectedId??Pn.artifacts[Pn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:h})!==!0&&(Rn=h,h||(Da=!1),Jn())}}),Ke.element.classList.add("persona-hidden"),yo=u,u.appendChild(i),u.appendChild(Ke.element),Ke.backdrop&&he.appendChild(Ke.backdrop),he.appendChild(u),lc=()=>{if(!yo||!Ke)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Fa?.(),Fa=null,cc(),xt&&(xt.remove(),xt=null),Ke.element.style.removeProperty("width"),Ke.element.style.removeProperty("maxWidth");return}if(!xt){let x=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let k=e.ownerDocument,W=k.defaultView??window,z=U=>{if(!Ke||U.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||W.innerWidth<=640)return;U.preventDefault(),cc();let j=U.clientX,Y=Ke.element.getBoundingClientRect().width,pe=o.features?.artifacts?.layout,le=Ge=>{let ht=yo.getBoundingClientRect().width,ct=e.classList.contains("persona-artifact-welded-split"),un=rf(yo,W),Mt=ct?0:x.getBoundingClientRect().width||6,It=Y-(Ge.clientX-j),_=Qy(It,ht,un,Mt,pe?.resizableMinWidth,pe?.resizableMaxWidth);Ke.element.style.width=`${_}px`,Ke.element.style.maxWidth="none",Gf()},ye=()=>{k.removeEventListener("pointermove",le),k.removeEventListener("pointerup",ye),k.removeEventListener("pointercancel",ye),$s=null;try{x.releasePointerCapture(U.pointerId)}catch{}};$s=ye,k.addEventListener("pointermove",le),k.addEventListener("pointerup",ye),k.addEventListener("pointercancel",ye);try{x.setPointerCapture(U.pointerId)}catch{}};x.addEventListener("pointerdown",z),xt=x,yo.insertBefore(x,Ke.element),Fa=()=>{x.removeEventListener("pointerdown",z)}}if(xt){let x=zs();xt.classList.toggle("persona-hidden",!x),Gf()}},Ks=()=>{if(!P||!Ke||(o.launcher?.sidebarMode??!1)||St(o)&&ln(o).reveal==="emerge")return;let x=e.ownerDocument.defaultView??window,k=o.launcher?.mobileFullscreen??!0,W=o.launcher?.mobileBreakpoint??640;if(k&&x.innerWidth<=W||!$y(o,P))return;let z=o.launcher?.width??o.launcherWidth??mn,U=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";zs()?(he.style.width=U,he.style.maxWidth=U):(he.style.width=z,he.style.maxWidth=z)},typeof ResizeObserver<"u"&&(Ha=new ResizeObserver(()=>{Jn()}),Ha.observe(he))}else he.appendChild(be);Q()&&tt&&(Te.peekBanner&&tt.appendChild(Te.peekBanner),tt.appendChild(we)),e.appendChild(Le),tt&&e.appendChild(tt);let dc=()=>{if(Q()){he.style.width="100%",he.style.maxWidth="100%";let Lt=o.launcher?.composerBar??{},an=Le.dataset.state==="expanded",fi=Lt.expandedSize??"anchored";if(!(an&&fi!=="fullscreen")){be.style.background="",be.style.border="",be.style.borderRadius="",be.style.overflow="",be.style.boxShadow="";return}let Ya=o.theme?.components?.panel,mi=Uo(o),Qr=(oo,gr)=>oo==null||oo===""?gr:en(mi,oo)??oo,gi="1px solid var(--persona-border)",Vc="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",mr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";be.style.background="var(--persona-surface, #ffffff)",be.style.border=Qr(Ya?.border,gi),be.style.borderRadius=Qr(Ya?.borderRadius,mr),be.style.boxShadow=Qr(Ya?.shadow,Vc),be.style.overflow="hidden";return}let i=St(o),u=o.launcher?.sidebarMode??!1,h=i||u||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,k=o.launcher?.detachedPanel===!0,W=o.theme?.components?.panel,z=Uo(o),U=(Lt,an)=>Lt==null||Lt===""?an:en(z,Lt)??Lt,j=e.ownerDocument.defaultView??window,Y=o.launcher?.mobileFullscreen??!0,pe=o.launcher?.mobileBreakpoint??640,le=j.innerWidth<=pe,ye=Y&&le&&P,Ge=i&&Y&&le,ht=o.launcher?.position??"bottom-left",ct=ht==="bottom-left"||ht==="top-left",un=o.launcher?.zIndex??Ut,Mt="var(--persona-panel-border, 1px solid var(--persona-border))",It="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",_="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Re=k&&!ye&&!Ge;Re?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Fe=Re?Mt:u||ye?"none":Mt,Ee=Re?It:ye?"none":u?ct?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":x?"none":It;i&&!ye&&!Re&&(Ee="none",Fe="none");let At=Re?_:u||ye?"0":_,dt=U(W?.border,Fe),Ot=U(W?.shadow,Ee),pt=U(W?.borderRadius,At),rn=Xs(),Wt=rn==="detached",Ie=rn==="welded";e.classList.toggle("persona-artifact-detached-split",Wt),e.classList.toggle("persona-artifact-welded-split",Ie);let Oe="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"&&tn(o)&&ef(o)&&x&&!i;e.classList.toggle("persona-artifact-chat-flush",Ct);let st=Wt||Ct?"none":Ot,ft=Wt?Mt:Ie?"none":dt,Xe=Wt?_:pt;Ct&&(ft="none",Xe="0");let He=W?.borderRadius!=null&&W.borderRadius!=="",yt=Ct&&!He?"0":pt,jt=re.scrollTop;e.style.cssText="",Le.style.cssText="",he.style.cssText="",be.style.cssText="",re.style.cssText="",we.style.cssText="",Me&&(re.style.display="none"),(h||x)&&(e.style.minWidth="0");let An=()=>{if(jt<=0)return;(re.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(re.scrollTop===jt)return;let an=re.scrollHeight-re.clientHeight;an<=0||(re.scrollTop=Math.min(jt,an))})};if(ye){Le.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"),Le.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 Ka=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: ${un} !important;
|
|
60
60
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
61
|
-
`,
|
|
61
|
+
`,he.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 Ka=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
|
+
`,be.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 Ka=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
|
+
`,re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",we.style.flexShrink="0",G=!0,An();return}let ui=o?.launcher?.width??o?.launcherWidth??mn;if(!u&&!i)x&&h?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=ui,he.style.maxWidth=ui);else if(i)if(ln(o).reveal==="emerge"&&!k){let an=ln(o).width;he.style.width=an,he.style.maxWidth=an}else he.style.width="100%",he.style.maxWidth="100%";if(Ks(),he.style.boxShadow=st,he.style.borderRadius=yt,Wt?he.style.border="none":Ie&&(he.style.border=dt),be.style.border=ft,be.style.borderRadius=Xe,be.style.boxShadow=Wt&&!Ct?Oe:"",Ct&&(be.style.background="transparent",re.style.background="transparent",we.style.background="transparent",we.style.borderTop="none"),Ie){let Lt=o.features?.artifacts?.layout;Vs=Lt?.unifiedSplitOuterRadius?.trim()||Lt?.paneBorderRadius?.trim()||pt}else Vs=null;if(i&&!ye&&!Re&&!Wt&&!Ie&&W?.border===void 0&&(be.style.border="none",ln(o).side==="right"?be.style.borderLeft="1px solid var(--persona-border)":be.style.borderRight="1px solid var(--persona-border)"),i&&!ye&&Ie&&W?.border===void 0&&(ln(o).side==="right"?he.style.borderLeft="1px solid var(--persona-border)":he.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),Le.style.display="flex",Le.style.flexDirection="column",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.maxHeight="100%",Le.style.height="100%",x&&(Le.style.overflow="hidden"),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%",Wt||(he.style.overflow="hidden"),be.style.display="flex",be.style.flexDirection="column",be.style.flex="1 1 0%",be.style.minHeight="0",be.style.maxHeight="100%",be.style.overflow="hidden",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",we.style.flexShrink="0"),x&&(Re||Wt||Ct)&&!i&&(Ct||(Le.style.padding="var(--persona-panel-inset)"),Le.style.background="var(--persona-panel-canvas-bg)"),Le.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"),!u&&!x&&!i&&(gn[ht]??gn["bottom-right"]).split(" ").forEach(an=>Le.classList.add(an)),u){let Lt=o.launcher?.sidebarWidth??"420px";k?Le.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: ${Lt} !important;
|
|
90
90
|
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
91
91
|
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
92
92
|
margin: 0 !important;
|
|
93
93
|
padding: 0 !important;
|
|
94
94
|
display: flex !important;
|
|
95
95
|
flex-direction: column !important;
|
|
96
|
-
z-index: ${
|
|
97
|
-
${
|
|
98
|
-
`:
|
|
96
|
+
z-index: ${un} !important;
|
|
97
|
+
${ct?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
98
|
+
`:Le.style.cssText=`
|
|
99
99
|
position: fixed !important;
|
|
100
100
|
top: 0 !important;
|
|
101
101
|
bottom: 0 !important;
|
|
102
|
-
width: ${
|
|
102
|
+
width: ${Lt} !important;
|
|
103
103
|
height: 100vh !important;
|
|
104
104
|
max-height: 100vh !important;
|
|
105
105
|
margin: 0 !important;
|
|
106
106
|
padding: 0 !important;
|
|
107
107
|
display: flex !important;
|
|
108
108
|
flex-direction: column !important;
|
|
109
|
-
z-index: ${
|
|
110
|
-
${
|
|
111
|
-
`,
|
|
109
|
+
z-index: ${un} !important;
|
|
110
|
+
${ct?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
111
|
+
`,he.style.cssText=`
|
|
112
112
|
position: relative !important;
|
|
113
113
|
display: flex !important;
|
|
114
114
|
flex-direction: column !important;
|
|
@@ -119,10 +119,10 @@ _Details: ${n.message}_`:o}var Ka=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
119
119
|
min-height: 0 !important;
|
|
120
120
|
margin: 0 !important;
|
|
121
121
|
padding: 0 !important;
|
|
122
|
-
box-shadow: ${
|
|
123
|
-
border-radius: ${
|
|
124
|
-
${
|
|
125
|
-
`,
|
|
122
|
+
box-shadow: ${st} !important;
|
|
123
|
+
border-radius: ${yt} !important;
|
|
124
|
+
${Wt?"border: none !important;":Ie?`border: ${dt} !important;`:""}
|
|
125
|
+
`,he.style.setProperty("width","100%","important"),he.style.setProperty("max-width","100%","important"),be.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 Ka=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: ${
|
|
134
|
+
border-radius: ${Xe} !important;
|
|
135
135
|
border: ${ft} !important;
|
|
136
|
-
${
|
|
137
|
-
${
|
|
138
|
-
`,
|
|
136
|
+
${Wt&&!Ct?`box-shadow: ${Oe} !important;`:""}
|
|
137
|
+
${Ct?"background: transparent !important;":""}
|
|
138
|
+
`,we.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 Tt="max-height: -moz-available !important; max-height: stretch !important;",rn=m?"":"padding-top: 1.25em !important;",Gs=m?"":`z-index: ${o.launcher?.zIndex??Gt} !important;`;De.style.cssText+=Tt+rn+Gs}vn()};Ps(),dr(e,o),us(e,o),fs(e,o),pa=()=>{Ps(),dr(e,o),us(e,o),fs(e,o),As?e.style.setProperty("--persona-artifact-welded-outer-radius",As):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let _e=[];_e.push(()=>{document.removeEventListener("keydown",Qu)}),_e.push(()=>{la!==null&&clearTimeout(la)});let Hn=null,Bn=null;_e.push(()=>{Hn?.(),Hn=null,Bn?.(),Bn=null}),ca&&_e.push(()=>{ca?.disconnect(),ca=null}),_e.push(()=>{ma?.(),ma=null,Nl(),yt&&(yt.remove(),yt=null),Xe?.element.style.removeProperty("width"),Xe?.element.style.removeProperty("maxWidth")}),le&&_e.push(()=>{Me!==null&&(cancelAnimationFrame(Me),Me=null),Ge?.destroy(),Ge=null,ke?.destroy(),ke=null,we=null});let Vo=null,ef=()=>{Vo&&(Vo(),Vo=null),o.colorScheme==="auto"&&(Vo=zr(()=>{dr(e,o)}))};ef(),_e.push(()=>{Vo&&(Vo(),Vo=null)}),_e.push(l);let Rs=o.features?.streamAnimation;if(Rs?.type&&Rs.type!=="none"){let i=Xr(Rs.type,Rs.plugins);i&&(rl(i,e),_e.push(()=>sh(e)))}let ga=al(ht),tf=al(Xt),nf=al(ut),ha=[ga,tf,nf];_e.push(()=>{ha.forEach(i=>i.destroy())});let zo=null,V,$o=null,of=!1,rf=0,af=null,sf=i=>i.reduce((m,y)=>y.role==="user"?m+1:m,0),lf=i=>{for(let m=i.length-1;m>=0;m--)if(or(i[m]))return i[m].id??null;return null},df=!1,Gy=()=>{df||o.debug!==!0||(df=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but copy.showWelcomeCard is false, so no starters render. Use "auto" or "composer".'))},cf=!1,pf=!1,uf=(i,m)=>{cf||o.debug!==!0||!m.enabled||m.expose||of||pf&&(V.isStreaming()||i.some(or)||(cf=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},ya=i=>{if(!V)return;let m=i??V.getMessages(),y=ee=>{ee.render([],V,j,m)},v=ee=>{ha.forEach(ce=>{ce!==ee&&y(ce)})};$o&&(sf(m)>rf||lf(m)!==af)&&($o=null);let L=To(o);uf(m,L);let I=L.enabled?li(m):null,Q=$o??I,z=$o?"host":"agent";if(Q){let ee=o.suggestions?.followUps,ce=ee?.placement??(ee?"auto":"composer"),ge=(ce==="auto"?D()?"composer":"after-message":ce)==="after-message"?nf:ga;v(ge),ge.render(Q,V,j,m,o.suggestionChipsConfig,{source:z,surface:"followUp",variant:ee?.variant??"chip",behavior:ee?.behavior??"send",overflow:ee?.overflow??"scroll",maxItems:ee?.maxItems??4,config:o,plugins:a});return}if(m.some(ee=>ee.role==="user")){ha.forEach(y);return}let X=o.suggestions?.starters;if(X){let ee=o.copy?.showWelcomeCard!==!1,ce=X.placement??"auto",re=ce==="auto"?ee?"welcome":"composer":ce;if(re==="welcome"&&!ee){Gy(),ha.forEach(y);return}let ge=re==="welcome"?tf:ga;v(ge),ge.render(X.items??o.suggestionChips,V,j,m,o.suggestionChipsConfig,{surface:"starter",variant:X.variant??"card",behavior:X.behavior??"send",overflow:X.overflow??"wrap",maxItems:X.maxItems??4,config:o,plugins:a});return}v(ga),ga.render(o.suggestionChips,V,j,m,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a})},ff=()=>{$o&&($o=null,ya())},Ky=i=>{let m=Array.isArray(i)?[...i]:[];if(!m.length){ff();return}let y=V?V.getMessages():[];$o=m,of=!0,rf=sf(y),af=lf(y),ya(y)},Sn=!1,jo=Jg(),Sr=new Map,Go=new Map,co=new Map,_l=0,Xy=Jn()!==null,dn=Yi(),hn=0,po=null,yn=!1,Is=!1,uo=0,Mn=null,Ko=null,Ul=!1,Ws=!1,ba=null,xa=!0,Hs=!1,Bs=null,Ds=!1,Xo=()=>{Ds=!0},ql=null,Jy=4,Fs=24,Qy=80,Vl=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},mf=o.voiceRecognition?.autoResume??!1,$n=i=>{p.emit("voice:state",{active:je.active,source:i,timestamp:Date.now()})},Tn=()=>{k(i=>({...i,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},Yy=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=vu(u.voiceState),m=!!i.active,y=Number(i.timestamp??0);je.manuallyDeactivated=!!i.manuallyDeactivated,m&&Date.now()-y<Ow&&setTimeout(()=>{je.active||(je.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?V.toggleVoice().then(()=>{je.active=V.isVoiceActive(),$n("restore"),V.isVoiceActive()&&Lr()}):qs("restore"))},1e3)},Zy=()=>V?Qh(V.getMessages()).filter(i=>!i.__skipPersist):[],Os=null,gf=(i,m)=>{typeof console<"u"&&console.error(i,m)},zl=(i,m)=>{let y=()=>{try{let Q=i();return!Q||typeof Q.then!="function"?null:Promise.resolve(Q).catch(z=>{gf(m,z)})}catch(Q){return gf(m,Q),null}},v=Os,L=v?v.then(()=>y()??void 0):y();if(!L)return;let I=L.finally(()=>{Os===I&&(Os=null)});Os=I};function $l(i){if(!d?.save)return;let y={messages:i?Qh(i):V?Zy():[],metadata:u,artifacts:wn.artifacts,selectedArtifactId:wn.selectedId};zl(()=>d.save(y),"[AgentWidget] Failed to persist state:")}let Mr=null,hf=()=>De.querySelector("#persona-scroll-container")||ie,va=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),yn=!1},yf=()=>{po!==null&&(cancelAnimationFrame(po),po=null),Is=!1,va()},eb=()=>Sn&&Gl()&&(gn()!=="anchor-top"||Ou()),jl=()=>{let i=ao()||"Jump to latest",m=eb();kt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),uo>0?(_o.textContent=String(uo),_o.style.display="",kt.setAttribute("aria-label",`${i} (${uo} new)`)):(_o.textContent="",_o.style.display="none",kt.setAttribute("aria-label",m?`${i} (response streaming below)`:i))},bf=()=>{uo!==0&&(uo=0,jl())},Gl=()=>so()?!dn.isFollowing():!Fo(ie,Fs),cn=()=>{if(!Ny()||ze){kt.parentNode&&kt.remove(),kt.style.display="none";return}kt.parentNode!==fe&&fe.appendChild(kt),vr();let m=_n(ie)>0&&Gl();m?jl():bf(),kt.style.display=m?"":"none"},Ca=()=>{dn.pause()&&(yf(),cn())},fo=()=>{dn.resume(),bf(),cn()},mo=(i=!1)=>{so()&&dn.isFollowing()&&(!i&&!Sn||(po!==null&&(cancelAnimationFrame(po),po=null),Is=!0,po=requestAnimationFrame(()=>{po=null,Is=!1,dn.isFollowing()&&tb(hf(),i?220:140)})))},xf=(i,m,y,v=()=>!0)=>{let L=i.scrollTop,I=m(),Q=I-L;if(va(),Math.abs(Q)<1){yn=!0,i.scrollTop=I,hn=i.scrollTop,yn=!1;return}let z=performance.now();yn=!0;let X=ce=>1-Math.pow(1-ce,3),ee=ce=>{if(!v()){va();return}let re=m();re!==I&&(I=re,Q=I-L);let ge=ce-z,Ve=Math.min(ge/y,1),dt=X(Ve),et=L+Q*dt;i.scrollTop=et,hn=i.scrollTop,Ve<1?Mr=requestAnimationFrame(ee):(i.scrollTop=I,hn=i.scrollTop,Mr=null,yn=!1)};Mr=requestAnimationFrame(ee)},tb=(i,m=500)=>{let y=_n(i)-i.scrollTop;if(Math.abs(y)<1){hn=i.scrollTop;return}if(Math.abs(y)>=Qy){va(),yn=!0,i.scrollTop=_n(i),hn=i.scrollTop,yn=!1;return}xf(i,()=>_n(i),m,()=>dn.isFollowing())},vf=()=>{let i=hf();yn=!0,i.scrollTop=_n(i),hn=i.scrollTop,yn=!1,cn()},Cf=i=>{let m=0,y=i;for(;y&&y!==ie;)m+=y.offsetTop,y=y.offsetParent;return m},nb=()=>{let i=ie.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ie.ownerDocument.getSelection()},Ns=()=>th(nb(),ie),wf=()=>{if(_y()!=="last-user-turn")return!1;let i=V?.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=ie.querySelector(`[data-message-id="${y}"]`);if(!v)return!1;let L=Math.min(Math.max(0,Cf(v)-Du()),_n(ie));return yn=!0,ie.scrollTop=L,hn=ie.scrollTop,yn=!1,gn()==="follow"&&!Fo(ie,Fs)&&dn.pause(),cn(),!0},Af=i=>{io.style.height=`${Math.max(0,Math.round(i))}px`,Mn&&(Mn.spacerHeight=Math.max(0,i))},wa=()=>{Ko!==null&&(cancelAnimationFrame(Ko),Ko=null),va(),Mn=null,io.style.height="0px"},Sf=i=>{Ko!==null&&cancelAnimationFrame(Ko),Ko=requestAnimationFrame(()=>{Ko=null;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=ie.querySelector(`[data-message-id="${m}"]`);if(!y)return;let v=Cf(y),L=Mn?.spacerHeight??0,I=ie.scrollHeight-L,{targetScrollTop:Q,spacerHeight:z}=nh({anchorOffsetTop:v,topOffset:Du(),viewportHeight:ie.clientHeight,contentHeight:I});Mn={initialSpacerHeight:z,contentHeightAtAnchor:I,spacerHeight:z},Af(z),xf(ie,()=>Q,220)})},ob=()=>{if(so()){if(!dn.isFollowing()||Fo(ie,1))return;mo(!Sn);return}if(Mn&&Mn.initialSpacerHeight>0){let i=ie.scrollHeight-Mn.spacerHeight,m=oh({initialSpacerHeight:Mn.initialSpacerHeight,contentHeightAtAnchor:Mn.contentHeightAtAnchor,currentContentHeight:i});m!==Mn.spacerHeight&&Af(m)}cn()},rb=i=>{let m=gn();m==="follow"?(fo(),mo(!0)):m==="anchor-top"&&(xa=!1,Hs=!0,Ds=!1,Bs=i,Sf(i))},ab=()=>{if(gn()==="anchor-top"){if(Hs){xa=!1;return}xa=!0,wa(),fo(),mo(!0)}},sb=i=>{if(gn()!=="anchor-top"||!Hs||Ds||Ns())return;let m=ba===null;for(let y of i){if(!m){y.id===ba&&(m=!0);continue}if(eh(y)){if(y.id===Bs)return;Bs=y.id,Sf(y.id);return}}},ib=i=>{let m=new Map;i.forEach(y=>{let v=Vl.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!v&&y.role==="assistant"&&(p.emit("assistant:message",y),!Ws&&(gn()!=="anchor-top"||Ou())&&Gl()&&(uo+=1,jl(),cn(),_u(uo===1?"1 new message below.":`${uo} 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}))}),Vl.clear(),m.forEach((y,v)=>{Vl.set(v,y)})},_s=(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),_s(y,m),y},lb=(i,m,y)=>{let v=document.createElement("div"),I=(()=>{let N=a.find(Le=>Le.renderLoadingIndicator);if(N?.renderLoadingIndicator)return N.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Q=(N,Le)=>Le==null?!1:typeof Le=="string"?(N.textContent=Le,!0):(N.appendChild(Le),!0),z=new Set,X=new Map,ee=new Set,ce=a.some(N=>N.renderAskUserQuestion),re=[],ge=[],Ve=o.enableComponentStreaming!==!1,dt=o.approval!==!1,et=[];if(m.forEach(N=>{z.add(N.id),X.set(N.id,N.role);let Le=ce&&Yn(N),Oe=dt&&N.variant==="approval"&&!!N.approval,Ae=!Le&&N.role==="assistant"&&!N.variant&&Ve&&bs(N);!Oe&&co.has(N.id)&&(i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),co.delete(N.id)),!Ae&&Go.has(N.id)&&(i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),Go.delete(N.id));let Ct=Yn(N)?`:${N.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${N.agentMetadata?.askUserQuestionAnswers?Object.keys(N.agentMetadata.askUserQuestionAnswers).length:0}`:"",ct=Xg(N,_l)+Ct,Ft=Le||Oe||Ae?null:Qg(jo,N.id,ct);if(Ft){v.appendChild(Ft.cloneNode(!0)),Yn(N)&&N.toolCall?.id&&N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(ee.add(N.toolCall.id),Or(N,o,He.composerOverlay));return}let pt=null,on=a.find(Ne=>!!(N.variant==="reasoning"&&Ne.renderReasoning||N.variant==="tool"&&Ne.renderToolCall||!N.variant&&Ne.renderMessage)),Rt=o.layout?.messages;if(Yn(N)&&N.agentMetadata?.askUserQuestionAnswered===!0){Sr.delete(N.id),i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime");return}if(or(N)&&To(o).enabled)return;if(Yn(N)&&o.features?.askUserQuestion?.enabled!==!1){let Ne=a.find(qt=>typeof qt.renderAskUserQuestion=="function");if(Ne&&st.current){let qt=Sr.get(N.id),Vt=qt!==ct,xt=null;if(Vt){let{payload:Je,complete:Be}=Zn(N),gt=N.id,zt=()=>st.current?.getMessages().find(vn=>vn.id===gt);xt=Ne.renderAskUserQuestion({message:N,payload:Je,complete:Be,resolve:vn=>{let Ia=zt();Ia&&st.current?.resolveAskUserQuestion(Ia,vn)},dismiss:()=>{let vn=zt();vn?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(vn),st.current?.resolveAskUserQuestion(vn,"(dismissed)"))},config:o})}let it=qt!=null;if(Vt&&xt===null&&!it){N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(ee.add(N.toolCall.id),Or(N,o,He.composerOverlay));return}let ft=Jo(N.id,N.role);ft.setAttribute("data-ask-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),v.appendChild(ft),re.push({messageId:N.id,fingerprint:ct,bubble:xt});return}else{N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(ee.add(N.toolCall.id),Or(N,o,He.composerOverlay));return}}else if(Oe){let Ne=a.find(it=>typeof it.renderApproval=="function")??s,Vt=co.get(N.id)!==ct,xt=null;if(Vt&&Ne?.renderApproval){let it=N.id,ft=(Je,Be)=>{let gt=st.current?.getMessages().find(zt=>zt.id===it);gt?.approval&&(gt.approval.toolType==="webmcp"?st.current?.resolveWebMcpApproval(gt.id,Je):st.current?.resolveApproval(gt.approval,Je,Be))};xt=Ne.renderApproval({message:N,defaultRenderer:()=>yl(N,o),config:o,approve:Je=>ft("approved",Je),deny:Je=>ft("denied",Je)})}if(Vt&&xt===null)i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),co.delete(N.id),pt=yl(N,o);else{let it=Jo(N.id,N.role);it.setAttribute("data-approval-plugin-stub","true"),it.setAttribute("data-preserve-runtime","true"),v.appendChild(it),et.push({messageId:N.id,fingerprint:ct,bubble:xt});return}}else if(on)if(N.variant==="reasoning"&&N.reasoning&&on.renderReasoning){if(!me)return;pt=on.renderReasoning({message:N,defaultRenderer:()=>au(N,o),config:o})}else if(N.variant==="tool"&&N.toolCall&&on.renderToolCall){if(!oe)return;pt=on.renderToolCall({message:N,defaultRenderer:()=>iu(N,o),config:o})}else on.renderMessage&&(pt=on.renderMessage({message:N,defaultRenderer:()=>{let Ne=Yr(N,y,Rt,o.messageActions,Ke,{loadingIndicatorRenderer:I,widgetConfig:o});return N.role!=="user"&&yu(Ne,N,o,V),Ne},config:o}));if(!pt&&Ae){let Ne=Ml(N);if(Ne){let qt=Go.get(N.id),Vt=qt!==ct,xt=o.wrapComponentDirectiveInBubble!==!1&&Rn.getOptions(Ne.component)?.bubbleChrome!==!1,it=null;if(Vt){let ft=Sl(Ne,{config:o,message:N,transform:y});if(ft&&Ne.component==="PersonaArtifactInline"){let Je=ft.hasAttribute("data-artifact-inline")?ft:ft.querySelector("[data-artifact-inline]"),Be=Je?.getAttribute("data-artifact-inline")??"",gt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Be):Be,zt=Be?i.querySelector(`#wrapper-${N.id}`)?.querySelector(`[data-artifact-inline="${gt}"]`)??null:null;Je&&zt&&zt!==Je&&Vg(zt)&&(Je===ft?ft=zt:Je.replaceWith(zt))}if(ft)if(xt){let Je=document.createElement("div");if(Je.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Je.id=`bubble-${N.id}`,Je.setAttribute("data-message-id",N.id),N.content&&N.content.trim()){let Be=document.createElement("div");Be.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Be.innerHTML=y({text:N.content,message:N,streaming:!!N.streaming,raw:N.rawContent}),Je.appendChild(Be)}Je.appendChild(ft),it=Je}else{let Je=document.createElement("div");if(Je.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Je.id=`bubble-${N.id}`,Je.setAttribute("data-message-id",N.id),Je.setAttribute("data-persona-component-directive","true"),N.content&&N.content.trim()){let Be=document.createElement("div");Be.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Be.innerHTML=y({text:N.content,message:N,streaming:!!N.streaming,raw:N.rawContent}),Je.appendChild(Be)}Je.appendChild(ft),it=Je}}if(it||qt!=null){let ft=Jo(N.id,N.role);ft.setAttribute("data-component-directive-stub","true"),ft.setAttribute("data-preserve-runtime","true"),v.appendChild(ft),ge.push({messageId:N.id,fingerprint:ct,bubble:it});return}}}if(!pt)if(N.variant==="reasoning"&&N.reasoning){if(!me)return;pt=au(N,o)}else if(N.variant==="tool"&&N.toolCall){if(!oe)return;pt=iu(N,o)}else if(N.variant==="approval"&&N.approval){if(o.approval===!1)return;pt=yl(N,o)}else{let Ne=o.layout?.messages;Ne?.renderUserMessage&&N.role==="user"?pt=Ne.renderUserMessage({message:N,config:o,streaming:!!N.streaming}):Ne?.renderAssistantMessage&&N.role==="assistant"?pt=Ne.renderAssistantMessage({message:N,config:o,streaming:!!N.streaming}):pt=Yr(N,y,Ne,o.messageActions,Ke,{loadingIndicatorRenderer:I,widgetConfig:o}),N.role!=="user"&&pt&&yu(pt,N,o,V)}let Pe=Jo(N.id,N.role);Pe.appendChild(pt),Yg(jo,N.id,ct,Pe),v.appendChild(Pe)}),He.composerOverlay&&He.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Le=>{let Oe=Le.getAttribute("data-persona-ask-sheet-for");Oe&&!ee.has(Oe)&&So(He.composerOverlay,Oe)}),o.features?.toolCallDisplay?.grouped){let N=[],Le=[],Oe=o.features.toolCallDisplay.groupedMode==="summary";m.forEach(Ae=>{if(Ae.variant==="tool"&&Ae.toolCall&&oe){Le.push(Ae);return}Ae.variant==="reasoning"&&!me||((Le.length>1||Oe&&Le.length>0)&&N.push(Le),Le=[])}),(Le.length>1||Oe&&Le.length>0)&&N.push(Le),N.forEach(Ae=>{let Ct=Ae.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 ct=Jo(`tool-group-${Ae[0].id}`,"assistant");ct.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 pt=document.createElement("div");pt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",pt.id=`tool-group-summary-${Ae[0].id}`;let on=`Called ${Ae.length} ${Ae.length===1?"tool":"tools"}`,Rt=o.toolCall?.renderGroupedSummary?.({messages:Ae,toolCalls:Ae.map(Ne=>Ne.toolCall).filter(Ne=>!!Ne),defaultSummary:on,config:o});Q(pt,Rt)||(pt.textContent=on);let Pe=document.createElement("div");Pe.className="persona-tool-group-stack persona-flex persona-flex-col",Pe.id=`tool-group-stack-${Ae[0].id}`,Pe.setAttribute("data-persona-tool-group-stack","true"),Ft.appendChild(pt),Oe||Ft.appendChild(Pe),ct.appendChild(Ft),Ct[0].before(ct),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),Pe.appendChild(Vt)})})}Zg(jo,z);let pn=m.some(N=>N.role==="assistant"&&N.streaming),St=m[m.length-1],Pt=St?.role==="assistant"&&!St.streaming&&St.variant!=="approval";if(Sn&&m.some(N=>N.role==="user")&&!pn&&!Pt){let N={config:o,streaming:!0,location:"standalone",defaultRenderer:fr},Le=a.find(Ae=>Ae.renderLoadingIndicator),Oe=null;if(Le?.renderLoadingIndicator&&(Oe=Le.renderLoadingIndicator(N)),Oe===null&&o.loadingIndicator?.render&&(Oe=o.loadingIndicator.render(N)),Oe===null&&(Oe=fr()),Oe){let Ae=document.createElement("div"),Ct=o.loadingIndicator?.showBubble!==!1,ct=o.layout?.messages?.layout??"bubble";Ae.className=Ct?ou("assistant",ct).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Ae.setAttribute("data-typing-indicator","true"),Ct&&(Ae.style.color="var(--persona-message-assistant-text, var(--persona-text))",ct!=="flat"&&(Ae.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Ae.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Ae.appendChild(Oe);let Ft=Jo("typing-indicator","assistant");Ft.appendChild(Ae),v.appendChild(Ft)}}if(!Sn&&m.length>0){let N=m[m.length-1],Le={config:o,lastMessage:N,messageCount:m.length},Oe=a.find(Ct=>Ct.renderIdleIndicator),Ae=null;if(Oe?.renderIdleIndicator&&(Ae=Oe.renderIdleIndicator(Le)),Ae===null&&o.loadingIndicator?.renderIdle&&(Ae=o.loadingIndicator.renderIdle(Le)),Ae){let Ct=document.createElement("div"),ct=o.loadingIndicator?.showBubble!==!1;Ct.className=ct?["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(Ae);let Ft=Jo("idle-indicator","assistant");Ft.appendChild(Ct),v.appendChild(Ft)}}if(Cm(v),Qi(i,v),cd(i),re.length>0)for(let{messageId:N,fingerprint:Le,bubble:Oe}of re){let Ae=i.querySelector(`#wrapper-${N}`);Ae&&(_s(Ae,X.get(N)??"assistant"),Oe!==null&&(Ae.replaceChildren(Oe),Ae.setAttribute("data-bubble-fp",Le),Sr.set(N,Le)))}if(Sr.size>0)for(let N of Sr.keys())z.has(N)||Sr.delete(N);if(ge.length>0)for(let{messageId:N,fingerprint:Le,bubble:Oe}of ge){let Ae=i.querySelector(`#wrapper-${N}`);Ae&&(_s(Ae,X.get(N)??"assistant"),Oe!==null&&(Ae.replaceChildren(Oe),Ae.setAttribute("data-bubble-fp",Le),Go.set(N,Le)))}if(Go.size>0)for(let N of Go.keys())z.has(N)||Go.delete(N);if(et.length>0)for(let{messageId:N,fingerprint:Le,bubble:Oe}of et){let Ae=i.querySelector(`#wrapper-${N}`);Ae&&(_s(Ae,X.get(N)??"assistant"),Oe!==null&&(Ae.replaceChildren(Oe),Ae.setAttribute("data-bubble-fp",Le),co.set(N,Le)))}if(co.size>0)for(let N of co.keys())z.has(N)||co.delete(N)},Aa=(i,m,y)=>{lb(i,m,y),Ku()},Sa=null,db=()=>{if(Sa)return;let i=y=>{let v=y.composedPath();v.includes(De)||Qe&&v.includes(Qe)||lt(!1,"user")};Sa=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},Mf=()=>{if(!Sa)return;(e.ownerDocument??document).removeEventListener("pointerdown",Sa,!0),Sa=null};_e.push(()=>Mf());let Ma=null,cb=()=>{if(Ma)return;let i=y=>{y.key==="Escape"&&(y.isComposing||lt(!1,"user"))};Ma=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Tf=()=>{if(!Ma)return;(e.ownerDocument??document).removeEventListener("keydown",Ma,!0),Ma=null};_e.push(()=>Tf());let Ta=!1,Ef=new Set,pb=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Tr=()=>{if(!D())return;let i=He.peekBanner,m=He.peekTextNode;if(!i||!m)return;if(Y){i.classList.remove("persona-pill-peek--visible");return}let y=V?.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,Q=pb(),z=tl(Q),X=z.type!=="none"?Xr(z.type,Q?.plugins):null,ee=X?.isAnimating?.(v)===!0,ce=X!==null&&(I||ee);ce&&X&&!Ef.has(X.name)&&(rl(X,e),Ef.add(X.name));let re=ce&&X?.containerClass?X.containerClass:null,ge=m.dataset.personaPeekStreamClass??null;ge&&ge!==re&&(m.classList.remove(ge),delete m.dataset.personaPeekStreamClass),re&&ge!==re&&(m.classList.add(re),m.dataset.personaPeekStreamClass=re),ce?(m.style.setProperty("--persona-stream-step",`${z.speed}ms`),m.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Ve=ce?nl(L,z.buffer,X,v,I):L;if(ce&&z.placeholder==="skeleton"&&I&&(!Ve||!Ve.trim())){let St=document.createElement("div"),Pt=ss();Pt.classList.add("persona-pill-peek__skeleton"),St.appendChild(Pt),Qi(m,St)}else{let St=Math.max(0,Ve.length-100),Pt=Ve.length>100?Ve.slice(-100):Ve,N=Fn(Pt);if(!ce||!X){let Le=Ve.length>100?`\u2026${Pt}`:Pt;m.textContent!==Le&&(m.textContent=Le)}else{let Le=N;(X.wrap==="char"||X.wrap==="word")&&(Le=as(N,X.wrap,`peek-${v.id}`,{skipTags:X.skipTags,startIndex:St}));let Oe=document.createElement("div");if(Oe.innerHTML=Le,X.useCaret&&Pt.length>0){let Ae=ol(),Ct=Oe.querySelectorAll(".persona-stream-char, .persona-stream-word"),ct=Ct[Ct.length-1];ct?.parentNode?ct.parentNode.insertBefore(Ae,ct.nextSibling):Oe.appendChild(Ae)}Qi(m,Oe),X.onAfterRender?.({container:m,bubble:i,messageId:v.id,message:v,speed:z.speed,duration:z.duration})}}let pn=Sn||Ta;i.classList.toggle("persona-pill-peek--visible",pn)};if(D()){let i=He.peekBanner;if(i){let v=L=>{L.preventDefault(),L.stopPropagation(),lt(!0,"user")};i.addEventListener("pointerdown",v),_e.push(()=>{i.removeEventListener("pointerdown",v)})}let m=()=>{Ta||(Ta=!0,Tr())},y=()=>{Ta&&(Ta=!1,Tr())};ue.addEventListener("pointerenter",m),ue.addEventListener("pointerleave",y),_e.push(()=>{ue.removeEventListener("pointerenter",m),ue.removeEventListener("pointerleave",y)}),Qe&&(Qe.addEventListener("pointerenter",m),Qe.addEventListener("pointerleave",y),_e.push(()=>{Qe.removeEventListener("pointerenter",m),Qe.removeEventListener("pointerleave",y)}))}let ub=i=>{let m=o.launcher?.composerBar??{},y=m.expandedSize??"anchored",v=m.bottomOffset??"16px",L=m.collapsedMaxWidth,I=m.expandedMaxWidth??"880px",Q=m.expandedTopOffset??"5vh",z=m.modalMaxWidth??"880px",X=m.modalMaxHeight??"min(90vh, 800px)",ee="calc(100vw - 32px)",ce="var(--persona-pill-area-height, 80px)",re=De.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",Qe){let ge=Qe.style;ge.bottom=v,ge.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=z,re.maxWidth=ee,re.maxHeight=X,re.height=X;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${v} + ${ce})`,re.top=Q,re.width=I,re.maxWidth=ee}},Ea=()=>{if(!q())return;if(D()){let ee=(o.launcher?.composerBar??{}).expandedSize??"anchored",ce=Y?"expanded":"collapsed";De.dataset.state=ce,De.dataset.expandedSize=ee,Qe&&(Qe.dataset.state=ce,Qe.dataset.expandedSize=ee),De.style.removeProperty("display"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ub(Y),fe.style.display=Y?"flex":"none",Ps(),Y?(db(),cb()):(Mf(),Tf()),Tr();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,Q=sn(o).reveal;Y?(De.style.removeProperty("display"),De.style.display=i?"flex":"",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-95","persona-opacity-0"),ue.classList.add("persona-scale-100","persona-opacity-100"),Ot?Ot.element.style.display="none":Qt&&(Qt.style.display="none")):(i?i&&(Q==="overlay"||Q==="push")&&!I?(De.style.removeProperty("display"),De.style.display="flex",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.setProperty("display","none","important"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.display="",De.classList.add("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100"),ue.classList.add("persona-scale-95","persona-opacity-0")),Ot?Ot.element.style.display=i?"none":"":Qt&&(Qt.style.display=i?"none":""))},lt=(i,m="user")=>{if(!q()||Y===i)return;let y=Y;Y=i,Ea();let v=(()=>{let I=o.launcher?.sidebarMode??!1,Q=e.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,ee=Q.innerWidth<=X,ce=Et(o)&&z&&ee,re=D()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return I||z&&ee&&C||ce||re})();if(Y&&v){if(!Hn){let I=e.getRootNode(),Q=I instanceof ShadowRoot?I.host:e.closest(".persona-host");Q&&(Hn=jp(Q,o.launcher?.zIndex??Gt))}Bn||(Bn=Gp(e.ownerDocument))}else Y||(Hn?.(),Hn=null,Bn?.(),Bn=null);Y&&(Pa(),wf()||(gn()==="follow"?mo(!0):vf()));let L={open:Y,source:m,timestamp:Date.now()};Y&&!y?p.emit("widget:opened",L):!Y&&y&&p.emit("widget:closed",L),p.emit("widget:state",{open:Y,launcherEnabled:C,voiceActive:je.active,streaming:V.isStreaming()})},Kl=i=>{Ye(i?"stop":"send"),G&&(G.disabled=i),ha.forEach(m=>{m.elements.forEach(y=>{y.toggleAttribute("data-disabled",i),y instanceof HTMLButtonElement||y.setAttribute("aria-disabled",i?"true":"false")}),m.buttons.forEach(y=>{y.disabled=i})}),ye.dataset.personaComposerStreaming=i?"true":"false",ye.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=i)})},Xl=()=>{je.active||j&&j.focus()};p.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Xl(),200)});let kf=()=>{B.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",_.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",j.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=ie.querySelector("[data-persona-intro-card]");if(i){let y=o.copy?.showWelcomeCard!==!1;i.style.display=y?"":"none",y?(ie.classList.remove("persona-gap-3"),ie.classList.add("persona-gap-6")):(ie.classList.remove("persona-gap-6"),ie.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!V?.isStreaming()&&(T.textContent=o.copy?.sendButtonLabel??"Send"),j.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',j.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=>{k(m=>({...m,sessionId:i}))}});let Qo=null,fb=()=>{Qo==null&&(Qo=setInterval(()=>{let i=We.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=ci(m-v))})},100))},Jl=(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((Q,z)=>Jl(Q,m[z]));let y=i,v=m,L=Object.keys(y),I=Object.keys(v);return L.length===I.length&&L.every(Q=>Object.prototype.hasOwnProperty.call(v,Q)&&Jl(y[Q],v[Q]))},Lf=i=>{let{content:m,rawContent:y,llmContent:v,...L}=i;return L},Ql=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!bs(i),mb=(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))&&Ql(v)&&Ql(L)&&Jl(Lf(v),Lf(L))},Pf=null,Er=null,Yo=null,jn=null,Us=i=>{Pf=i;let m,y;Er=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),!Er&&Ql(I)&&(Er={index:L,id:I.id}),m&&y&&Er)break}Aa(We,i,te),Op(We,wn.artifacts,{suppressTransition:Sn}),fb(),ya(i),mo(!Sn),ib(i),i.length===0&&(wa(),xa=!0,Hs=!1,Bs=null,Ds=!1),!Ul||Ws?(Ul=!0,ba=m?.id??null,ql=y?.id??null):m&&m.id!==ba?(ba=m.id,rb(m.id)):y&&y.id!==ql&&ab(),y&&(ql=y.id),sb(i);let v=je.lastUserMessageId;m&&m.id!==v&&(je.lastUserMessageId=m.id,p.emit("user:message",m)),je.lastUserMessageWasVoice=!!m?.viaVoice,$l(i),Tr()},Yl=()=>{jn!==null&&(cancelAnimationFrame(jn),jn=null);let i=Yo;Yo=null,i&&Us(i)},Rf=()=>{jn!==null&&cancelAnimationFrame(jn),jn=null,Yo=null},gb=i=>{let m=Yo??Pf;if(Sn&&m&&Er&&mb(m,i,Er)){Yo=i,jn===null&&(jn=requestAnimationFrame(()=>{jn=null;let y=Yo;Yo=null,y&&Us(y)}));return}if(i.length===0){Rf(),Us(i);return}Yl(),Us(i)};V=new qr(o,{onMessagesChanged(i){gb(i)},onStatusChanged(i){let m=o.statusIndicator??{};Kt(W,(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||(V?.getMessages().length===0?Rf():Yl()),Sn=i,Kl(i),V&&Aa(We,V.getMessages(),te),i||(mo(!0),pf=!0,V&&uf(V.getMessages(),To(o))),cn(),_u(i?"Responding\u2026":"Response complete."),Tr()},onVoiceStatusChanged(i){if(p.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Gn(),Lr();break;case"processing":Gn(),Tb();break;case"speaking":Gn(),Eb();break;default:i==="idle"&&V.isBargeInActive()?(Gn(),Lr(),G?.setAttribute("aria-label","End voice session")):(je.active=!1,Gn(),$n("system"),Tn());break}},onArtifactsState(i){wn=i,i.artifacts.length===0&&(Cr=!1),Op(We,i.artifacts,{suppressTransition:Sn}),zn(),$l()},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})}}),st.current=V,_e.push(()=>V.cancel());let Zl=null;if(V.onReadAloudChange((i,m)=>{ju=i,Gu=m,Ku();let y=i??Zl;i&&(Zl=i);let v=y?V.getMessages().find(L=>L.id===y)??null:null;p.emit("message:read-aloud",{messageId:y,message:v,state:m,timestamp:Date.now()}),m==="idle"&&(Zl=null)}),Ul=!0,o.voiceRecognition?.provider?.type==="runtype")try{V.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&V.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(ke||o.onSSEEvent)&&V.setSSEEventCallback((i,m)=>{o.onSSEEvent?.(i,m),Se?.processEvent(i,m),ke?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(m)})});let If=()=>{o.resume&&typeof o.reconnectStream=="function"&&V.resumeFromHandle(o.resume)};g?g.then(i=>{if(i){if(i.metadata&&(u=vu(i.metadata),A.syncFromMetadata()),i.messages?.length){Ws=!0;try{V.hydrateMessages(i.messages)}finally{Ws=!1}}i.artifacts?.length&&V.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>If()):If();let Wf=()=>{!D()||Y||!(o.launcher?.composerBar?.expandOnSubmit??!0)||lt(!0,"auto")},hb=(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),$w(L)}}:i:m,yb=()=>{let m=j.getInlineMessageFields?.();return m&&m.contentSegments.some(v=>v.kind==="mention")?m.contentSegments:void 0},ka=!1,bb=async i=>{let m=j.value.trim(),y=At?.hasAttachments()??!1,v=m?await(ln?.takeInlineCommand(m)??Promise.resolve(null)):null;if(v?.kind==="action"){j.value="",j.style.height="auto",La(),ln?.clear();return}let L=ln?.collectForSubmit()??null,I=v?.kind==="server"?v.mentions:null,Q=hb(L,I),z=v?.kind==="prompt"?v.sendText:m,X=!!L&&L.refs.length>0;if(!z&&!y&&!X&&!I)return;Wf();let ee;y&&(ee=[],ee.push(...At.getContentParts()),z&&ee.push(Lo(z)));let ce=v?.kind==="prompt"?void 0:yb();j.value="",j.style.height="auto",La(),V.sendMessage(z,{contentParts:ee,mentions:Q??void 0,contentSegments:ce,viaVoice:i?.viaVoice}),y&&At.clearAttachments(),L&&ln?.clear()},ed=async i=>{if(!ka){ka=!0;try{await bb(i)}finally{ka=!1}}},Hf=i=>{if(i.preventDefault(),V.isStreaming()){V.cancel(),Se?.reset(),Ge?.update();return}ka||ed()},xb=()=>o.features?.composerHistory!==!1,td={...Up},nd=!1,La=()=>{td={...Up}},vb=()=>V.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Cb=i=>{if(!j)return;nd=!0,j.value=i,j.dispatchEvent(new Event("input",{bubbles:!0})),nd=!1;let m=j.value.length;j.setSelectionRange(m,m)},wb=i=>{nd||(i.isComposing||ln?.handleInput(i.inputType??void 0),La())},Ab=i=>{if(j&&!(!i.isComposing&&ln?.handleKeydown(i))){if(xb()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let m=j.selectionStart===0&&j.selectionEnd===0,y=Kg({direction:i.key==="ArrowUp"?"up":"down",history:vb(),currentValue:j.value,atStart:m,state:td});if(td=y.state,y.handled){i.preventDefault(),y.value!==void 0&&Cb(y.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(V.isStreaming()){i.preventDefault();return}if(ka){i.preventDefault();return}La(),i.preventDefault(),T.click()}}},Bf=i=>{i.key!=="Escape"||i.isComposing||V.isStreaming()&&i.composedPath().includes(fe)&&(V.cancel(),Se?.reset(),Ge?.update(),La(),i.preventDefault(),i.stopImmediatePropagation())},Sb=async i=>{if(o.attachments?.enabled!==!0||!At)return;let m=Uw(i.clipboardData);m.length!==0&&(i.preventDefault(),await At.handleFiles(m))},bn=null,Dn=!1,kr=null,bt=null,Df=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,qs=(i="user")=>{if(Dn||V.isStreaming())return;let m=Df();if(!m)return;bn=new m;let v=(o.voiceRecognition??{}).pauseDuration??2e3;bn.continuous=!0,bn.interimResults=!0,bn.lang="en-US";let L=j.value;bn.onresult=I=>{let Q="",z="";for(let ee=0;ee<I.results.length;ee++){let ce=I.results[ee],re=ce[0].transcript;ce.isFinal?Q+=re+" ":z=re}let X=L+Q+z;j.value=X,kr&&clearTimeout(kr),(Q||z)&&(kr=window.setTimeout(()=>{j.value.trim()&&bn&&Dn&&(go(),ed({viaVoice:!0}))},v))},bn.onerror=I=>{I.error!=="no-speech"&&go()},bn.onend=()=>{if(Dn){let I=j.value.trim();I&&I!==L.trim()&&ed({viaVoice:!0}),go()}};try{if(bn.start(),Dn=!0,je.active=!0,i!=="system"&&(je.manuallyDeactivated=!1),$n(i),Tn(),G){let I=o.voiceRecognition??{};bt={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 Q=I.recordingBackgroundColor,z=I.recordingIconColor,X=I.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=Q??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=z??"var(--persona-voice-recording-indicator, #ffffff)",z){let ee=G.querySelector("svg");ee&&ee.setAttribute("stroke",z)}X&&(G.style.borderColor=X),G.setAttribute("aria-label","Stop voice recognition")}}catch{go("system")}},go=(i="user")=>{if(Dn){if(Dn=!1,kr&&(clearTimeout(kr),kr=null),bn){try{bn.stop()}catch{}bn=null}if(je.active=!1,$n(i),Tn(),G){if(G.classList.remove("persona-voice-recording"),bt){G.style.backgroundColor=bt.backgroundColor,G.style.color=bt.color,G.style.borderColor=bt.borderColor;let m=G.querySelector("svg");m&&m.setAttribute("stroke",bt.color||"currentColor"),bt=null}G.setAttribute("aria-label","Start voice recognition")}}},Mb=(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 Q=x("div","persona-send-button-wrapper"),z=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");z.type="button";let X=i?.tooltipText??"Start voice recognition";z.setAttribute("aria-label",X);let ee=i?.iconName??"mic",ce=m?.size??"40px",re=i?.iconSize??ce,ge=parseFloat(re)||24,Ve=i?.backgroundColor??m?.backgroundColor,dt=i?.iconColor??m?.textColor;z.style.width=re,z.style.height=re,z.style.minWidth=re,z.style.minHeight=re,z.style.fontSize="18px",z.style.lineHeight="1",dt?z.style.color=dt:z.style.color="var(--persona-text, #111827)";let pn=ae(ee,ge,dt||"currentColor",1.5);pn?z.appendChild(pn):z.textContent="\u{1F3A4}",Ve?z.style.backgroundColor=Ve:z.style.backgroundColor="",i?.borderWidth&&(z.style.borderWidth=i.borderWidth,z.style.borderStyle="solid"),i?.borderColor&&(z.style.borderColor=i.borderColor),i?.paddingX&&(z.style.paddingLeft=i.paddingX,z.style.paddingRight=i.paddingX),i?.paddingY&&(z.style.paddingTop=i.paddingY,z.style.paddingBottom=i.paddingY),Q.appendChild(z);let St=i?.showTooltip??!1;return Ut({anchor:z,trigger:Q,text:()=>z.getAttribute("aria-label")??X,enabled:St}),{micButton:z,micButtonWrapper:Q}},od=()=>{if(!G||bt)return;let i=o.voiceRecognition??{};bt={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}},rd=(i,m)=>{if(!G)return;let y=G.querySelector("svg");y&&y.remove();let v=bt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),L=ae(i,v,m,1.5);L&&G.appendChild(L)},Vs=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Lr=()=>{if(!G)return;od();let i=o.voiceRecognition??{},m=i.recordingBackgroundColor,y=i.recordingIconColor,v=i.recordingBorderColor;if(Vs(),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;od();let i=o.voiceRecognition??{},m=V.getVoiceInterruptionMode(),y=i.processingIconName??"loader",v=i.processingIconColor??bt?.color??"",L=i.processingBackgroundColor??bt?.backgroundColor??"",I=i.processingBorderColor??bt?.borderColor??"";Vs(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=L,G.style.borderColor=I;let Q=v||"currentColor";G.style.color=Q,rd(y,Q),G.setAttribute("aria-label","Processing voice input"),m==="none"&&(G.style.cursor="default")},Eb=()=>{if(!G)return;od();let i=o.voiceRecognition??{},m=V.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",v=i.speakingIconName??y,L=i.speakingIconColor??(m==="barge-in"?i.recordingIconColor??bt?.color??"":bt?.color??""),I=i.speakingBackgroundColor??(m==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":bt?.backgroundColor??""),Q=i.speakingBorderColor??(m==="barge-in"?i.recordingBorderColor??"":bt?.borderColor??"");Vs(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=I,G.style.borderColor=Q;let z=L||"currentColor";G.style.color=z,rd(v,z);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")},Gn=()=>{G&&(Vs(),bt&&(G.style.backgroundColor=bt.backgroundColor??"",G.style.color=bt.color??"",G.style.borderColor=bt.borderColor??"",rd(bt.iconName,bt.color||"currentColor"),bt=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},zs=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=V.getVoiceStatus(),m=V.getVoiceInterruptionMode();if(m==="none"&&(i==="processing"||i==="speaking"))return;if(m==="cancel"&&(i==="processing"||i==="speaking")){V.stopVoicePlayback();return}if(V.isBargeInActive()){V.stopVoicePlayback(),V.deactivateBargeIn().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Tn(),$n("user"),Gn()});return}V.toggleVoice().then(()=>{je.active=V.isVoiceActive(),je.manuallyDeactivated=!V.isVoiceActive(),Tn(),$n("user"),V.isVoiceActive()?Lr():Gn()});return}if(Dn){let i=j.value.trim();je.manuallyDeactivated=!0,Tn(),go("user"),i&&(j.value="",j.style.height="auto",V.sendMessage(i))}else je.manuallyDeactivated=!1,Tn(),qs("user")};qu=zs,G&&(G.addEventListener("click",zs),_e.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(V.isVoiceActive()&&V.toggleVoice(),Gn()):go("system"),G&&G.removeEventListener("click",zs)}));let kb=p.on("assistant:complete",()=>{mf&&(je.active||je.manuallyDeactivated||mf==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{!je.active&&!je.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?V.toggleVoice().then(()=>{je.active=V.isVoiceActive(),$n("auto"),V.isVoiceActive()&&Lr()}):qs("auto"))},600))});_e.push(kb);let Lb=p.on("action:resubmit",()=>{setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)});_e.push(Lb);let Ff=()=>{lt(!Y,"user")},Ot=null,Qt=null;if(C&&!D()){let{instance:i,element:m}=Zp({config:o,plugins:a,onToggle:Ff});Ot=i,i||(Qt=m)}Ot?e.appendChild(Ot.element):Qt&&e.appendChild(Qt),Ea(),ya(),kf(),Kl(V.isStreaming()),wf()||(gn()==="follow"?mo(!0):vf()),Yy(),R&&(!C||D()?setTimeout(()=>Xl(),0):Y&&setTimeout(()=>Xl(),200));let Pa=()=>{if(D()){vr(),Ea();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,Q=v.innerWidth<=I,z=L&&Q&&C;try{if(z){pa(),ua=Ls();return}let X=!1;K&&(K=!1,pa(),X=!0);let ee=Ls();if(!X&&ee!==ua&&(pa(),X=!0),ua=ee,X&&Ol(),!C&&!i){ue.style.height="",ue.style.width="";return}if(!m&&!i){let re=o?.launcher?.width??o?.launcherWidth??fn;ue.style.width=re,ue.style.maxWidth=re}if(ks(),!y){let ce=v.innerHeight,re=64,ge=o.launcher?.heightOffset??0,Ve=Math.max(200,ce-re),dt=Math.min(640,Ve),et=Math.max(200,dt-ge);ue.style.height=`${et}px`}}finally{if(vr(),Ea(),Y&&C){let ee=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ce=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,ge=Et(o)&&re&&ee,Ve=ce||re&&ee&&C||ge;if(Ve&&!Bn){let dt=e.getRootNode(),et=dt instanceof ShadowRoot?dt.host:e.closest(".persona-host");et&&!Hn&&(Hn=jp(et,o.launcher?.zIndex??Gt)),Bn=Gp(e.ownerDocument)}else Ve||(Hn?.(),Hn=null,Bn?.(),Bn=null)}}};Pa();let Of=e.ownerDocument.defaultView??window;if(Of.addEventListener("resize",Pa),_e.push(()=>Of.removeEventListener("resize",Pa)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{vr()});i.observe(ye),_e.push(()=>i.disconnect())}hn=ie.scrollTop;let Nf=_n(ie),_f=()=>{let i=ie.scrollTop,m=_n(ie),y=m<Nf;if(Nf=m,!so()){hn=i,cn();return}let{action:v,nextLastScrollTop:L}=Zi({following:dn.isFollowing(),currentScrollTop:i,lastScrollTop:hn,nearBottom:Fo(ie,Fs),userScrollThreshold:Jy,isAutoScrolling:yn||Is||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(hn=L,v==="resume"){Ns()||fo();return}v==="pause"&&Ca()};if(ie.addEventListener("scroll",_f,{passive:!0}),_e.push(()=>ie.removeEventListener("scroll",_f)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{ob(),cd(We)});i.observe(We),i.observe(ie),_e.push(()=>i.disconnect())}let Uf=()=>{so()&&dn.isFollowing()&&Ns()&&Ca()},qf=ie.ownerDocument;qf.addEventListener("selectionchange",Uf),_e.push(()=>{qf.removeEventListener("selectionchange",Uf)});let Pb=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Vf=i=>{Pb.has(i.key)&&(Xo(),Fu()&&so()&&dn.isFollowing()&&Ca())},zf=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Xo(),Fu()&&so()&&dn.isFollowing()&&Ca())};ie.addEventListener("keydown",Vf),ie.addEventListener("focusin",zf),_e.push(()=>{ie.removeEventListener("keydown",Vf),ie.removeEventListener("focusin",zf)});let $f=i=>{if(i.deltaY!==0&&Xo(),!so())return;let m=el({following:dn.isFollowing(),deltaY:i.deltaY,nearBottom:Fo(ie,Fs),resumeWhenNearBottom:!0});m==="pause"?Ca():m==="resume"&&!Ns()&&fo()};ie.addEventListener("wheel",$f,{passive:!0}),ie.addEventListener("touchmove",Xo,{passive:!0}),ie.addEventListener("pointerdown",Xo,{passive:!0}),_e.push(()=>{ie.removeEventListener("touchmove",Xo),ie.removeEventListener("pointerdown",Xo)}),_e.push(()=>ie.removeEventListener("wheel",$f)),kt.addEventListener("click",()=>{wa(),ie.scrollTop=ie.scrollHeight,hn=ie.scrollTop,fo(),mo(!0),cn()}),_e.push(()=>kt.remove()),_e.push(()=>{yf(),wa()});let jf=()=>{U&&(zo&&(U.removeEventListener("click",zo),zo=null),q()?(U.style.display="",zo=()=>{lt(!1,"user")},U.addEventListener("click",zo)):U.style.display="none")};jf(),(()=>{let{clearChatButton:i}=He;i&&i.addEventListener("click",()=>{V.clearMessages(),jo.clear(),fo(),So(He.composerOverlay);try{localStorage.removeItem(aa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${aa}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==aa)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&&zl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},A.syncFromMetadata(),ke?.clear(),Se?.reset(),Ge?.update()})})(),b&&b.addEventListener("submit",Hf);let Gf=[["keydown",Ab],["input",wb],["paste",Sb],["focus",Vy]],Kf=i=>{if(i)for(let[m,y]of Gf)i.addEventListener(m,y)},Xf=i=>{if(i)for(let[m,y]of Gf)i.removeEventListener(m,y)};Kf(j),ln?.onComposerSwap((i,m)=>{Xf(m),j=i,Kf(i)});let Jf=e.ownerDocument??document;Jf.addEventListener("keydown",Bf,!0);let Qf="persona-attachment-drop-active",Ra=0,ad=()=>{Ra=0,fe.classList.remove(Qf)},Pr=()=>o.attachments?.enabled===!0&&At!==null,Yf=i=>{!kl(i.dataTransfer)||!Pr()||(Ra++,Ra===1&&fe.classList.add(Qf))},Zf=i=>{!kl(i.dataTransfer)||!Pr()||(Ra--,Ra<=0&&ad())},em=i=>{!kl(i.dataTransfer)||!Pr()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},tm=i=>{if(!kl(i.dataTransfer)||!Pr())return;i.preventDefault(),i.stopPropagation(),ad();let m=Array.from(i.dataTransfer.files??[]);m.length!==0&&At.handleFiles(m)},ho=!0;fe.addEventListener("dragenter",Yf,ho),fe.addEventListener("dragleave",Zf,ho),e.addEventListener("dragover",em,ho),e.addEventListener("drop",tm,ho);let $s=e.ownerDocument,nm=i=>{Pr()&&i.preventDefault()},om=i=>{Pr()&&i.preventDefault()};$s.addEventListener("dragover",nm),$s.addEventListener("drop",om),_e.push(()=>{b&&b.removeEventListener("submit",Hf),Xf(j),Jf.removeEventListener("keydown",Bf,!0),ln?.destroy()}),_e.push(()=>{fe.removeEventListener("dragenter",Yf,ho),fe.removeEventListener("dragleave",Zf,ho),e.removeEventListener("dragover",em,ho),e.removeEventListener("drop",tm,ho),$s.removeEventListener("dragover",nm),$s.removeEventListener("drop",om),ad()}),_e.push(()=>{V.cancel()}),Ot?_e.push(()=>{Ot?.destroy()}):Qt&&_e.push(()=>{Qt?.remove()});let Lt={update(i){let m=o.toolCall,y=o.messageActions,v=o.layout?.messages,L=o.colorScheme,I=o.loadingIndicator,Q=o.iterationDisplay,z=o.features?.showReasoning,X=o.features?.showToolCalls,ee=o.features?.toolCallDisplay,ce=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o=Cl({...o,features:r},i),r=o.features,o=ms(o),Ps(),dr(e,o),us(e,o),fs(e,o),zn(),o.colorScheme!==L&&ef();let ge=gs.getForInstance(o.plugins);a.length=0,a.push(...ge),C=o.launcher?.enabled??!0,E=o.launcher?.autoExpand??!1,me=o.features?.showReasoning??!0,oe=o.features?.showToolCalls??!0,Z=o.features?.scrollToBottom??{};let Ve=gn();he=o.features?.scrollBehavior??{},Ve!==gn()&&(wa(),fo()),Uu(),cn();let dt=le;if(le=o.features?.showEventStreamToggle??!1,le&&!dt){if(ke||(we=new cs(ve),ke=new ds(Ee,we),Se=Se??new ps,we.open().then(()=>ke?.restore()).catch(()=>{}),V.setSSEEventCallback((ne,$e)=>{o.onSSEEvent?.(ne,$e),Se?.processEvent(ne,$e),ke.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify($e)})})),!Ze&&Te){let ne=o.features?.eventStream?.classNames,$e="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"+(ne?.toggleButton?" "+ne.toggleButton:"");Ze=x("button",$e),Ze.style.width="28px",Ze.style.height="28px",Ze.style.color=en.actionIconColor,Ze.type="button",Ze.setAttribute("aria-label","Event Stream"),Ze.title="Event Stream";let mt=ae("activity","18px","currentColor",1.5);mt&&Ze.appendChild(mt);let tt=He.clearChatButtonWrapper,rt=He.closeButtonWrapper,$t=tt||rt;$t&&$t.parentNode===Te?Te.insertBefore(Ze,$t):Te.appendChild(Ze),Ze.addEventListener("click",()=>{ze?da():Hl()})}}else!le&&dt&&(da(),Ze&&(Ze.remove(),Ze=null),ke?.clear(),we?.destroy(),ke=null,we=null,Se?.reset(),Se=null);if(o.launcher?.enabled===!1&&Ot&&(Ot.destroy(),Ot=null),o.launcher?.enabled===!1&&Qt&&(Qt.remove(),Qt=null),o.launcher?.enabled!==!1&&!Ot&&!Qt){let{instance:ne,element:$e}=Zp({config:o,plugins:a,onToggle:Ff});Ot=ne,ne||(Qt=$e),e.appendChild($e)}Ot&&Ot.update(o),J&&o.launcher?.title!==void 0&&(J.textContent=o.launcher.title),se&&o.launcher?.subtitle!==void 0&&(se.textContent=o.launcher.subtitle);let et=o.layout?.header;if(et?.layout!==F&&Te){let ne=et?Jr(o,et,{showClose:q(),onClose:()=>lt(!1,"user")}):oo({config:o,showClose:q(),onClose:()=>lt(!1,"user")});wt.replaceHeader(ne),Te=wt.header.element,O=wt.header.iconHolder,J=wt.header.headerTitle,se=wt.header.headerSubtitle,U=wt.header.closeButton,F=et?.layout}else if(et){if(O&&(O.style.display=et.showIcon===!1?"none":""),J&&(J.style.display=et.showTitle===!1?"none":""),se&&(se.style.display=et.showSubtitle===!1?"none":""),U){let ne=q()&&et.showCloseButton!==!1;U.style.display=ne?"":"none"}if(He.clearChatButtonWrapper){let ne=et.showClearChat;if(ne!==void 0){He.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:$e}=He;$e&&!$e.classList.contains("persona-absolute")&&(ne?$e.classList.remove("persona-ml-auto"):$e.classList.add("persona-ml-auto"))}}}let St=o.layout?.showHeader!==!1;Te&&(Te.style.display=St?"":"none");let Pt=o.layout?.showFooter!==!1;ye&&(ye.style.display=Pt?"":"none"),vr(),cn(),C!==H?C?lt(E,"auto"):(Y=!0,Ea()):E!==w&<(E,"auto"),w=E,H=C,Pa(),jf();let Oe=JSON.stringify(o.toolCall)!==JSON.stringify(m),Ae=JSON.stringify(o.messageActions)!==JSON.stringify(y),Ct=JSON.stringify(o.layout?.messages)!==JSON.stringify(v),ct=o.loadingIndicator?.render!==I?.render||o.loadingIndicator?.renderIdle!==I?.renderIdle||o.loadingIndicator?.showBubble!==I?.showBubble,Ft=o.iterationDisplay!==Q,pt=(o.features?.showReasoning??!0)!==(z??!0)||(o.features?.showToolCalls??!0)!==(X??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ee)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ce);(Oe||Ae||Ct||ct||Ft||pt)&&V&&(_l++,Aa(We,V.getMessages(),te));let Rt=o.features?.streamAnimation?.type;if(Rt!==re&&Rt&&Rt!=="none"){let ne=Xr(Rt,o.features?.streamAnimation?.plugins);ne&&rl(ne,e)}let Pe=o.launcher??{},Ne=Pe.headerIconHidden??!1,qt=o.layout?.header?.showIcon,Vt=Ne||qt===!1,xt=Pe.headerIconName,it=Pe.headerIconSize??"48px";if(O){let ne=fe.querySelector(".persona-border-b-persona-divider"),$e=ne?.querySelector(".persona-flex-col");if(Vt)O.style.display="none",ne&&$e&&!ne.contains($e)&&ne.insertBefore($e,ne.firstChild);else{if(O.style.display="",O.style.height=it,O.style.width=it,ne&&$e&&(ne.contains(O)?O.nextSibling!==$e&&(O.remove(),ne.insertBefore(O,$e)):ne.insertBefore(O,$e)),xt){let tt=parseFloat(it)||24,rt=ae(xt,tt*.6,"currentColor",1);rt?O.replaceChildren(rt):O.textContent=Pe.agentIconText??"\u{1F4AC}"}else if(Pe.iconUrl){let tt=O.querySelector("img");if(tt)tt.src=Pe.iconUrl,tt.style.height=it,tt.style.width=it;else{let rt=document.createElement("img");rt.src=Pe.iconUrl,rt.alt="",rt.className="persona-rounded-xl persona-object-cover",rt.style.height=it,rt.style.width=it,O.replaceChildren(rt)}}else{let tt=O.querySelector("svg"),rt=O.querySelector("img");(tt||rt)&&O.replaceChildren(),O.textContent=Pe.agentIconText??"\u{1F4AC}"}let mt=O.querySelector("img");mt&&(mt.style.height=it,mt.style.width=it)}}let ft=o.layout?.header?.showTitle,Je=o.layout?.header?.showSubtitle;if(J&&(J.style.display=ft===!1?"none":""),se&&(se.style.display=Je===!1?"none":""),U){let ne=q()&&o.layout?.header?.showCloseButton!==!1;U.style.display=ne?"":"none";let $e=Pe.closeButtonSize??"32px",mt=Pe.closeButtonPlacement??"inline";U.style.height=$e,U.style.width=$e;let{closeButtonWrapper:tt}=He,rt=mt==="top-right",$t=tt?.classList.contains("persona-absolute");if(tt&&rt!==$t)if(tt.remove(),rt)tt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",fe.style.position="relative",fe.appendChild(tt);else{let bo=Pe.clearChat?.placement??"inline",Ha=Pe.clearChat?.enabled??!0;tt.className=Ha&&bo==="inline"?"":"persona-ml-auto";let rm=fe.querySelector(".persona-border-b-persona-divider");rm&&rm.appendChild(tt)}if(U.style.color=Pe.closeButtonColor||en.actionIconColor,Pe.closeButtonBackgroundColor?(U.style.backgroundColor=Pe.closeButtonBackgroundColor,U.classList.remove("hover:persona-bg-gray-100")):(U.style.backgroundColor="",U.classList.add("hover:persona-bg-gray-100")),Pe.closeButtonBorderWidth||Pe.closeButtonBorderColor){let bo=Pe.closeButtonBorderWidth||"0px",Ha=Pe.closeButtonBorderColor||"transparent";U.style.border=`${bo} solid ${Ha}`,U.classList.remove("persona-border-none")}else U.style.border="",U.classList.add("persona-border-none");Pe.closeButtonBorderRadius?(U.style.borderRadius=Pe.closeButtonBorderRadius,U.classList.remove("persona-rounded-full")):(U.style.borderRadius="",U.classList.add("persona-rounded-full")),Pe.closeButtonPaddingX?(U.style.paddingLeft=Pe.closeButtonPaddingX,U.style.paddingRight=Pe.closeButtonPaddingX):(U.style.paddingLeft="",U.style.paddingRight=""),Pe.closeButtonPaddingY?(U.style.paddingTop=Pe.closeButtonPaddingY,U.style.paddingBottom=Pe.closeButtonPaddingY):(U.style.paddingTop="",U.style.paddingBottom="");let un=Pe.closeButtonIconName??"x",En=Pe.closeButtonIconText??"\xD7";U.innerHTML="";let Nt=ae(un,"28px","currentColor",1);Nt?(Nt.style.display="block",U.appendChild(Nt)):U.textContent=En;let jt=Pe.closeButtonTooltipText??"Close chat",Xn=Pe.closeButtonShowTooltip??!0;U.setAttribute("aria-label",jt),tt&&Ut({anchor:U,trigger:tt,text:()=>U?.getAttribute("aria-label")??jt,enabled:Xn})}let{clearChatButton:Be,clearChatButtonWrapper:gt}=He;if(Be){let ne=Pe.clearChat??{},$e=ne.enabled??!0,mt=o.layout?.header?.showClearChat,tt=mt!==void 0?mt:$e,rt=ne.placement??"inline";if(gt){gt.style.display=tt?"":"none";let{closeButtonWrapper:$t}=He;!D()&&$t&&!$t.classList.contains("persona-absolute")&&(tt?$t.classList.remove("persona-ml-auto"):$t.classList.add("persona-ml-auto"));let un=rt==="top-right",En=gt.classList.contains("persona-absolute");if(!D()&&un!==En&&tt){if(gt.remove(),un)gt.className="persona-absolute persona-top-4 persona-z-50",gt.style.right="48px",fe.style.position="relative",fe.appendChild(gt);else{gt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",gt.style.right="";let jt=fe.querySelector(".persona-border-b-persona-divider"),Xn=He.closeButtonWrapper;jt&&Xn&&Xn.parentElement===jt?jt.insertBefore(gt,Xn):jt&&jt.appendChild(gt)}let Nt=He.closeButtonWrapper;Nt&&!Nt.classList.contains("persona-absolute")&&(un?Nt.classList.add("persona-ml-auto"):Nt.classList.remove("persona-ml-auto"))}}if(tt){if(!D()){let bo=ne.size??"32px";Be.style.height=bo,Be.style.width=bo}let $t=ne.iconName??"refresh-cw",un=ne.iconColor??"";Be.style.color=un||en.actionIconColor,Be.innerHTML="";let En=D()?"14px":"20px",Nt=ae($t,En,"currentColor",1);if(Nt&&(Nt.style.display="block",Be.appendChild(Nt)),ne.backgroundColor?(Be.style.backgroundColor=ne.backgroundColor,Be.classList.remove("hover:persona-bg-gray-100")):(Be.style.backgroundColor="",Be.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let bo=ne.borderWidth||"0px",Ha=ne.borderColor||"transparent";Be.style.border=`${bo} solid ${Ha}`,Be.classList.remove("persona-border-none")}else Be.style.border="",Be.classList.add("persona-border-none");ne.borderRadius?(Be.style.borderRadius=ne.borderRadius,Be.classList.remove("persona-rounded-full")):(Be.style.borderRadius="",Be.classList.add("persona-rounded-full")),ne.paddingX?(Be.style.paddingLeft=ne.paddingX,Be.style.paddingRight=ne.paddingX):(Be.style.paddingLeft="",Be.style.paddingRight=""),ne.paddingY?(Be.style.paddingTop=ne.paddingY,Be.style.paddingBottom=ne.paddingY):(Be.style.paddingTop="",Be.style.paddingBottom="");let jt=ne.tooltipText??"Clear chat",Xn=ne.showTooltip??!0;Be.setAttribute("aria-label",jt),gt&&Ut({anchor:Be,trigger:gt,text:()=>Be?.getAttribute("aria-label")??jt,enabled:Xn})}}let zt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[hs],vn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[xr.message,xr.messageAndClick];A=ys({parsers:zt,handlers:vn,getSessionMetadata:S,updateSessionMetadata:k,emit:p.emit,documentRef:typeof document<"u"?document:null}),te=Yh(o,A,pe),V.updateConfig(o),Aa(We,V.getMessages(),te),ya(),kf(),Kl(V.isStreaming());let Ia=o.voiceRecognition?.enabled===!0,js=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Tt=o.voiceRecognition?.provider?.type==="runtype";if(Ia&&(js||Tt))if(!G||!qe){let ne=Mb(o.voiceRecognition,o.sendButton);ne&&(G=ne.micButton,qe=ne.micButtonWrapper,nt.insertBefore(qe,$),G.addEventListener("click",zs),G.disabled=V.isStreaming())}else{let ne=o.voiceRecognition??{},$e=o.sendButton??{},mt=ne.iconName??"mic",tt=$e.size??"40px",rt=ne.iconSize??tt,$t=parseFloat(rt)||24;G.style.width=rt,G.style.height=rt,G.style.minWidth=rt,G.style.minHeight=rt;let un=ne.iconColor??$e.textColor;G.innerHTML="";let En=ae(mt,$t,un||"currentColor",1.5);En?G.appendChild(En):G.textContent="\u{1F3A4}";let Nt=ne.backgroundColor??$e.backgroundColor;Nt?G.style.backgroundColor=Nt:G.style.backgroundColor="",un?G.style.color=un:G.style.color="var(--persona-text, #111827)",ne.borderWidth?(G.style.borderWidth=ne.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),ne.borderColor?G.style.borderColor=ne.borderColor:G.style.borderColor="",ne.paddingX?(G.style.paddingLeft=ne.paddingX,G.style.paddingRight=ne.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),ne.paddingY?(G.style.paddingTop=ne.paddingY,G.style.paddingBottom=ne.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let jt=ne.tooltipText??"Start voice recognition",Xn=ne.showTooltip??!1;G.setAttribute("aria-label",jt),qe&&Ut({anchor:G,trigger:qe,text:()=>G?.getAttribute("aria-label")??jt,enabled:Xn}),qe.style.display="",G.disabled=V.isStreaming()}else G&&qe&&(qe.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?V.isVoiceActive()&&V.toggleVoice():Dn&&go());if(o.attachments?.enabled===!0){if(!Dt||!Fe){let ne=o.attachments??{},mt=(o.sendButton??{}).size??"40px";Jt||(Jt=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Jt.style.display="none",b.insertBefore(Jt,j)),vt||(vt=document.createElement("input"),vt.type="file",vt.accept=(ne.allowedTypes??to).join(","),vt.multiple=(ne.maxFiles??4)>1,vt.style.display="none",vt.setAttribute("aria-label","Attach files"),b.insertBefore(vt,j)),Dt=x("div","persona-send-button-wrapper"),Fe=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Fe.type="button",Fe.setAttribute("aria-label",ne.buttonTooltipText??"Attach file");let tt=ne.buttonIconName??"paperclip",rt=mt,$t=parseFloat(rt)||40,un=Math.round($t*.6);Fe.style.width=rt,Fe.style.height=rt,Fe.style.minWidth=rt,Fe.style.minHeight=rt,Fe.style.fontSize="18px",Fe.style.lineHeight="1";let En=ae(tt,un,"currentColor",1.5);En?Fe.appendChild(En):Fe.textContent="\u{1F4CE}",Fe.addEventListener("click",jt=>{jt.preventDefault(),vt?.click()}),Dt.appendChild(Fe);let Nt=ne.buttonTooltipText??"Attach file";Ut({anchor:Fe,trigger:Dt,text:()=>Fe?.getAttribute("aria-label")??Nt}),Ue?Ue.append(Dt):b.appendChild(Dt),!At&&vt&&Jt&&(At=lr.fromConfig(ne),At.setPreviewsContainer(Jt),vt.addEventListener("change",async()=>{At&&vt?.files&&(await At.handleFileSelect(vt.files),vt.value="")}))}else{Dt.style.display="";let ne=o.attachments??{};vt&&(vt.accept=(ne.allowedTypes??to).join(","),vt.multiple=(ne.maxFiles??4)>1),At&&At.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}if(fe.querySelector(".persona-attachment-drop-overlay")?.remove(),fe.appendChild(Zh(o.attachments?.dropOverlay)),Fe){let ne=o.attachments??{},$e=ne.buttonTooltipText??"Attach file";Fe.setAttribute("aria-label",$e),Fe.textContent="";let mt=parseFloat(o.sendButton?.size??"40px")||40,tt=ae(ne.buttonIconName??"paperclip",Math.round(mt*.6),"currentColor",1.5);tt?Fe.appendChild(tt):Fe.textContent="\u{1F4CE}",Dt&&Ut({anchor:Fe,trigger:Dt,text:()=>Fe?.getAttribute("aria-label")??$e})}}else Dt&&(Dt.style.display="none"),At&&At.clearAttachments(),fe.querySelector(".persona-attachment-drop-overlay")?.remove();let Ht=o.sendButton??{},Wa=Ht.useIcon??!1,Ks=Ht.iconText??"\u2191",Rr=Ht.iconName,Xs=Ht.tooltipText??"Send message",sd=Ht.showTooltip??!1,Zo=Ht.size??"40px",Kn=Ht.backgroundColor,er=Ht.textColor;if(Wa){if(T.style.width=Zo,T.style.height=Zo,T.style.minWidth=Zo,T.style.minHeight=Zo,T.style.fontSize="18px",T.style.lineHeight="1",er?T.style.color=er:T.style.color="var(--persona-button-primary-fg, #ffffff)",!V.isStreaming())if(T.innerHTML="",Rr){let ne=parseFloat(Zo)||24,$e=er?.trim()||"currentColor",mt=ae(Rr,ne,$e,2);mt?T.appendChild(mt):T.textContent=Ks}else T.textContent=Ks;T.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Kn?(T.style.backgroundColor=Kn,T.classList.remove("persona-bg-persona-primary")):(T.style.backgroundColor="",T.classList.add("persona-bg-persona-primary"))}else T.textContent=o.copy?.sendButtonLabel??"Send",T.style.width="",T.style.height="",T.style.minWidth="",T.style.minHeight="",T.style.fontSize="",T.style.lineHeight="",T.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",Kn?(T.style.backgroundColor=Kn,T.classList.remove("persona-bg-persona-accent")):T.classList.add("persona-bg-persona-accent"),er?T.style.color=er:T.classList.add("persona-text-white");Ht.borderWidth?(T.style.borderWidth=Ht.borderWidth,T.style.borderStyle="solid"):(T.style.borderWidth="",T.style.borderStyle=""),Ht.borderColor?T.style.borderColor=Ht.borderColor:T.style.borderColor="",Ht.paddingX?(T.style.paddingLeft=Ht.paddingX,T.style.paddingRight=Ht.paddingX):(T.style.paddingLeft="",T.style.paddingRight=""),Ht.paddingY?(T.style.paddingTop=Ht.paddingY,T.style.paddingBottom=Ht.paddingY):(T.style.paddingTop="",T.style.paddingBottom=""),V.isStreaming()||T.setAttribute("aria-label",Xs),$&&Ut({anchor:T,trigger:$,text:()=>T.getAttribute("aria-label")??Xs,enabled:sd});let Js=o.layout?.contentMaxWidth??(D()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);Js?(We.style.maxWidth=Js,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",b&&(b.style.maxWidth=Js,b.style.marginLeft="auto",b.style.marginRight="auto"),ht&&(ht.style.maxWidth=Js,ht.style.marginLeft="auto",ht.style.marginRight="auto")):(We.style.maxWidth="",We.style.marginLeft="",We.style.marginRight="",We.style.width="",b&&(b.style.maxWidth="",b.style.marginLeft="",b.style.marginRight=""),ht&&(ht.style.maxWidth="",ht.style.marginLeft="",ht.style.marginRight=""));let yo=o.statusIndicator??{},Rb=yo.visible??!0;if(W.style.display=Rb?"":"none",V){let ne=V.getStatus();Kt(W,(mt=>mt==="idle"?yo.idleText??It.idle:mt==="connecting"?yo.connectingText??It.connecting:mt==="connected"?yo.connectedText??It.connected:mt==="error"?yo.errorText??It.error:It[mt])(ne),yo,ne)}W.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Ib=yo.align==="left"?"persona-text-left":yo.align==="center"?"persona-text-center":"persona-text-right";W.classList.add(Ib)},open(){q()&<(!0,"api")},close(){q()&<(!1,"api")},toggle(){q()&<(!Y,"api")},reconnect(){V.reconnectNow()},clearChat(){Vn=!1,V.clearMessages(),jo.clear(),fo();try{localStorage.removeItem(aa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${aa}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==aa)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&&zl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},A.syncFromMetadata(),ke?.clear(),Se?.reset(),Ge?.update()},setMessage(i){return!j||V.isStreaming()?!1:(!Y&&q()&<(!0,"system"),j.value=i,j.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(V.isStreaming())return!1;let m=i?.trim()||j.value.trim();return m?(!Y&&q()&<(!0,"system"),j.value="",j.style.height="auto",V.sendMessage(m),!0):!1},startVoiceRecognition(){return V.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(V.isVoiceActive()||(!Y&&q()&<(!0,"system"),je.manuallyDeactivated=!1,Tn(),V.toggleVoice().then(()=>{je.active=V.isVoiceActive(),$n("user"),V.isVoiceActive()&&Lr()})),!0):Dn?!0:Df()?(!Y&&q()&<(!0,"system"),je.manuallyDeactivated=!1,Tn(),qs("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?V.isVoiceActive()?(V.toggleVoice().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Tn(),$n("user"),Gn()}),!0):!1:Dn?(je.manuallyDeactivated=!0,Tn(),go("user"),!0):!1},injectMessage(i){return!Y&&q()&<(!0,"system"),V.injectMessage(i)},injectAssistantMessage(i){!Y&&q()&<(!0,"system");let m=V.injectAssistantMessage(i);return de&&(de=!1,be&&(clearTimeout(be),be=null),setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)),m},injectUserMessage(i){return!Y&&q()&<(!0,"system"),V.injectUserMessage(i)},injectSystemMessage(i){return!Y&&q()&<(!0,"system"),V.injectSystemMessage(i)},injectMessageBatch(i){return!Y&&q()&<(!0,"system"),V.injectMessageBatch(i)},injectComponentDirective(i){return!Y&&q()&<(!0,"system"),V.injectComponentDirective(i)},injectTestMessage(i){!Y&&q()&<(!0,"system"),V.injectTestEvent(i)},async connectStream(i,m){return V.connectStream(i,m)},__pushEventStreamEvent(i){ke&&(Se?.processEvent(i.type,i.payload),ke.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||!ke||Hl()},hideEventStream(){ze&&da()},isEventStreamVisible(){return ze},showArtifacts(){tn(o)&&(Vn=!1,Cr=!0,zn(),Xe?.setMobileOpen(!0))},hideArtifacts(){tn(o)&&(Vn=!0,zn())},upsertArtifact(i){return tn(o)?(On(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Vn=!1,Cr=!0),V.upsertArtifact(i)):null},selectArtifact(i){tn(o)&&V.selectArtifact(i)},clearArtifacts(){tn(o)&&V.clearArtifacts()},getArtifacts(){return V?.getArtifacts()??[]},getSelectedArtifactId(){return V?.getSelectedArtifactId()??null},focusInput(){return C&&!Y&&!D()||!j?!1:(j.focus(),!0)},async resolveApproval(i,m,y){let L=V.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"){V.resolveWebMcpApproval(L.id,m);return}return V.resolveApproval(L.approval,m,y)},setFollowUpSuggestions(i){Ky(i)},clearFollowUpSuggestions(){ff()},getMessages(){return V.getMessages()},getStatus(){return V.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(i){k(i)},on(i,m){return p.on(i,m)},off(i,m){p.off(i,m)},isOpen(){return q()&&Y},isVoiceActive(){return je.active},toggleReadAloud(i){V.toggleReadAloud(i)},stopReadAloud(){V.stopSpeaking()},getReadAloudState(i){return V.getReadAloudState(i)},onReadAloudChange(i){return V.onReadAloudChange(i)},getState(){return{open:q()&&Y,launcherEnabled:C,voiceActive:je.active,streaming:V.isStreaming()}},showCSATFeedback(i){!Y&&q()&<(!0,"system");let m=We.querySelector(".persona-feedback-container");m&&m.remove();let y=Tl({onSubmit:async(v,L)=>{V.isClientTokenMode()&&await V.submitCSATFeedback(v,L),i?.onSubmit?.(v,L)},onDismiss:i?.onDismiss,...i});We.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Y&&q()&<(!0,"system");let m=We.querySelector(".persona-feedback-container");m&&m.remove();let y=El({onSubmit:async(v,L)=>{V.isClientTokenMode()&&await V.submitNPSFeedback(v,L),i?.onSubmit?.(v,L)},onDismiss:i?.onDismiss,...i});We.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,m){return V.submitCSATFeedback(i,m)},async submitNPSFeedback(i,m){return V.submitNPSFeedback(i,m)},destroy(){Yl(),Qo!=null&&(clearInterval(Qo),Qo=null),_e.forEach(i=>i()),De.remove(),Qe?.remove(),Ot?.destroy(),Qt?.remove(),zo&&U.removeEventListener("click",zo)}};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,_e.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=z=>{let X=z.detail;(!X?.instanceId||X.instanceId===i)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",m),_e.push(()=>{window.removeEventListener("persona:focusInput",m)}),le){let z=ee=>{let ce=ee.detail;(!ce?.instanceId||ce.instanceId===i)&&Lt.showEventStream()},X=ee=>{let ce=ee.detail;(!ce?.instanceId||ce.instanceId===i)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",X),_e.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",X)})}let y=z=>{let X=z.detail;(!X?.instanceId||X.instanceId===i)&&Lt.showArtifacts()},v=z=>{let X=z.detail;(!X?.instanceId||X.instanceId===i)&&Lt.hideArtifacts()},L=z=>{let X=z.detail;X?.instanceId&&X.instanceId!==i||X?.artifact&&Lt.upsertArtifact(X.artifact)},I=z=>{let X=z.detail;X?.instanceId&&X.instanceId!==i||typeof X?.id=="string"&&Lt.selectArtifact(X.id)},Q=z=>{let X=z.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",Q),_e.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",Q)})}let xn=qw(o.persistState);if(xn&&q()){let i=Vw(xn.storage),m=`${xn.keyPrefix}widget-open`,y=`${xn.keyPrefix}widget-voice`,v=`${xn.keyPrefix}widget-voice-mode`;if(i){let L=xn.persist?.openState&&i.getItem(m)==="true",I=xn.persist?.voiceState&&i.getItem(y)==="true",Q=xn.persist?.voiceState&&i.getItem(v)==="true";if(L&&setTimeout(()=>{Lt.open(),setTimeout(()=>{if(I||Q)Lt.startVoiceRecognition();else if(xn.persist?.focusInput){let z=e.querySelector("textarea");z&&z.focus()}},100)},0),xn.persist?.openState&&(p.on("widget:opened",()=>{i.setItem(m,"true")}),p.on("widget:closed",()=>{i.setItem(m,"false")})),xn.persist?.voiceState&&(p.on("voice:state",z=>{i.setItem(y,z.active?"true":"false")}),p.on("user:message",z=>{i.setItem(v,z.viaVoice?"true":"false")})),xn.clearOnChatClear){let z=()=>{i.removeItem(m),i.removeItem(y),i.removeItem(v)},X=()=>z();window.addEventListener("persona:clear-chat",X),_e.push(()=>{window.removeEventListener("persona:clear-chat",X)})}}}if(f&&q()&&setTimeout(()=>{Lt.open()},0),Tr(),!Xy){let i=Wr(()=>{V&&(_l++,jo.clear(),Aa(We,V.getMessages(),te))});_e.push(i)}return Lt};var ey=(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},jw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Gw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Kw=(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.")},ty=(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"},Su=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=""},ny=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Su(e)},Cu=e=>{e.style.transition=""},wu=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=""},Au=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Pl=(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))},Jw=(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)},Qw=e=>{let t=Io(e),n=t.components?.panel,o=(r,a)=>r==null||r===""?a:Zt(t,r)??r;return{inset:o(n?.inset,Ni),canvasBackground:o(n?.canvasBackground,_i)}},oy=(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},Yw=(e,t,n,o,r,a,s,l)=>{let p=sn(a),c=p.reveal==="push",d=l!=null,u=l?.inset??"",g=l?.canvasBackground??"";Xw(e,t,n,o,c),Jw(e,t,n,o,p.side,c),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=s?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,h=a?.launcher?.mobileFullscreen??!0,S=a?.launcher?.mobileBreakpoint??640,k=f!=null?f.innerWidth<=S:!1;if(h&&k&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),wu(t),Cu(o),ny(o),Au(n),Pl(r,o),oy(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"),ny(o),jw(o,p.maxHeight),oy(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",wu(t),Cu(o),Au(n),Pl(r,o);let M=p.animate?"transform 180ms ease":"none",A=p.side==="right"?"translateX(100%)":"translateX(-100%)",C=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=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",Cu(o),Su(o),Pl(r,o);let M=ey(p.width,e.clientWidth),A=Math.max(0,e.clientWidth),C=p.animate?"margin-left 180ms ease":"none",E=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=C,t.style.marginLeft=`${E}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="",wu(t),Su(o),Au(n),Pl(r,o);let M=p.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let A=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",E=!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",Gw(o,p.maxHeight),o.style.overflow=M||E?"hidden":"visible",o.style.transition=C,M){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let R=d?`calc(${ey(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=R,r.style.minWidth=R,r.style.maxWidth=R,r.style.boxSizing="border-box"}}},Zw=(e,t)=>{let n=e.ownerDocument.createElement("div");return ty(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){ty(n,o)},destroy(){n.remove()}}},eA=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),c=n.createElement("aside"),d=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",c.appendChild(d),o.insertBefore(s,e),p.appendChild(e);let g=null,f=()=>{g?.disconnect(),g=null},h=null,S=()=>{h=t?.launcher?.detachedPanel===!0?Qw(t):null};S();let k=()=>{Yw(s,l,p,c,d,t,u,h)},P=null,M=()=>{P?.(),P=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(P=zr(()=>{S(),k()}))},A=()=>{f(),sn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{k()}),g.observe(s)))},C=!1,E=()=>{k(),A(),u&&!C&&s.dataset.personaDockMobileFullscreen!=="true"&&(C=!0,Kw(s,sn(t)))},R=s.ownerDocument.defaultView,w=()=>{E()};return R?.addEventListener("resize",w),sn(t).reveal==="push"?(l.appendChild(p),l.appendChild(c),s.appendChild(l)):(s.appendChild(p),s.appendChild(c)),E(),M(),{mode:"docked",host:d,shell:s,syncWidgetState(H){let F=H.launcherEnabled?H.open:!0;u!==F&&(u=F,E())},updateConfig(H){t=H,(t?.launcher?.enabled??!0)===!1&&(u=!0),S(),E(),M()},destroy(){R?.removeEventListener("resize",w),P?.(),P=null,f(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},xs=(e,t)=>Et(t)?eA(e,t):Zw(e,t);var tA=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},ry=(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)},ay=e=>{let t=tA(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,a=xs(t,r),s,l=[],p=(k,P)=>{let A=!(P?.launcher?.enabled??!0)||Et(P),C=o.createElement("div");if(C.setAttribute("data-persona-root","true"),A&&(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 E=k.attachShadow({mode:"open"});E.appendChild(C),ry(E,o)}else k.appendChild(C),ry(k,o);return t.id&&C.setAttribute("data-persona-instance",t.id),C},c=()=>{a.syncWidgetState(s.getState())},d=()=>{l.forEach(k=>k()),l=[s.on("widget:opened",c),s.on("widget:closed",c)],c()},u=()=>{let k=p(a.host,r);s=Ll(k,r,{debugTools:e.debugTools}),d()},g=()=>{l.forEach(k=>k()),l=[],s.destroy()};u(),e.onChatReady?.();let f=k=>{g(),a.destroy(),a=xs(t,k),r=k,u()},h={update(k){let P=Cl(r??{},k),M=Et(r),A=Et(P),C=No(r),E=No(P);if(M!==A||C!==E){f(P);return}r=P,a.updateConfig(r),s.update(k),c()},destroy(){g(),a.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},S=new Proxy(h,{get(k,P,M){if(P==="host")return a.host;if(P in k)return Reflect.get(k,P,M);let A=s[P];return typeof A=="function"?A.bind(s):A}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=S),S};function nA(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 oA(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:nA(o,n)?2:3}function sy(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function Rl(e,t){let n=t.trim();if(!n)return[...e].sort(sy);let o=[];for(let r of e){let a=oA(r.label,n);a!==3&&o.push({item:r,tier:a})}return o.sort((r,a)=>r.tier!==a.tier?r.tier-a.tier:sy(r.item,a.item)),o.map(r=>r.item)}function rA(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 iy(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Rl(e.items,t),resolve:e.resolve}}function ly(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>Rl(t,rA(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 fy=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),aA=new Set(["button","a","input","select","textarea","details","summary"]),sA=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Mu=/\b(product|card|item|listing|result)\b/i,Eu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,iA=3e3,lA=100;function my(e){let t=typeof e.className=="string"?e.className:"";if(Mu.test(t)||e.id&&Mu.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Mu.test(o.value))return!0}return!1}function gy(e){return Eu.test((e.textContent??"").trim())}function hy(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 dA(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function dy(e){let t=e.match(Eu);return t?t[0]:null}function cy(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 cA(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 pA="commerce-card",uA="result-card";function py(e){return!my(e)||!gy(e)||!hy(e)&&!dA(e)?0:5200}function uy(e){return!my(e)||gy(e)||!hy(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var ku=[{id:pA,scoreElement(e){return py(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||Eu.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(py(e)===0)return null;let{title:n,href:o}=cy(e),r=dy((e.textContent??"").trim())??dy(t.text)??"",a=cA(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
|
+
${Ct?"background: transparent !important;":""}
|
|
143
|
+
`}if(!x&&!i){let Lt="max-height: -moz-available !important; max-height: stretch !important;",an=u?"":"padding-top: 1.25em !important;",fi=u?"":`z-index: ${o.launcher?.zIndex??Ut} !important;`;Le.style.cssText+=Lt+an+fi}An()},pc=()=>{e.style.setProperty("--persona-content-max-width",qo(o,Q()))},Kf=()=>{if(Q())return;let i=St(o),u=o.launcher?.sidebarMode??!1;if(i||u||(o.launcher?.fullHeight??!1)||!P)return;let x=e.ownerDocument.defaultView??window,k=o.launcher?.mobileFullscreen??!0,W=o.launcher?.mobileBreakpoint??640;if(k&&x.innerWidth<=W)return;let z=x.innerHeight,U=64,j=o.launcher?.heightOffset??0,Y=Math.max(200,z-U),pe=Math.min(640,Y);he.style.height=`${Math.max(200,pe-j)}px`};dc(),Sr(e,o),Is(e,o),Ws(e,o),pc(),Zo=()=>{dc(),Kf(),Sr(e,o),Is(e,o),Ws(e,o),pc(),Vs?e.style.setProperty("--persona-artifact-welded-outer-radius",Vs):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let De=[];De.push(()=>{document.removeEventListener("keydown",$f)}),De.push(()=>{Ra!==null&&clearTimeout(Ra)});let _n=null,Un=null;De.push(()=>{_n?.(),_n=null,Un?.(),Un=null}),Ha&&De.push(()=>{Ha?.disconnect(),Ha=null}),De.push(()=>{Fa?.(),Fa=null,cc(),xt&&(xt.remove(),xt=null),Ke?.element.style.removeProperty("width"),Ke?.element.style.removeProperty("maxWidth")}),me&&De.push(()=>{qe!==null&&(cancelAnimationFrame(qe),qe=null),Ae?.destroy(),Ae=null,Ne?.destroy(),Ne=null,Je=null});let tr=null,Xf=()=>{tr&&(tr(),tr=null),o.colorScheme==="auto"&&(tr=pa(()=>{Sr(e,o)}))};Xf(),De.push(()=>{tr&&(tr(),tr=null)}),De.push(d);let Js=o.features?.streamAnimation;if(Js?.type&&Js.type!=="none"){let i=ha(Js.type,Js.plugins);i&&(Al(i,e),De.push(()=>ry(e)))}let Qn=Es(I),Jf=Es(kn),Qf=Es(ee),nr=[Qn,Jf,Qf];De.push(()=>{nr.forEach(i=>i.destroy())});let or=null,q,rr=null,Yf=!1,Zf=0,em=null,tm=i=>i.reduce((u,h)=>h.role==="user"?u+1:u,0),nm=i=>{for(let u=i.length-1;u>=0;u--)if(br(i[u]))return i[u].id??null;return null},om=!1,tx=()=>{om||o.debug!==!0||(om=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},rm=!1,am=!1,sm=(i,u)=>{rm||o.debug!==!0||!u.enabled||u.expose||Yf||am&&(q.isStreaming()||i.some(br)||(rm=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},_r=i=>{if(!q)return;let u=i??q.getMessages(),h=Y=>{Y.render([],q,B,u)},x=Y=>{nr.forEach(pe=>{pe!==Y&&h(pe)})};rr&&(tm(u)>Zf||nm(u)!==em)&&(rr=null);let k=Bo(o);sm(u,k);let W=k.enabled?Ei(u):null,z=rr??W,U=rr?"host":"agent";if(z){let Y=o.suggestions?.followUps,pe=Y?.placement??(Y?"auto":"composer"),ye=(pe==="auto"?Q()?"composer":"after-message":pe)==="after-message"?Qf:Qn;x(ye),ye.render(z,q,B,u,o.suggestionChipsConfig,{source:U,surface:"followUp",variant:Y?.variant??"chip",behavior:Y?.behavior??"send",overflow:Y?.overflow??"wrap",maxItems:Y?.maxItems??4,config:o,plugins:a});return}if(u.some(Y=>Y.role==="user")){nr.forEach(h);return}let j=o.suggestions?.starters;if(j){let Y=Xo(mo(o),u),pe=j.placement??"auto",le=pe==="auto"?Y?"welcome":"composer":pe;if(le==="welcome"&&!Y){tx(),nr.forEach(h);return}let ye=le==="welcome"?Jf:Qn;x(ye),ye.render(j.items??o.suggestionChips,q,B,u,o.suggestionChipsConfig,{surface:"starter",variant:j.variant??"card",behavior:j.behavior??"send",overflow:j.overflow??"wrap",maxItems:j.maxItems??4,config:o,plugins:a});return}x(Qn),Qn.render(o.suggestionChips,q,B,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a})},im=()=>{rr&&(rr=null,_r())},nx=i=>{let u=Array.isArray(i)?[...i]:[];if(!u.length){im();return}let h=q?q.getMessages():[];rr=u,Yf=!0,Zf=tm(h),em=nm(h),_r(h)},In=!1,ar=Xh(),Ur=new Map,sr=new Map,bo=new Map,uc=0,ox=ao()!==null,dn=yl(),pn=0,xo=null,on=!1,Qs=!1,vo=0,Dt=null,ir=null,fc=!1,Ys=!1,lr=null,Oa=!0,Zs=!1,qr=null,ei=!1,cr=()=>{ei=!0,ix()},mc=null,rx=4,Yn=24,ax=80,sx=1e3,Zn=null,lm=()=>{e.setAttribute("data-persona-scrollbar",ec()),ec()!=="on-scroll"&&(Zn!==null&&clearTimeout(Zn),Zn=null,re.removeAttribute("data-persona-scrollbar-visible"))},ix=()=>{ec()==="on-scroll"&&(re.setAttribute("data-persona-scrollbar-visible",""),Zn!==null&&clearTimeout(Zn),Zn=setTimeout(()=>{Zn=null,uo(re,Yn)&&re.removeAttribute("data-persona-scrollbar-visible")},sx))};lm(),De.push(()=>{Zn!==null&&clearTimeout(Zn)});let gc=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},cm=o.voiceRecognition?.autoResume??!1,eo=i=>{c.emit("voice:state",{active:je.active,source:i,timestamp:Date.now()})},Wn=()=>{A(i=>({...i,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},lx=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=cf(m.voiceState),u=!!i.active,h=Number(i.timestamp??0);je.manuallyDeactivated=!!i.manuallyDeactivated,u&&Date.now()-h<gS&&setTimeout(()=>{je.active||(je.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?q.toggleVoice().then(()=>{je.active=q.isVoiceActive(),eo("restore"),q.isVoiceActive()&&Kr()}):ci("restore"))},1e3)},cx=()=>q?sb(q.getMessages()).filter(i=>!i.__skipPersist):[],ti=null,dm=(i,u)=>{typeof console<"u"&&console.error(i,u)},hc=(i,u)=>{let h=()=>{try{let z=i();return!z||typeof z.then!="function"?null:Promise.resolve(z).catch(U=>{dm(u,U)})}catch(z){return dm(u,z),null}},x=ti,k=x?x.then(()=>h()??void 0):h();if(!k)return;let W=k.finally(()=>{ti===W&&(ti=null)});ti=W};function yc(i){if(!g?.save)return;let h={messages:i?sb(i):q?cx():[],metadata:m,artifacts:Pn.artifacts,selectedArtifactId:Pn.selectedId};hc(()=>g.save(h),"[AgentWidget] Failed to persist state:")}let Vr=null,pm=()=>Le.querySelector("#persona-scroll-container")||re,zr=()=>{Vr!==null&&(cancelAnimationFrame(Vr),Vr=null),on=!1},um=()=>{xo!==null&&(cancelAnimationFrame(xo),xo=null),Qs=!1,zr()},dx=()=>In&&xc()&&(cn()!=="anchor-top"||Tf()),bc=()=>{let i=ka()||"Jump to latest",u=dx();Pt.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),vo>0?(Jo.textContent=String(vo),Jo.style.display="",Pt.setAttribute("aria-label",`${i} (${vo} new)`)):(Jo.textContent="",Jo.style.display="none",Pt.setAttribute("aria-label",u?`${i} (response streaming below)`:i))},fm=()=>{vo!==0&&(vo=0,bc())},px=()=>{let i=Dt?.spacerHeight??0;return i<=0?uo(re,Yn):ri(i)-re.scrollTop-re.clientHeight<=Yn},xc=()=>ho()?!dn.isFollowing():!px(),vc=()=>!!q&&q.getMessages().length>0,Vt=()=>{if(!Xb()||Me){Pt.parentNode&&Pt.remove(),Pt.style.display="none";return}Pt.parentNode!==be&&be.appendChild(Pt),Yo();let u=jn(re)>0&&xc()&&vc();u?bc():fm(),Pt.style.display=u?"":"none"},Na=()=>{dn.pause()&&(um(),Vt())},Co=()=>{dn.resume(),fm(),Vt()},wo=(i=!1)=>{ho()&&vc()&&dn.isFollowing()&&(!i&&!In||(xo!==null&&(cancelAnimationFrame(xo),xo=null),Qs=!0,xo=requestAnimationFrame(()=>{xo=null,Qs=!1,dn.isFollowing()&&ux(pm(),i?220:140)})))},mm=(i,u,h,x=()=>!0)=>{let k=i.scrollTop,W=u(),z=W-k;if(zr(),Math.abs(z)<1){on=!0,i.scrollTop=W,pn=i.scrollTop,on=!1;return}let U=performance.now();on=!0;let j=pe=>1-Math.pow(1-pe,3),Y=pe=>{if(!x()){zr();return}let le=u();le!==W&&(W=le,z=W-k);let ye=pe-U,Ge=Math.min(ye/h,1),ht=j(Ge),ct=k+z*ht;i.scrollTop=ct,pn=i.scrollTop,Ge<1?Vr=requestAnimationFrame(Y):(i.scrollTop=W,pn=i.scrollTop,Vr=null,on=!1)};Vr=requestAnimationFrame(Y)},ux=(i,u=500)=>{let h=jn(i)-i.scrollTop;if(Math.abs(h)<1){pn=i.scrollTop;return}if(Math.abs(h)>=ax){zr(),on=!0,i.scrollTop=jn(i),pn=i.scrollTop,on=!1;return}mm(i,()=>jn(i),u,()=>dn.isFollowing())},gm=()=>{if(!vc()){Vt();return}let i=pm();on=!0,i.scrollTop=jn(i),pn=i.scrollTop,on=!1,Vt()},dr=i=>{let u=0,h=i;for(;h&&h!==re;)u+=h.offsetTop,h=h.offsetParent;return u},fx=()=>{let i=re.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??re.ownerDocument.getSelection()},ni=()=>ey(fx(),re),hm=()=>{if(Jb()!=="last-user-turn")return!1;let i=q?.getMessages()??[];if(i.length<2)return!1;let u=[...i].reverse().find(W=>W.role==="user");if(!u)return!1;let h=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(u.id):u.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=re.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let k=Math.min(Math.max(0,dr(x)-La()),jn(re));return on=!0,re.scrollTop=k,pn=re.scrollTop,on=!1,cn()==="follow"&&!uo(re,Yn)&&dn.pause(),Vt(),!0},oi=i=>{let u=Math.max(0,Math.round(i));vn.style.height=`${u}px`,vn.style.display=u>0?"":"none",Dt&&(Dt.spacerHeight=Math.max(0,i))},ri=i=>{let u=parseFloat(getComputedStyle(re).paddingBottom)||0,h=0;for(let k of Array.from(re.children)){if(k===vn||k.offsetHeight===0)continue;let W=dr(k)+k.offsetHeight;W>h&&(h=W)}let x=re.scrollHeight-i;return h>0?Math.min(h+u,x):x},mx=()=>{if(!Dt||Dt.spacerHeight<=0)return;let i=ri(Dt.spacerHeight),u=Math.max(0,Math.round(re.scrollTop)+re.clientHeight-i+Yn);u<Dt.spacerHeight&&(oi(u),Vt())},_a=()=>{ir!==null&&(cancelAnimationFrame(ir),ir=null),zr(),Dt=null,vn.style.height="0px",vn.style.display="none"},ym=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Cc=i=>re.querySelector(`[data-message-id="${ym(i)}"]`),bm=i=>{ir!==null&&cancelAnimationFrame(ir),ir=requestAnimationFrame(()=>{ir=null;let u=ym(i),h=re.querySelector(`[data-message-id="${u}"]`);if(!h)return;let x=dr(h),k=Dt?.spacerHeight??0,W=ri(k),{targetScrollTop:z,spacerHeight:U}=Mu({anchorOffsetTop:x,topOffset:La(),viewportHeight:re.clientHeight,contentHeight:W,slack:Yn});Dt={initialSpacerHeight:U,contentHeightAtAnchor:W,spacerHeight:U},oi(U),mm(re,()=>h.isConnected?Math.max(0,dr(h)-La()):z,220)})},xm=()=>{if(cn()!=="anchor-top"||!Dt||!qr)return;let i=Cc(qr);if(!i)return;zr();let u=Dt.spacerHeight,h=ri(u),{targetScrollTop:x,spacerHeight:k}=Mu({anchorOffsetTop:dr(i),topOffset:La(),viewportHeight:re.clientHeight,contentHeight:h,slack:Yn});Dt={initialSpacerHeight:k,contentHeightAtAnchor:h,spacerHeight:k},oi(k),on=!0,re.scrollTop=x,pn=re.scrollTop,on=!1,Vt()},gx=()=>{if(ho()){if(!dn.isFollowing()||uo(re,1))return;wo(!In);return}if(Dt&&Dt.initialSpacerHeight>0){let i=re.scrollHeight-Dt.spacerHeight,u=ty({initialSpacerHeight:Dt.initialSpacerHeight,contentHeightAtAnchor:Dt.contentHeightAtAnchor,currentContentHeight:i});u!==Dt.spacerHeight&&oi(u)}Vt()},hx=i=>{let u=cn();u==="follow"?(Co(),wo(!0)):u==="anchor-top"&&(Oa=!1,Zs=!0,ei=!1,qr=i,bm(i))},yx=()=>{if(cn()==="anchor-top"){if(Zs){Oa=!1;return}Oa=!0,_a(),Co(),wo(!0)}},bx=96,xx=i=>{if(lr===null)return!0;let u=Cc(lr),h=Cc(i);if(!u||!h)return!0;let x=dr(h)-dr(u);return La()+x>re.clientHeight-bx},vx=i=>{if(cn()!=="anchor-top"||!Zs||ei||ni())return;let u=lr===null;for(let h of i){if(!u){h.id===lr&&(u=!0);continue}if(Zh(h)){if(h.id===qr||!xx(h.id))return;qr=h.id,bm(h.id);return}}},Cx=i=>{let u=new Map;i.forEach(h=>{let x=gc.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(c.emit("assistant:message",h),!Ys&&(cn()!=="anchor-top"||Tf())&&xc()&&(vo+=1,bc(),Vt(),kf(vo===1?"1 new message below.":`${vo} new messages below.`))),h.role==="assistant"&&x?.streaming&&h.streaming===!1&&c.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(x?h.approval.status!=="pending"&&c.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):c.emit("approval:requested",{approval:h.approval,message:h}))}),gc.clear(),u.forEach((h,x)=>{gc.set(x,h)})},ai=(i,u)=>{let h=u==="user"?"user":"assistant",x=o.layout?.messages?.[h],k=x?.width??"content",W=x?.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-${u}`,`persona-message-width-${k}`),i.classList.toggle("persona-justify-end",u==="user"),i.setAttribute("data-message-role",u),i.setAttribute("data-message-width",k),i.style.setProperty("--persona-message-row-max-width",W)},pr=(i,u)=>{let h=document.createElement("div");return h.className="persona-flex",h.id=`wrapper-${i}`,h.setAttribute("data-wrapper-id",i),ai(h,u),h},wx=(i,u,h)=>{let x=document.createElement("div"),W=(()=>{let _=a.find(Re=>Re.renderLoadingIndicator);if(_?.renderLoadingIndicator)return _.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),z=(_,Re)=>Re==null?!1:typeof Re=="string"?(_.textContent=Re,!0):(_.appendChild(Re),!0),U=new Set,j=new Map,Y=new Set,pe=a.some(_=>_.renderAskUserQuestion),le=[],ye=[],Ge=o.enableComponentStreaming!==!1,ht=o.approval!==!1,ct=[];if(u.forEach(_=>{U.add(_.id),j.set(_.id,_.role);let Re=pe&&so(_),Fe=ht&&_.variant==="approval"&&!!_.approval,Ee=!Re&&_.role==="assistant"&&!_.variant&&Ge&&Os(_);!Fe&&bo.has(_.id)&&(i.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),bo.delete(_.id)),!Ee&&sr.has(_.id)&&(i.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),sr.delete(_.id));let At=so(_)?`:${_.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${_.agentMetadata?.askUserQuestionAnswers?Object.keys(_.agentMetadata.askUserQuestionAnswers).length:0}`:"",dt=Kh(_,uc)+At,Ot=Re||Fe||Ee?null:Jh(ar,_.id,dt);if(Ot){x.appendChild(Ot.cloneNode(!0)),so(_)&&_.toolCall?.id&&_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(Y.add(_.toolCall.id),aa(_,o,Te.composerOverlay));return}let pt=null,rn=a.find(Oe=>!!(_.variant==="reasoning"&&Oe.renderReasoning||_.variant==="tool"&&Oe.renderToolCall||!_.variant&&Oe.renderMessage)),Wt=o.layout?.messages;if(so(_)&&_.agentMetadata?.askUserQuestionAnswered===!0){Ur.delete(_.id),i.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime");return}if(br(_)&&Bo(o).enabled)return;if(so(_)&&o.features?.askUserQuestion?.enabled!==!1){let Oe=a.find(zt=>typeof zt.renderAskUserQuestion=="function");if(Oe&&at.current){let zt=Ur.get(_.id),$t=zt!==dt,Ct=null;if($t){let{payload:Xe,complete:He}=io(_),yt=_.id,jt=()=>at.current?.getMessages().find(An=>An.id===yt);Ct=Oe.renderAskUserQuestion({message:_,payload:Xe,complete:He,resolve:An=>{let Qa=jt();Qa&&at.current?.resolveAskUserQuestion(Qa,An)},dismiss:()=>{let An=jt();An?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(An),at.current?.resolveAskUserQuestion(An,"(dismissed)"))},config:o})}let st=zt!=null;if($t&&Ct===null&&!st){_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(Y.add(_.toolCall.id),aa(_,o,Te.composerOverlay));return}let ft=pr(_.id,_.role);ft.setAttribute("data-ask-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),x.appendChild(ft),le.push({messageId:_.id,fingerprint:dt,bubble:Ct});return}else{_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(Y.add(_.toolCall.id),aa(_,o,Te.composerOverlay));return}}else if(Fe){let Oe=a.find(st=>typeof st.renderApproval=="function")??p,$t=bo.get(_.id)!==dt,Ct=null;if($t&&Oe?.renderApproval){let st=_.id,ft=(Xe,He)=>{let yt=at.current?.getMessages().find(jt=>jt.id===st);yt?.approval&&(yt.approval.toolType==="webmcp"?at.current?.resolveWebMcpApproval(yt.id,Xe):at.current?.resolveApproval(yt.approval,Xe,He))};Ct=Oe.renderApproval({message:_,defaultRenderer:()=>Ol(_,o),config:o,approve:Xe=>ft("approved",Xe),deny:Xe=>ft("denied",Xe)})}if($t&&Ct===null)i.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),bo.delete(_.id),pt=Ol(_,o);else{let st=pr(_.id,_.role);st.setAttribute("data-approval-plugin-stub","true"),st.setAttribute("data-preserve-runtime","true"),x.appendChild(st),ct.push({messageId:_.id,fingerprint:dt,bubble:Ct});return}}else if(rn)if(_.variant==="reasoning"&&_.reasoning&&rn.renderReasoning){if(!ue)return;pt=rn.renderReasoning({message:_,defaultRenderer:()=>Gu(_,o),config:o})}else if(_.variant==="tool"&&_.toolCall&&rn.renderToolCall){if(!oe)return;pt=rn.renderToolCall({message:_,defaultRenderer:()=>Xu(_,o),config:o})}else rn.renderMessage&&(pt=rn.renderMessage({message:_,defaultRenderer:()=>{let Oe=ba(_,h,Wt,o.messageActions,gt,{loadingIndicatorRenderer:W,widgetConfig:o});return _.role!=="user"&&af(Oe,_,o,q),Oe},config:o}));if(!pt&&Ee){let Oe=jl(_);if(Oe){let zt=sr.get(_.id),$t=zt!==dt,Ct=o.wrapComponentDirectiveInBubble!==!1&&Nn.getOptions(Oe.component)?.bubbleChrome!==!1,st=null;if($t){let ft=$l(Oe,{config:o,message:_,transform:h});if(ft&&Oe.component==="PersonaArtifactInline"){let Xe=ft.hasAttribute("data-artifact-inline")?ft:ft.querySelector("[data-artifact-inline]"),He=Xe?.getAttribute("data-artifact-inline")??"",yt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(He):He,jt=He?i.querySelector(`#wrapper-${_.id}`)?.querySelector(`[data-artifact-inline="${yt}"]`)??null:null;Xe&&jt&&jt!==Xe&&qh(jt)&&(Xe===ft?ft=jt:Xe.replaceWith(jt))}if(ft)if(Ct){let Xe=document.createElement("div");if(Xe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Xe.id=`bubble-${_.id}`,Xe.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let He=document.createElement("div");He.className="persona-mb-3 persona-text-sm persona-leading-relaxed",He.innerHTML=h({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),Xe.appendChild(He)}Xe.appendChild(ft),st=Xe}else{let Xe=document.createElement("div");if(Xe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Xe.id=`bubble-${_.id}`,Xe.setAttribute("data-message-id",_.id),Xe.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let He=document.createElement("div");He.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",He.innerHTML=h({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),Xe.appendChild(He)}Xe.appendChild(ft),st=Xe}}if(st||zt!=null){let ft=pr(_.id,_.role);ft.setAttribute("data-component-directive-stub","true"),ft.setAttribute("data-preserve-runtime","true"),x.appendChild(ft),ye.push({messageId:_.id,fingerprint:dt,bubble:st});return}}}if(!pt)if(_.variant==="reasoning"&&_.reasoning){if(!ue)return;pt=Gu(_,o)}else if(_.variant==="tool"&&_.toolCall){if(!oe)return;pt=Xu(_,o)}else if(_.variant==="approval"&&_.approval){if(o.approval===!1)return;pt=Ol(_,o)}else{let Oe=o.layout?.messages;Oe?.renderUserMessage&&_.role==="user"?pt=Oe.renderUserMessage({message:_,config:o,streaming:!!_.streaming}):Oe?.renderAssistantMessage&&_.role==="assistant"?pt=Oe.renderAssistantMessage({message:_,config:o,streaming:!!_.streaming}):pt=ba(_,h,Oe,o.messageActions,gt,{loadingIndicatorRenderer:W,widgetConfig:o}),_.role!=="user"&&pt&&af(pt,_,o,q)}let Ie=pr(_.id,_.role);Ie.appendChild(pt),Qh(ar,_.id,dt,Ie),x.appendChild(Ie)}),Te.composerOverlay&&Te.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Fe=Re.getAttribute("data-persona-ask-sheet-for");Fe&&!Y.has(Fe)&&Wo(Te.composerOverlay,Fe)}),o.features?.toolCallDisplay?.grouped){let _=[],Re=[],Fe=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(Ee=>{if(Ee.variant==="tool"&&Ee.toolCall&&oe){Re.push(Ee);return}Ee.variant==="reasoning"&&!ue||((Re.length>1||Fe&&Re.length>0)&&_.push(Re),Re=[])}),(Re.length>1||Fe&&Re.length>0)&&_.push(Re),_.forEach(Ee=>{let At=Ee.map(Oe=>Array.from(x.children).find(zt=>zt instanceof HTMLElement&&zt.getAttribute("data-wrapper-id")===Oe.id)).filter(Oe=>!!Oe);if(At.length<(Fe?1:2))return;let dt=pr(`tool-group-${Ee[0].id}`,"assistant");dt.setAttribute("data-persona-tool-group-row","true");let Ot=document.createElement("div");Ot.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ot.setAttribute("data-persona-tool-group","true");let pt=document.createElement("div");pt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",pt.id=`tool-group-summary-${Ee[0].id}`;let rn=`Called ${Ee.length} ${Ee.length===1?"tool":"tools"}`,Wt=o.toolCall?.renderGroupedSummary?.({messages:Ee,toolCalls:Ee.map(Oe=>Oe.toolCall).filter(Oe=>!!Oe),defaultSummary:rn,config:o});z(pt,Wt)||(pt.textContent=rn);let Ie=document.createElement("div");Ie.className="persona-tool-group-stack persona-flex persona-flex-col",Ie.id=`tool-group-stack-${Ee[0].id}`,Ie.setAttribute("data-persona-tool-group-stack","true"),Ot.appendChild(pt),Fe||Ot.appendChild(Ie),dt.appendChild(Ot),At[0].before(dt),At.forEach((Oe,zt)=>{if(Fe){Oe.remove();return}Oe.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"),zt<At.length-1&&$t.setAttribute("data-persona-tool-group-connector","true"),$t.appendChild(Oe),Ie.appendChild($t)})})}Yh(ar,U);let un=u.some(_=>_.role==="assistant"&&_.streaming),Mt=u[u.length-1],It=Mt?.role==="assistant"&&!Mt.streaming&&Mt.variant!=="approval";if(In&&u.some(_=>_.role==="user")&&!un&&!It){let _={config:o,streaming:!0,location:"standalone",defaultRenderer:Pr},Re=a.find(Ee=>Ee.renderLoadingIndicator),Fe=null;if(Re?.renderLoadingIndicator&&(Fe=Re.renderLoadingIndicator(_)),Fe===null&&o.loadingIndicator?.render&&(Fe=o.loadingIndicator.render(_)),Fe===null&&(Fe=Pr()),Fe){let Ee=document.createElement("div"),At=o.loadingIndicator?.showBubble!==!1,dt=o.layout?.messages?.layout??"bubble";Ee.className=At?ks("assistant",dt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Ee.setAttribute("data-typing-indicator","true"),At&&(Ee.style.color="var(--persona-message-assistant-text, var(--persona-text))",dt!=="flat"&&(Ee.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Ee.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Ee.appendChild(Fe);let Ot=pr("typing-indicator","assistant");Ot.appendChild(Ee),x.appendChild(Ot)}}if(!In&&u.length>0){let _=u[u.length-1],Re={config:o,lastMessage:_,messageCount:u.length},Fe=a.find(At=>At.renderIdleIndicator),Ee=null;if(Fe?.renderIdleIndicator&&(Ee=Fe.renderIdleIndicator(Re)),Ee===null&&o.loadingIndicator?.renderIdle&&(Ee=o.loadingIndicator.renderIdle(Re)),Ee){let At=document.createElement("div"),dt=o.loadingIndicator?.showBubble!==!1;At.className=dt?["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(" "),At.setAttribute("data-idle-indicator","true"),At.appendChild(Ee);let Ot=pr("idle-indicator","assistant");Ot.appendChild(At),x.appendChild(Ot)}}if(vg(x),hl(i,x),Gc(i),le.length>0)for(let{messageId:_,fingerprint:Re,bubble:Fe}of le){let Ee=i.querySelector(`#wrapper-${_}`);Ee&&(ai(Ee,j.get(_)??"assistant"),Fe!==null&&(Ee.replaceChildren(Fe),Ee.setAttribute("data-bubble-fp",Re),Ur.set(_,Re)))}if(Ur.size>0)for(let _ of Ur.keys())U.has(_)||Ur.delete(_);if(ye.length>0)for(let{messageId:_,fingerprint:Re,bubble:Fe}of ye){let Ee=i.querySelector(`#wrapper-${_}`);Ee&&(ai(Ee,j.get(_)??"assistant"),Fe!==null&&(Ee.replaceChildren(Fe),Ee.setAttribute("data-bubble-fp",Re),sr.set(_,Re)))}if(sr.size>0)for(let _ of sr.keys())U.has(_)||sr.delete(_);if(ct.length>0)for(let{messageId:_,fingerprint:Re,bubble:Fe}of ct){let Ee=i.querySelector(`#wrapper-${_}`);Ee&&(ai(Ee,j.get(_)??"assistant"),Fe!==null&&(Ee.replaceChildren(Fe),Ee.setAttribute("data-bubble-fp",Re),bo.set(_,Re)))}if(bo.size>0)for(let _ of bo.keys())U.has(_)||bo.delete(_)},Ua=(i,u,h)=>{wx(i,u,h),qf()},qa=null,Ax=()=>{if(qa)return;let i=h=>{let x=h.composedPath();x.includes(Le)||tt&&x.includes(tt)||lt(!1,"user")};qa=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},vm=()=>{if(!qa)return;(e.ownerDocument??document).removeEventListener("pointerdown",qa,!0),qa=null};De.push(()=>vm());let Va=null,Sx=()=>{if(Va)return;let i=h=>{h.key==="Escape"&&(h.isComposing||lt(!1,"user"))};Va=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Cm=()=>{if(!Va)return;(e.ownerDocument??document).removeEventListener("keydown",Va,!0),Va=null};De.push(()=>Cm());let za=!1,wm=new Set,Mx=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},$r=()=>{if(!Q())return;let i=Te.peekBanner,u=Te.peekTextNode;if(!i||!u)return;if(J){i.classList.remove("persona-pill-peek--visible");return}let h=q?.getMessages()??[],x;for(let Mt=h.length-1;Mt>=0;Mt--){let It=h[Mt];if(It.role==="assistant"&&It.content){x=It;break}}if(!x){i.classList.remove("persona-pill-peek--visible");return}let k=x.content,W=!!x.streaming,z=Mx(),U=vl(z),j=U.type!=="none"?ha(U.type,z?.plugins):null,Y=j?.isAnimating?.(x)===!0,pe=j!==null&&(W||Y);pe&&j&&!wm.has(j.name)&&(Al(j,e),wm.add(j.name));let le=pe&&j?.containerClass?j.containerClass:null,ye=u.dataset.personaPeekStreamClass??null;ye&&ye!==le&&(u.classList.remove(ye),delete u.dataset.personaPeekStreamClass),le&&ye!==le&&(u.classList.add(le),u.dataset.personaPeekStreamClass=le),pe?(u.style.setProperty("--persona-stream-step",`${U.speed}ms`),u.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Ge=pe?Cl(k,U.buffer,j,x,W):k;if(pe&&U.placeholder==="skeleton"&&W&&(!Ge||!Ge.trim())){let Mt=document.createElement("div"),It=Ss();It.classList.add("persona-pill-peek__skeleton"),Mt.appendChild(It),hl(u,Mt)}else{let Mt=Math.max(0,Ge.length-100),It=Ge.length>100?Ge.slice(-100):Ge,_=Vn(It);if(!pe||!j){let Re=Ge.length>100?`\u2026${It}`:It;u.textContent!==Re&&(u.textContent=Re)}else{let Re=_;(j.wrap==="char"||j.wrap==="word")&&(Re=As(_,j.wrap,`peek-${x.id}`,{skipTags:j.skipTags,startIndex:Mt}));let Fe=document.createElement("div");if(Fe.innerHTML=Re,j.useCaret&&It.length>0){let Ee=wl(),At=Fe.querySelectorAll(".persona-stream-char, .persona-stream-word"),dt=At[At.length-1];dt?.parentNode?dt.parentNode.insertBefore(Ee,dt.nextSibling):Fe.appendChild(Ee)}hl(u,Fe),j.onAfterRender?.({container:u,bubble:i,messageId:x.id,message:x,speed:U.speed,duration:U.duration})}}let un=In||za;i.classList.toggle("persona-pill-peek--visible",un)};if(Q()){let i=Te.peekBanner;if(i){let x=k=>{k.preventDefault(),k.stopPropagation(),lt(!0,"user")};i.addEventListener("pointerdown",x),De.push(()=>{i.removeEventListener("pointerdown",x)})}let u=()=>{za||(za=!0,$r())},h=()=>{za&&(za=!1,$r())};he.addEventListener("pointerenter",u),he.addEventListener("pointerleave",h),De.push(()=>{he.removeEventListener("pointerenter",u),he.removeEventListener("pointerleave",h)}),tt&&(tt.addEventListener("pointerenter",u),tt.addEventListener("pointerleave",h),De.push(()=>{tt.removeEventListener("pointerenter",u),tt.removeEventListener("pointerleave",h)}))}let Tx=i=>{let u=o.launcher?.composerBar??{},h=u.expandedSize??"anchored",x=u.bottomOffset??"16px",k=u.collapsedMaxWidth,W=u.expandedMaxWidth??"880px",z=u.expandedTopOffset??"5vh",U=u.modalMaxWidth??"880px",j=u.modalMaxHeight??"min(90vh, 800px)",Y="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",le=Le.style;if(le.left="",le.right="",le.top="",le.bottom="",le.transform="",le.width="",le.maxWidth="",le.height="",le.maxHeight="",tt){let ye=tt.style;ye.bottom=x,ye.width=k??""}if(i&&h!=="fullscreen"){if(h==="modal"){le.top="50%",le.left="50%",le.transform="translate(-50%, -50%)",le.bottom="auto",le.right="auto",le.width=U,le.maxWidth=Y,le.maxHeight=j,le.height=j;return}le.left="50%",le.transform="translateX(-50%)",le.bottom=`calc(${x} + ${pe})`,le.top=z,le.width=W,le.maxWidth=Y}},$a=()=>{if(!Z())return;if(Q()){let Y=(o.launcher?.composerBar??{}).expandedSize??"anchored",pe=J?"expanded":"collapsed";Le.dataset.state=pe,Le.dataset.expandedSize=Y,tt&&(tt.dataset.state=pe,tt.dataset.expandedSize=Y),Le.style.removeProperty("display"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Tx(J),be.style.display=J?"flex":"none",Zo(),J?(Ax(),Sx()):(vm(),Cm()),$r();return}let i=St(o),u=e.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,k=u.innerWidth<=h,W=x&&k&&P,z=ln(o).reveal;J?(Le.style.removeProperty("display"),Le.style.display=i?"flex":"",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),kt?(kt.setPanelOpen(!0),kt.element.style.display="none"):Yt&&(Yt.style.display="none")):(i?i&&(z==="overlay"||z==="push")&&!W?(Le.style.removeProperty("display"),Le.style.display="flex",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.setProperty("display","none","important"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.display="",Le.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),kt?(kt.setPanelOpen(!1),kt.element.style.display=i?"none":""):Yt&&(Yt.style.display=i?"none":""))},lt=(i,u="user")=>{if(!Z()||J===i)return;let h=J;J=i,$a();let x=(()=>{let W=o.launcher?.sidebarMode??!1,z=e.ownerDocument.defaultView??window,U=o.launcher?.mobileFullscreen??!0,j=o.launcher?.mobileBreakpoint??640,Y=z.innerWidth<=j,pe=St(o)&&U&&Y,le=Q()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return W||U&&Y&&P||pe||le})();if(J&&x){if(!_n){let W=e.getRootNode(),z=W instanceof ShadowRoot?W.host:e.closest(".persona-host");z&&(_n=Pu(z,o.launcher?.zIndex??Ut))}Un||(Un=Ru(e.ownerDocument))}else J||(_n?.(),_n=null,Un?.(),Un=null);J&&(Xa(),hm()||(cn()==="follow"?wo(!0):gm()));let k={open:J,source:u,timestamp:Date.now()};J&&!h?c.emit("widget:opened",k):!J&&h&&c.emit("widget:closed",k),c.emit("widget:state",{open:J,launcherEnabled:P,voiceActive:je.active,streaming:q.isStreaming()})},si=i=>{Us(i?"stop":"send"),te&&(te.disabled=i),nr.forEach(u=>{u.elements.forEach(h=>{h.toggleAttribute("data-disabled",i),h instanceof HTMLButtonElement||h.setAttribute("aria-disabled",i?"true":"false")}),u.buttons.forEach(h=>{h.disabled=i})}),Tc.forEach(u=>{u.toggleAttribute("data-disabled",i),u instanceof HTMLButtonElement?u.disabled=i:u.setAttribute("aria-disabled",i?"true":"false"),u.querySelectorAll("button").forEach(h=>{h.disabled=i})}),we.dataset.personaComposerStreaming=i?"true":"false",we.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=i)})},wc=()=>{je.active||B&&B.focus()};c.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>wc(),200)});let Ac=!K.hidden,Ao=null,Am=!b,Sm=null,Mm,Tm=null,ja=null,Sc=i=>{let u=mo(o),h=`${u.variant}|${u.dismiss}|${u.title}|${u.subtitle}`;(h!==Sm||u.icon!==Mm)&&(Sm=h,Mm=u.icon,Bl({host:K,iconHolder:V,title:ce,subtitle:Ve,starterSuggestions:kn},u));let x=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;x!==Tm&&(Tm=x,Dl(X,u.message,o));let k=i??(q?q.getMessages():o.initialMessages),W=Xo(u,k),z=W!==Ac;if(Ac=W,ja){Ao?.cancel(),Ao=null,xa(re,K,!0);return}if(z&&!W&&u.dismiss==="on-first-message"&&Am){Ao=yy(K,U=>{Ao===U&&(Ao=null),!Ac&&!ja&&(xa(re,K,!1),xm()),U?.cancel()});return}if(Ao){if(!W)return;Ao.cancel(),Ao=null}xa(re,K,W),z&&!W&&xm()},Mc=[],Tc=[],Ec=!1,Em=null,km,Lm=()=>{Tc.length=0;let i=Mc.splice(0,Mc.length);for(let u of i)try{u()}catch(h){console.warn("[persona] renderWelcome cleanup threw",h)}};De.push(Lm);let Ex=(i,u)=>{let h=Wu(i,u);if(!h)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let x=o.suggestions?.starters,k=Hu({item:{...h,behavior:h.behavior??x?.behavior??"send"},index:u,surface:"starter",source:"config",variant:x?.variant??"card",streaming:s?q.isStreaming():!1,config:o,plugins:a,chipsConfig:o.suggestionChipsConfig,session:q,getTextarea:()=>B,eventTarget:K});return Tc.push(k),k},kc=()=>{if(Ec)return;Ec=!0;let i=mo(o);Em=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,km=i.icon;try{Lm(),gy(re,K,ja),ja=null;let u=q?q.getMessages():o.initialMessages,h=Xo(i,u),x=0,k=null;for(let W of a)if(W.renderWelcome&&(k=W.renderWelcome({config:i,variant:i.variant,visible:h,defaultRenderer:()=>K,sendMessage:z=>{if(!q||q.isStreaming())return;let U=z.trim();U&&q.sendMessage(U)},requestRender:()=>kc(),renderStarter:z=>Ex(z,x++),storage:l(W.id),onCleanup:z=>{Mc.push(z)}}),k))break;k&&k!==K&&(ja=k,my(re,K,k))}finally{Ec=!1}Sc()},kx=()=>{let i=mo(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Em&&i.icon===km||kc()},Lc=()=>{Sc(),rc||(B.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!q?.isStreaming()&&(y.textContent=o.copy?.sendButtonLabel??"Send")),B.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',B.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=m.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{A(u=>({...u,sessionId:i}))}});let ur=null,Lx=()=>{ur==null&&(ur=setInterval(()=>{let i=xe.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(ur),ur=null;return}let u=Date.now();i.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=Li(u-x))})},100))},Pc=(i,u)=>{if(Object.is(i,u))return!0;if(i===null||u===null||typeof i!="object"||typeof u!="object")return!1;if(Array.isArray(i)||Array.isArray(u))return!Array.isArray(i)||!Array.isArray(u)||i.length!==u.length?!1:i.every((z,U)=>Pc(z,u[U]));let h=i,x=u,k=Object.keys(h),W=Object.keys(x);return k.length===W.length&&k.every(z=>Object.prototype.hasOwnProperty.call(x,z)&&Pc(h[z],x[z]))},Pm=i=>{let{content:u,rawContent:h,llmContent:x,...k}=i;return k},Rc=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Os(i),Px=(i,u,h)=>{if(i.length!==u.length)return!1;let x=i[h.index],k=u[h.index];return!x||!k||x.id!==h.id||k.id!==h.id?!1:(!Object.is(x.content,k.content)||!Object.is(x.rawContent,k.rawContent)||!Object.is(x.llmContent,k.llmContent))&&Rc(x)&&Rc(k)&&Pc(Pm(x),Pm(k))},Rm=null,jr=null,fr=null,to=null,ii=i=>{Rm=i;let u,h;jr=null;for(let k=i.length-1;k>=0;k-=1){let W=i[k];if(!u&&W.role==="user"&&(u=W),!h&&W.role==="assistant"&&(h=W),!jr&&Rc(W)&&(jr={index:k,id:W.id}),u&&h&&jr)break}Ua(xe,i,ie),Cu(xe,Pn.artifacts,{suppressTransition:In}),Lx(),Sc(i),_r(i),wo(!In),Cx(i),i.length===0&&(_a(),Oa=!0,Zs=!1,qr=null,ei=!1),!fc||Ys?(fc=!0,lr=u?.id??null,mc=h?.id??null):u&&u.id!==lr?(lr=u.id,hx(u.id)):h&&h.id!==mc&&yx(),h&&(mc=h.id),vx(i);let x=je.lastUserMessageId;u&&u.id!==x&&(je.lastUserMessageId=u.id,c.emit("user:message",u)),je.lastUserMessageWasVoice=!!u?.viaVoice,yc(i),$r()},Ic=()=>{to!==null&&(cancelAnimationFrame(to),to=null);let i=fr;fr=null,i&&ii(i)},Im=()=>{to!==null&&cancelAnimationFrame(to),to=null,fr=null},Rx=i=>{let u=fr??Rm;if(In&&u&&jr&&Px(u,i,jr)){fr=i,to===null&&(to=requestAnimationFrame(()=>{to=null;let h=fr;fr=null,h&&ii(h)}));return}if(i.length===0){Im(),ii(i);return}Ic(),ii(i)};q=new ca(o,{onMessagesChanged(i){Rx(i)},onStatusChanged(i){let u=o.statusIndicator??{};En(N,(x=>x==="idle"?u.idleText??Ht.idle:x==="connecting"?u.connectingText??Ht.connecting:x==="connected"?u.connectedText??Ht.connected:x==="error"?u.errorText??Ht.error:x==="paused"?u.pausedText??Ht.paused:x==="resuming"?u.resumingText??Ht.resuming:Ht[x])(i),u,i)},onStreamingChanged(i){i||(q?.getMessages().length===0?Im():Ic()),In=i,si(i),q&&Ua(xe,q.getMessages(),ie),i||(wo(!0),mx(),am=!0,q&&sm(q.getMessages(),Bo(o))),Vt(),kf(i?"Responding\u2026":"Response complete."),$r()},onVoiceStatusChanged(i){if(c.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":no(),Kr();break;case"processing":no(),qx();break;case"speaking":no(),Vx();break;default:i==="idle"&&q.isBargeInActive()?(no(),Kr(),te?.setAttribute("aria-label","End voice session")):(je.active=!1,no(),eo("system"),Wn());break}},onArtifactsState(i){Pn=i,i.artifacts.length===0&&(Fr=!1),Cu(xe,i.artifacts,{suppressTransition:In}),Jn(),yc()},onReconnect(i){let{executionId:u,lastEventId:h}=i.handle;i.phase==="paused"?c.emit("stream:paused",{executionId:u,after:h}):i.phase==="resuming"?c.emit("stream:resuming",{executionId:u,after:h,attempt:i.attempt??1}):c.emit("stream:resumed",{executionId:u,after:h})}}),at.current=q,De.push(()=>q.cancel());let Wc=null;if(q.onReadAloudChange((i,u)=>{_f=i,Uf=u,qf();let h=i??Wc;i&&(Wc=i);let x=h?q.getMessages().find(k=>k.id===h)??null:null;c.emit("message:read-aloud",{messageId:h,message:x,state:u,timestamp:Date.now()}),u==="idle"&&(Wc=null)}),s=!0,fc=!0,o.voiceRecognition?.provider?.type==="runtype")try{q.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&q.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Ne||o.onSSEEvent)&&q.setSSEEventCallback((i,u)=>{o.onSSEEvent?.(i,u),_e?.processEvent(i,u),Ne?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(u)})});let Wm=()=>{o.resume&&typeof o.reconnectStream=="function"&&q.resumeFromHandle(o.resume)};b?b.then(i=>{if(i){if(i.metadata&&(m=cf(i.metadata),M.syncFromMetadata()),i.messages?.length){Ys=!0;try{q.hydrateMessages(i.messages)}finally{Ys=!1}}i.artifacts?.length&&q.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{Am=!0,Wm()}):Wm();let Hm=()=>{!Q()||J||!(o.launcher?.composerBar?.expandOnSubmit??!0)||lt(!0,"auto")},Ix=(i,u)=>i?u?{refs:[...i.refs,...u.refs],finalize:async()=>{let[h,x]=await Promise.allSettled([i.finalize(),u.finalize()]),k=[];return h.status==="fulfilled"?k.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),x.status==="fulfilled"?k.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),wS(k)}}:i:u,Wx=()=>{let u=B.getInlineMessageFields?.();return u&&u.contentSegments.some(x=>x.kind==="mention")?u.contentSegments:void 0},Ga=!1,Hx=async i=>{let u=B.value.trim(),h=bt?.hasAttachments()??!1,x=u?await(Qt?.takeInlineCommand(u)??Promise.resolve(null)):null;if(x?.kind==="action"){B.value="",B.style.height="auto",Ka(),Qt?.clear();return}let k=Qt?.collectForSubmit()??null,W=x?.kind==="server"?x.mentions:null,z=Ix(k,W),U=x?.kind==="prompt"?x.sendText:u,j=!!k&&k.refs.length>0;if(!U&&!h&&!j&&!W)return;Hm();let Y;h&&(Y=[],Y.push(...bt.getContentParts()),U&&Y.push(Oo(U)));let pe=x?.kind==="prompt"?void 0:Wx();B.value="",B.style.height="auto",Ka(),q.sendMessage(U,{contentParts:Y,mentions:z??void 0,contentSegments:pe,viaVoice:i?.viaVoice}),h&&bt.clearAttachments(),k&&Qt?.clear()},Hc=async i=>{if(!Ga){Ga=!0;try{await Hx(i)}finally{Ga=!1}}},li=i=>{if(i.preventDefault(),q.isStreaming()){q.cancel(),_e?.reset(),Ae?.update();return}Ga||Hc()},Bx=()=>o.features?.composerHistory!==!1,Bc={...Su},Dc=!1,Ka=()=>{Bc={...Su}},Dx=()=>q.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Fx=i=>{if(!B)return;Dc=!0,B.value=i,B.dispatchEvent(new Event("input",{bubbles:!0})),Dc=!1;let u=B.value.length;B.setSelectionRange(u,u)},Ox=i=>{Dc||(i.isComposing||Qt?.handleInput(i.inputType??void 0),Ka())},Nx=i=>{if(B&&!(!i.isComposing&&Qt?.handleKeydown(i))){if(Bx()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let u=B.selectionStart===0&&B.selectionEnd===0,h=Gh({direction:i.key==="ArrowUp"?"up":"down",history:Dx(),currentValue:B.value,atStart:u,state:Bc});if(Bc=h.state,h.handled){i.preventDefault(),h.value!==void 0&&Fx(h.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(q.isStreaming()){i.preventDefault();return}if(Ga){i.preventDefault();return}Ka(),i.preventDefault(),y.click()}}},Bm=i=>{i.key!=="Escape"||i.isComposing||q.isStreaming()&&i.composedPath().includes(be)&&(q.cancel(),_e?.reset(),Ae?.update(),Ka(),i.preventDefault(),i.stopImmediatePropagation())},_x=async i=>{if(o.attachments?.enabled!==!0||!bt)return;let u=bS(i.clipboardData);u.length!==0&&(i.preventDefault(),await bt.handleFiles(u))},Cn=null,qn=!1,Gr=null,vt=null,Dm=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ci=(i="user")=>{if(qn||q.isStreaming())return;let u=Dm();if(!u)return;Cn=new u;let x=(o.voiceRecognition??{}).pauseDuration??2e3;Cn.continuous=!0,Cn.interimResults=!0,Cn.lang="en-US";let k=B.value;Cn.onresult=W=>{let z="",U="";for(let Y=0;Y<W.results.length;Y++){let pe=W.results[Y],le=pe[0].transcript;pe.isFinal?z+=le+" ":U=le}let j=k+z+U;B.value=j,Gr&&clearTimeout(Gr),(z||U)&&(Gr=window.setTimeout(()=>{B.value.trim()&&Cn&&qn&&(So(),Hc({viaVoice:!0}))},x))},Cn.onerror=W=>{W.error!=="no-speech"&&So()},Cn.onend=()=>{if(qn){let W=B.value.trim();W&&W!==k.trim()&&Hc({viaVoice:!0}),So()}};try{if(Cn.start(),qn=!0,je.active=!0,i!=="system"&&(je.manuallyDeactivated=!1),eo(i),Wn(),te){let W=o.voiceRecognition??{};vt={backgroundColor:te.style.backgroundColor,color:te.style.color,borderColor:te.style.borderColor,iconName:W.iconName??"mic",iconSize:parseFloat(W.iconSize??o.sendButton?.size??"40")||24};let z=W.recordingBackgroundColor,U=W.recordingIconColor,j=W.recordingBorderColor;if(te.classList.add("persona-voice-recording"),te.style.backgroundColor=z??"var(--persona-voice-recording-bg, #ef4444)",te.style.color=U??"var(--persona-voice-recording-indicator, #ffffff)",U){let Y=te.querySelector("svg");Y&&Y.setAttribute("stroke",U)}j&&(te.style.borderColor=j),te.setAttribute("aria-label","Stop voice recognition")}}catch{So("system")}},So=(i="user")=>{if(qn){if(qn=!1,Gr&&(clearTimeout(Gr),Gr=null),Cn){try{Cn.stop()}catch{}Cn=null}if(je.active=!1,eo(i),Wn(),te){if(te.classList.remove("persona-voice-recording"),vt){te.style.backgroundColor=vt.backgroundColor,te.style.color=vt.color,te.style.borderColor=vt.borderColor;let u=te.querySelector("svg");u&&u.setAttribute("stroke",vt.color||"currentColor"),vt=null}te.setAttribute("aria-label","Start voice recognition")}}},Ux=(i,u)=>{let h=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=i?.provider?.type==="runtype",k=i?.provider?.type==="custom";if(!(h||x||k))return null;let z=v("div","persona-send-button-wrapper"),U=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button";let j=i?.tooltipText??"Start voice recognition";U.setAttribute("aria-label",j);let Y=i?.iconName??"mic",pe=u?.size??"40px",le=i?.iconSize??pe,ye=parseFloat(le)||24,Ge=i?.backgroundColor??u?.backgroundColor,ht=i?.iconColor??u?.textColor;U.style.width=le,U.style.height=le,U.style.minWidth=le,U.style.minHeight=le,U.style.fontSize="18px",U.style.lineHeight="1",ht?U.style.color=ht:U.style.color="var(--persona-text, #111827)";let un=ae(Y,ye,ht||"currentColor",1.5);un?U.appendChild(un):U.textContent="\u{1F3A4}",Ge?U.style.backgroundColor=Ge:U.style.backgroundColor="",i?.borderWidth&&(U.style.borderWidth=i.borderWidth,U.style.borderStyle="solid"),i?.borderColor&&(U.style.borderColor=i.borderColor),i?.paddingX&&(U.style.paddingLeft=i.paddingX,U.style.paddingRight=i.paddingX),i?.paddingY&&(U.style.paddingTop=i.paddingY,U.style.paddingBottom=i.paddingY),z.appendChild(U);let Mt=i?.showTooltip??!1;return qt({anchor:U,trigger:z,text:()=>U.getAttribute("aria-label")??j,enabled:Mt}),{micButton:U,micButtonWrapper:z}},Fc=()=>{if(!te||vt)return;let i=o.voiceRecognition??{};vt={backgroundColor:te.style.backgroundColor,color:te.style.color,borderColor:te.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Oc=(i,u)=>{if(!te)return;let h=te.querySelector("svg");h&&h.remove();let x=vt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),k=ae(i,x,u,1.5);k&&te.appendChild(k)},di=()=>{te&&te.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Kr=()=>{if(!te)return;Fc();let i=o.voiceRecognition??{},u=i.recordingBackgroundColor,h=i.recordingIconColor,x=i.recordingBorderColor;if(di(),te.classList.add("persona-voice-recording"),te.style.backgroundColor=u??"var(--persona-voice-recording-bg, #ef4444)",te.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let k=te.querySelector("svg");k&&k.setAttribute("stroke",h)}x&&(te.style.borderColor=x),te.setAttribute("aria-label","Stop voice recognition")},qx=()=>{if(!te)return;Fc();let i=o.voiceRecognition??{},u=q.getVoiceInterruptionMode(),h=i.processingIconName??"loader",x=i.processingIconColor??vt?.color??"",k=i.processingBackgroundColor??vt?.backgroundColor??"",W=i.processingBorderColor??vt?.borderColor??"";di(),te.classList.add("persona-voice-processing"),te.style.backgroundColor=k,te.style.borderColor=W;let z=x||"currentColor";te.style.color=z,Oc(h,z),te.setAttribute("aria-label","Processing voice input"),u==="none"&&(te.style.cursor="default")},Vx=()=>{if(!te)return;Fc();let i=o.voiceRecognition??{},u=q.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",x=i.speakingIconName??h,k=i.speakingIconColor??(u==="barge-in"?i.recordingIconColor??vt?.color??"":vt?.color??""),W=i.speakingBackgroundColor??(u==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),z=i.speakingBorderColor??(u==="barge-in"?i.recordingBorderColor??"":vt?.borderColor??"");di(),te.classList.add("persona-voice-speaking"),te.style.backgroundColor=W,te.style.borderColor=z;let U=k||"currentColor";te.style.color=U,Oc(x,U);let j=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";te.setAttribute("aria-label",j),u==="none"&&(te.style.cursor="default"),u==="barge-in"&&te.classList.add("persona-voice-recording")},no=()=>{te&&(di(),vt&&(te.style.backgroundColor=vt.backgroundColor??"",te.style.color=vt.color??"",te.style.borderColor=vt.borderColor??"",Oc(vt.iconName,vt.color||"currentColor"),vt=null),te.style.cursor="",te.setAttribute("aria-label","Start voice recognition"))},Xr=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=q.getVoiceStatus(),u=q.getVoiceInterruptionMode();if(u==="none"&&(i==="processing"||i==="speaking"))return;if(u==="cancel"&&(i==="processing"||i==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Wn(),eo("user"),no()});return}q.toggleVoice().then(()=>{je.active=q.isVoiceActive(),je.manuallyDeactivated=!q.isVoiceActive(),Wn(),eo("user"),q.isVoiceActive()?Kr():no()});return}if(qn){let i=B.value.trim();je.manuallyDeactivated=!0,Wn(),So("user"),i&&(B.value="",B.style.height="auto",q.sendMessage(i))}else je.manuallyDeactivated=!1,Wn(),ci("user")};Pf=Xr,te&&(te.addEventListener("click",Xr),De.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),no()):So("system"),te&&te.removeEventListener("click",Xr)}));let zx=c.on("assistant:complete",()=>{cm&&(je.active||je.manuallyDeactivated||cm==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{!je.active&&!je.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?q.toggleVoice().then(()=>{je.active=q.isVoiceActive(),eo("auto"),q.isVoiceActive()&&Kr()}):ci("auto"))},600))});De.push(zx);let $x=c.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});De.push($x);let Fm=()=>{lt(!J,"user")},kt=null,Yt=null;if(P&&!Q()){let{instance:i,element:u}=ju({config:o,plugins:a,onToggle:Fm});kt=i,i||(Yt=u)}kt?e.appendChild(kt.element):Yt&&e.appendChild(Yt),$a(),_r(),Lc(),kc(),si(q.isStreaming()),hm()||(cn()==="follow"?wo(!0):gm()),lx(),F&&(!P||Q()?setTimeout(()=>wc(),0):J&&setTimeout(()=>wc(),200));let Xa=()=>{if(Q()){Yo(),$a();return}let i=St(o),u=o.launcher?.sidebarMode??!1,h=e.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640,W=h.innerWidth<=k,z=x&&W&&P;try{if(z){Zo(),Ba=Xs();return}let U=!1;G&&(G=!1,Zo(),U=!0);let j=Xs();if(!U&&j!==Ba&&(Zo(),U=!0),Ba=j,U&&lc(),!P&&!i){he.style.height="",he.style.width="";return}if(!u&&!i){let pe=o?.launcher?.width??o?.launcherWidth??mn;he.style.width=pe,he.style.maxWidth=pe}Ks(),Kf()}finally{if(Yo(),$a(),J&&P){let j=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),Y=o.launcher?.sidebarMode??!1,pe=o.launcher?.mobileFullscreen??!0,le=St(o)&&pe&&j,ye=Y||pe&&j&&P||le;if(ye&&!Un){let Ge=e.getRootNode(),ht=Ge instanceof ShadowRoot?Ge.host:e.closest(".persona-host");ht&&!_n&&(_n=Pu(ht,o.launcher?.zIndex??Ut)),Un=Ru(e.ownerDocument)}else ye||(_n?.(),_n=null,Un?.(),Un=null)}}};Xa();let Om=e.ownerDocument.defaultView??window;if(Om.addEventListener("resize",Xa),De.push(()=>Om.removeEventListener("resize",Xa)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Yo()});i.observe(we),De.push(()=>i.disconnect())}pn=re.scrollTop;let Nm=jn(re),_m=()=>{let i=re.scrollTop,u=jn(re),h=u<Nm;if(Nm=u,!ho()){pn=i,Vt();return}let{action:x,nextLastScrollTop:k}=bl({following:dn.isFollowing(),currentScrollTop:i,lastScrollTop:pn,nearBottom:uo(re,Yn),userScrollThreshold:rx,isAutoScrolling:on||Qs||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(pn=k,x==="resume"){ni()||Co();return}x==="pause"&&Na()};if(re.addEventListener("scroll",_m,{passive:!0}),De.push(()=>re.removeEventListener("scroll",_m)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{gx(),Gc(xe)});i.observe(xe),i.observe(re),De.push(()=>i.disconnect())}let Um=()=>{ho()&&dn.isFollowing()&&ni()&&Na()},qm=re.ownerDocument;qm.addEventListener("selectionchange",Um),De.push(()=>{qm.removeEventListener("selectionchange",Um)});let jx=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Vm=i=>{jx.has(i.key)&&(cr(),Mf()&&ho()&&dn.isFollowing()&&Na())},zm=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(cr(),Mf()&&ho()&&dn.isFollowing()&&Na())};re.addEventListener("keydown",Vm),re.addEventListener("focusin",zm),De.push(()=>{re.removeEventListener("keydown",Vm),re.removeEventListener("focusin",zm)});let $m=i=>{if(i.deltaY!==0&&cr(),!ho())return;let u=xl({following:dn.isFollowing(),deltaY:i.deltaY,nearBottom:uo(re,Yn),resumeWhenNearBottom:!0});u==="pause"?Na():u==="resume"&&!ni()&&Co()};re.addEventListener("wheel",$m,{passive:!0}),re.addEventListener("touchmove",cr,{passive:!0}),re.addEventListener("pointerdown",cr,{passive:!0}),De.push(()=>{re.removeEventListener("touchmove",cr),re.removeEventListener("pointerdown",cr)}),De.push(()=>re.removeEventListener("wheel",$m)),Pt.addEventListener("click",()=>{_a(),re.scrollTop=re.scrollHeight,pn=re.scrollTop,Co(),wo(!0),Vt()}),De.push(()=>Pt.remove()),De.push(()=>{um(),_a()});let jm=()=>{de&&(or&&(de.removeEventListener("click",or),or=null),Z()?(de.style.display="",or=()=>{lt(!1,"user")},de.addEventListener("click",or)):de.style.display="none")};jm(),(()=>{let{clearChatButton:i}=Te;i&&i.addEventListener("click",()=>{q.clearMessages(),ar.clear(),Co(),Wo(Te.composerOverlay);try{localStorage.removeItem(Ta),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ta}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ta)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(u),g?.clear&&hc(()=>g.clear(),"[AgentWidget] Failed to clear storage adapter:"),m={},M.syncFromMetadata(),Ne?.clear(),_e?.reset(),Ae?.update()})})(),H&&H.addEventListener("submit",li);let Gm=[["keydown",Nx],["input",Ox],["paste",_x],["focus",Qb]],Nc=i=>{if(i)for(let[u,h]of Gm)i.addEventListener(u,h)},_c=i=>{if(i)for(let[u,h]of Gm)i.removeEventListener(u,h)};Nc(B);let Km=()=>{Qt?.onComposerSwap((i,u)=>{_c(u),B=i,Nc(i)})};Km();let Uc=!1;function Gx(){if(!Uc){Uc=!0;try{let i=B?.value??"",u=we.ownerDocument??document,h=B?u.activeElement===B:!1;_c(B),H?.removeEventListener("submit",li),te?.removeEventListener("click",Xr),Qt?.destroy(),Qt=null;let x=null,k=()=>(x=Q()?Wl({config:o}):Lr({config:o}),x.footer),W=Wf(k)??k();et.replaceComposer(W),we=et.composer.footer;let z=x!==null&&W===x.footer;rc=!z,Us=z?x.setSendButtonMode:()=>{},If(we),Bf(we),Df(),Ff(),Of(),Km(),H&&H.addEventListener("submit",li),Nc(B),te?.addEventListener("click",Xr);let U=nr.indexOf(Qn);Qn.destroy(),Qn=Es(I),U>=0&&(nr[U]=Qn),B&&(B.value=i),Lc(),_r(),si(q.isStreaming()),Zo(),Yo(),h&&B?.focus()}finally{Uc=!1}}}let Xm=e.ownerDocument??document;Xm.addEventListener("keydown",Bm,!0);let Jm="persona-attachment-drop-active",Ja=0,qc=()=>{Ja=0,be.classList.remove(Jm)},Jr=()=>o.attachments?.enabled===!0&&bt!==null,Qm=i=>{!Xl(i.dataTransfer)||!Jr()||(Ja++,Ja===1&&be.classList.add(Jm))},Ym=i=>{!Xl(i.dataTransfer)||!Jr()||(Ja--,Ja<=0&&qc())},Zm=i=>{!Xl(i.dataTransfer)||!Jr()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},eg=i=>{if(!Xl(i.dataTransfer)||!Jr())return;i.preventDefault(),i.stopPropagation(),qc();let u=Array.from(i.dataTransfer.files??[]);u.length!==0&&bt.handleFiles(u)},Mo=!0;be.addEventListener("dragenter",Qm,Mo),be.addEventListener("dragleave",Ym,Mo),e.addEventListener("dragover",Zm,Mo),e.addEventListener("drop",eg,Mo);let pi=e.ownerDocument,tg=i=>{Jr()&&i.preventDefault()},ng=i=>{Jr()&&i.preventDefault()};pi.addEventListener("dragover",tg),pi.addEventListener("drop",ng),De.push(()=>{H&&H.removeEventListener("submit",li),_c(B),Xm.removeEventListener("keydown",Bm,!0),Qt?.destroy()}),De.push(()=>{be.removeEventListener("dragenter",Qm,Mo),be.removeEventListener("dragleave",Ym,Mo),e.removeEventListener("dragover",Zm,Mo),e.removeEventListener("drop",eg,Mo),pi.removeEventListener("dragover",tg),pi.removeEventListener("drop",ng),qc()}),De.push(()=>{q.cancel()}),kt?De.push(()=>{kt?.destroy()}):Yt&&De.push(()=>{Yt?.remove()});let Rt={update(i){let u=o.toolCall,h=o.messageActions,x=o.layout?.messages,k=o.colorScheme,W=o.loadingIndicator,z=o.iterationDisplay,U=o.features?.showReasoning,j=o.features?.showToolCalls,Y=o.features?.toolCallDisplay,pe=o.features?.reasoningDisplay,le=o.features?.streamAnimation?.type;o=ql({...o,features:r},i),r=o.features,o=Hs(o),dc(),Sr(e,o),Is(e,o),Ws(e,o),Jn(),o.colorScheme!==k&&Xf();let ye=Bs.getForInstance(o.plugins);a.length=0,a.push(...ye),P=o.launcher?.enabled??!0,R=o.launcher?.autoExpand??!1,ue=o.features?.showReasoning??!0,oe=o.features?.showToolCalls??!0,Se=o.features?.scrollToBottom??{};let Ge=cn();Ce=o.features?.scrollBehavior??{},Ge!==cn()&&(_a(),Co()),lm(),Lf(),Vt();let ht=me;if(me=o.features?.showEventStreamToggle??!1,me&&!ht){if(Ne||(Je=new Ps(ut),Ne=new Ls(Qe,Je),_e=_e??new Rs,Je.open().then(()=>Ne?.restore()).catch(()=>{}),q.setSSEEventCallback((se,$e)=>{o.onSSEEvent?.(se,$e),_e?.processEvent(se,$e),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:se,timestamp:Date.now(),payload:JSON.stringify($e)})})),!Ye&&We){let se=o.features?.eventStream?.classNames,$e="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"+(se?.toggleButton?" "+se.toggleButton:"");Ye=v("button",$e),Ye.style.width="28px",Ye.style.height="28px",Ye.style.color=Xt.actionIconColor,Ye.type="button",Ye.setAttribute("aria-label","Event Stream"),Ye.title="Event Stream";let mt=ae("activity","18px","currentColor",1.5);mt&&Ye.appendChild(mt);let Ze=Te.clearChatButtonWrapper,ot=Te.closeButtonWrapper,Gt=Ze||ot;Gt&&Gt.parentNode===We?We.insertBefore(Ye,Gt):We.appendChild(Ye),Ye.addEventListener("click",()=>{Me?Ia():nc()})}}else!me&&ht&&(Ia(),Ye&&(Ye.remove(),Ye=null),Ne?.clear(),Je?.destroy(),Ne=null,Je=null,_e?.reset(),_e=null);if(o.launcher?.enabled===!1&&kt&&(kt.destroy(),kt=null),o.launcher?.enabled===!1&&Yt&&(Yt.remove(),Yt=null),o.launcher?.enabled!==!1&&!kt&&!Yt){let{instance:se,element:$e}=ju({config:o,plugins:a,onToggle:Fm});kt=se,se||(Yt=$e),e.appendChild($e)}kt&&kt.update(o),ze&&o.launcher?.title!==void 0&&(ze.textContent=o.launcher.title),Ue&&o.launcher?.subtitle!==void 0&&(Ue.textContent=o.launcher.subtitle);let ct=o.layout?.header;if(ct?.layout!==E&&We){let se=ct?ya(o,ct,{showClose:Z(),onClose:()=>lt(!1,"user")}):fo({config:o,showClose:Z(),onClose:()=>lt(!1,"user")});et.replaceHeader(se),We=et.header.element,Pe=et.header.iconHolder,ze=et.header.headerTitle,Ue=et.header.headerSubtitle,de=et.header.closeButton,E=ct?.layout}else if(ct){if(Pe&&(Pe.style.display=ct.showIcon===!1?"none":""),ze&&(ze.style.display=ct.showTitle===!1?"none":""),Ue&&(Ue.style.display=ct.showSubtitle===!1?"none":""),de){let se=Z()&&ct.showCloseButton!==!1;de.style.display=se?"":"none"}if(Te.clearChatButtonWrapper){let se=ct.showClearChat;if(se!==void 0){Te.clearChatButtonWrapper.style.display=se?"":"none";let{closeButtonWrapper:$e}=Te;$e&&!$e.classList.contains("persona-absolute")&&(se?$e.classList.remove("persona-ml-auto"):$e.classList.add("persona-ml-auto"))}}}let Mt=o.layout?.showHeader!==!1;We&&(We.style.display=Mt?"":"none");let It=o.layout?.showFooter!==!1;we&&(we.style.display=It?"":"none"),Yo(),Vt(),P!==$?P?lt(R,"auto"):(J=!0,$a()):R!==O&<(R,"auto"),O=R,$=P,Xa(),jm();let Fe=JSON.stringify(o.toolCall)!==JSON.stringify(u),Ee=JSON.stringify(o.messageActions)!==JSON.stringify(h),At=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),dt=o.loadingIndicator?.render!==W?.render||o.loadingIndicator?.renderIdle!==W?.renderIdle||o.loadingIndicator?.showBubble!==W?.showBubble,Ot=o.iterationDisplay!==z,pt=(o.features?.showReasoning??!0)!==(U??!0)||(o.features?.showToolCalls??!0)!==(j??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(Y)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(pe);(Fe||Ee||At||dt||Ot||pt)&&q&&(uc++,Ua(xe,q.getMessages(),ie));let Wt=o.features?.streamAnimation?.type;if(Wt!==le&&Wt&&Wt!=="none"){let se=ha(Wt,o.features?.streamAnimation?.plugins);se&&Al(se,e)}let Ie=o.launcher??{},Oe=Ie.headerIconHidden??!1,zt=o.layout?.header?.showIcon,$t=Oe||zt===!1,Ct=Ie.headerIconName,st=Ie.headerIconSize??"48px";if(Pe){let se=be.querySelector(".persona-border-b-persona-divider"),$e=se?.querySelector(".persona-flex-col");if($t)Pe.style.display="none",se&&$e&&!se.contains($e)&&se.insertBefore($e,se.firstChild);else{if(Pe.style.display="",Pe.style.height=st,Pe.style.width=st,se&&$e&&(se.contains(Pe)?Pe.nextSibling!==$e&&(Pe.remove(),se.insertBefore(Pe,$e)):se.insertBefore(Pe,$e)),Ct){let Ze=parseFloat(st)||24,ot=ae(Ct,Ze*.6,"currentColor",1);ot?Pe.replaceChildren(ot):Pe.textContent=Ie.agentIconText??"\u{1F4AC}"}else if(Ie.iconUrl){let Ze=Pe.querySelector("img");if(Ze)Ze.src=Ie.iconUrl,Ze.style.height=st,Ze.style.width=st;else{let ot=document.createElement("img");ot.src=Ie.iconUrl,ot.alt="",ot.className="persona-rounded-xl persona-object-cover",ot.style.height=st,ot.style.width=st,Pe.replaceChildren(ot)}}else{let Ze=Pe.querySelector("svg"),ot=Pe.querySelector("img");(Ze||ot)&&Pe.replaceChildren(),Pe.textContent=Ie.agentIconText??"\u{1F4AC}"}let mt=Pe.querySelector("img");mt&&(mt.style.height=st,mt.style.width=st)}}let ft=o.layout?.header?.showTitle,Xe=o.layout?.header?.showSubtitle;if(ze&&(ze.style.display=ft===!1?"none":""),Ue&&(Ue.style.display=Xe===!1?"none":""),de){let se=Z()&&o.layout?.header?.showCloseButton!==!1;de.style.display=se?"":"none";let $e=Ie.closeButtonSize??"32px",mt=Ie.closeButtonPlacement??"inline";de.style.height=$e,de.style.width=$e;let{closeButtonWrapper:Ze}=Te,ot=mt==="top-right",Gt=Ze?.classList.contains("persona-absolute");if(Ze&&ot!==Gt)if(Ze.remove(),ot)Ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",be.style.position="relative",be.appendChild(Ze);else{let Eo=Ie.clearChat?.placement??"inline",Za=Ie.clearChat?.enabled??!0;Ze.className=Za&&Eo==="inline"?"":"persona-ml-auto";let og=be.querySelector(".persona-border-b-persona-divider");og&&og.appendChild(Ze)}if(de.style.color=Ie.closeButtonColor||Xt.actionIconColor,Ie.closeButtonBackgroundColor?(de.style.backgroundColor=Ie.closeButtonBackgroundColor,de.classList.remove("hover:persona-bg-gray-100")):(de.style.backgroundColor="",de.classList.add("hover:persona-bg-gray-100")),Ie.closeButtonBorderWidth||Ie.closeButtonBorderColor){let Eo=Ie.closeButtonBorderWidth||"0px",Za=Ie.closeButtonBorderColor||"transparent";de.style.border=`${Eo} solid ${Za}`,de.classList.remove("persona-border-none")}else de.style.border="",de.classList.add("persona-border-none");Ie.closeButtonBorderRadius?(de.style.borderRadius=Ie.closeButtonBorderRadius,de.classList.remove("persona-rounded-full")):(de.style.borderRadius="",de.classList.add("persona-rounded-full")),Ie.closeButtonPaddingX?(de.style.paddingLeft=Ie.closeButtonPaddingX,de.style.paddingRight=Ie.closeButtonPaddingX):(de.style.paddingLeft="",de.style.paddingRight=""),Ie.closeButtonPaddingY?(de.style.paddingTop=Ie.closeButtonPaddingY,de.style.paddingBottom=Ie.closeButtonPaddingY):(de.style.paddingTop="",de.style.paddingBottom="");let fn=Ie.closeButtonIconName??"x",Hn=Ie.closeButtonIconText??"\xD7";de.innerHTML="";let Nt=ae(fn,"28px","currentColor",1);Nt?(Nt.style.display="block",de.appendChild(Nt)):de.textContent=Hn;let Kt=Ie.closeButtonTooltipText??"Close chat",ro=Ie.closeButtonShowTooltip??!0;de.setAttribute("aria-label",Kt),Ze&&qt({anchor:de,trigger:Ze,text:()=>de?.getAttribute("aria-label")??Kt,enabled:ro})}let{clearChatButton:He,clearChatButtonWrapper:yt}=Te;if(He){let se=Ie.clearChat??{},$e=se.enabled??!0,mt=o.layout?.header?.showClearChat,Ze=mt!==void 0?mt:$e,ot=se.placement??"inline";if(yt){yt.style.display=Ze?"":"none";let{closeButtonWrapper:Gt}=Te;!Q()&&Gt&&!Gt.classList.contains("persona-absolute")&&(Ze?Gt.classList.remove("persona-ml-auto"):Gt.classList.add("persona-ml-auto"));let fn=ot==="top-right",Hn=yt.classList.contains("persona-absolute");if(!Q()&&fn!==Hn&&Ze){if(yt.remove(),fn)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",be.style.position="relative",be.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let Kt=be.querySelector(".persona-border-b-persona-divider"),ro=Te.closeButtonWrapper;Kt&&ro&&ro.parentElement===Kt?Kt.insertBefore(yt,ro):Kt&&Kt.appendChild(yt)}let Nt=Te.closeButtonWrapper;Nt&&!Nt.classList.contains("persona-absolute")&&(fn?Nt.classList.add("persona-ml-auto"):Nt.classList.remove("persona-ml-auto"))}}if(Ze){if(!Q()){let Eo=se.size??"32px";He.style.height=Eo,He.style.width=Eo}let Gt=se.iconName??"refresh-cw",fn=se.iconColor??"";He.style.color=fn||Xt.actionIconColor,He.innerHTML="";let Hn=Q()?"14px":"20px",Nt=ae(Gt,Hn,"currentColor",1);if(Nt&&(Nt.style.display="block",He.appendChild(Nt)),se.backgroundColor?(He.style.backgroundColor=se.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),se.borderWidth||se.borderColor){let Eo=se.borderWidth||"0px",Za=se.borderColor||"transparent";He.style.border=`${Eo} solid ${Za}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");se.borderRadius?(He.style.borderRadius=se.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),se.paddingX?(He.style.paddingLeft=se.paddingX,He.style.paddingRight=se.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),se.paddingY?(He.style.paddingTop=se.paddingY,He.style.paddingBottom=se.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let Kt=se.tooltipText??"Clear chat",ro=se.showTooltip??!0;He.setAttribute("aria-label",Kt),yt&&qt({anchor:He,trigger:yt,text:()=>He?.getAttribute("aria-label")??Kt,enabled:ro})}}let jt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ds],An=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Dr.message,Dr.messageAndClick];M=Fs({parsers:jt,handlers:An,getSessionMetadata:L,updateSessionMetadata:A,emit:c.emit,documentRef:typeof document<"u"?document:null}),ie=ib(o,M,ge),q.updateConfig(o),Ua(xe,q.getMessages(),ie),_r(),Lc(),kx(),si(q.isStreaming());let Qa=o.voiceRecognition?.enabled===!0,ui=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Lt=o.voiceRecognition?.provider?.type==="runtype";if(Qa&&(ui||Lt))if(!te||!bn){let se=Ux(o.voiceRecognition,o.sendButton);se&&(te=se.micButton,bn=se.micButtonWrapper,wt.insertBefore(bn,D),te.addEventListener("click",Xr),te.disabled=q.isStreaming())}else{let se=o.voiceRecognition??{},$e=o.sendButton??{},mt=se.iconName??"mic",Ze=$e.size??"40px",ot=se.iconSize??Ze,Gt=parseFloat(ot)||24;te.style.width=ot,te.style.height=ot,te.style.minWidth=ot,te.style.minHeight=ot;let fn=se.iconColor??$e.textColor;te.innerHTML="";let Hn=ae(mt,Gt,fn||"currentColor",1.5);Hn?te.appendChild(Hn):te.textContent="\u{1F3A4}";let Nt=se.backgroundColor??$e.backgroundColor;Nt?te.style.backgroundColor=Nt:te.style.backgroundColor="",fn?te.style.color=fn:te.style.color="var(--persona-text, #111827)",se.borderWidth?(te.style.borderWidth=se.borderWidth,te.style.borderStyle="solid"):(te.style.borderWidth="",te.style.borderStyle=""),se.borderColor?te.style.borderColor=se.borderColor:te.style.borderColor="",se.paddingX?(te.style.paddingLeft=se.paddingX,te.style.paddingRight=se.paddingX):(te.style.paddingLeft="",te.style.paddingRight=""),se.paddingY?(te.style.paddingTop=se.paddingY,te.style.paddingBottom=se.paddingY):(te.style.paddingTop="",te.style.paddingBottom="");let Kt=se.tooltipText??"Start voice recognition",ro=se.showTooltip??!1;te.setAttribute("aria-label",Kt),bn&&qt({anchor:te,trigger:bn,text:()=>te?.getAttribute("aria-label")??Kt,enabled:ro}),bn.style.display="",te.disabled=q.isStreaming()}else te&&bn&&(bn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?q.isVoiceActive()&&q.toggleVoice():qn&&So());if(o.attachments?.enabled===!0){if(!xn||!it){let se=o.attachments??{},mt=(o.sendButton??{}).size??"40px";Ln||(Ln=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ln.style.display="none",H.insertBefore(Ln,B)),Et||(Et=document.createElement("input"),Et.type="file",Et.accept=(se.allowedTypes??co).join(","),Et.multiple=(se.maxFiles??4)>1,Et.style.display="none",Et.setAttribute("aria-label","Attach files"),H.insertBefore(Et,B)),xn=v("div","persona-send-button-wrapper"),it=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),it.type="button",it.setAttribute("aria-label",se.buttonTooltipText??"Attach file");let Ze=se.buttonIconName??"paperclip",ot=mt,Gt=parseFloat(ot)||40,fn=Math.round(Gt*.6);it.style.width=ot,it.style.height=ot,it.style.minWidth=ot,it.style.minHeight=ot,it.style.fontSize="18px",it.style.lineHeight="1";let Hn=ae(Ze,fn,"currentColor",1.5);Hn?it.appendChild(Hn):it.textContent="\u{1F4CE}",it.addEventListener("click",Kt=>{Kt.preventDefault(),Et?.click()}),xn.appendChild(it);let Nt=se.buttonTooltipText??"Attach file";qt({anchor:it,trigger:xn,text:()=>it?.getAttribute("aria-label")??Nt}),yn?yn.append(xn):H.appendChild(xn),!bt&&Et&&Ln&&(bt=Ar.fromConfig(se),bt.setPreviewsContainer(Ln),Et.addEventListener("change",async()=>{bt&&Et?.files&&(await bt.handleFileSelect(Et.files),Et.value="")}))}else{xn.style.display="";let se=o.attachments??{};Et&&(Et.accept=(se.allowedTypes??co).join(","),Et.multiple=(se.maxFiles??4)>1),bt&&bt.updateConfig({allowedTypes:se.allowedTypes,maxFileSize:se.maxFileSize,maxFiles:se.maxFiles})}if(be.querySelector(".persona-attachment-drop-overlay")?.remove(),be.appendChild(lb(o.attachments?.dropOverlay)),it){let se=o.attachments??{},$e=se.buttonTooltipText??"Attach file";it.setAttribute("aria-label",$e),it.textContent="";let mt=parseFloat(o.sendButton?.size??"40px")||40,Ze=ae(se.buttonIconName??"paperclip",Math.round(mt*.6),"currentColor",1.5);Ze?it.appendChild(Ze):it.textContent="\u{1F4CE}",xn&&qt({anchor:it,trigger:xn,text:()=>it?.getAttribute("aria-label")??$e})}}else xn&&(xn.style.display="none"),bt&&bt.clearAttachments(),be.querySelector(".persona-attachment-drop-overlay")?.remove();let Ft=o.sendButton??{},Ya=Ft.useIcon??!1,mi=Ft.iconText??"\u2191",Qr=Ft.iconName,gi=Ft.tooltipText??"Send message",Vc=Ft.showTooltip??!1,mr=Ft.size??"40px",oo=Ft.backgroundColor,gr=Ft.textColor;if(Ya){if(y.style.width=mr,y.style.height=mr,y.style.minWidth=mr,y.style.minHeight=mr,y.style.fontSize="18px",y.style.lineHeight="1",gr?y.style.color=gr:y.style.color="var(--persona-button-primary-fg, #ffffff)",!q.isStreaming())if(y.innerHTML="",Qr){let se=parseFloat(mr)||24,$e=gr?.trim()||"currentColor",mt=ae(Qr,se,$e,2);mt?y.appendChild(mt):y.textContent=mi}else y.textContent=mi;y.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",oo?(y.style.backgroundColor=oo,y.classList.remove("persona-bg-persona-primary")):(y.style.backgroundColor="",y.classList.add("persona-bg-persona-primary"))}else y.textContent=o.copy?.sendButtonLabel??"Send",y.style.width="",y.style.height="",y.style.minWidth="",y.style.minHeight="",y.style.fontSize="",y.style.lineHeight="",y.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",oo?(y.style.backgroundColor=oo,y.classList.remove("persona-bg-persona-accent")):y.classList.add("persona-bg-persona-accent"),gr?y.style.color=gr:y.classList.add("persona-text-white");Ft.borderWidth?(y.style.borderWidth=Ft.borderWidth,y.style.borderStyle="solid"):(y.style.borderWidth="",y.style.borderStyle=""),Ft.borderColor?y.style.borderColor=Ft.borderColor:y.style.borderColor="",Ft.paddingX?(y.style.paddingLeft=Ft.paddingX,y.style.paddingRight=Ft.paddingX):(y.style.paddingLeft="",y.style.paddingRight=""),Ft.paddingY?(y.style.paddingTop=Ft.paddingY,y.style.paddingBottom=Ft.paddingY):(y.style.paddingTop="",y.style.paddingBottom=""),q.isStreaming()||y.setAttribute("aria-label",gi),D&&qt({anchor:y,trigger:D,text:()=>y.getAttribute("aria-label")??gi,enabled:Vc});let Yr=qo(o,Q());pc(),Yr?(xe.style.maxWidth=Yr,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",X.style.maxWidth=Yr,X.style.marginLeft="auto",X.style.marginRight="auto",X.style.width="100%",H&&(H.style.maxWidth=Yr,H.style.marginLeft="auto",H.style.marginRight="auto"),I&&(I.style.maxWidth=Yr,I.style.marginLeft="auto",I.style.marginRight="auto"),N.style.maxWidth=Yr,N.style.marginLeft="auto",N.style.marginRight="auto"):(xe.style.maxWidth="",xe.style.marginLeft="",xe.style.marginRight="",xe.style.width="",X.style.maxWidth="",X.style.marginLeft="",X.style.marginRight="",X.style.width="",H&&(H.style.maxWidth="",H.style.marginLeft="",H.style.marginRight=""),I&&(I.style.maxWidth="",I.style.marginLeft="",I.style.marginRight=""),N.style.maxWidth="",N.style.marginLeft="",N.style.marginRight="");let To=o.statusIndicator??{},Kx=To.visible??!0;if(N.style.display=Kx?"":"none",q){let se=q.getStatus();En(N,(mt=>mt==="idle"?To.idleText??Ht.idle:mt==="connecting"?To.connectingText??Ht.connecting:mt==="connected"?To.connectedText??Ht.connected:mt==="error"?To.errorText??Ht.error:Ht[mt])(se),To,se)}N.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Xx=To.align==="left"?"persona-text-left":To.align==="center"?"persona-text-center":"persona-text-right";N.classList.add(Xx)},open(){Z()&<(!0,"api")},close(){Z()&<(!1,"api")},toggle(){Z()&<(!J,"api")},reconnect(){q.reconnectNow()},clearChat(){Xn=!1,q.clearMessages(),ar.clear(),Co();try{localStorage.removeItem(Ta),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ta}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ta)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),g?.clear&&hc(()=>g.clear(),"[AgentWidget] Failed to clear storage adapter:"),m={},M.syncFromMetadata(),Ne?.clear(),_e?.reset(),Ae?.update()},setMessage(i){return!B||q.isStreaming()?!1:(!J&&Z()&<(!0,"system"),B.value=i,B.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(q.isStreaming())return!1;let u=i?.trim()||B.value.trim();return u?(!J&&Z()&<(!0,"system"),B.value="",B.style.height="auto",q.sendMessage(u),!0):!1},startVoiceRecognition(){return q.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(q.isVoiceActive()||(!J&&Z()&<(!0,"system"),je.manuallyDeactivated=!1,Wn(),q.toggleVoice().then(()=>{je.active=q.isVoiceActive(),eo("user"),q.isVoiceActive()&&Kr()})),!0):qn?!0:Dm()?(!J&&Z()&<(!0,"system"),je.manuallyDeactivated=!1,Wn(),ci("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Wn(),eo("user"),no()}),!0):!1:qn?(je.manuallyDeactivated=!0,Wn(),So("user"),!0):!1},injectMessage(i){return!J&&Z()&<(!0,"system"),q.injectMessage(i)},injectAssistantMessage(i){!J&&Z()&<(!0,"system");let u=q.injectAssistantMessage(i);return fe&&(fe=!1,ne&&(clearTimeout(ne),ne=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),u},injectUserMessage(i){return!J&&Z()&<(!0,"system"),q.injectUserMessage(i)},injectSystemMessage(i){return!J&&Z()&<(!0,"system"),q.injectSystemMessage(i)},injectMessageBatch(i){return!J&&Z()&<(!0,"system"),q.injectMessageBatch(i)},injectComponentDirective(i){return!J&&Z()&<(!0,"system"),q.injectComponentDirective(i)},injectTestMessage(i){!J&&Z()&<(!0,"system"),q.injectTestEvent(i)},async connectStream(i,u){return q.connectStream(i,u)},__pushEventStreamEvent(i){Ne&&(_e?.processEvent(i.type,i.payload),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!me||!Ne||nc()},hideEventStream(){Me&&Ia()},isEventStreamVisible(){return Me},showArtifacts(){tn(o)&&(Xn=!1,Fr=!0,Jn(),Ke?.setMobileOpen(!0))},hideArtifacts(){tn(o)&&(Xn=!0,Jn())},upsertArtifact(i){return tn(o)?(zn(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Xn=!1,Fr=!0),q.upsertArtifact(i)):null},selectArtifact(i){tn(o)&&q.selectArtifact(i)},clearArtifacts(){tn(o)&&q.clearArtifacts()},getArtifacts(){return q?.getArtifacts()??[]},getSelectedArtifactId(){return q?.getSelectedArtifactId()??null},focusInput(){return P&&!J&&!Q()||!B?!1:(B.focus(),!0)},async resolveApproval(i,u,h){let k=q.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"){q.resolveWebMcpApproval(k.id,u);return}return q.resolveApproval(k.approval,u,h)},setFollowUpSuggestions(i){nx(i)},clearFollowUpSuggestions(){im()},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...m}},updatePersistentMetadata(i){A(i)},on(i,u){return c.on(i,u)},off(i,u){c.off(i,u)},isOpen(){return Z()&&J},isVoiceActive(){return je.active},toggleReadAloud(i){q.toggleReadAloud(i)},stopReadAloud(){q.stopSpeaking()},getReadAloudState(i){return q.getReadAloudState(i)},onReadAloudChange(i){return q.onReadAloudChange(i)},getState(){return{open:Z()&&J,launcherEnabled:P,voiceActive:je.active,streaming:q.isStreaming()}},showCSATFeedback(i){!J&&Z()&<(!0,"system");let u=xe.querySelector(".persona-feedback-container");u&&u.remove();let h=Gl({onSubmit:async(x,k)=>{q.isClientTokenMode()&&await q.submitCSATFeedback(x,k),i?.onSubmit?.(x,k)},onDismiss:i?.onDismiss,...i});xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!J&&Z()&<(!0,"system");let u=xe.querySelector(".persona-feedback-container");u&&u.remove();let h=Kl({onSubmit:async(x,k)=>{q.isClientTokenMode()&&await q.submitNPSFeedback(x,k),i?.onSubmit?.(x,k)},onDismiss:i?.onDismiss,...i});xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,u){return q.submitCSATFeedback(i,u)},async submitNPSFeedback(i,u){return q.submitNPSFeedback(i,u)},destroy(){Ic(),ur!=null&&(clearInterval(ur),ur=null),De.forEach(i=>i()),Le.remove(),tt?.remove(),kt?.destroy(),Yt?.remove(),or&&de.removeEventListener("click",or)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,u={controller:Rt,getMessages:Rt.getMessages,getStatus:Rt.getStatus,getMetadata:Rt.getPersistentMetadata,updateMetadata:Rt.updatePersistentMetadata,clearHistory:()=>Rt.clearChat(),setVoiceActive:h=>h?Rt.startVoiceRecognition():Rt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,De.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=U=>{let j=U.detail;(!j?.instanceId||j.instanceId===i)&&Rt.focusInput()};if(window.addEventListener("persona:focusInput",u),De.push(()=>{window.removeEventListener("persona:focusInput",u)}),me){let U=Y=>{let pe=Y.detail;(!pe?.instanceId||pe.instanceId===i)&&Rt.showEventStream()},j=Y=>{let pe=Y.detail;(!pe?.instanceId||pe.instanceId===i)&&Rt.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",j),De.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",j)})}let h=U=>{let j=U.detail;(!j?.instanceId||j.instanceId===i)&&Rt.showArtifacts()},x=U=>{let j=U.detail;(!j?.instanceId||j.instanceId===i)&&Rt.hideArtifacts()},k=U=>{let j=U.detail;j?.instanceId&&j.instanceId!==i||j?.artifact&&Rt.upsertArtifact(j.artifact)},W=U=>{let j=U.detail;j?.instanceId&&j.instanceId!==i||typeof j?.id=="string"&&Rt.selectArtifact(j.id)},z=U=>{let j=U.detail;(!j?.instanceId||j.instanceId===i)&&Rt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",z),De.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",z)})}let wn=xS(o.persistState);if(wn&&Z()){let i=vS(wn.storage),u=`${wn.keyPrefix}widget-open`,h=`${wn.keyPrefix}widget-voice`,x=`${wn.keyPrefix}widget-voice-mode`;if(i){let k=wn.persist?.openState&&i.getItem(u)==="true",W=wn.persist?.voiceState&&i.getItem(h)==="true",z=wn.persist?.voiceState&&i.getItem(x)==="true";if(k&&(kt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Rt.open(),setTimeout(()=>{if(W||z)Rt.startVoiceRecognition();else if(wn.persist?.focusInput){let U=e.querySelector("textarea");U&&U.focus()}},100)},0)),wn.persist?.openState&&(c.on("widget:opened",()=>{i.setItem(u,"true")}),c.on("widget:closed",()=>{i.setItem(u,"false")})),wn.persist?.voiceState&&(c.on("voice:state",U=>{i.setItem(h,U.active?"true":"false")}),c.on("user:message",U=>{i.setItem(x,U.viaVoice?"true":"false")})),wn.clearOnChatClear){let U=()=>{i.removeItem(u),i.removeItem(h),i.removeItem(x)},j=()=>U();window.addEventListener("persona:clear-chat",j),De.push(()=>{window.removeEventListener("persona:clear-chat",j)})}}}if(w&&Z()&&(kt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Rt.open()},0)),$r(),!ox){let i=ea(()=>{q&&(uc++,ar.clear(),Ua(xe,q.getMessages(),ie))});De.push(i)}return Rt};var cb=(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},AS=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},SS=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},MS=(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.")},db=(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"},ff=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=""},pb=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",ff(e)},df=e=>{e.style.transition=""},pf=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=""},uf=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ql=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},TS=(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))},ES=(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)},kS=e=>{let t=Uo(e),n=t.components?.panel,o=(r,a)=>r==null||r===""?a:en(t,r)??r;return{inset:o(n?.inset,rl),canvasBackground:o(n?.canvasBackground,al)}},ub=(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},LS=(e,t,n,o,r,a,s,l)=>{let p=ln(a),d=p.reveal==="push",c=l!=null,f=l?.inset??"",g=l?.canvasBackground??"";TS(e,t,n,o,d),ES(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 m=e.ownerDocument.defaultView,b=a?.launcher?.mobileFullscreen??!0,w=a?.launcher?.mobileBreakpoint??640,T=m!=null?m.innerWidth<=w:!1;if(b&&T&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),pf(t),df(o),pb(o),uf(n),Ql(r,o),ub(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??Ut),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"),pb(o),AS(o,p.maxHeight),ub(o,c&&s,f,g),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",pf(t),df(o),uf(n),Ql(r,o);let A=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=A,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",df(o),ff(o),Ql(r,o);let A=cb(p.width,e.clientWidth),S=Math.max(0,e.clientWidth),C=p.animate?"margin-left 180ms ease":"none",M=p.side==="right"?s?-A:0:s?0:-A;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+A}px`,t.style.transition=C,t.style.marginLeft=`${M}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="",pf(t),ff(o),uf(n),Ql(r,o);let A=p.reveal==="emerge";A?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${c?", padding 180ms ease":""}`:"none",M=!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",SS(o,p.maxHeight),o.style.overflow=A||M?"hidden":"visible",o.style.transition=C,A){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let P=c?`calc(${cb(p.width,e.clientWidth)}px - (2 * ${f}))`:p.width;r.style.width=P,r.style.minWidth=P,r.style.maxWidth=P,r.style.boxSizing="border-box"}}},PS=(e,t)=>{let n=e.ownerDocument.createElement("div");return db(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){db(n,o)},destroy(){n.remove()}}},RS=(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"),f=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,m=()=>{g?.disconnect(),g=null},b=null,w=()=>{b=t?.launcher?.detachedPanel===!0?kS(t):null};w();let T=()=>{LS(s,l,p,d,c,t,f,b)},L=null,A=()=>{L?.(),L=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(L=pa(()=>{w(),T()}))},S=()=>{m(),ln(t).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{T()}),g.observe(s)))},C=!1,M=()=>{T(),S(),f&&!C&&s.dataset.personaDockMobileFullscreen!=="true"&&(C=!0,MS(s,ln(t)))},P=s.ownerDocument.defaultView,R=()=>{M()};return P?.addEventListener("resize",R),ln(t).reveal==="push"?(l.appendChild(p),l.appendChild(d),s.appendChild(l)):(s.appendChild(p),s.appendChild(d)),M(),A(),{mode:"docked",host:c,shell:s,syncWidgetState(F){let O=F.launcherEnabled?F.open:!0;f!==O&&(f=O,M())},updateConfig(F){t=F,(t?.launcher?.enabled??!0)===!1&&(f=!0),w(),M(),A()},destroy(){P?.removeEventListener("resize",R),L?.(),L=null,m(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Ns=(e,t)=>St(t)?RS(e,t):PS(e,t);var IS=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},fb=(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)},mb=e=>{let t=IS(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,a=Ns(t,r),s,l=[],p=(T,L)=>{let S=!(L?.launcher?.enabled??!0)||St(L),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 M=T.attachShadow({mode:"open"});M.appendChild(C),fb(M,o)}else T.appendChild(C),fb(T,o);return t.id&&C.setAttribute("data-persona-instance",t.id),C},d=()=>{a.syncWidgetState(s.getState())},c=()=>{l.forEach(T=>T()),l=[s.on("widget:opened",d),s.on("widget:closed",d)],d()},f=()=>{let T=p(a.host,r);s=Jl(T,r,{debugTools:e.debugTools}),c()},g=()=>{l.forEach(T=>T()),l=[],s.destroy()};f(),e.onChatReady?.();let m=T=>{g(),a.destroy(),a=Ns(t,T),r=T,f()},b={update(T){let L=ql(r??{},T),A=St(r),S=St(L),C=Ko(r),M=Ko(L);if(A!==S||C!==M){m(L);return}r=L,a.updateConfig(r),s.update(T),d()},destroy(){g(),a.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},w=new Proxy(b,{get(T,L,A){if(L==="host")return a.host;if(L in T)return Reflect.get(T,L,A);let S=s[L];return typeof S=="function"?S.bind(s):S}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=w),w};function WS(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 HS(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:WS(o,n)?2:3}function gb(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function Yl(e,t){let n=t.trim();if(!n)return[...e].sort(gb);let o=[];for(let r of e){let a=HS(r.label,n);a!==3&&o.push({item:r,tier:a})}return o.sort((r,a)=>r.tier!==a.tier?r.tier-a.tier:gb(r.item,a.item)),o.map(r=>r.item)}function BS(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 hb(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Yl(e.items,t),resolve:e.resolve}}function yb(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=>Yl(t,BS(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 wb=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),DS=new Set(["button","a","input","select","textarea","details","summary"]),FS=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),mf=/\b(product|card|item|listing|result)\b/i,hf=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,OS=3e3,NS=100;function Ab(e){let t=typeof e.className=="string"?e.className:"";if(mf.test(t)||e.id&&mf.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&mf.test(o.value))return!0}return!1}function Sb(e){return hf.test((e.textContent??"").trim())}function Mb(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 _S(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function bb(e){let t=e.match(hf);return t?t[0]:null}function xb(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 US(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 qS="commerce-card",VS="result-card";function vb(e){return!Ab(e)||!Sb(e)||!Mb(e)&&!_S(e)?0:5200}function Cb(e){return!Ab(e)||Sb(e)||!Mb(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var yf=[{id:qS,scoreElement(e){return vb(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||hf.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(vb(e)===0)return null;let{title:n,href:o}=xb(e),r=bb((e.textContent??"").trim())??bb(t.text)??"",a=US(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:VS,scoreElement(e){return Cb(e)},formatSummary(e,t){if(Cb(e)===0)return null;let{title:n,href:o}=xb(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
145
|
+
`)}}];function zS(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function $S(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,s=t.root??e.root,l=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),d=e.rules??yf;return l==="simple"&&e.rules&&e.rules.length>0?(zS(),d=[]):l==="simple"&&(d=[]),{mode:l,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:a,root:s,rules:d}}function gf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var jS=["data-testid","data-product","data-action","data-id","data-name","data-type"];function GS(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"||DS.has(t)||n&&FS.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Tb(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 KS(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let l=e.getAttribute("name");l&&(t.name=l);let p=e.getAttribute("role");p&&(t.role=p);for(let d=0;d<e.attributes.length;d++){let c=e.attributes[d];c.name.startsWith("data-")&&(t[c.name]=c.value)}return t}function bf(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${gf(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of jS){let a=e.getAttribute(r);if(a){let s=`${t}[${r}="${gf(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=>gf(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 XS(e){return e==="static"?NS:OS}function Eb(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:bf(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:GS(e),attributes:KS(e)}}function JS(e,t,n,o){let r=XS(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 QS(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 YS(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=s.currentNode;for(;l&&r.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let d=l,c=d.tagName.toLowerCase();if(wb.has(c)){l=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){l=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Tb(d)){l=s.nextNode();continue}let f=Eb(d,e.maxTextLength),g=f.text.length>0,m=Object.keys(f.attributes).length>0&&!Object.keys(f.attributes).every(T=>T==="role");if(!g&&!m){l=s.nextNode();continue}if(o.has(f.selector)){l=s.nextNode();continue}o.add(f.selector);let{score:b,formattingRule:w}=JS(d,f,e.rules,n);r.push({el:d,domIndex:a,enriched:f,score:b,formattingRule:w}),a+=1}l=s.nextNode()}r.sort((d,c)=>{let f=d.enriched.interactivity==="static"?1:0,g=c.enriched.interactivity==="static"?1:0;return f!==g?f-g:c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex});let p=[];for(let d of r){if(p.length>=e.maxElements)break;QS(p,d)||p.push(d)}return p.sort((d,c)=>{let f=d.enriched.interactivity==="static"?1:0,g=c.enriched.interactivity==="static"?1:0;return f!==g?f-g:f===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let g=d.formattingRule.formatSummary(d.el,d.enriched,n);g&&(c=g)}let f={...d.enriched};return c&&(f.formattedSummary=c),f})}function ZS(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=r.currentNode;for(;a&&n.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let p=a,d=p.tagName.toLowerCase();if(wb.has(d)){a=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Tb(p)){a=r.nextNode();continue}let c=Eb(p,e.maxTextLength),f=c.text.length>0,g=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(m=>m==="role");if(!f&&!g){a=r.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}a=r.nextNode()}let s=[],l=[];for(let p of n)p.interactivity!=="static"?s.push(p):l.push(p);return[...s,...l].slice(0,e.maxElements)}function kb(e={}){let t=$S(e),n=t.root??document.body;return n?t.mode==="simple"?ZS(t,n):YS(t,n):[]}var Zl=100;function Lb(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,Zl)}" (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,Zl)}" (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,Zl)}" (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,Zl)}"`);o.push(`Content:
|
|
156
156
|
${a.join(`
|
|
157
157
|
`)}`)}return o.join(`
|
|
158
158
|
|
|
159
|
-
`)}function
|
|
159
|
+
`)}function Pb(){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 Rb(){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 Ib(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:Kn(e.colors.primary,.95),100:Kn(e.colors.primary,.9),200:Kn(e.colors.primary,.8),300:Kn(e.colors.primary,.7),400:Kn(e.colors.primary,.6),500:e.colors.primary,600:Kn(e.colors.primary,.8),700:Kn(e.colors.primary,.7),800:Kn(e.colors.primary,.6),900:Kn(e.colors.primary,.5),950:Kn(e.colors.primary,.45)}}),{...t,palette:n}}}}function Wb(){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 Hb(){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 Kn(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 Bb(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var e0={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"}}},Db={components:{panel:{borderRadius:"0",shadow:"none"}}},xf={id:"shop",label:"Shopping Assistant",config:{theme:e0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:mn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},vf={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Db}},Cf={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Db}},wf={shop:xf,minimal:vf,fullscreen:Cf};function Fb(e){return wf[e]}var t0=`
|
|
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(),n0={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:t0};Er(n0);var o0=`
|
|
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(),_s="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",r0=10,a0=120,Af=120,s0=.4,i0=50,l0=e=>{if(!e)return Af;let n=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):Af},$b=e=>{let t=e.closest(".persona-stream-glyph-cycle"),n=l0(t);return a0*n/Af},Sf=e=>{let t=_s[Math.floor(Math.random()*_s.length)];return e&&t===e&&(t=_s[(_s.indexOf(t)+1)%_s.length]),t},c0=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()<s0&&(r.textContent=Sf())}},Ob=new WeakMap,Nb=25,_b=.5,d0=6,Ub=.25,qb=new WeakMap,Vb=new WeakMap,p0=(e,t)=>{if(!e)return Nb*_b;let n=qb.get(e);qb.set(e,t);let o=Vb.get(e)??Nb;if(n!==void 0){let r=t-n;r>1&&(o=o*(1-Ub)+r*Ub,Vb.set(e,o))}return Math.max(d0,o*_b)},Ea=new Map,u0=e=>e.closest("[data-message-id]")?.dataset.messageId??null,f0=e=>{e&&Ea.set(e,(Ea.get(e)??0)+1)},m0=e=>{if(!e)return;let t=Ea.get(e)??0;t<=1?Ea.delete(e):Ea.set(e,t-1)},jb=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=Sf();let n=u0(e);n&&(e.dataset.glyphCycleMessageId=n),f0(n);let o=e.closest(".persona-stream-glyph-cycle"),r=Date.now(),a=p0(o,r),s=$b(e),l=r0*s,p=r+l;if(o){let d=Ob.get(o);d!==void 0&&(p=Math.max(p,d)),Ob.set(o,p+a)}g0(e,t,p)},g0=(e,t,n)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=$b(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,m0(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let s=Sf(r);e.textContent=s,r=s,c0(e),setTimeout(a,o)};setTimeout(a,o)},zb=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))jb(n)},h0=e=>e.nodeType===1,y0={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:o0,bufferContent(e){if(e.length<i0)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(Ea.get(e.id)??0)>0},onAttach(e){zb(e);let t=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))h0(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?jb(r):zb(r))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};Er(y0);var nn=typeof document<"u"?document.currentScript?.src??null:null;Ag(()=>{let e=nn?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===nn?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${nn??"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)});ig(()=>{let e=nn?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===nn?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${nn??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});ts().catch(e=>{typeof console<"u"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});ih(()=>{let e=nn?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===nn?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${nn??"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)});bh(()=>{let e=nn?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===nn?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${nn??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});xh(()=>{let e=nn?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===nn?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${nn??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});return nv(b0);})();
|
|
214
214
|
/*! Bundled license information:
|
|
215
215
|
|
|
216
216
|
lucide/dist/esm/icons/activity.mjs:
|